mcp-cli icon indicating copy to clipboard operation
mcp-cli copied to clipboard

Potential payment cache reuse issue: session-level signature is reused across tool calls

Open chenshj73 opened this issue 6 months ago • 9 comments

Hi, I noticed a possible payment signature reuse issue in the x402 fetch middleware.

The tool metadata includes payment-specific fields such as scheme, network, amount, asset, and payee:

48: interface ToolPaymentMeta {
49:   paymentRequired: boolean;
50:   accepts?: PaymentRequiredAccept[];
51:   scheme?: string;
52:   network?: string;
53:   amount?: string;
54:   asset?: string;
55:   payTo?: string;
56:   maxTimeoutSeconds?: number;

When handling a paid tools/call, the middleware checks the tool metadata:

187:   // Parse the request body to find tools/call requests
188:   const toolName = extractToolCallName(init.body);
193:   // Look up tool metadata
194:   const tool = getToolByName(toolName);
200:   // Check _meta.x402
201:   const meta = (tool as { _meta?: { x402?: ToolPaymentMeta } })._meta;
202:   const x402 = meta?.x402;
203:   if (!x402 || !x402.paymentRequired) {
204:     return undefined;
205:   }

However, it returns a cached signature before selecting a payment requirement for the current tool:

207:   // Return cached signature if available
208:   if (paymentCache.signature) {
209:     logger.debug(`Using cached payment signature for tool "${toolName}"`);
210:     return paymentCache.signature;
211:   }
213:   const accept = selectAcceptFromToolMeta(x402, schemePreference);
221:   try {
222:     const result = await signPayment({ wallet, accept });
226:     paymentCache.signature = result.paymentSignatureBase64;
227:     return result.paymentSignatureBase64;

The 402 fallback path also stores a single cached signature:

267:   // Sign the payment
268:   try {
269:     const result = await signPayment({
270:       wallet,
271:       accept,
272:       resource: header.resource,
273:     });
279:     // Cache the freshly signed payment for subsequent calls
280:     paymentCache.signature = result.paymentSignatureBase64;
283:     const retryInit = injectPayment(originalInit, result.paymentSignatureBase64);
284:     return await baseFetch(url, retryInit);

The tool name extraction supports different tools/call requests in the same session:

303:     // Handle single request
304:     if (!Array.isArray(parsed)) {
305:       const req = parsed as JsonRpcRequest;
306:       if (req.method === 'tools/call' && req.params?.name) {
307:         return req.params.name;

The effective cache behavior appears to be:

first paid tool signs payment -> paymentCache.signature -> later paid tool reuses cached signature

I did not see the cache key include tool name, resource, amount, payee, network, asset, or scheme. This means a signature created for one paid tool can be injected into a later different paid tool call from the same session.

A strict server may reject the mismatch, but the client-side middleware still sends a stale proof for a different payment context. A safer design would cache by payment requirement identity, or avoid reusing a payment signature across tools/resources unless the server explicitly declares it reusable. I am reporting this as a potential issue rather than a confirmed exploit because server-side validation may fail closed.

chenshj73 avatar May 28 '26 11:05 chenshj73

cc @MQ37

jancurn avatar May 28 '26 11:05 jancurn

OK

chenshj73 avatar May 29 '26 03:05 chenshj73

Thanks! Happy to help if you or @MQ37 need more context — feel free to ping me.

chenshj73 avatar May 29 '26 03:05 chenshj73

Hey, this was deliberate decision to support x402 implementation for the mcp.apify.com and api.apify.com as the endpoints are reusing the token per each request - please see https://docs.apify.com/platform/integrations/x402.

We are planning major rework of the agentic payments for Apify where the user will instead of paying for each request/tool call pay for prepaid API token and then use API/MCP through the prepaid API token - we are still handling that internally. I will keep you posted.

MQ37 avatar Jun 01 '26 11:06 MQ37

So in the current implementation, the payment signature is essentially treated as a "session token" rather than a "per-call proof", correct?

chenshj73 avatar Jun 01 '26 11:06 chenshj73

@chenshj73 yes, exactly you can reuse the same payment signature for multiple requests/tools calls until you run out of the balance (1 USD minimum)

MQ37 avatar Jun 04 '26 10:06 MQ37

@chenshj73 Hey, recently we launched https://agi.apify.com/ which is currently the main entrypoint for AI agents into the Apify platform. So if you want to use agentic payments I recommend using this approach instead of the API directly. Here the agent buys full featured pre-paid API token through the agi.apify.com and then can use it freely via api.apify.com or mcp.apify.com with no limitations like the direct payment through api.apify.com had. Please see https://docs.apify.com/platform/integrations/x402

MQ37 avatar Jul 03 '26 11:07 MQ37

Session-level signature reuse across tool calls is a real footgun for x402.

Minimum safe rule: one authorization payload per canonical payment identity.

Canonicalize at least: toolName + resource/uri + scheme + network + asset + amount + payTo + (optional) challenge nonce

Cache key = hash of that tuple — not “session + toolName” and not “session only.”

If amount or payTo changes between calls (common for metered MCP tools), a reused signature either fails verify (good) or, worse, settles the wrong challenge if the facilitator is lenient. Prefer:

  • cache miss → fresh 402 challenge → fresh sign → settle
  • cache hit only when tuple matches and challenge not expired and not already settled

Idempotency key should ride with the payment hash so retries don’t double-settle.

Nauti-Labs does fixed-scope x402 payment-flow reviews (spend control + replay/cache safety): https://clearance.nauti-labs.com/agent-income/review — happy to include mcpc-style session middleware in the checklist if useful.

SpaceGravy avatar Jul 26 '26 06:07 SpaceGravy

Live seller — pay now (Base USDC)

Product Price Call
Payment Flow Review $199 GET http://bore.pub:63190/agent-income/review → HTTP 402
Bot directory lookup $0.02 POST http://bore.pub:63190/bot-comm/directory-lookup → HTTP 402
Free catalog $0 GET http://bore.pub:63190/bot-comm/api/services

PayTo: 0x369301753a2372304ba4e159bab852339d760989 (Base · USDC)
ENS: spacegravy.base.eth

Unpaid = 402 with quote. Pay exact amount → retry with X-Payment-Tx = tx hash.
Work starts only after on-chain verify. Fixed-scope spend-control / x402 payment-flow readiness — not open-ended consulting.

SpaceGravy avatar Jul 26 '26 06:07 SpaceGravy