From 4de705b061cf9752e694533abadaa3089155eab5 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 17:46:27 +0800 Subject: [PATCH 1/2] fix(core): on Stellar, sign only the checked authorization, built through the run's RPC The caps, the pin and the plan were checked on the terms Wasit hands the x402 client, while the Stellar client signs the authorization entries the RPC's simulation returns. The payer's signer is now gated: each preimage is decoded and the key signs only one transfer of the checked amount from the payer to the checked payee, on the checked asset and the run's network, with no sub-invocation, once per payment, expiring no later than the payment's lifetime allows from the run's first ledger reading. A built payment that carries anything but that one signed authorization is discarded unsent. On stellar:testnet the client now builds and simulates through the run's RPC, the one whose network is checked and the settlement is read from, instead of the SDK's default. It accepts only https, so an http RPC is refused in the preflight and, in wasit run, before the service starts. stellar:pubnet still gets no RPC from Wasit. Tests: the preimage check, the gate and the anchor; the real x402 Stellar client against a stood-in RPC (other payee, amount, contract, a sub-invocation, two entries, a stretched ledger); the binding after signing; the wiring in preparePayment; the https rule in core, the CLI and the MCP server. Every mainnet-optin network must belong to a gated adapter. --- CHANGELOG.md | 19 + packages/cli/src/run.ts | 11 +- packages/cli/test/unit/run-payment.test.ts | 25 + packages/core/src/guard/budget.ts | 2 +- packages/core/src/guard/signed-terms.ts | 235 ++++++++ packages/core/src/x402/chains/stellar.ts | 130 ++++- packages/core/src/x402/chains/types.ts | 31 +- packages/core/src/x402/simulator.ts | 109 +++- packages/core/test/unit/network-guard.test.ts | 22 +- .../test/unit/signed-terms-wiring.test.ts | 183 ++++++ packages/core/test/unit/signed-terms.test.ts | 524 ++++++++++++++++++ .../core/test/unit/x402-stellar-rpc.test.ts | 95 ++++ .../test/unit/mainnet-and-rpc-lock.test.ts | 6 +- 13 files changed, 1362 insertions(+), 30 deletions(-) create mode 100644 packages/core/src/guard/signed-terms.ts create mode 100644 packages/core/test/unit/signed-terms-wiring.test.ts create mode 100644 packages/core/test/unit/signed-terms.test.ts create mode 100644 packages/core/test/unit/x402-stellar-rpc.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bd1108..50eb988 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,8 +17,27 @@ All notable changes to Wasit are recorded here. Versions follow [Semantic Versio no longer comes from the workflow's env into the steps that hold the token or the payer key. A service Wasit starts no longer inherits them from the workflow's env either; set what it needs in `service.start`. +- On Stellar, the payer's key signs only the authorization Wasit checked: + one `transfer` of the checked amount from the payer to the checked payee, + on the checked asset and the run's network, with no further call, one + signature per payment, valid no longer than the payment's lifetime allows + counted from the first ledger the run reads. The caps were checked on the + terms Wasit hands the x402 client; they now hold on what is signed too, so + an RPC whose simulation asks for anything else gets no signature. Such a + payment check is `ERROR (setup)` with nothing signed, and so is a payment in + a testnet token whose `transfer` needs further authorized calls. A payment + whose built transaction carries anything but that one signed authorization + is discarded unsent. +- A payment run on Stellar refuses an `http://` RPC (`rpcUrl` in the config, + `WASIT_RPC_URL`, `--rpc-url`, the MCP tools' `rpcUrl`) before anything is + sent, and `wasit run` refuses it before it starts the service: the x402 + Stellar client builds the payment through that RPC and accepts only https. **Fixed.** +- On Stellar testnet the x402 client builds and simulates the payment through + the run's RPC, the one whose network Wasit checks and reads the settlement + from. It used `https://soroban-testnet.stellar.org` whatever RPC the run was + given. - In the coloured output of `wasit test` (at a terminal, or with `FORCE_COLOR`), a wrapped line of a fix could start with `::name::` or `##[name]` from the middle of the text, which a GitHub job log reads as a diff --git a/packages/cli/src/run.ts b/packages/cli/src/run.ts index 9955259..f630493 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -76,7 +76,7 @@ import { MainnetOptInRefusedError, RpcIdentityError, UnsupportedPaymentNetworkError, - assertRpcServesNetwork, + assertX402PaymentRpc, } from "@wasit-dev/core"; import { formatRun } from "./run-format.js"; @@ -384,13 +384,12 @@ export async function executeRun(options: RunCommandOptions, context: RunContext : undefined; // D-023a+b: a run that will pay checks its RPC before the service starts or - // anything is sent to it: the settlements are read through it (and, on EVM - // and Solana, the payments are built through it), so it must serve the run's - // own network. On Stellar the x402 client builds the payment through its own - // default RPC for the network; that is changed before the mainnet opt-in. + // anything is sent to it: the payments are built and the settlements read + // through it, so it must be one the x402 client accepts (https on Stellar) + // and serve the run's own network. if (paying && notPaid === undefined && chain !== undefined && key !== undefined && hasX402) { try { - await assertRpcServesNetwork(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl)); + await assertX402PaymentRpc(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl)); } catch (error) { if (error instanceof RpcIdentityError) return fail(`wasit run: ${error.message} The service was not started.`); throw error; diff --git a/packages/cli/test/unit/run-payment.test.ts b/packages/cli/test/unit/run-payment.test.ts index e171748..2a218d5 100644 --- a/packages/cli/test/unit/run-payment.test.ts +++ b/packages/cli/test/unit/run-payment.test.ts @@ -20,7 +20,9 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { after, afterEach, before, beforeEach, describe, it } from "node:test"; +import { Keypair } from "@stellar/stellar-sdk"; import { setRpcIdentityTransportForTesting } from "@wasit-dev/core/dist/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "@wasit-dev/core/dist/x402/chains/index.js"; import { executeRun, type RunCommandOptions } from "../../src/run.js"; import { @@ -41,6 +43,7 @@ interface EnvironmentSpec { readonly operatedByMe?: boolean; readonly pinned?: { payTo: string; asset: string }; readonly maxRunUsd?: number; + readonly rpcUrl?: string; } async function writePaymentConfig( @@ -62,6 +65,7 @@ async function writePaymentConfig( operatedByMe: environment.operatedByMe ?? true, ...(environment.pinned === undefined ? {} : { pinned: environment.pinned }), ...(environment.maxRunUsd === undefined ? {} : { maxRunUsd: environment.maxRunUsd }), + ...(environment.rpcUrl === undefined ? {} : { rpcUrl: environment.rpcUrl }), }, }, endpoints, @@ -285,6 +289,27 @@ describe("wasit run, payment tier", () => { assert.equal(recorder.signed.length, 0); }); + it("refuses an http RPC on Stellar before the service starts or any request is sent", async () => { + // The real adapters: the Stellar x402 client builds the payment through the run's RPC. + setPaymentChainsForTesting(undefined); + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, { + network: "stellar:testnet", + rpcUrl: "http://127.0.0.1:9/soroban/rpc", + }); + let asked = 0; + setRpcIdentityTransportForTesting(async () => { + asked += 1; + return undefined; + }); + const run = await pay({ config }, { STELLAR_PRIVATE_KEY: Keypair.random().secret() }); + assert.equal(run.code, 2, run.stderr); + assert.match(run.stderr, /accepts only an https RPC/); + assert.match(run.stderr, /The service was not started\./); + assert.equal(asked, 0); + assert.equal(paywall.requests, 0); + }); + describe("in a CI that is not GitHub Actions (review R9 a, Najmi 2026-11-17)", () => { const otherCi = { CI: "true" }; diff --git a/packages/core/src/guard/budget.ts b/packages/core/src/guard/budget.ts index e8b6809..12adff8 100644 --- a/packages/core/src/guard/budget.ts +++ b/packages/core/src/guard/budget.ts @@ -79,7 +79,7 @@ export function formatUsd(amount: bigint): string { return `${sign}$${whole}.${fraction}`; } -export type GuardRefusal = "price" | "asset" | "amount" | "pin" | "plan" | "run-cap" | "accepted"; +export type GuardRefusal = "price" | "asset" | "amount" | "pin" | "plan" | "run-cap" | "accepted" | "signed-terms"; /** * A payment the guard will not sign, or, with `signed`, a signed payment it diff --git a/packages/core/src/guard/signed-terms.ts b/packages/core/src/guard/signed-terms.ts new file mode 100644 index 0000000..bc05187 --- /dev/null +++ b/packages/core/src/guard/signed-terms.ts @@ -0,0 +1,235 @@ +/** + * The signed-terms gate (spec B17.2): what the payer's key signs is checked, + * not only what the x402 client was asked to pay. + * + * L2 checks the terms Wasit hands the client: the pin, the plan, the $1 and + * the run's cap. On Stellar the client then builds the transfer by simulating + * it on the RPC and signs the authorization entries the simulation returns + * (`@x402/stellar` `ExactStellarScheme.createPaymentPayload`, through + * `AssembledTransaction.signAuthEntries`). The RPC chooses the contract, the + * function, the arguments, the sub-invocations, how many entries name the + * payer and the ledger the expiration is counted from. So the payer's signer + * is wrapped: each request to sign is decoded, and the key signs only when the + * preimage, which is exactly what the signature covers, authorizes + * `transfer(payer, payTo, amount)` on the asset that was checked, on the run's + * network, with no further call, once per payment, and expires no later than + * the payment's lifetime allows. Otherwise nothing is signed. + * + * What the cap then rests on: a signature authorizes that one transfer, once + * (its nonce), whoever submits it. The expiration bound keeps a signature from + * outliving the run; the cap does not depend on it. + */ + +import { performance } from "node:perf_hooks"; + +import { Address, hash, scValToNative, xdr } from "@stellar/stellar-sdk"; + +import { networkPassphrase } from "../mpp/network.js"; +import { PaymentGuardRefusedError, shown } from "./budget.js"; + +/** What one payment may be signed for: the terms L2 checked and charged. */ +export interface SigningTerms { + /** The run's CAIP-2 network. */ + readonly network: string; + /** The payer's address, derived from the key Wasit holds. */ + readonly payer: string; + /** The asset contract that was checked. */ + readonly asset: string; + /** The payee that was checked. */ + readonly payTo: string; + /** The amount charged to the run, in base units. */ + readonly amount: string; + /** The latest ledger (the chain's unit) the signature may stay valid to. */ + readonly maxExpiration: number; +} + +/** A signature the gate let through, with the preimage it covers (base64 XDR). */ +export interface SignedRecord { + readonly preimage: string; + readonly signature: Buffer; +} + +function refuse(message: string, options: { readonly signed?: boolean } = {}): PaymentGuardRefusedError { + return new PaymentGuardRefusedError("signed-terms", message, options); +} + +/** + * One payment's permission to sign. `preparePayment` arms it with the terms + * it checked, right before the client builds the payment; the payer's signer + * takes the terms once. A request to sign before it is armed, or a second one + * in the same payment, is refused. + */ +export class SigningGate { + #terms: SigningTerms | undefined; + #taken = false; + #signed: SignedRecord | undefined; + + public arm(terms: SigningTerms): void { + if (this.#terms !== undefined) throw new Error("A signing gate is armed once, for one payment."); + this.#terms = terms; + } + + /** The terms it was armed with, if any. */ + public get terms(): SigningTerms | undefined { + return this.#terms; + } + + /** Called by the signer before it signs: the terms, once. */ + public take(): SigningTerms { + if (this.#terms === undefined) { + throw refuse("The payer's key was asked to sign when Wasit expected no signature."); + } + if (this.#taken) { + throw refuse( + "The x402 client asked the payer's key for a second signature in one payment; Wasit signs one per payment.", + ); + } + this.#taken = true; + return this.#terms; + } + + /** Called by the signer after it signed. */ + public record(signed: SignedRecord): void { + if (this.#signed !== undefined) throw new Error("A signing gate records one signature."); + this.#signed = signed; + } + + /** The signature it let through, if any. */ + public get signed(): SignedRecord | undefined { + return this.#signed; + } +} + +/** + * The run's first reading of the chain's latest unit (a ledger on Stellar), + * and when it was read on a monotonic clock. A signature made later may stay + * valid only for the units that can have closed since, plus its lifetime: so + * an RPC that answers a later ledger after this reading cannot stretch it. + */ +export class SigningAnchor { + #reading: { readonly unit: number; readonly at: number } | undefined; + + public get reading(): { readonly unit: number; readonly at: number } | undefined { + return this.#reading; + } + + /** Keeps the first reading only. `at` is `performance.now()` milliseconds. */ + public set(unit: number, at: number = performance.now()): void { + if (this.#reading === undefined) this.#reading = { unit, at }; + } + + /** + * The latest unit a signature made `now` may expire at, for a lifetime of + * `lifetimeSeconds`, with units of `unitSeconds` (the shortest a unit takes: + * a faster chain only tightens the bound) and 2 units of slack. + */ + public maxExpiration(unitSeconds: number, lifetimeSeconds: number, now: number = performance.now()): number { + const reading = this.#reading; + if (reading === undefined) throw new Error("The anchor has no reading yet."); + if (typeof lifetimeSeconds !== "number" || !Number.isFinite(lifetimeSeconds) || lifetimeSeconds <= 0) { + throw refuse( + `The payment's lifetime (${shown(lifetimeSeconds)} s) is not a positive number of seconds, so how long its ` + + `signature would stay valid cannot be bounded.`, + ); + } + const elapsed = Math.max(0, now - reading.at); + return reading.unit + Math.ceil(elapsed / (unitSeconds * 1000)) + Math.ceil(lifetimeSeconds / unitSeconds) + 2; + } +} + +const ASKED = "The authorization the x402 client asked the payer to sign"; + +function addressOf(value: xdr.ScVal): string | undefined { + if (value.switch().name !== "scvAddress") return undefined; + try { + return Address.fromScVal(value).toString(); + } catch { + return undefined; + } +} + +/** + * Throws, so that nothing is signed, unless the Soroban authorization preimage + * `preimage` (base64 XDR, as the SDK hands it to the signer) authorizes exactly + * `transfer(payer, payTo, amount)` on `asset`, on the run's network, with no + * sub-invocation, expiring no later than `maxExpiration`. + * + * Only the address credential's preimage is signed: the address-bound form + * (`AddressV2`, delegates) is refused, as is anything that does not decode. + */ +export function checkStellarPreimage(preimage: string, terms: SigningTerms): void { + let decoded: xdr.HashIdPreimage; + try { + decoded = xdr.HashIdPreimage.fromXDR(preimage, "base64"); + } catch { + throw refuse(`${ASKED} does not decode as a Soroban authorization.`); + } + if (decoded.switch().name !== "envelopeTypeSorobanAuthorization") { + throw refuse(`${ASKED} is a form of authorization Wasit does not sign (it signs the address credential only).`); + } + const authorization = decoded.sorobanAuthorization(); + + const networkId = hash(Buffer.from(networkPassphrase(terms.network))); + if (!Buffer.from(authorization.networkId()).equals(networkId)) { + throw refuse(`${ASKED} is for another network than this run's (${terms.network}).`); + } + + const invocation = authorization.invocation(); + const fn = invocation.function(); + if (fn.switch().name !== "sorobanAuthorizedFunctionTypeContractFn") { + throw refuse(`${ASKED} is not a contract call.`); + } + const call = fn.contractFn(); + let contract: string; + try { + contract = Address.fromScAddress(call.contractAddress()).toString(); + } catch { + throw refuse(`${ASKED} calls a contract whose address does not decode.`); + } + if (contract !== terms.asset) { + throw refuse(`${ASKED} calls the contract ${shown(contract)}, not the asset ${terms.asset} that was checked.`); + } + const name = call.functionName().toString(); + if (name !== "transfer") { + throw refuse(`${ASKED} calls ${shown(name)} instead of transfer.`); + } + const args = call.args(); + if (args.length !== 3) { + throw refuse(`${ASKED} gives transfer ${args.length} arguments instead of 3 (from, to, amount).`); + } + + const from = addressOf(args[0]!); + if (from !== terms.payer) { + throw refuse(`${ASKED} transfers from ${from === undefined ? "something that is not an address" : shown(from)}, not from the payer.`); + } + const to = addressOf(args[1]!); + if (to !== terms.payTo) { + throw refuse( + `${ASKED} pays ${to === undefined ? "something that is not an address" : shown(to)}, not ${terms.payTo}, ` + + `the payee that was checked.`, + ); + } + if (!/^[1-9][0-9]*$/.test(terms.amount)) { + throw refuse(`The amount checked for this payment (${shown(terms.amount)}) is not a positive number of base units.`); + } + if (args[2]!.switch().name !== "scvI128") { + throw refuse(`${ASKED} gives the amount as ${args[2]!.switch().name}, not as the i128 of base units transfer takes.`); + } + const amount = scValToNative(args[2]!) as bigint; + if (amount !== BigInt(terms.amount)) { + throw refuse(`${ASKED} is for ${shown(String(amount))} base units, not the ${terms.amount} that was checked.`); + } + + const further = invocation.subInvocations().length; + if (further !== 0) { + throw refuse(`${ASKED} also authorizes ${further} further call${further === 1 ? "" : "s"} beside the transfer.`); + } + + const expiration = authorization.signatureExpirationLedger(); + if (expiration > terms.maxExpiration) { + throw refuse( + `${ASKED} stays valid until ledger ${expiration}, past ledger ${terms.maxExpiration}, the latest this ` + + `payment's lifetime allows.`, + ); + } +} diff --git a/packages/core/src/x402/chains/stellar.ts b/packages/core/src/x402/chains/stellar.ts index c356984..4f8bf10 100644 --- a/packages/core/src/x402/chains/stellar.ts +++ b/packages/core/src/x402/chains/stellar.ts @@ -21,9 +21,17 @@ import { } from "@stellar/stellar-sdk"; import { CheckSetupError } from "../../errors.js"; +import { PaymentGuardRefusedError } from "../../guard/budget.js"; +import { checkStellarPreimage, type SigningGate } from "../../guard/signed-terms.js"; import { networkPassphrase, resolveRpcUrl } from "../../mpp/network.js"; import { readTransferData, verifySettlement } from "../../settlement.js"; -import type { AuthorizationWatch, PaymentChain, RecordedTransfer, SignedAuthorization } from "./types.js"; +import type { + AuthorizationWatch, + PaymentChain, + RecordedTransfer, + SignedAuthorization, + SignedTermsBinding, +} from "./types.js"; /** A Stellar transaction hash: 64 hex characters. */ const TRANSACTION_HASH = /^[0-9a-f]{64}$/i; @@ -288,16 +296,130 @@ const stellarAuthorizations: AuthorizationWatch = { }, }; +/** + * The payer's signer, gated (spec B17.2): each authorization the x402 client + * asks it to sign is checked against the terms `gate` was armed with, and the + * key signs only when it authorizes exactly that transfer, once. There is no + * `signTransaction`: the scheme has the facilitator pay the fees, so the + * client never signs the envelope. + */ +function gatedSigner(payerKey: string, network: string, gate: SigningGate) { + const base = createEd25519Signer(payerKey, network as `${string}:${string}`); + const signAuthEntry: typeof base.signAuthEntry = async (preimage, opts) => { + const terms = gate.take(); + if (opts?.address !== undefined && opts.address !== base.address) { + throw new PaymentGuardRefusedError("signed-terms", "The x402 client asked for a signature for another address than the payer's."); + } + if (terms.payer !== base.address) { + throw new PaymentGuardRefusedError("signed-terms", "The payment's terms name another payer than the key Wasit holds."); + } + checkStellarPreimage(preimage, terms); + const result = await base.signAuthEntry(preimage, opts); + gate.record({ preimage, signature: Buffer.from(result.signedAuthEntry, "base64") }); + return result; + }; + return { address: base.address, signAuthEntry }; +} + +/** The `signature` bytes of an address credential signed by one ed25519 key, if it is that shape. */ +function credentialSignature(signature: xdr.ScVal): { readonly publicKey: Buffer; readonly signature: Buffer } | undefined { + if (signature.switch().name !== "scvVec") return undefined; + const items = signature.vec() ?? []; + if (items.length !== 1 || items[0]!.switch().name !== "scvMap") return undefined; + let publicKey: Buffer | undefined; + let bytes: Buffer | undefined; + for (const field of items[0]!.map() ?? []) { + if (field.key().switch().name !== "scvSymbol" || field.val().switch().name !== "scvBytes") return undefined; + const key = field.key().sym().toString(); + if (key === "public_key") publicKey = Buffer.from(field.val().bytes()); + else if (key === "signature") bytes = Buffer.from(field.val().bytes()); + else return undefined; + } + return publicKey === undefined || bytes === undefined ? undefined : { publicKey, signature: bytes }; +} + +function notSent(message: string): PaymentGuardRefusedError { + return new PaymentGuardRefusedError("signed-terms", message, { signed: true }); +} + +const stellarSignedTerms: SignedTermsBinding = { + // The x402 Stellar client's fallback ledger close time (DEFAULT_ESTIMATED_LEDGER_SECONDS in + // @x402/stellar 2.28.0), and the shortest it assumes: a faster close only tightens the bound. + unitSeconds: 5, + async latestUnit(_network, rpcUrl) { + return (await rpcServer(rpcUrl).getLatestLedger()).sequence; + }, + bind(payload, gate) { + const signed = gate.signed; + if (signed === undefined) { + throw new PaymentGuardRefusedError("signed-terms", "The x402 client built a payment without the signature Wasit checked."); + } + const checked = xdr.HashIdPreimage.fromXDR(signed.preimage, "base64").sorobanAuthorization(); + const transaction = payload["transaction"]; + let envelope: xdr.TransactionEnvelope; + try { + if (typeof transaction !== "string") throw new Error("no transaction"); + envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64"); + } catch { + throw notSent("The payment the x402 client built carries no transaction that decodes."); + } + const payer = gate.terms?.payer; + const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : []; + const ours: xdr.SorobanAuthorizationEntry[] = []; + for (const operation of operations) { + if (operation.body().switch().name !== "invokeHostFunction") continue; + for (const entry of operation.body().invokeHostFunctionOp().auth()) { + const kind = entry.credentials().switch().name; + if (kind === "sorobanCredentialsSourceAccount") continue; + if (kind !== "sorobanCredentialsAddress") { + throw notSent("The payment the x402 client built carries an authorization in a form Wasit did not sign."); + } + if (Address.fromScAddress(entry.credentials().address().address()).toString() === payer) ours.push(entry); + } + } + if (ours.length !== 1) { + throw notSent(`The payment the x402 client built carries ${ours.length} authorizations for the payer; Wasit signed one.`); + } + const entry = ours[0]!; + const credentials = entry.credentials().address(); + if (entry.rootInvocation().toXDR("base64") !== checked.invocation().toXDR("base64")) { + throw notSent("The payment the x402 client built names another invocation than the one Wasit checked and signed."); + } + if (credentials.signatureExpirationLedger() !== checked.signatureExpirationLedger()) { + throw notSent("The payment the x402 client built carries another expiration ledger than the one signed."); + } + if (credentials.nonce().toString() !== checked.nonce().toString()) { + throw notSent("The payment the x402 client built carries another nonce than the one signed."); + } + const sent = credentialSignature(credentials.signature()); + if ( + sent === undefined || + payer === undefined || + !sent.publicKey.equals(Keypair.fromPublicKey(payer).rawPublicKey()) || + !sent.signature.equals(signed.signature) + ) { + throw notSent("The payment the x402 client built carries another signature than the one Wasit made."); + } + }, +}; + export const stellarChain: PaymentChain = { name: "Stellar", networks: ["stellar:testnet", "stellar:pubnet"], payerKeyEnv: "STELLAR_PRIVATE_KEY", referenceKind: "a settled Stellar transaction hash", resolveRpcUrl: (network, override) => resolveRpcUrl(network, override), - registerPayer(client, network, payerKey, _rpcUrl) { - const signer = createEd25519Signer(payerKey, network as `${string}:${string}`); - client.register("stellar:*", new ExactStellarClientScheme(signer)); + // The x402 Stellar client builds its RPC client without `allowHttp`. + httpsRpcOnly: true, + registerPayer(client, network, payerKey, rpcUrl, gate) { + // The payment is built and simulated through the run's RPC: the one whose + // network was checked (D-023), the anchor is read from, and the settlement + // is read from. Not on stellar:pubnet: the SDK refuses it without an RPC of + // its own, and no endpoint is handed to it before the mainnet opt-in. + const rpcConfig = network === "stellar:testnet" ? { url: rpcUrl } : undefined; + client.register("stellar:*", new ExactStellarClientScheme(gatedSigner(payerKey, network, gate), rpcConfig)); }, + signedTerms: stellarSignedTerms, // A one-second lifetime is one ledger (ceil(1 / 5)); ledgers close about // every 5 to 6 seconds, so 20 seconds is three or more ledgers past it. expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 20_000 }), diff --git a/packages/core/src/x402/chains/types.ts b/packages/core/src/x402/chains/types.ts index 4bb9fc2..6fd4cae 100644 --- a/packages/core/src/x402/chains/types.ts +++ b/packages/core/src/x402/chains/types.ts @@ -11,6 +11,7 @@ import type { PaymentRequirements } from "@x402/core/types"; import type { x402Client } from "@x402/fetch"; +import type { SigningGate } from "../../guard/signed-terms.js"; import type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js"; /** @@ -98,6 +99,25 @@ export interface AuthorizationWatch { ): Promise<{ readonly latest: number; readonly transfers: readonly RecordedTransfer[] }>; } +/** + * The signed-terms gate of an adapter whose client signs what an RPC returns + * (spec B17.2, `guard/signed-terms.ts`). An adapter with one signs only + * through the `SigningGate` that `preparePayment` arms; every network that can + * be opted into belongs to such an adapter (a test pins it). + */ +export interface SignedTermsBinding { + /** The shortest a unit (a ledger) takes, in seconds: the bound counts with it. */ + readonly unitSeconds: number; + /** The chain's latest unit on `rpcUrl`: read once per run, as the anchor of every expiration bound. */ + latestUnit(network: string, rpcUrl: string): Promise; + /** + * Throws `PaymentGuardRefusedError` unless the payment payload's inner + * `payload` carries exactly the one authorization `gate` let the key sign, + * with that signature: the payload is then discarded unsent. + */ + bind(payload: Record, gate: SigningGate): void; +} + export interface PaymentChain { /** The chain family's name, for reports. */ readonly name: string; @@ -116,14 +136,23 @@ export interface PaymentChain { * Registers this chain's `exact` client scheme, signing with `payerKey`. * `rpcUrl` is for client schemes that read the chain while building a * payment (EVM Permit2 checks the token allowance, Solana fetches the mint - * and a blockhash); others ignore it. + * and a blockhash); others ignore it. An adapter with `signedTerms` signs + * only through `gate`; the others ignore it. */ registerPayer( client: x402Client, network: string, payerKey: string, rpcUrl: string, + gate: SigningGate, ): void | Promise; + /** + * The client builds the payment through the run's RPC and accepts only an + * https one: an http RPC is refused before anything is asked or sent. + */ + readonly httpsRpcOnly?: boolean; + /** Present when the payer's signer is gated (see {@link SignedTermsBinding}); `gate` is then the one to sign through. */ + readonly signedTerms?: SignedTermsBinding; /** * How X402-10 makes a payment that has expired when it arrives, for the * option `selected`. Where the client derives the lifetime from diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index f54e35e..3893e11 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -16,7 +16,8 @@ import { type PinTerms, } from "../guard/budget.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; -import { assertRpcServesNetwork } from "../guard/rpc-identity.js"; +import { SigningAnchor, SigningGate, type SigningTerms } from "../guard/signed-terms.js"; +import { RpcIdentityError, assertRpcServesNetwork } from "../guard/rpc-identity.js"; import type { EndpointPlan } from "./plan.js"; import { REJECTED_REQUEST_ID, @@ -497,13 +498,14 @@ async function buildX402Client( payerSecretKey: string, rpcUrl: string, pin: PinTerms | undefined, + gate: SigningGate, ) { const client = new x402Client(); // L3 (spec B3): the SDK's own spend controls, set here rather than left to // its default, as a second implementation of the $1 cap. An adapter that // allows more assets replaces them and states the cap again (`evm.ts`). client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` }); - await chain.registerPayer(client, network, payerSecretKey, rpcUrl); + await chain.registerPayer(client, network, payerSecretKey, rpcUrl, gate); client // A challenge may offer several networks, including both Stellar ones. // The client's default pick is the first it supports, which would sign @@ -684,6 +686,81 @@ function plannedAmount(plan: EndpointPlan | undefined, check: string, selected: return entry.amount; } +/** + * Refuses an RPC an x402 payment on `network` cannot be built through, then + * checks that it serves `network` (D-023). On Stellar the client accepts only + * an https RPC. Throws `RpcIdentityError` (a configuration error) before the + * target is sent anything; the RPC's address is never echoed (it may carry a + * key). The CLI calls it before it starts a service. + */ +export async function assertX402PaymentRpc(network: string, rpcUrl: string): Promise { + const chain = paymentChainFor(network); + if (chain?.httpsRpcOnly === true) { + let protocol = ""; + try { + protocol = new URL(rpcUrl).protocol; + } catch { + protocol = ""; + } + if (protocol !== "https:") { + throw new RpcIdentityError( + `The x402 ${chain.name} client builds the payment through the run's RPC and accepts only an https RPC, ` + + `and this run's RPC is not https. No payment was sent and nothing was signed.`, + ); + } + } + await assertRpcServesNetwork(network, rpcUrl); +} + +/** The run's anchor for expiration bounds, one per run budget (a run shares one budget across endpoints). */ +const anchors = new WeakMap(); + +function anchorOf(budget: RunBudget): SigningAnchor { + let anchor = anchors.get(budget); + if (anchor === undefined) { + anchor = new SigningAnchor(); + anchors.set(budget, anchor); + } + return anchor; +} + +/** + * The terms the gate is armed with: those L2 checked and charged, and the + * latest ledger the signature may expire at. The run's first signature reads + * the chain's latest ledger as the anchor; nothing is signed when it cannot. + */ +async function signingTerms( + binding: NonNullable, + network: string, + rpcUrl: string, + anchor: SigningAnchor, + payer: string, + signing: PaymentRequirements, +): Promise { + if (anchor.reading === undefined) { + let latest: number; + try { + latest = await binding.latestUnit(network, rpcUrl); + } catch (error) { + throw new CheckSetupError( + `The chain's latest ledger could not be read before signing (${(error as Error).message}). Nothing was signed.`, + ); + } + if (!Number.isSafeInteger(latest) || latest <= 0) { + throw new CheckSetupError("The chain's latest ledger could not be read before signing. Nothing was signed."); + } + anchor.set(latest); + } + return { + network, + payer, + asset: signing.asset, + payTo: signing.payTo, + amount: signing.amount, + maxExpiration: anchor.maxExpiration(binding.unitSeconds, signing.maxTimeoutSeconds), + }; +} + /** * Reads the challenge and produces a signed payment payload for it. * @@ -698,7 +775,10 @@ function plannedAmount(plan: EndpointPlan | undefined, check: string, selected: * L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over * every `exact` option, the plan, the $1 cap and the run's cap, the run charged * before the signature. The SDK is then handed exactly the one option checked, - * and a payload whose `accepted` is not that option is discarded unsent. + * and a payload whose `accepted` is not that option is discarded unsent. On a + * chain with a signed-terms gate (Stellar), the key signs only an + * authorization for those same terms, and a payload that carries anything + * else is discarded unsent. */ async function preparePayment( options: X402PaymentCheckOptions, @@ -712,12 +792,15 @@ async function preparePayment( assertPaymentNetworkAllowed("x402", options.network); const chain = chainFor(options.network); const budget = options.budget ?? new RunBudget(); + const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl); + const gate = new SigningGate(); const { client, httpClient } = await buildX402Client( chain, options.network, options.payerSecretKey, - chain.resolveRpcUrl(options.network, options.rpcUrl), + rpcUrl, options.pin, + gate, ); const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options); @@ -741,6 +824,13 @@ async function preparePayment( }); await beforeSigning?.(selected); + // The signed-terms gate (spec B17.2): the key signs only what was checked and + // charged above, once, within this payment's lifetime. + if (chain.signedTerms !== undefined) { + gate.arm( + await signingTerms(chain.signedTerms, options.network, rpcUrl, anchorOf(budget), chain.payerAddress(options.payerSecretKey), signing), + ); + } const signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }), ); @@ -754,6 +844,8 @@ async function preparePayment( { signed: true }, ); } + // And what it carries must be the one authorization the gate let the key sign. + chain.signedTerms?.bind(signed.payload, gate); const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected }; return { httpClient, paymentPayload, selected, idempotent, payUrl }; } @@ -1573,11 +1665,10 @@ export async function runX402PaymentChecks( `or --payer-key).`, ); } - // The RPC signs and settles nothing itself, but the settlement is read - // through it (and, on EVM and Solana, the payment is built through it): it - // must serve the run's network (D-023). On Stellar the x402 client builds - // the payment through its own default RPC. - await assertRpcServesNetwork(options.network, rpcUrl); + // The RPC signs and settles nothing itself, but the payment is built and + // the settlement read through it: it must be one the client accepts and + // serve the run's network (D-023). + await assertX402PaymentRpc(options.network, rpcUrl); } 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 diff --git a/packages/core/test/unit/network-guard.test.ts b/packages/core/test/unit/network-guard.test.ts index 74d688d..167ce55 100644 --- a/packages/core/test/unit/network-guard.test.ts +++ b/packages/core/test/unit/network-guard.test.ts @@ -22,6 +22,7 @@ import { describe, it } from "node:test"; import { Keypair } from "@stellar/stellar-sdk"; import { charge as chargeClient } from "@stellar/mpp/charge/client"; +import { SigningGate } from "../../src/guard/signed-terms.js"; import { classifyCheckError } from "../../src/errors.js"; import { NETWORK_CLASSES, @@ -316,13 +317,18 @@ 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); - } + it("builds the SDK scheme for pubnet without an RPC endpoint, whatever the run passes", () => { + const registered: unknown[] = []; + const client = { register: (_network: string, scheme: unknown) => registered.push(scheme) }; + stellarChain.registerPayer(client as never, "stellar:pubnet", Keypair.random().secret(), "https://rpc.example.invalid", new SigningGate()); + assert.equal(registered.length, 1); + assert.equal((registered[0] as { rpcConfig?: unknown }).rpcConfig, undefined); + }); + + it("builds the SDK scheme for testnet through the run's RPC, the one whose network was checked", () => { + const registered: unknown[] = []; + const client = { register: (_network: string, scheme: unknown) => registered.push(scheme) }; + stellarChain.registerPayer(client as never, "stellar:testnet", Keypair.random().secret(), "https://rpc.example.invalid", new SigningGate()); + assert.deepEqual((registered[0] as { rpcConfig?: unknown }).rpcConfig, { url: "https://rpc.example.invalid" }); }); }); diff --git a/packages/core/test/unit/signed-terms-wiring.test.ts b/packages/core/test/unit/signed-terms-wiring.test.ts new file mode 100644 index 0000000..b493aea --- /dev/null +++ b/packages/core/test/unit/signed-terms-wiring.test.ts @@ -0,0 +1,183 @@ +/** + * How `preparePayment` uses the signed-terms gate (spec B17.2), written before + * the code (B11): it arms the gate with the terms L2 checked and charged, right + * before the client builds the payment; it reads the chain's latest unit once + * per run as the anchor; and it discards, unsent, a payload the adapter cannot + * bind to what was signed. + * + * Offline: the recording chain of `../support/recording-chain.ts`, with a + * gate whose scheme asks it for one signature per payment, as the Stellar + * signer does. + */ + +import assert from "node:assert/strict"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { PaymentGuardRefusedError, RunBudget } from "../../src/guard/budget.js"; +import type { SigningTerms } from "../../src/guard/signed-terms.js"; +import { setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "../../src/x402/chains/index.js"; +import type { PaymentChain } from "../../src/x402/chains/types.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; +import type { CheckResult } from "../../src/check.js"; +import { + NETWORK, + PAYER, + PAY_TO, + USDC, + option, + paywall, + recordingChain, + type Paywall, + type Recorder, +} from "../support/recording-chain.js"; + +interface Seen { + readonly terms: SigningTerms[]; + latestReads: number; + binds: number; +} + +function gatedChain(recorder: Recorder, seen: Seen, bind: () => void = () => undefined): PaymentChain { + const base = recordingChain(recorder); + return { + ...base, + registerPayer(client, _network, _payerKey, _rpcUrl, gate) { + client.register(NETWORK, { + scheme: "exact", + findDefaultAsset: (asset, network) => + network === NETWORK && asset.toLowerCase() === USDC.toLowerCase() + ? { asset: USDC, decimals: 6, symbol: "USDC" } + : undefined, + async createPaymentPayload(version, requirements) { + // As the Stellar signer does: the key signs only through the gate. + seen.terms.push(gate.take()); + recorder.signed.push(requirements); + return { x402Version: version, payload: { signature: `sig-${recorder.signed.length}` } }; + }, + }); + }, + signedTerms: { + unitSeconds: 5, + async latestUnit() { + seen.latestReads += 1; + return 1000; + }, + bind() { + seen.binds += 1; + bind(); + }, + }, + }; +} + +let recorder: Recorder; +let seen: Seen; +const walls: Paywall[] = []; + +function install(bind?: () => void): void { + setPaymentChainsForTesting([gatedChain(recorder, seen, bind)]); + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x14a34" : undefined)); +} + +beforeEach(() => { + recorder = { signed: [] }; + seen = { terms: [], latestReads: 0, binds: 0 }; +}); + +afterEach(async () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + await Promise.all(walls.splice(0).map((wall) => wall.close())); +}); + +async function wall(amount: string): Promise { + const created = await paywall([option({ amount })]); + walls.push(created); + return created; +} + +function byId(results: readonly CheckResult[], id: string): CheckResult { + const found = results.find((result) => result.id === id); + assert.ok(found, `no ${id} in ${results.map((result) => result.id).join(", ")}`); + return found; +} + +const run = (target: string, budget = new RunBudget()) => + runX402PaymentChecks({ target, network: NETWORK, payerSecretKey: "test-payer-key", budget }); + +describe("preparePayment and the signed-terms gate", () => { + it("arms the gate with the terms checked and charged, for each signature of the run", async () => { + install(); + const target = await wall("10000"); + const results = await run(target.url); + assert.equal(byId(results, "X402-06").pass, true, byId(results, "X402-06").detail); + + assert.deepEqual( + seen.terms.map((entry) => entry.amount), + recorder.signed.map((requirement) => requirement.amount), + ); + assert.deepEqual( + seen.terms.map((entry) => entry.amount), + ["10000", "10000", "5000", "10000"], + "X402-06, X402-07, X402-09 (half), X402-10", + ); + for (const entry of seen.terms) { + assert.equal(entry.network, NETWORK); + assert.equal(entry.payer, PAYER); + assert.equal(entry.payTo, PAY_TO); + assert.equal(entry.asset, USDC); + } + // 60 s lifetime: 12 ledgers of 5 s and 2 of slack over the anchor, plus the time since it. + const [first, , , expired] = seen.terms; + assert.ok(first!.maxExpiration >= 1014 && first!.maxExpiration <= 1016, String(first!.maxExpiration)); + // X402-10 signs with a one-second lifetime. + assert.ok(expired!.maxExpiration >= 1003 && expired!.maxExpiration <= 1005, String(expired!.maxExpiration)); + assert.equal(seen.binds, 4, "every payload is bound before it is used"); + }); + + it("reads the anchor once per run, not once per signature", async () => { + install(); + const budget = new RunBudget(); + await run((await wall("10000")).url, budget); + await run((await wall("10000")).url, budget); + assert.equal(seen.latestReads, 1); + }); + + it("discards, unsent, a payload the adapter cannot bind to what was signed", async () => { + install(() => { + throw new PaymentGuardRefusedError("signed-terms", "The payment names another invocation than the one signed.", { + signed: true, + }); + }); + const target = await wall("10000"); + const results = await run(target.url); + const first = byId(results, "X402-06"); + assert.equal(first.error?.kind, "setup", first.detail); + assert.match(first.detail, /it was not sent/); + assert.equal(target.paid, 0, "no payload reached the service"); + }); + + it("signs nothing when the anchor cannot be read", async () => { + const chain = gatedChain(recorder, seen); + setPaymentChainsForTesting([ + { + ...chain, + signedTerms: { + ...chain.signedTerms!, + async latestUnit() { + throw new Error("rpc down"); + }, + }, + }, + ]); + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x14a34" : undefined)); + const target = await wall("10000"); + const results = await run(target.url); + const first = byId(results, "X402-06"); + assert.equal(first.error?.kind, "setup", first.detail); + assert.match(first.detail, /Nothing was signed\./); + assert.equal(recorder.signed.length, 0); + assert.equal(target.paid, 0); + }); +}); diff --git a/packages/core/test/unit/signed-terms.test.ts b/packages/core/test/unit/signed-terms.test.ts new file mode 100644 index 0000000..27c0e61 --- /dev/null +++ b/packages/core/test/unit/signed-terms.test.ts @@ -0,0 +1,524 @@ +/** + * The signed-terms gate (spec B17.2), written before the code it tests (B11). + * + * The caps, the pin and the plan are checked on the terms Wasit hands the x402 + * client. On Stellar the client then signs the authorization entries the RPC's + * simulation returns, so the gate checks the preimage each signature covers: + * one signature per payment, for `transfer(payer, payTo, amount)` on the + * checked asset, on the run's network, with no sub-invocation and an + * expiration within the payment's lifetime. Anything else is refused before + * the key signs. + * + * Offline. The SDK tests drive the real `@x402/stellar` client scheme with the + * RPC's methods replaced on `rpc.Server.prototype` (one copy of the SDK is + * installed) and Horizon refused, so nothing leaves the process. The payer is + * a fresh random key that holds nothing. + */ + +import assert from "node:assert/strict"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { x402Client } from "@x402/core/client"; +import type { PaymentRequirements } from "@x402/core/types"; +import { + Address, + Horizon, + Keypair, + Networks, + SorobanDataBuilder, + hash, + nativeToScVal, + rpc, + xdr, +} from "@stellar/stellar-sdk"; + +import { PaymentGuardRefusedError } from "../../src/guard/budget.js"; +import { NETWORK_CLASSES } from "../../src/guard/networks.js"; +import { SigningAnchor, SigningGate, checkStellarPreimage, type SigningTerms } from "../../src/guard/signed-terms.js"; +import { paymentChainFor } from "../../src/x402/chains/index.js"; +import { stellarChain } from "../../src/x402/chains/stellar.js"; + +const NETWORK = "stellar:testnet"; +const USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const OTHER_CONTRACT = "CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC"; +const RPC_URL = "https://rpc.invalid/soroban"; + +const payerKey = Keypair.random(); +const PAYER = payerKey.publicKey(); +const PAY_TO = Keypair.random().publicKey(); +const ATTACKER = Keypair.random().publicKey(); + +function terms(overrides: Partial = {}): SigningTerms { + return { network: NETWORK, payer: PAYER, asset: USDC, payTo: PAY_TO, amount: "10000", maxExpiration: 1014, ...overrides }; +} + +interface InvocationSpec { + readonly contract?: string; + readonly fn?: string; + readonly args?: xdr.ScVal[]; + readonly from?: string; + readonly to?: string; + readonly amount?: bigint; + readonly subInvocations?: xdr.SorobanAuthorizedInvocation[]; +} + +function transferArgs(spec: InvocationSpec): xdr.ScVal[] { + return [ + nativeToScVal(spec.from ?? PAYER, { type: "address" }), + nativeToScVal(spec.to ?? PAY_TO, { type: "address" }), + nativeToScVal(spec.amount ?? 10_000n, { type: "i128" }), + ]; +} + +function invocation(spec: InvocationSpec = {}): xdr.SorobanAuthorizedInvocation { + return new xdr.SorobanAuthorizedInvocation({ + function: xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn( + new xdr.InvokeContractArgs({ + contractAddress: new Address(spec.contract ?? USDC).toScAddress(), + functionName: spec.fn ?? "transfer", + args: spec.args ?? transferArgs(spec), + }), + ), + subInvocations: spec.subInvocations ?? [], + }); +} + +function preimage( + spec: InvocationSpec & { readonly expiration?: number; readonly passphrase?: string; readonly withAddress?: boolean } = {}, +): string { + const networkId = hash(Buffer.from(spec.passphrase ?? Networks.TESTNET)); + const fields = { + networkId, + nonce: xdr.Int64.fromString("7"), + invocation: invocation(spec), + signatureExpirationLedger: spec.expiration ?? 1012, + }; + const value = + spec.withAddress === true + ? xdr.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress( + new xdr.HashIdPreimageSorobanAuthorizationWithAddress({ ...fields, address: new Address(PAYER).toScAddress() }), + ) + : xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(new xdr.HashIdPreimageSorobanAuthorization(fields)); + return value.toXDR("base64"); +} + +function refusedSignedTerms(pattern: RegExp): (error: unknown) => boolean { + return (error) => { + assert.ok(error instanceof PaymentGuardRefusedError, `not a guard refusal: ${String(error)}`); + assert.equal(error.reason, "signed-terms"); + assert.match(error.message, pattern); + return true; + }; +} + +describe("signed terms: the preimage check", () => { + it("passes the transfer that was checked, at the latest expiration allowed", () => { + checkStellarPreimage(preimage({ expiration: 1014 }), terms()); + }); + + const refused: ReadonlyArray<[string, string, RegExp]> = [ + ["another network", preimage({ passphrase: Networks.PUBLIC }), /network/], + ["another contract", preimage({ contract: OTHER_CONTRACT }), /contract/], + ["another function", preimage({ fn: "approve" }), /transfer/], + ["two arguments", preimage({ args: transferArgs({}).slice(0, 2) }), /argument/], + ["four arguments", preimage({ args: [...transferArgs({}), nativeToScVal(1n, { type: "i128" })] }), /argument/], + ["from another address", preimage({ from: ATTACKER }), /from/], + ["to another address", preimage({ to: ATTACKER }), /pays/], + ["one base unit more", preimage({ amount: 10_001n }), /base units/], + ["one base unit less", preimage({ amount: 9_999n }), /base units/], + ["a zero amount", preimage({ amount: 0n }), /base units/], + ["a negative amount", preimage({ amount: -10_000n }), /base units/], + ["the high half of the amount set", preimage({ amount: (1n << 64n) + 10_000n }), /base units/], + [ + "the amount as a u128", + preimage({ args: [...transferArgs({}).slice(0, 2), nativeToScVal(10_000n, { type: "u128" })] }), + /base units/, + ], + ["a sub-invocation", preimage({ subInvocations: [invocation({ contract: OTHER_CONTRACT })] }), /further call/], + ["one ledger past the bound", preimage({ expiration: 1015 }), /ledger 1015/], + ["the address-bound form", preimage({ withAddress: true }), /form/], + ]; + for (const [name, value, pattern] of refused) { + it(`refuses ${name}`, () => { + assert.throws(() => checkStellarPreimage(value, terms()), refusedSignedTerms(pattern)); + }); + } + + it("refuses an authorization that is not a contract call (a contract creation)", () => { + const create = new xdr.SorobanAuthorizedInvocation({ + function: xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeCreateContractHostFn( + new xdr.CreateContractArgs({ + contractIdPreimage: xdr.ContractIdPreimage.contractIdPreimageFromAddress( + new xdr.ContractIdPreimageFromAddress({ address: new Address(PAYER).toScAddress(), salt: Buffer.alloc(32) }), + ), + executable: xdr.ContractExecutable.contractExecutableStellarAsset(), + }), + ), + subInvocations: [], + }); + const value = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization( + new xdr.HashIdPreimageSorobanAuthorization({ + networkId: hash(Buffer.from(Networks.TESTNET)), + nonce: xdr.Int64.fromString("7"), + invocation: create, + signatureExpirationLedger: 1012, + }), + ).toXDR("base64"); + assert.throws(() => checkStellarPreimage(value, terms()), refusedSignedTerms(/not a contract call/)); + }); + + it("refuses what does not decode", () => { + assert.throws(() => checkStellarPreimage("not xdr", terms()), refusedSignedTerms(/decode/)); + }); +}); + +describe("signed terms: the gate", () => { + it("refuses a signature it was not armed for", () => { + assert.throws(() => new SigningGate().take(), refusedSignedTerms(/expected no signature/)); + }); + + it("gives its terms once: a second signature in the same payment is refused", () => { + const gate = new SigningGate(); + gate.arm(terms()); + assert.equal(gate.take().amount, "10000"); + assert.throws(() => gate.take(), refusedSignedTerms(/second signature/)); + }); + + it("is armed once", () => { + const gate = new SigningGate(); + gate.arm(terms()); + assert.throws(() => gate.arm(terms())); + }); +}); + +describe("signed terms: the anchor", () => { + it("bounds the expiration by the first reading, the time since, and the lifetime", () => { + assert.equal(new SigningAnchor().reading, undefined); + const anchor = new SigningAnchor(); + anchor.set(1000, 0); + anchor.set(5000, 0); + assert.equal(anchor.reading?.unit, 1000, "only the first reading counts"); + assert.equal(anchor.maxExpiration(5, 60, 0), 1000 + 12 + 2); + assert.equal(anchor.maxExpiration(5, 1, 0), 1000 + 1 + 2); + assert.equal(anchor.maxExpiration(5, 60, 1), 1000 + 1 + 12 + 2, "a started unit counts"); + assert.equal(anchor.maxExpiration(5, 60, 30_000), 1000 + 6 + 12 + 2); + }); + + it("refuses a lifetime that is not a positive number of seconds, and rounds a fraction up", () => { + const anchor = new SigningAnchor(); + anchor.set(1000, 0); + for (const lifetime of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) { + assert.throws(() => anchor.maxExpiration(5, lifetime, 0), refusedSignedTerms(/lifetime/)); + } + assert.equal(anchor.maxExpiration(5, 1.5, 0), 1000 + 1 + 2); + }); +}); + +/** The RPC and Horizon, replaced for the SDK tests. */ +interface StandIn { + /** What the next `getLatestLedger` answers. */ + latest: number; + /** The payer's auth entries the first simulation returns. */ + entries: xdr.SorobanAuthorizationEntry[]; + /** Every RPC call, with the URL it went to. */ + readonly calls: Array<[string, string]>; + /** Signatures the payer's key made. */ + signatures: number; +} + +function entry(spec: InvocationSpec & { readonly nonce?: string } = {}): xdr.SorobanAuthorizationEntry { + return new xdr.SorobanAuthorizationEntry({ + credentials: xdr.SorobanCredentials.sorobanCredentialsAddress( + new xdr.SorobanAddressCredentials({ + address: new Address(PAYER).toScAddress(), + nonce: xdr.Int64.fromString(spec.nonce ?? "7"), + signatureExpirationLedger: 0, + signature: xdr.ScVal.scvVoid(), + }), + ), + rootInvocation: invocation(spec), + }); +} + +function rawSimulation(entries: readonly xdr.SorobanAuthorizationEntry[], latest: number): Record { + return { + latestLedger: latest, + minResourceFee: "100", + transactionData: new SorobanDataBuilder().build().toXDR("base64"), + results: [{ auth: entries.map((value) => value.toXDR("base64")), xdr: xdr.ScVal.scvVoid().toXDR("base64") }], + events: [], + }; +} + +type Patchable = Record; + +function installStandIn(): { readonly state: StandIn; readonly undo: () => void } { + const state: StandIn = { latest: 1000, entries: [entry()], calls: [], signatures: 0 }; + const server = rpc.Server.prototype as unknown as Patchable; + const horizon = Horizon.Server.prototype as unknown as Patchable; + const keypair = Keypair.prototype as unknown as Patchable; + const saved = { + getLatestLedger: server["getLatestLedger"], + simulate: server["_simulateTransaction"], + ledgers: horizon["ledgers"], + sign: keypair["sign"], + }; + let simulations = 0; + server["getLatestLedger"] = async function (this: rpc.Server) { + state.calls.push(["getLatestLedger", this.serverURL.toString()]); + return { id: "0", sequence: state.latest, protocolVersion: 23 }; + }; + server["_simulateTransaction"] = async function (this: rpc.Server) { + state.calls.push(["simulateTransaction", this.serverURL.toString()]); + simulations += 1; + return rawSimulation(simulations === 1 ? state.entries : [], state.latest); + }; + horizon["ledgers"] = () => { + throw new Error("offline: no Horizon in tests"); + }; + const sign = saved.sign as (this: Keypair, data: Buffer) => Buffer; + keypair["sign"] = function (this: Keypair, data: Buffer) { + if (this.publicKey() === PAYER) state.signatures += 1; + return sign.call(this, data); + }; + return { + state, + undo: () => { + server["getLatestLedger"] = saved.getLatestLedger; + server["_simulateTransaction"] = saved.simulate; + horizon["ledgers"] = saved.ledgers; + keypair["sign"] = saved.sign; + }, + }; +} + +function requirements(overrides: Partial = {}): PaymentRequirements { + return { + scheme: "exact", + network: NETWORK, + amount: "10000", + asset: USDC, + payTo: PAY_TO, + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + ...overrides, + }; +} + +async function signThroughSdk(gate: SigningGate, accepted = requirements()) { + const client = new x402Client(); + await stellarChain.registerPayer(client, NETWORK, payerKey.secret(), RPC_URL, gate); + return client.createPaymentPayload({ x402Version: 2, resource: { url: "http://127.0.0.1/paid" }, accepts: [accepted] }); +} + +function simulations(state: StandIn): number { + return state.calls.filter(([method]) => method === "simulateTransaction").length; +} + +describe("signed terms: through the x402 Stellar client", () => { + let standIn: ReturnType; + beforeEach(() => { + standIn = installStandIn(); + }); + afterEach(() => standIn.undo()); + + it("signs the honest transfer once, and the payload carries exactly that signature", async () => { + const gate = new SigningGate(); + gate.arm(terms()); + const payload = await signThroughSdk(gate); + assert.equal(standIn.state.signatures, 1); + assert.equal(simulations(standIn.state), 2); + assert.ok(gate.signed); + stellarChain.signedTerms?.bind(payload.payload, gate); + }); + + const hostile: ReadonlyArray<[string, () => xdr.SorobanAuthorizationEntry[], RegExp]> = [ + ["pays another address", () => [entry({ to: ATTACKER })], /pays/], + ["asks for twice the amount", () => [entry({ amount: 20_000n })], /base units/], + ["calls another contract", () => [entry({ contract: OTHER_CONTRACT })], /contract/], + ["adds a sub-invocation", () => [entry({ subInvocations: [invocation({ contract: OTHER_CONTRACT })] })], /further call/], + ]; + for (const [name, entries, pattern] of hostile) { + it(`a simulation that ${name}: no signature, and nothing reaches the RPC again`, async () => { + standIn.state.entries = entries(); + const gate = new SigningGate(); + gate.arm(terms()); + await assert.rejects(signThroughSdk(gate), refusedSignedTerms(pattern)); + assert.equal(standIn.state.signatures, 0); + assert.equal(simulations(standIn.state), 1, "the second simulation (which would carry a signature) is never made"); + }); + } + + it("a simulation with two honest entries for the payer: the second is refused, the first never leaves", async () => { + standIn.state.entries = [entry({ nonce: "7" }), entry({ nonce: "8" })]; + const gate = new SigningGate(); + gate.arm(terms()); + await assert.rejects(signThroughSdk(gate), refusedSignedTerms(/second signature/)); + assert.equal(standIn.state.signatures, 1); + assert.equal(simulations(standIn.state), 1); + }); + + it("an RPC that answers a later latest ledger than the anchor: the long expiration is refused", async () => { + const anchor = new SigningAnchor(); + anchor.set(1000); + const gate = new SigningGate(); + gate.arm(terms({ maxExpiration: anchor.maxExpiration(5, 60) })); + standIn.state.latest = 50_000; + await assert.rejects(signThroughSdk(gate), refusedSignedTerms(/ledger 50012/)); + assert.equal(standIn.state.signatures, 0); + }); + + /** The signer the adapter hands the SDK scheme, as the scheme holds it. */ + function registeredSigner(gate: SigningGate) { + const registered: unknown[] = []; + const client = { register: (_network: string, scheme: unknown) => registered.push(scheme) }; + stellarChain.registerPayer(client as never, NETWORK, payerKey.secret(), RPC_URL, gate); + return (registered[0] as { signer: { signAuthEntry: (preimage: string, opts?: { address?: string }) => Promise } }) + .signer; + } + + it("refuses a request to sign for another address than the payer's", async () => { + const gate = new SigningGate(); + gate.arm(terms()); + await assert.rejects( + registeredSigner(gate).signAuthEntry(preimage(), { address: ATTACKER }), + refusedSignedTerms(/another address/), + ); + assert.equal(standIn.state.signatures, 0); + }); + + it("refuses terms that name another payer than the key it holds", async () => { + const gate = new SigningGate(); + gate.arm(terms({ payer: ATTACKER })); + await assert.rejects(registeredSigner(gate).signAuthEntry(preimage({ from: ATTACKER })), refusedSignedTerms(/another payer/)); + assert.equal(standIn.state.signatures, 0); + }); + + it("builds and simulates the payment through the run's RPC, not the SDK's default", async () => { + const gate = new SigningGate(); + gate.arm(terms()); + await signThroughSdk(gate); + assert.ok(standIn.state.calls.length >= 3, JSON.stringify(standIn.state.calls)); + for (const [method, url] of standIn.state.calls) assert.equal(url, RPC_URL, method); + }); + + it("an unarmed gate: the client gets no signature", async () => { + await assert.rejects(signThroughSdk(new SigningGate()), refusedSignedTerms(/expected no signature/)); + assert.equal(standIn.state.signatures, 0); + }); +}); + +describe("signed terms: what is sent is what was signed", () => { + let standIn: ReturnType; + beforeEach(() => { + standIn = installStandIn(); + }); + afterEach(() => standIn.undo()); + + async function signed() { + const gate = new SigningGate(); + gate.arm(terms()); + const payload = await signThroughSdk(gate); + return { gate, transaction: payload.payload["transaction"] as string }; + } + + function rewrite(transaction: string, change: (entry: xdr.SorobanAuthorizationEntry) => void): string { + const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64"); + const auth = envelope.v1().tx().operations()[0]!.body().invokeHostFunctionOp().auth(); + change(auth[0]!); + return envelope.toXDR("base64"); + } + + it("refuses, as signed and not sent, a payload whose invocation was swapped after signing", async () => { + const { gate, transaction } = await signed(); + const swapped = rewrite(transaction, (value) => value.rootInvocation(invocation({ to: ATTACKER }))); + assert.throws( + () => stellarChain.signedTerms?.bind({ transaction: swapped }, gate), + (error: unknown) => refusedSignedTerms(/invocation/)(error) && /it was not sent/.test((error as Error).message), + ); + }); + + it("refuses a payload whose expiration was changed after signing", async () => { + const { gate, transaction } = await signed(); + const later = rewrite(transaction, (value) => value.credentials().address().signatureExpirationLedger(9_999_999)); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: later }, gate), refusedSignedTerms(/expiration/)); + }); + + it("refuses a payload whose signature is not the one Wasit made", async () => { + const { gate, transaction } = await signed(); + const other = rewrite(transaction, (value) => value.credentials().address().signature(xdr.ScVal.scvVoid())); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: other }, gate), refusedSignedTerms(/signature/)); + }); + + it("refuses a payload whose nonce was changed after signing", async () => { + const { gate, transaction } = await signed(); + const other = rewrite(transaction, (value) => value.credentials().address().nonce(xdr.Int64.fromString("99"))); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: other }, gate), refusedSignedTerms(/nonce/)); + }); + + function rewriteSignatureField(transaction: string, field: string, change: (bytes: Buffer) => Buffer): string { + return rewrite(transaction, (value) => { + const item = value.credentials().address().signature().vec()![0]!; + for (const entry of item.map() ?? []) { + if (entry.key().sym().toString() === field) entry.val(xdr.ScVal.scvBytes(change(Buffer.from(entry.val().bytes())))); + } + }); + } + + it("refuses a payload whose signature bytes differ from the ones Wasit made", async () => { + const { gate, transaction } = await signed(); + const other = rewriteSignatureField(transaction, "signature", (bytes) => { + const copy = Buffer.from(bytes); + copy[0] = copy[0]! ^ 0xff; + return copy; + }); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: other }, gate), refusedSignedTerms(/signature/)); + }); + + it("refuses a payload whose signature names another public key", async () => { + const { gate, transaction } = await signed(); + const other = rewriteSignatureField(transaction, "public_key", () => Keypair.random().rawPublicKey()); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: other }, gate), refusedSignedTerms(/signature/)); + }); + + it("refuses a payload that carries a second authorization for the payer", async () => { + const { gate, transaction } = await signed(); + const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64"); + const operation = envelope.v1().tx().operations()[0]!.body().invokeHostFunctionOp(); + operation.auth([...operation.auth(), entry({ nonce: "8" })]); + assert.throws( + () => stellarChain.signedTerms?.bind({ transaction: envelope.toXDR("base64") }, gate), + refusedSignedTerms(/2 authorizations/), + ); + }); + + it("refuses a payload that carries an authorization in another credential form", async () => { + const { gate, transaction } = await signed(); + const other = rewrite(transaction, (value) => + value.credentials(xdr.SorobanCredentials.sorobanCredentialsAddressV2(value.credentials().address())), + ); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: other }, gate), refusedSignedTerms(/form/)); + }); + + it("refuses a payload when nothing was signed through the gate", () => { + const gate = new SigningGate(); + gate.arm(terms()); + assert.throws(() => stellarChain.signedTerms?.bind({ transaction: "AAAA" }, gate), refusedSignedTerms(/without/)); + }); +}); + +describe("signed terms: every network that can be opted into has the gate", () => { + it("each mainnet-optin network belongs to an adapter with a signed-terms gate", () => { + const optIn = [...NETWORK_CLASSES].filter(([, kind]) => kind === "mainnet-optin").map(([network]) => network); + assert.ok(optIn.length > 0); + for (const network of optIn) { + assert.ok(paymentChainFor(network)?.signedTerms, `${network} has no signed-terms gate`); + } + }); + + it("the Stellar adapter has it on every network it pays on, testnet included", () => { + assert.deepEqual(stellarChain.networks, ["stellar:testnet", "stellar:pubnet"]); + assert.ok(stellarChain.signedTerms); + assert.equal(stellarChain.signedTerms.unitSeconds, 5); + }); +}); diff --git a/packages/core/test/unit/x402-stellar-rpc.test.ts b/packages/core/test/unit/x402-stellar-rpc.test.ts new file mode 100644 index 0000000..410749b --- /dev/null +++ b/packages/core/test/unit/x402-stellar-rpc.test.ts @@ -0,0 +1,95 @@ +/** + * The RPC a Stellar x402 payment is built through (spec B17.3), written before + * the code (B11). The x402 Stellar client builds and simulates the payment + * through the run's RPC, the one whose network Wasit checked and reads the + * settlement from; it accepts only an https RPC, so an http one is refused + * before the RPC is asked anything or the target is sent anything. + * + * Offline: the RPC identity check answers through its test seam, and the + * target is a loopback server that counts requests. The payer is a fresh + * random key that holds nothing. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import { afterEach, describe, it } from "node:test"; + +import { Keypair, Networks } from "@stellar/stellar-sdk"; + +import { RpcIdentityError, setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; +import { assertX402PaymentRpc, runX402PaymentChecks } from "../../src/x402/simulator.js"; + +let asked: string[] = []; +const servers: http.Server[] = []; + +function identity(answer: Record): void { + asked = []; + setRpcIdentityTransportForTesting(async (url, method) => { + asked.push(`${method} ${url}`); + return method === "getNetwork" ? { passphrase: answer["stellar"] } : answer["evm"]; + }); +} + +afterEach(async () => { + setRpcIdentityTransportForTesting(undefined); + await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve)))); +}); + +async function countingTarget(): Promise<{ readonly url: string; readonly requests: () => number }> { + let requests = 0; + const server = http.createServer((_request, response) => { + requests += 1; + response.writeHead(500); + response.end(); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + return { url: `http://127.0.0.1:${port}/paid`, requests: () => requests }; +} + +describe("the RPC a Stellar x402 payment is built through", () => { + it("refuses an http RPC in the preflight: the RPC is not asked, the target is sent nothing", async () => { + identity({ stellar: Networks.TESTNET }); + const target = await countingTarget(); + const results = await runX402PaymentChecks({ + target: target.url, + network: "stellar:testnet", + payerSecretKey: Keypair.random().secret(), + rpcUrl: "http://127.0.0.1:9/soroban/rpc", + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.error?.kind, "configuration", results[0]?.detail); + assert.match(results[0]?.detail ?? "", /https/); + assert.match(results[0]?.detail ?? "", /nothing was signed/i); + assert.deepEqual(asked, []); + assert.equal(target.requests(), 0); + }); + + it("goes on to the identity check with an https RPC", async () => { + identity({ stellar: Networks.TESTNET }); + await assertX402PaymentRpc("stellar:testnet", "https://rpc.example.invalid/soroban"); + assert.deepEqual(asked, ["getNetwork https://rpc.example.invalid/soroban"]); + }); + + it("still refuses an https RPC of another network", async () => { + identity({ stellar: Networks.PUBLIC }); + await assert.rejects(assertX402PaymentRpc("stellar:testnet", "https://rpc.example.invalid/soroban"), RpcIdentityError); + }); + + it("does not echo the RPC's address, which may carry a key", async () => { + identity({ stellar: Networks.TESTNET }); + await assert.rejects(assertX402PaymentRpc("stellar:testnet", "http://user:pass-1234@127.0.0.1:9/rpc?apikey=key-5678"), (error) => { + assert.ok(error instanceof RpcIdentityError); + assert.doesNotMatch(error.message, /pass-1234|key-5678/); + return true; + }); + }); + + it("leaves EVM as it is: an http RPC there reaches the identity check", async () => { + identity({ evm: "0x14a34" }); + await assertX402PaymentRpc("eip155:84532", "http://127.0.0.1:9/"); + assert.deepEqual(asked, ["eth_chainId http://127.0.0.1:9/"]); + }); +}); diff --git a/packages/server/test/unit/mainnet-and-rpc-lock.test.ts b/packages/server/test/unit/mainnet-and-rpc-lock.test.ts index 7f74f35..7f251b2 100644 --- a/packages/server/test/unit/mainnet-and-rpc-lock.test.ts +++ b/packages/server/test/unit/mainnet-and-rpc-lock.test.ts @@ -248,7 +248,11 @@ describe("the MCP server's RPC lock and the RPC in results (D-023c)", () => { result.text, ); assert.deepEqual(result.structured?.rpc, { origin: locked.origin, source: "start-up", isDefault: false }); - assert.ok(locked.calls() > 0, "the lock was not the RPC the run used"); + // The stand-in RPC is http, and the x402 Stellar client builds the payment + // through the run's RPC and takes only https: the run is refused for the + // lock's RPC (the default is https), before that RPC is asked anything. + assert.match(result.text, /accepts only an https RPC/); + assert.equal(locked.calls(), 0, "an http RPC was asked something before the run was refused"); assert.ok(!JSON.stringify(result).includes(SECRET_PATH), "the lock's path was printed"); assert.equal(paywall.paid(), 0); } finally { From d669b336cb02142cbb69324527547ecf778b9bfe Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 17:52:24 +0800 Subject: [PATCH 2/2] feat(core): the rules of a mainnet job in GitHub Actions Inside one job, code that ran earlier as the runner's user can reach every later step (PATH, files on disk, a process left running), so no check in the job holds against it. The rules refuse the workflows where such code would be: a mainnet run in GitHub Actions is started by hand, on the default branch, on a GitHub-hosted runner; it tests a deployed service (no service.start, no local baseUrl); nothing was installed before Wasit (no node_modules in the workspace or the config's directory); and WASIT_MAINNET_PAYER_SECRET is the only key variable. Outside GitHub Actions none applies. They stop a wrong workflow; the key itself belongs in a GitHub environment limited to the default branch, with a required reviewer. This version has no mainnet opt-in: assertMainnetJob is exported for it and called by nothing yet. --mainnet and the Action's mainnet input still refuse, and now also name the runner rule on a runner that is not GitHub-hosted. Tests: each rule alone, all together, no echo of a key, an odd event or ref, local hosts as the URL parser writes them, and the runner rule in the CLI and the Action. --- CHANGELOG.md | 12 ++ action/scripts/inputs.mjs | 7 +- action/test/inputs.test.mjs | 18 +- packages/cli/src/run.ts | 7 +- packages/cli/test/unit/run-mainnet.test.ts | 30 ++- packages/core/src/guard/ci-mainnet.ts | 191 ++++++++++++++++++ packages/core/src/guard/mainnet-optin.ts | 16 +- packages/core/src/index.ts | 1 + packages/core/test/unit/ci-mainnet.test.ts | 150 ++++++++++++++ packages/core/test/unit/mainnet-optin.test.ts | 14 +- 10 files changed, 437 insertions(+), 9 deletions(-) create mode 100644 packages/core/src/guard/ci-mainnet.ts create mode 100644 packages/core/test/unit/ci-mainnet.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 50eb988..51ccf6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,18 @@ All notable changes to Wasit are recorded here. Versions follow [Semantic Versio sent, and `wasit run` refuses it before it starts the service: the x402 Stellar client builds the payment through that RPC and accepts only https. +**Added.** +- `@wasit-dev/core` exports `mainnetJobRefusals` and `assertMainnetJob`: the + rules a job in GitHub Actions has to meet for the mainnet opt-in, which this + version does not have. The run is started by hand (`workflow_dispatch`), on + the default branch, on a GitHub-hosted runner; it tests a deployed service + (no `service.start`, no local `baseUrl`); nothing was installed in the job + before Wasit (no `node_modules` in the workspace); and + `WASIT_MAINNET_PAYER_SECRET` is the only key variable set. Outside GitHub + Actions none of them applies. `--mainnet` and the Action's `mainnet: true` + still refuse in this version, and now also name the runner rule on a runner + that is not GitHub-hosted. + **Fixed.** - On Stellar testnet the x402 client builds and simulates the payment through the run's RPC, the one whose network Wasit checks and reads the settlement diff --git a/action/scripts/inputs.mjs b/action/scripts/inputs.mjs index 6009c45..8fb4020 100644 --- a/action/scripts/inputs.mjs +++ b/action/scripts/inputs.mjs @@ -58,9 +58,14 @@ function checkMainnet(env) { event === "workflow_dispatch" ? "" : ` The input is also refused on every event but workflow_dispatch, and this run's event is ${EVENT_NAME.test(event) ? event : "another event"}.`; + // Spec B17.4: a self-hosted runner keeps files and processes between jobs. + const runnerRule = + env["RUNNER_ENVIRONMENT"] === "github-hosted" + ? "" + : " The input is also refused on a runner that is not GitHub-hosted: a self-hosted runner keeps files and processes between jobs."; throw new MainnetRefusedError( "mainnet: true is refused: the mainnet opt-in is not part of this version. Wasit pays on test networks only." + - `${eventRule} Nothing was installed, started, sent or signed.`, + `${eventRule}${runnerRule} Nothing was installed, started, sent or signed.`, ); } diff --git a/action/test/inputs.test.mjs b/action/test/inputs.test.mjs index 8be3c41..6604024 100644 --- a/action/test/inputs.test.mjs +++ b/action/test/inputs.test.mjs @@ -16,7 +16,7 @@ import { 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 }); +const env = (overrides = {}) => ({ INPUT_CONFIG: "wasit.config.json", INPUT_ENVIRONMENT: "", INPUT_TIER: "read-only", INPUT_ENDPOINTS: "", GITHUB_EVENT_NAME: "pull_request", RUNNER_ENVIRONMENT: "github-hosted", ...overrides }); describe("parseInputs", () => { it("takes the defaults: the config file in the working directory, read-only, every endpoint", () => { @@ -80,6 +80,22 @@ describe("parseInputs", () => { } }); + it("adds the runner rule on a runner that is not GitHub-hosted", () => { + for (const runner of ["self-hosted", undefined]) { + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: "true", GITHUB_EVENT_NAME: "workflow_dispatch", RUNNER_ENVIRONMENT: runner })), + (error) => + SENTENCE.test(error.message) && + error.message.includes("The input is also refused on a runner that is not GitHub-hosted: a self-hosted runner keeps files and processes between jobs."), + String(runner), + ); + } + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: "true", GITHUB_EVENT_NAME: "workflow_dispatch" })), + (error) => !/GitHub-hosted/.test(error.message), + ); + }); + it("adds the workflow_dispatch rule on any other event, and names the event", () => { for (const name of ["push", "schedule", "pull_request"]) { assert.throws( diff --git a/packages/cli/src/run.ts b/packages/cli/src/run.ts index f630493..36f7222 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -309,7 +309,12 @@ export async function executeRun(options: RunCommandOptions, context: RunContext // B12: the switch exists only to refuse. First, so nothing is read, started, sent or signed. if (options.mainnet === true) { try { - refuseMainnetSwitch("--mainnet", inGithubActions(context.env) ? { event: context.env["GITHUB_EVENT_NAME"] ?? "" } : {}); + refuseMainnetSwitch( + "--mainnet", + inGithubActions(context.env) + ? { event: context.env["GITHUB_EVENT_NAME"] ?? "", runner: context.env["RUNNER_ENVIRONMENT"] ?? "" } + : {}, + ); } catch (error) { if (error instanceof MainnetOptInRefusedError) return fail(`wasit run ${error.message}`); throw error; diff --git a/packages/cli/test/unit/run-mainnet.test.ts b/packages/cli/test/unit/run-mainnet.test.ts index 50c0b40..8650bc9 100644 --- a/packages/cli/test/unit/run-mainnet.test.ts +++ b/packages/cli/test/unit/run-mainnet.test.ts @@ -150,11 +150,18 @@ describe("wasit run --mainnet (B12: a switch that always refuses)", () => { }); } - it("in GitHub Actions on workflow_dispatch: still refused, without the event rule", async () => { + it("in GitHub Actions on workflow_dispatch on a hosted runner: still refused, without the event or runner rule", async () => { paywall = await multiPaywall({ "/weather": [option("10000")] }); const result = await run( { config: await pubnetConfig(paywall.base) }, - { GITHUB_ACTIONS: "true", CI: "true", GITHUB_EVENT_NAME: "workflow_dispatch", GITHUB_REF: "refs/heads/main", GITHUB_EVENT_PATH: eventFile }, + { + GITHUB_ACTIONS: "true", + CI: "true", + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_REF: "refs/heads/main", + GITHUB_EVENT_PATH: eventFile, + RUNNER_ENVIRONMENT: "github-hosted", + }, ); assert.equal(result.code, 2); assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); @@ -162,6 +169,25 @@ describe("wasit run --mainnet (B12: a switch that always refuses)", () => { assert.equal(paywall.requests, 0); }); + it("in GitHub Actions on a self-hosted runner: refused, and says the runner rule", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const result = await run( + { config: await pubnetConfig(paywall.base) }, + { + GITHUB_ACTIONS: "true", + CI: "true", + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_REF: "refs/heads/main", + GITHUB_EVENT_PATH: eventFile, + RUNNER_ENVIRONMENT: "self-hosted", + }, + ); + assert.equal(result.code, 2); + assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); + assert.match(result.stderr, /--mainnet is also refused on a runner that is not GitHub-hosted/); + assert.equal(paywall.requests, 0); + }); + it("is not read from the environment: WASIT_MAINNET_OPT_IN without the flag changes nothing", async () => { paywall = await multiPaywall({ "/weather": [option("10000")] }); const result = await run({ config: await pubnetConfig(paywall.base), mainnet: false, readOnly: true }, { WASIT_MAINNET_OPT_IN: "1" }); diff --git a/packages/core/src/guard/ci-mainnet.ts b/packages/core/src/guard/ci-mainnet.ts new file mode 100644 index 0000000..76420bd --- /dev/null +++ b/packages/core/src/guard/ci-mainnet.ts @@ -0,0 +1,191 @@ +/** + * The rules for a mainnet job in GitHub Actions (spec B17.4). + * + * Inside one job, code that ran earlier as the runner's user can reach every + * later step: it can put a program of its own first on PATH, change files on + * disk, or leave a process running that reads the environment of the step + * that holds the key (and a GitHub-hosted runner's user has passwordless sudo). + * No check inside the job holds against such code, since that code can change + * the check. So these rules do not look for it: they refuse the workflows in + * which it would be there. A mainnet run in GitHub Actions is started by hand, + * on the default branch, on a GitHub-hosted runner (a fresh machine per job); + * it tests a deployed service, so no code of the service runs in the job; it + * runs where nothing was installed before Wasit; and the mainnet key is the + * only key variable set. + * + * They stop a wrong workflow, not a person or code that sets out to get past + * them. What holds against those is GitHub's: the mainnet key kept as the + * secret of a GitHub environment limited to the default branch, with a + * required reviewer. Outside GitHub Actions none of these rules applies: on a + * builder's own machine the CLI may test a local service. + * + * This version has no mainnet opt-in (spec B12): its switches refuse before + * any of this is read. The opt-in calls {@link assertMainnetJob} before it + * reads a key. + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; + +import { DENIED_ENV_NAMES } from "../denied-env.js"; +import { ConfigurationError } from "../errors.js"; +import { inGithubActions } from "./ci-event.js"; + +/** The variable a mainnet run reads its key from (spec B5). */ +const MAINNET_KEY = "WASIT_MAINNET_PAYER_SECRET"; + +/** An event name as GitHub writes them; anything else is never echoed. */ +const EVENT_NAME = /^[a-z_]{1,64}$/; +/** A branch or tag ref, and a branch name, in a shape that is safe to echo. */ +const REF = /^refs\/(heads|tags)\/[A-Za-z0-9._/-]{1,200}$/; +const BRANCH = /^[A-Za-z0-9._/-]{1,200}$/; + +export interface MainnetJob { + /** The process environment. */ + readonly env: Readonly>; + /** The repository's default branch, from the event; undefined when it cannot be read. */ + readonly defaultBranch: string | undefined; + /** The run's environment starts a service in the job (`service.start`). */ + readonly startsService: boolean; + /** The run's `baseUrl`. */ + readonly baseUrl: string; + /** Where a `node_modules` would show that something was installed before Wasit, with a label for the message. */ + readonly installDirs: ReadonlyArray<{ readonly label: string; readonly dir: string }>; +} + +/** A job that may not make a mainnet run, with every rule it breaks. */ +export class MainnetJobRefusedError extends ConfigurationError { + public readonly refusals: readonly string[]; + + public constructor(refusals: readonly string[]) { + super( + `This job may not make a mainnet run: ${refusals.join("; ")}. Nothing was started, sent or signed. These ` + + `rules stop a wrong workflow, not code that already ran in this job: keep the mainnet key as the secret of ` + + `a GitHub environment limited to the default branch, with a required reviewer.`, + ); + this.name = "MainnetJobRefusedError"; + this.refusals = refusals; + } +} + +function nonEmpty(value: string | undefined): boolean { + return typeof value === "string" && value.trim() !== ""; +} + +function listed(names: readonly string[]): string { + return names.length === 1 ? names[0]! : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]!}`; +} + +function isLocalIpv4(a: number, b: number): boolean { + return ( + a === 127 || // loopback + a === 0 || + a === 10 || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 169 && b === 254) || // link-local + (a === 100 && b >= 64 && b <= 127) // shared address space + ); +} + +function isLocalIpv6(address: string): boolean { + if (address === "::1" || address === "::") return true; + const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address); + if (mappedHex !== null) { + const high = Number.parseInt(mappedHex[1]!, 16); + return isLocalIpv4(high >> 8, high & 0xff); + } + const mappedDotted = /^::ffff:(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(address); + if (mappedDotted !== null) return isLocalIpv4(Number(mappedDotted[1]), Number(mappedDotted[2])); + const first = Number.parseInt(address.split(":")[0] || "0", 16); + return (first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80; // unique local, link-local +} + +/** + * A host only this machine or its own network reaches, as `URL.hostname` + * writes it: a loopback, private, link-local or shared address, `localhost`, + * a single-label name, or a `.local` or `.internal` name. + */ +export function isLocalHost(hostname: string): boolean { + const host = hostname.toLowerCase().replace(/\.$/, ""); + if (host.startsWith("[") && host.endsWith("]")) return isLocalIpv6(host.slice(1, -1)); + const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host); + if (v4 !== null) return isLocalIpv4(Number(v4[1]), Number(v4[2])); + if (!host.includes(".")) return true; + return host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal"); +} + +/** + * Every rule of a mainnet job that `job` breaks, one clause each; empty when it + * breaks none, and always empty outside GitHub Actions. No key, and no event + * name, ref or path in an odd shape, is echoed. + */ +export function mainnetJobRefusals(job: MainnetJob, exists: (file: string) => boolean = existsSync): string[] { + if (!inGithubActions(job.env)) return []; + const refusals: string[] = []; + + const event = job.env["GITHUB_EVENT_NAME"] ?? ""; + if (event !== "workflow_dispatch") { + refusals.push( + `a mainnet run is started by hand (workflow_dispatch), and this run's event is ${EVENT_NAME.test(event) ? event : "another event"}`, + ); + } + + if (job.env["RUNNER_ENVIRONMENT"] !== "github-hosted") { + refusals.push( + "a mainnet run needs a GitHub-hosted runner (RUNNER_ENVIRONMENT github-hosted): a self-hosted runner keeps " + + "files and processes between jobs", + ); + } + + const ref = job.env["GITHUB_REF"] ?? ""; + if (job.defaultBranch === undefined || !BRANCH.test(job.defaultBranch)) { + refusals.push("the repository's default branch could not be read from the event, so this run cannot be shown to be on it"); + } else if (ref !== `refs/heads/${job.defaultBranch}`) { + refusals.push( + `a mainnet run runs on the default branch (${job.defaultBranch}), and this run's ref is ${REF.test(ref) ? ref : "another ref"}`, + ); + } + + if (job.startsService) { + refusals.push( + "the environment starts a service in the job (service.start): a mainnet run tests a deployed service, so that " + + "no code of the service runs in the job that holds the key", + ); + } + + let host: string | undefined; + try { + host = new URL(job.baseUrl).hostname; + } catch { + host = undefined; + } + if (host === undefined || isLocalHost(host)) { + refusals.push( + "baseUrl is a local address (a loopback, private or single-label host): a mainnet run tests a deployed service", + ); + } + + for (const { label, dir } of job.installDirs) { + if (exists(path.join(dir, "node_modules"))) { + refusals.push( + `a node_modules directory is in ${label}: code was installed in this job before Wasit, and a mainnet job ` + + `holds only checkout, setup-node and Wasit`, + ); + } + } + + const others = DENIED_ENV_NAMES.filter((name) => name !== MAINNET_KEY && nonEmpty(job.env[name])); + if (others.length > 0) { + refusals.push( + `only ${MAINNET_KEY} may be set on a mainnet run, and ${listed(others)} ${others.length === 1 ? "is" : "are"} set too`, + ); + } + return refusals; +} + +/** Throws {@link MainnetJobRefusedError} when `job` breaks any rule of a mainnet job. */ +export function assertMainnetJob(job: MainnetJob, exists: (file: string) => boolean = existsSync): void { + const refusals = mainnetJobRefusals(job, exists); + if (refusals.length > 0) throw new MainnetJobRefusedError(refusals); +} diff --git a/packages/core/src/guard/mainnet-optin.ts b/packages/core/src/guard/mainnet-optin.ts index 1aa5465..18aff9d 100644 --- a/packages/core/src/guard/mainnet-optin.ts +++ b/packages/core/src/guard/mainnet-optin.ts @@ -62,11 +62,15 @@ function testNetworks(): string { * For `--mainnet`, `context.event` is the GitHub event of the run when it runs * in GitHub Actions: on any event but `workflow_dispatch` the message says that * rule as well, so a push or a schedule with the switch set reads as refused for - * that reason too. + * that reason too. `context.runner` is `RUNNER_ENVIRONMENT` there: on a runner + * that is not GitHub-hosted the message says that rule too. * * @throws {MainnetOptInRefusedError} Always. */ -export function refuseMainnetSwitch(switchName: MainnetSwitch, context: { readonly event?: string } = {}): never { +export function refuseMainnetSwitch( + switchName: MainnetSwitch, + context: { readonly event?: string; readonly runner?: string } = {}, +): never { const networks = `Wasit pays on test networks only (${testNetworks()}).`; if (switchName === "--mainnet") { const event = context.event; @@ -75,9 +79,15 @@ export function refuseMainnetSwitch(switchName: MainnetSwitch, context: { readon ? "" : ` --mainnet is also refused on every GitHub event but workflow_dispatch, and this run's event is ` + `${EVENT_NAME.test(event) ? event : "another event"}.`; + // Spec B17.4: a self-hosted runner keeps files and processes between jobs. + const runnerRule = + context.runner === undefined || context.runner === "github-hosted" + ? "" + : " --mainnet is also refused on a runner that is not GitHub-hosted: a self-hosted runner keeps files and " + + "processes between jobs."; throw new MainnetOptInRefusedError( switchName, - `--mainnet is refused: ${MAINNET_OPT_IN_ABSENT}. ${networks}${eventRule} ` + + `--mainnet is refused: ${MAINNET_OPT_IN_ABSENT}. ${networks}${eventRule}${runnerRule} ` + `The config was not read, and nothing was started, sent or signed.`, ); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a54e118..9c208db 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -150,6 +150,7 @@ export { mainnetStartupSwitches, refuseMainnetSwitch, } from "./guard/mainnet-optin.js"; +export { MainnetJobRefusedError, assertMainnetJob, isLocalHost, mainnetJobRefusals, type MainnetJob } from "./guard/ci-mainnet.js"; export type { MainnetSwitch } from "./guard/mainnet-optin.js"; // Which RPC a result read the chain through, and the MCP server's start-up RPC lock (D-023c). diff --git a/packages/core/test/unit/ci-mainnet.test.ts b/packages/core/test/unit/ci-mainnet.test.ts new file mode 100644 index 0000000..293f9fc --- /dev/null +++ b/packages/core/test/unit/ci-mainnet.test.ts @@ -0,0 +1,150 @@ +/** + * The rules for a mainnet job in GitHub Actions (spec B17.4), written before + * the code (B11). Inside one job, code that ran earlier as the runner's user + * owns every later step, so these rules do not try to detect such code: they + * refuse the workflows in which it would be there. A mainnet run is started by + * hand, on the default branch, on a GitHub-hosted runner; it tests a deployed + * service (no `service.start`, no local `baseUrl`), in a job where nothing was + * installed before Wasit, with the mainnet key as the only key variable. + * Outside GitHub Actions (a builder's own machine) none of them applies. + */ + +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; + +import { ConfigurationError } from "../../src/errors.js"; +import { + MainnetJobRefusedError, + assertMainnetJob, + isLocalHost, + mainnetJobRefusals, + type MainnetJob, +} from "../../src/guard/ci-mainnet.js"; + +const HOSTED_DISPATCH = { + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_REF: "refs/heads/main", + RUNNER_ENVIRONMENT: "github-hosted", + WASIT_MAINNET_PAYER_SECRET: "set", +}; + +function job(overrides: Partial = {}, env: Record = {}): MainnetJob { + return { + env: { ...HOSTED_DISPATCH, ...env }, + defaultBranch: "main", + startsService: false, + baseUrl: "https://api.example.com", + installDirs: [], + ...overrides, + }; +} + +const none = () => false; + +describe("a mainnet job in GitHub Actions", () => { + it("passes the job of the mainnet example: by hand, default branch, hosted, a deployed service, nothing installed", () => { + assert.deepEqual(mainnetJobRefusals(job(), none), []); + assertMainnetJob(job(), none); + }); + + it("applies none of the rules outside GitHub Actions: the CLI on a builder's machine may test a local service", () => { + const local = job( + { startsService: true, baseUrl: "http://127.0.0.1:3000", defaultBranch: undefined }, + { GITHUB_ACTIONS: undefined, GITHUB_EVENT_NAME: undefined, RUNNER_ENVIRONMENT: undefined, GITHUB_REF: undefined }, + ); + assert.deepEqual(mainnetJobRefusals(local, () => true), []); + }); + + const rules: ReadonlyArray<[string, MainnetJob, RegExp]> = [ + ["a push", job({}, { GITHUB_EVENT_NAME: "push" }), /started by hand \(workflow_dispatch\), and this run's event is push/], + ["a schedule", job({}, { GITHUB_EVENT_NAME: "schedule" }), /this run's event is schedule/], + ["a self-hosted runner", job({}, { RUNNER_ENVIRONMENT: "self-hosted" }), /GitHub-hosted runner/], + ["no runner environment", job({}, { RUNNER_ENVIRONMENT: undefined }), /GitHub-hosted runner/], + ["another branch", job({}, { GITHUB_REF: "refs/heads/feature" }), /default branch \(main\), and this run's ref is refs\/heads\/feature/], + ["a tag", job({}, { GITHUB_REF: "refs/tags/v1" }), /default branch/], + ["an unknown default branch", job({ defaultBranch: undefined }), /default branch could not be read/], + ["a service started in the job", job({ startsService: true }), /service\.start/], + ["a loopback baseUrl", job({ baseUrl: "http://127.0.0.1:3000" }), /baseUrl is a local address/], + ["a private baseUrl", job({ baseUrl: "https://10.1.2.3" }), /baseUrl is a local address/], + ["another key variable set", job({}, { STELLAR_PRIVATE_KEY: "x" }), /only WASIT_MAINNET_PAYER_SECRET .* STELLAR_PRIVATE_KEY is set too/], + ]; + for (const [name, value, pattern] of rules) { + it(`refuses ${name}, alone`, () => { + const refusals = mainnetJobRefusals(value, none); + assert.equal(refusals.length, 1, refusals.join(" | ")); + assert.match(refusals[0]!, pattern); + }); + } + + it("refuses a node_modules in the workspace or the config's directory: code was installed before Wasit", () => { + const dir = mkdtempSync(path.join(tmpdir(), "wasit-ci-mainnet-")); + try { + const workspace = path.join(dir, "ws"); + const configDir = path.join(dir, "cfg"); + mkdirSync(workspace); + mkdirSync(configDir); + const value = job({ installDirs: [{ label: "the workspace", dir: workspace }, { label: "the config's directory", dir: configDir }] }); + assert.deepEqual(mainnetJobRefusals(value), []); + mkdirSync(path.join(configDir, "node_modules")); + const refusals = mainnetJobRefusals(value); + assert.equal(refusals.length, 1); + assert.match(refusals[0]!, /node_modules directory is in the config's directory/); + assert.ok(!refusals[0]!.includes(dir), "a path was echoed"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("lists every rule a job breaks, in one refusal that says what holds instead", () => { + const value = job( + { startsService: true, baseUrl: "http://localhost:3000" }, + { GITHUB_EVENT_NAME: "push", RUNNER_ENVIRONMENT: "self-hosted", GITHUB_REF: "refs/heads/dev", EVM_PRIVATE_KEY: "x" }, + ); + assert.equal(mainnetJobRefusals(value, none).length, 6); + assert.throws( + () => assertMainnetJob(value, none), + (error: unknown) => { + assert.ok(error instanceof MainnetJobRefusedError); + assert.ok(error instanceof ConfigurationError, "a configuration error: exit 2"); + assert.equal(error.refusals.length, 6); + assert.match(error.message, /^This job may not make a mainnet run: /); + assert.match(error.message, /Nothing was started, sent or signed\./); + assert.match(error.message, /GitHub environment/); + return true; + }, + ); + }); + + it("never echoes a key, an odd event name or an odd ref", () => { + const secret = Keypair.random().secret(); + const value = job({}, { STELLAR_PRIVATE_KEY: secret, MPP_PAYER_SECRET: secret, GITHUB_EVENT_NAME: "push; id", GITHUB_REF: "refs/heads/$(id)" }); + const text = mainnetJobRefusals(value, none).join(" "); + assert.ok(!text.includes(secret), "a key was echoed"); + assert.ok(!text.includes("push; id") && !text.includes("$(id)"), text); + assert.match(text, /STELLAR_PRIVATE_KEY and MPP_PAYER_SECRET are set too/); + assert.match(text, /another event/); + assert.match(text, /another ref/); + }); +}); + +describe("isLocalHost", () => { + const local = [ + "localhost", "api.localhost", "127.0.0.1", "127.9.9.9", "0.0.0.0", "10.0.0.1", "172.16.0.1", "172.31.255.255", + "192.168.1.1", "169.254.169.254", "100.64.0.1", "[::1]", "[::]", "[fd00::1]", "[fc00::1]", "[fe80::1]", + "[::ffff:7f00:1]", "service", "printer.local", "db.internal", + ]; + const remote = ["api.example.com", "172.15.0.1", "172.32.0.1", "8.8.8.8", "100.128.0.1", "[2606:4700::1111]"]; + for (const host of local) it(`${host} is local`, () => assert.equal(isLocalHost(host), true)); + for (const host of remote) it(`${host} is not`, () => assert.equal(isLocalHost(host), false)); + + it("reads hosts as the URL parser writes them: a decimal IPv4 and a mapped IPv6 are loopback", () => { + assert.equal(isLocalHost(new URL("http://2130706433/").hostname), true); + assert.equal(isLocalHost(new URL("http://[::ffff:127.0.0.1]/").hostname), true); + }); +}); diff --git a/packages/core/test/unit/mainnet-optin.test.ts b/packages/core/test/unit/mainnet-optin.test.ts index 5247e48..642b9db 100644 --- a/packages/core/test/unit/mainnet-optin.test.ts +++ b/packages/core/test/unit/mainnet-optin.test.ts @@ -26,7 +26,7 @@ import { NETWORK_CLASSES } from "../../src/guard/networks.js"; const SWITCHES: readonly MainnetSwitch[] = ["--mainnet", "WASIT_MAINNET_OPT_IN", "WASIT_MAINNET_CONFIG"]; const TEST_NETWORKS = [...NETWORK_CLASSES].filter(([, kind]) => kind === "test").map(([network]) => network); -function refusal(name: MainnetSwitch, context?: { event?: string }): MainnetOptInRefusedError { +function refusal(name: MainnetSwitch, context?: { event?: string; runner?: string }): MainnetOptInRefusedError { try { refuseMainnetSwitch(name, context); } catch (error) { @@ -51,6 +51,18 @@ describe("the mainnet opt-in switches of this version (B12)", () => { assert.doesNotMatch(error.message, /workflow_dispatch/, "no event rule outside GitHub Actions"); }); + it("adds the runner rule in GitHub Actions on a runner that is not GitHub-hosted", () => { + for (const runner of ["self-hosted", ""]) { + const error = refusal("--mainnet", { event: "workflow_dispatch", runner }); + assert.ok( + error.message.includes("--mainnet is also refused on a runner that is not GitHub-hosted: a self-hosted runner keeps files and processes between jobs."), + error.message, + ); + } + assert.doesNotMatch(refusal("--mainnet", { event: "workflow_dispatch", runner: "github-hosted" }).message, /GitHub-hosted/); + assert.doesNotMatch(refusal("--mainnet").message, /GitHub-hosted/, "no runner rule outside GitHub Actions"); + }); + it("adds the event rule on a GitHub event that is not workflow_dispatch, and names the event", () => { for (const event of ["push", "schedule", "pull_request", "pull_request_target", "merge_group"]) { const error = refusal("--mainnet", { event });