Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test(a2a): prove the spend guard refuses an agent that does not exist

nirholas4dfc94fa60ad
diff --git a/scripts/a2a-spend-hardening-proof.mjs b/scripts/a2a-spend-hardening-proof.mjs
index a6aff61c2..031bd9c0f 100644
--- a/scripts/a2a-spend-hardening-proof.mjs
+++ b/scripts/a2a-spend-hardening-proof.mjs
@@ -15,8 +15,15 @@
// uses (PUT /api/agents/:id/solana/limits -> the very next reserve throws).
// This script is the second half of that proof.
//
+// Every guard call below deliberately passes NEITHER a pre-resolved `limits`
+// object NOR the agent's `meta`, because that is the shape autonomy actually
+// takes: a background caller with an agent id and an amount. The guard has to
+// resolve the real policy itself, so each block here is also a proof that the
+// enforcement fails closed on its inputs.
+//
// What it proves, in order:
-// 1. per_tx_usd an over-cap reserve is rejected; an at-cap one lands
+// 1. per_tx_usd an over-cap reserve is rejected; an at-cap one lands,
+// and an unknown agent is refused outright
// 2. daily_usd a wallet at its rolling-24h ceiling rejects the next
// reserve, and 8 CONCURRENT reserves cannot race past it
// 3. per_counterparty_daily_usd a payee at its ceiling rejects more, while the
@@ -454,6 +461,15 @@ process.stdin.on('data', (d) => {
const at = await callErr('reserveSpendUsd', spend({ usdValue: 1 }));
check('at-cap reserve allowed', !at.thrown && !!at.out?.reservationId, at.thrown?.message || `reservation ${at.out?.reservationId}`);
if (at.out?.reservationId) await call('releaseSpendReservation', at.out.reservationId, 'proof_cleanup');
+
+ // Every reserve in this proof passes NEITHER `limits` NOR `meta`, so the
+ // block above came from the policy the guard read off the agent row itself.
+ // The other half of that guarantee: an agent that no longer exists can hold
+ // no policy, so its spend is refused rather than waved through an empty one.
+ const ghost = await callErr('reserveSpendUsd', spend({ agentId: '00000000-0000-0000-0000-000000000000' }));
+ check('a spend for an agent that does not exist is refused, not defaulted',
+ ghost.thrown?.code === 'agent_not_found',
+ ghost.thrown ? `${ghost.thrown.code}: ${ghost.thrown.message}` : 'ERROR: reserve was allowed');
}
// ── 2. daily ceiling + concurrency race ──────────────────────────────────
diff --git a/scripts/reputation-market-proof.mjs b/scripts/reputation-market-proof.mjs
index 6c7049595..d5abedc7d 100644
--- a/scripts/reputation-market-proof.mjs
+++ b/scripts/reputation-market-proof.mjs
@@ -23,8 +23,16 @@
// Either way the proof settles with a real signature; mode 2 exists so the
// proof is runnable by anyone with no credentials at all.
//
+// Staker funding, in order:
+// 1. REPUTATION_MARKET_PROOF_FUNDER_SECRET_KEY (a keypair you funded once)
+// 2. the public devnet faucet
+// The faucet rate-limits per source IP, so a shared machine can find it already
+// exhausted. Rung 1 exists for exactly that case: fund any devnet keypair once
+// at https://faucet.solana.com and the proof never touches the faucet again.
+//
// Env (all optional):
// REPUTATION_MARKET_ESCROW_SECRET_KEY escrow secret (base58/base64/JSON)
+// REPUTATION_MARKET_PROOF_FUNDER_SECRET_KEY pre-funded staker funder
// SOLANA_RPC_URL_DEVNET devnet RPC override
// REPUTATION_MARKET_EPOCH_POOL_LAMPORTS epoch pool for the quote
// (default 2000000: 0.002 SOL)
@@ -55,6 +63,7 @@ const NETWORK = 'devnet';
const STAKE_LAMPORTS = 2_000_000n; // 0.002 SOL, twice the minimum
const DEFAULT_POOL_LAMPORTS = 2_000_000n;
const AIRDROP_LAMPORTS = 100_000_000; // 0.1 SOL per request, devnet-friendly
+const FUNDER_FEE_HEADROOM = 5_000n; // one signature's fee, so the funder can pay for its own transfer
const CONFIRM_TIMEOUT_MS = 60_000;
const results = [];
@@ -79,7 +88,14 @@ async function fundWithAirdrops(conn, pubkey, targetLamports) {
} catch (err) {
// Devnet faucets rate-limit hard; back off and retry.
await new Promise((r) => setTimeout(r, 3_000 * (attempt + 1)));
- if (attempt === 4) throw new Error(`airdrop failed: ${err.message}`);
+ if (attempt === 4) {
+ throw new Error(
+ `airdrop failed: ${err.message}\n` +
+ 'The public devnet faucet rate-limits per source IP, so a shared machine can exhaust it ' +
+ 'for everyone on it. Fund any devnet keypair once at https://faucet.solana.com and re-run ' +
+ 'with REPUTATION_MARKET_PROOF_FUNDER_SECRET_KEY set to its secret; the proof then needs no faucet.',
+ );
+ }
}
}
balance = BigInt(await conn.getBalance(pubkey, 'confirmed'));
@@ -87,6 +103,37 @@ async function fundWithAirdrops(conn, pubkey, targetLamports) {
return balance;
}
+/**
+ * Fund the staker for the run. The faucet is one rung, not the only one: a
+ * pre-funded keypair in REPUTATION_MARKET_PROOF_FUNDER_SECRET_KEY takes
+ * priority, which is what makes the proof runnable from a machine whose IP the
+ * public devnet faucet has already cut off.
+ */
+async function fundStaker(conn, pubkey, targetLamports) {
+ const secret = process.env.REPUTATION_MARKET_PROOF_FUNDER_SECRET_KEY;
+ const bytes = secret ? decodeAttesterSecret(secret) : null;
+ if (!bytes) return { balance: await fundWithAirdrops(conn, pubkey, targetLamports), source: 'faucet' };
+
+ const funder = Keypair.fromSecretKey(bytes);
+ const need = BigInt(targetLamports) + FUNDER_FEE_HEADROOM;
+ const held = BigInt(await conn.getBalance(funder.publicKey, 'confirmed'));
+ if (held < need) {
+ throw new Error(
+ `funder ${funder.publicKey.toBase58()} holds ${held} lamports but needs ${need}. ` +
+ `Top it up on ${NETWORK} at https://faucet.solana.com and re-run.`,
+ );
+ }
+
+ const tx = new Transaction().add(
+ SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: pubkey, lamports: Number(targetLamports) }),
+ );
+ await sendAndConfirm(conn, tx, [funder], { commitment: 'confirmed', timeoutMs: CONFIRM_TIMEOUT_MS });
+ return {
+ balance: BigInt(await conn.getBalance(pubkey, 'confirmed')),
+ source: `funder ${funder.publicKey.toBase58()}`,
+ };
+}
+
async function attest(conn, signer, agentAsset, payload) {
const memoIx = new TransactionInstruction({
keys: [
@@ -121,8 +168,8 @@ const main = async () => {
const escrow = escrowKeypair.publicKey;
step('config', true, `network=${NETWORK} escrow=${escrow.toBase58()} (${escrowMode})`);
- await fundWithAirdrops(conn, staker.publicKey, 20_000_000); // stake + fees + headroom
- step('fund', true, `staker=${staker.publicKey.toBase58()}`);
+ const funded = await fundStaker(conn, staker.publicKey, 20_000_000); // stake + fees + headroom
+ step('fund', true, `staker=${staker.publicKey.toBase58()} via ${funded.source}`);
const poolLamports = process.env.REPUTATION_MARKET_EPOCH_POOL_LAMPORTS
? BigInt(process.env.REPUTATION_MARKET_EPOCH_POOL_LAMPORTS)
diff --git a/tests/a2a-payment-hardening.test.js b/tests/a2a-payment-hardening.test.js
index 03e38338f..14461aced 100644
--- a/tests/a2a-payment-hardening.test.js
+++ b/tests/a2a-payment-hardening.test.js
@@ -141,6 +141,75 @@ describe('per-counterparty daily ceiling', () => {
});
});
+// ── 1b. the policy resolves fail-closed ───────────────────────────────────────
+//
+// The ceilings above are only guarantees if there is no way to call the guard
+// that skips them. There used to be one: with neither `limits` nor `meta`, both
+// shared guards fell back to an empty default policy (every cap null, frozen
+// false), so a caller that forgot to load the agent row spent unbounded and
+// nothing said so. The guard now reads the agent's real policy itself.
+
+const AGENT_ROW = (spendLimits) => [{ user_id: 'owner-1', meta: { spend_limits: spendLimits } }];
+
+describe('spend policy resolution', () => {
+ it('reads the kill switch off the agent row when the caller passes neither limits nor meta', async () => {
+ sqlState.queue.push(AGENT_ROW({ frozen: true }));
+ await expect(
+ enforceSpendLimit({ agentId: 'agent-1', category: 'x402', usdValue: 1, destination: PEER_A }),
+ ).rejects.toMatchObject({ code: 'wallet_frozen' });
+ });
+
+ it('reads the per-transaction ceiling off the agent row the same way', async () => {
+ sqlState.queue.push(AGENT_ROW({ per_tx_usd: 1 }));
+ await expect(
+ enforceSpendLimit({ agentId: 'agent-1', category: 'x402', usdValue: 5, destination: PEER_A }),
+ ).rejects.toMatchObject({ code: 'per_tx_exceeded' });
+ });
+
+ it('refuses the spend outright when the agent row is gone', async () => {
+ // A deleted agent can hold no policy, so there is nothing to enforce against.
+ // Fail closed: refuse, never fall through to an unrestricted wallet.
+ sqlState.queue.push([]);
+ await expect(
+ enforceSpendLimit({ agentId: 'agent-1', category: 'x402', usdValue: 1, destination: PEER_A }),
+ ).rejects.toMatchObject({ code: 'agent_not_found' });
+ });
+
+ it('does not re-read the row when the caller already resolved the limits', async () => {
+ // The safety net must not cost every well-behaved call site an extra query.
+ await expect(
+ enforceSpendLimit({
+ agentId: 'agent-1',
+ limits: normalizeSpendLimits({ per_tx_usd: 10 }),
+ policyRules: null,
+ category: 'x402',
+ usdValue: 1,
+ destination: PEER_A,
+ }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(sqlState.calls.some((c) => /FROM agent_identities/.test(c.query))).toBe(false);
+ });
+
+ it('honors an explicitly empty meta as an explicitly empty policy', async () => {
+ // `meta: {}` is a real answer from the caller ("this agent has set nothing"),
+ // not a missing one, so it must not trigger the row read.
+ await expect(
+ enforceSpendLimit({ agentId: 'agent-1', meta: {}, category: 'x402', usdValue: 1000, destination: PEER_A }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(sqlState.calls.some((c) => /FROM agent_identities/.test(c.query))).toBe(false);
+ });
+
+ it('halts the atomic reserve on the same row-resolved kill switch', async () => {
+ // Part 2 stubs reserveSpendUsd to steer the handler, so reach past the stub
+ // for the real one: both guards have to resolve the policy the same way.
+ const real = await vi.importActual('../api/_lib/agent-trade-guards.js');
+ sqlState.queue.push(AGENT_ROW({ frozen: true, daily_usd: 1000 }));
+ await expect(
+ real.reserveSpendUsd({ agentId: 'agent-1', category: 'x402', usdValue: 1, destination: PEER_A }),
+ ).rejects.toMatchObject({ code: 'wallet_frozen' });
+ });
+});
+
// ── 2. the a2a-call handler ───────────────────────────────────────────────────
const AGENT_ID = '33333333-3333-4333-8333-333333333333';