From f4a9f1c35598ced658c74275c55b2f963ea989cc Mon Sep 17 00:00:00 2001 From: Samet Date: Tue, 24 Nov 2026 22:10:03 +0300 Subject: [PATCH] fix(appraisal-api): cap and sanitize appraisal request IDs --- services/appraisal-api/package.json | 2 +- services/appraisal-api/src/index.ts | 7 + services/appraisal-api/src/request-id.test.ts | 228 ++++++++++++++++++ services/appraisal-api/src/request-id.ts | 58 +++++ services/appraisal-api/src/server.ts | 65 +++-- 5 files changed, 344 insertions(+), 16 deletions(-) create mode 100644 services/appraisal-api/src/request-id.test.ts create mode 100644 services/appraisal-api/src/request-id.ts diff --git a/services/appraisal-api/package.json b/services/appraisal-api/package.json index 3f5a2ef4..f9125879 100644 --- a/services/appraisal-api/package.json +++ b/services/appraisal-api/package.json @@ -12,7 +12,7 @@ "main": "src/index.ts", "scripts": { "start": "node --import tsx src/run.ts", - "test": "node --import tsx --test src/appraisal.test.ts src/appraisal-fixtures.test.ts src/config.test.ts src/client.test.ts src/quote-guard.test.ts src/quote-rate-limit.test.ts src/body-limit.test.ts", + "test": "node --import tsx --test src/appraisal.test.ts src/appraisal-fixtures.test.ts src/config.test.ts src/client.test.ts src/quote-guard.test.ts src/quote-rate-limit.test.ts src/body-limit.test.ts src/request-id.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/services/appraisal-api/src/index.ts b/services/appraisal-api/src/index.ts index eeebc330..6f2d1679 100644 --- a/services/appraisal-api/src/index.ts +++ b/services/appraisal-api/src/index.ts @@ -24,6 +24,13 @@ export { withNonCacheableHeaders, type AppraisalServerOptions, } from "./server.js"; +export { + APPRAISAL_REQUEST_ID_HEADER, + MAX_APPRAISAL_REQUEST_ID_LENGTH, + isValidAppraisalRequestId, + readInboundAppraisalRequestId, + resolveAppraisalRequestId, +} from "./request-id.js"; export { AppraisalConfigError, configFromEnv, diff --git a/services/appraisal-api/src/request-id.test.ts b/services/appraisal-api/src/request-id.test.ts new file mode 100644 index 00000000..6945e72e --- /dev/null +++ b/services/appraisal-api/src/request-id.test.ts @@ -0,0 +1,228 @@ +// Copyright (c) 2026 Sub Rosa contributors +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { describe, test } from "node:test"; + +import { createLogger } from "@sub-rosa/logging"; +import { Keypair, Networks } from "@stellar/stellar-sdk"; +import { STELLAR_TESTNET_CAIP2, USDC_TESTNET_ADDRESS } from "@x402/stellar"; + +import { validRequest } from "./fixtures/index.js"; +import { + APPRAISAL_REQUEST_ID_HEADER, + MAX_APPRAISAL_REQUEST_ID_LENGTH, + isValidAppraisalRequestId, + readInboundAppraisalRequestId, + resolveAppraisalRequestId, +} from "./request-id.js"; +import { buildAppraisalServer } from "./server.js"; + +function listen(server: http.Server): Promise { + server.listen(0, "127.0.0.1"); + return once(server, "listening").then(() => { + const address = server.address(); + if (address === null || typeof address === "string") { + throw new Error("expected a TCP port"); + } + return address.port; + }); +} + +async function buildTestServer(options: Parameters[1] = {}) { + const facilitator = Keypair.fromRawEd25519Seed(Buffer.alloc(32, 3)); + const payee = Keypair.fromRawEd25519Seed(Buffer.alloc(32, 4)); + return buildAppraisalServer( + { + facilitatorSecret: facilitator.secret(), + payTo: payee.publicKey(), + asset: USDC_TESTNET_ADDRESS, + price: 0.1, + network: STELLAR_TESTNET_CAIP2, + networkPassphrase: Networks.TESTNET, + rpcUrl: "https://soroban-testnet.stellar.org", + port: 0, + }, + { nowSeconds: () => 1_700_000_000, ...options }, + ); +} + +describe("appraisal request id sanitization", () => { + test("documents and enforces the maximum header length", () => { + assert.equal(MAX_APPRAISAL_REQUEST_ID_LENGTH, 128); + assert.equal(isValidAppraisalRequestId("a".repeat(128)), true); + assert.equal(isValidAppraisalRequestId("a".repeat(129)), false); + }); + + test("preserves printable safe ids up to the cap", () => { + const safe = [ + "request-123", + "trace_01HZX.abc-def", + "550e8400-e29b-41d4-a716-446655440000", + "a".repeat(MAX_APPRAISAL_REQUEST_ID_LENGTH), + ]; + for (const id of safe) { + assert.equal(resolveAppraisalRequestId(id, () => "generated"), id); + } + }); + + test("replaces missing, overlong, or control-character values with a server id", () => { + const generated = "server-generated-id"; + const unsafe = [ + undefined, + "", + 123, + ["a", "b"], + "line\nforged", + "line\rforged", + "column\tforged", + "ansi\x1b[31m", + "nul\u0000byte", + "id with space", + "id/slash", + "a".repeat(MAX_APPRAISAL_REQUEST_ID_LENGTH + 1), + ]; + for (const value of unsafe) { + assert.equal(resolveAppraisalRequestId(value, () => generated), generated); + } + }); + + test("reads the first inbound x-request-id header value", () => { + assert.equal( + readInboundAppraisalRequestId({ [APPRAISAL_REQUEST_ID_HEADER]: "abc-123" }), + "abc-123", + ); + assert.equal( + readInboundAppraisalRequestId({ [APPRAISAL_REQUEST_ID_HEADER]: ["first", "second"] }), + "first", + ); + assert.equal(readInboundAppraisalRequestId({}), undefined); + }); +}); + +describe("appraisal request id response headers", () => { + test("echoes a safe inbound x-request-id on quotes and errors", async () => { + const inbound = "client-trace-01"; + const server = await buildTestServer(); + const port = await listen(server); + try { + const challenge = await fetch(`http://127.0.0.1:${port}/appraise`, { + method: "POST", + headers: { + "content-type": "application/json", + [APPRAISAL_REQUEST_ID_HEADER]: inbound, + }, + body: JSON.stringify(validRequest.value), + }); + assert.equal(challenge.status, 402); + assert.equal(challenge.headers.get(APPRAISAL_REQUEST_ID_HEADER), inbound); + + const bad = await fetch(`http://127.0.0.1:${port}/appraise`, { + method: "POST", + headers: { + "content-type": "application/json", + [APPRAISAL_REQUEST_ID_HEADER]: inbound, + }, + body: "", + }); + assert.equal(bad.status, 400); + assert.equal(bad.headers.get(APPRAISAL_REQUEST_ID_HEADER), inbound); + + const health = await fetch(`http://127.0.0.1:${port}/healthz`, { + headers: { [APPRAISAL_REQUEST_ID_HEADER]: inbound }, + }); + assert.equal(health.status, 200); + assert.equal(health.headers.get(APPRAISAL_REQUEST_ID_HEADER), inbound); + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); + + test("replaces unsafe inbound ids (spaces, overlong) in the response header", async () => { + const generated = "safe-server-id"; + const server = await buildTestServer({ generateRequestId: () => generated }); + const port = await listen(server); + try { + for (const unsafe of ["id with space", "a".repeat(MAX_APPRAISAL_REQUEST_ID_LENGTH + 1)]) { + const challenge = await fetch(`http://127.0.0.1:${port}/appraise`, { + method: "POST", + headers: { + "content-type": "application/json", + [APPRAISAL_REQUEST_ID_HEADER]: unsafe, + }, + body: JSON.stringify(validRequest.value), + }); + assert.equal(challenge.status, 402); + assert.equal(challenge.headers.get(APPRAISAL_REQUEST_ID_HEADER), generated); + } + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); +}); + +describe("appraisal request id logging", () => { + test("structured logs record the safe server id, never unsafe inbound content", () => { + const unsafe = "attacker\nforged-log-entry"; + const generated = "safe-server-id"; + const lines: string[] = []; + const logger = createLogger("appraisal-api.server.test", { + sink: (line) => { + lines.push(line); + }, + }); + + const requestId = resolveAppraisalRequestId(unsafe, () => generated); + assert.equal(requestId, generated); + + // Mirrors the server catch path: log.error("request-failed", err, { requestId }). + logger.error("request-failed", "forced-handler-failure", { requestId }); + + assert.equal(lines.length, 1); + const record = JSON.parse(lines[0]!) as { + event: string; + context: { requestId: string }; + }; + assert.equal(record.event, "request-failed"); + assert.equal(record.context.requestId, generated); + assert.ok(!lines[0]!.includes("forged-log-entry")); + assert.ok(!lines[0]!.includes("attacker")); + }); + + test("server 402 path never echoes an overlong inbound id into logs via headers", async () => { + const unsafe = "a".repeat(MAX_APPRAISAL_REQUEST_ID_LENGTH + 1); + const generated = "safe-server-id"; + const lines: string[] = []; + const logger = createLogger("appraisal-api.server.test", { + sink: (line) => { + lines.push(line); + }, + }); + const server = await buildTestServer({ + generateRequestId: () => generated, + logger, + }); + const port = await listen(server); + try { + const challenge = await fetch(`http://127.0.0.1:${port}/appraise`, { + method: "POST", + headers: { + "content-type": "application/json", + [APPRAISAL_REQUEST_ID_HEADER]: unsafe, + }, + body: JSON.stringify(validRequest.value), + }); + assert.equal(challenge.status, 402); + assert.equal(challenge.headers.get(APPRAISAL_REQUEST_ID_HEADER), generated); + // No request-failed log on the happy 402 path; confirm nothing logged the overlong id. + for (const line of lines) { + assert.ok(!line.includes(unsafe)); + } + } finally { + server.closeAllConnections?.(); + server.close(); + } + }); +}); diff --git a/services/appraisal-api/src/request-id.ts b/services/appraisal-api/src/request-id.ts new file mode 100644 index 00000000..e2626e0c --- /dev/null +++ b/services/appraisal-api/src/request-id.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 Sub Rosa contributors +import { randomUUID } from "node:crypto"; +import type { IncomingHttpHeaders } from "node:http"; + +/** + * Canonical response/request header for appraisal quote correlation. + * Clients may send it; the server always echoes a safe id back. + */ +export const APPRAISAL_REQUEST_ID_HEADER = "x-request-id"; + +/** + * Maximum accepted inbound request-id length. + * + * 128 characters fits UUIDv4, common tracing ids, and short vendor prefixes + * while bounding log amplification if a client sends a multi-kilobyte header. + */ +export const MAX_APPRAISAL_REQUEST_ID_LENGTH = 128; + +/** Safe-by-construction charset: alphanumerics plus `.`, `_`, `-`. */ +const REQUEST_ID_PATTERN = /^[A-Za-z0-9._-]+$/; + +/** + * Whether a value is safe to reuse as an appraisal request id. + * + * Rejects missing/empty values, oversize strings, arrays (multi-header), + * and any character outside the documented safe charset — including + * whitespace and control characters that would corrupt quote tracing logs. + */ +export function isValidAppraisalRequestId(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= MAX_APPRAISAL_REQUEST_ID_LENGTH && + REQUEST_ID_PATTERN.test(value) + ); +} + +/** Read the first inbound `x-request-id` value from Node headers. */ +export function readInboundAppraisalRequestId( + headers: IncomingHttpHeaders, +): string | undefined { + const raw = headers[APPRAISAL_REQUEST_ID_HEADER]; + if (Array.isArray(raw)) return raw[0]; + return raw; +} + +/** + * Resolve a log- and header-safe appraisal request id. + * + * Reuses a valid inbound `x-request-id`; otherwise generates a server id + * (default: `randomUUID`). Invalid inbound values are never echoed or logged. + */ +export function resolveAppraisalRequestId( + inbound: unknown, + generate: () => string = randomUUID, +): string { + return isValidAppraisalRequestId(inbound) ? inbound : generate(); +} diff --git a/services/appraisal-api/src/server.ts b/services/appraisal-api/src/server.ts index 566e099a..eb59afc9 100644 --- a/services/appraisal-api/src/server.ts +++ b/services/appraisal-api/src/server.ts @@ -47,6 +47,11 @@ import { type QuoteRateLimitDecision, type QuoteRateLimiter, } from "./quote-rate-limit.js"; +import { + APPRAISAL_REQUEST_ID_HEADER, + readInboundAppraisalRequestId, + resolveAppraisalRequestId, +} from "./request-id.js"; const APPRAISE_ROUTE = "POST /appraise"; @@ -89,6 +94,10 @@ export interface AppraisalServerOptions { quoteRateLimiter?: QuoteRateLimiter; /** Client key for the quote limiter. Defaults to the socket address. */ quoteRateKey?: (req: http.IncomingMessage) => string; + /** Optional request-id generator (defaults to `randomUUID`). */ + generateRequestId?: () => string; + /** Optional logger override (used by deterministic unit tests). */ + logger?: ReturnType; } /** Minimal HTTPAdapter over a Node request + already-read body. */ @@ -113,29 +122,44 @@ function makeAdapter( }; } +function withRequestIdHeaders( + requestId: string, + headers: Record = {}, +): Record { + return { + ...withNonCacheableHeaders(headers), + [APPRAISAL_REQUEST_ID_HEADER]: requestId, + }; +} + function send( res: http.ServerResponse, status: number, headers: Record, body: unknown, + requestId: string, ) { const payload = typeof body === "string" ? body : JSON.stringify(body ?? {}, null, 2); res.writeHead(status, { "content-type": "application/json", - ...withNonCacheableHeaders(headers), + ...withRequestIdHeaders(requestId, headers), }); res.end(payload); } -function writeInstructions(res: http.ServerResponse, i: HTTPResponseInstructions) { +function writeInstructions( + res: http.ServerResponse, + i: HTTPResponseInstructions, + requestId: string, +) { const body = i.isHtml || typeof i.body === "string" ? (i.body as string) : JSON.stringify(i.body ?? {}, null, 2); res.writeHead(i.status, { "content-type": i.isHtml ? "text/html" : "application/json", - ...withNonCacheableHeaders(i.headers), + ...withRequestIdHeaders(requestId, i.headers), }); res.end(body ?? ""); } @@ -197,14 +221,19 @@ export async function buildAppraisalServer( const quoteLimiter = options.quoteRateLimiter ?? createMemoryQuoteRateLimiter(DEVELOPMENT_QUOTE_RATE_LIMIT); const quoteRateKey = options.quoteRateKey ?? appraisalQuoteRateKey; + const log = options.logger ?? diagnostics; return http.createServer(async (req, res) => { + const requestId = resolveAppraisalRequestId( + readInboundAppraisalRequestId(req.headers), + options.generateRequestId, + ); try { const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`); const method = req.method ?? "GET"; if (method === "GET" && url.pathname === "/healthz") { - return send(res, 200, {}, { ok: true, service: "sub-rosa-appraisal" }); + return send(res, 200, {}, { ok: true, service: "sub-rosa-appraisal" }, requestId); } if (method === "GET" && url.pathname === "/") { return send(res, 200, {}, { @@ -213,13 +242,13 @@ export async function buildAppraisalServer( asset: config.asset, price: config.price, network: config.network, - }); + }, requestId); } const taken = await takeAppraisalRequestBody(req, MAX_APPRAISAL_BODY_BYTES); if ("status" in taken) { // Fail closed before JSON parsing and before any payment offer. - send(res, taken.status, {}, taken.body); + send(res, taken.status, {}, taken.body, requestId); res.on("finish", () => req.destroy()); return; } @@ -229,11 +258,11 @@ export async function buildAppraisalServer( try { parsedBody = JSON.parse(rawBody.toString("utf8")); } catch { - return send(res, 400, {}, { error: "invalid JSON body" }); + return send(res, 400, {}, { error: "invalid JSON body" }, requestId); } } else if (method === "POST" && url.pathname === "/appraise") { // Empty POST bodies are a stable 400 — never a 402, never a settlement. - return send(res, 400, {}, { error: "Invalid appraisal request" }); + return send(res, 400, {}, { error: "Invalid appraisal request" }, requestId); } const adapter = makeAdapter(req, url, parsedBody); @@ -247,10 +276,10 @@ export async function buildAppraisalServer( const result = await httpServer.processHTTPRequest(ctx); if (result.type === "no-payment-required") { - return send(res, 404, {}, { error: "not found" }); + return send(res, 404, {}, { error: "not found" }, requestId); } if (result.type === "payment-error") { - return writeInstructions(res, result.response); + return writeInstructions(res, result.response, requestId); } // result.type === "payment-verified": funds are authorized but not yet @@ -273,6 +302,7 @@ export async function buildAppraisalServer( 429, { "retry-after": String(retryAfterSeconds) }, { error: "appraisal quote rate limit exceeded" }, + requestId, ); } @@ -292,7 +322,7 @@ export async function buildAppraisalServer( }; } catch (e) { if (e instanceof AppraisalInputError) { - return send(res, 400, {}, { error: "Invalid appraisal request" }); + return send(res, 400, {}, { error: "Invalid appraisal request" }, requestId); } throw e; } @@ -302,11 +332,15 @@ export async function buildAppraisalServer( result.paymentPayload as PaymentPayload, result.paymentRequirements as PaymentRequirements, result.declaredExtensions, - { request: ctx, responseBody, responseHeaders: withNonCacheableHeaders() }, + { + request: ctx, + responseBody, + responseHeaders: withRequestIdHeaders(requestId), + }, ); if (!settle.success) { - return writeInstructions(res, settle.response); + return writeInstructions(res, settle.response, requestId); } return send( res, @@ -320,10 +354,11 @@ export async function buildAppraisalServer( payer: settle.payer, }, }, + requestId, ); } catch (err) { - diagnostics.error("request-failed", normalizeError(err)); - send(res, 500, {}, { error: publicErrorMessage(err) }); + log.error("request-failed", normalizeError(err), { requestId }); + send(res, 500, {}, { error: publicErrorMessage(err) }, requestId); } }); }