diff --git a/.github/scripts/pr-verify/key-proxy.mjs b/.github/scripts/pr-verify/key-proxy.mjs new file mode 100644 index 00000000000..7acccdef392 --- /dev/null +++ b/.github/scripts/pr-verify/key-proxy.mjs @@ -0,0 +1,641 @@ +// The key proxy: the only path from pr-verify's driven Claude Code to the +// Messages API. It runs as its own OS user, holds the real key (read from +// stdin, never argv or env) and listens on a unix socket, so pull request code +// in the no-network sandbox never sees the key. Every request passes an +// ordered pipeline of checks (path, query, size, parse, body keys, model, +// max_tokens, betas, server tools, content, count_tokens limits, in-flight +// slot, cap reservation). One that passes goes upstream as the re-serialized +// checked object with the client's credential replaced, and the response is +// relayed as it arrives. One budget holds the committed and in-flight reserved +// tokens, so concurrent requests cannot pass the per-job cap together; each +// /v1/messages reservation is the upstream's own count_tokens figure for the +// request plus its max_tokens. +// +// node key-proxy.mjs --socket --config [--upstream ] < key +// +// Config (JSON, read from the base branch by the workflow, never the head): +// tokenCap per-job token budget (input, cache and output tokens) +// models model ids the driven session may use +// maxTokensCeiling largest max_tokens a /v1/messages request may ask for +// maxBodyBytes largest request body accepted +// maxInFlight concurrent forwarded requests, count_tokens included +// maxCountTokensRequests client count_tokens requests allowed per job +// betas anthropic-beta values a request may name +// bodyKeys top-level request body keys a request may carry +// blockTypes content block types allowed in messages and system +// upstreamTimeoutMs idle time after which a stalled upstream request is aborted; +// set it longer than the longest non-streaming generation and +// the longest gap between SSE pings. Claude Code's own +// API_TIMEOUT_MS bounds only the time to response headers. +// Pointer: https://code.claude.com/docs/en/errors#tune-retry-behavior +// As of: 2026-11-06. Recheck trigger: the API_TIMEOUT_MS row changes. +// upstream API base URL (default https://api.anthropic.com) +// socketMode octal mode set on the socket after listen, e.g. "660" +// +// It logs one JSON line per request to stderr: method, path without query, +// status and token counts, and for a beta refusal the refused beta names, so a +// failed capture says what to add to `betas`. Never the key, any other header +// value, or a body. +import { chmodSync, readFileSync, rmSync } from "node:fs"; +import http from "node:http"; +import https from "node:https"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; + +export const ALLOWED_PATHS = Object.freeze(["/v1/messages", "/v1/messages/count_tokens"]); +const COUNT_TOKENS = "/v1/messages/count_tokens"; +const DEFAULT_UPSTREAM = "https://api.anthropic.com"; +// The one query the driven session sends; any other is refused (our decision). +const ALLOWED_QUERY = "beta=true"; +// Request headers forwarded upstream (our allowlist): the API version and +// betas, session attribution, accept and user-agent. The client's +// accept-encoding is never forwarded; every upstream request asks for +// identity instead, because the proxy reads usage from the bytes it relays +// and relays them untouched (our decision). A request with no Accept-Encoding +// would accept any coding. +// Pointer: https://www.rfc-editor.org/rfc/rfc9110#section-12.5.3 +// As of: 2026-11-06. Recheck trigger: an RFC obsoletes RFC 9110's Accept-Encoding section. +const FORWARD_NAMED = new Set(["anthropic-version", "anthropic-beta", "accept", "user-agent"]); +const FORWARD_PREFIX = /^x-claude-code-/; +// Response headers relayed to the client (our allowlist). +const RELAY_NAMED = new Set(["content-type", "cache-control", "request-id", "x-should-retry", "retry-after"]); +const RELAY_PREFIX = /^anthropic-ratelimit-/; +// Content sources that carry their data inline in the request. A url or file +// source names data held elsewhere, so it is refused (our decision). +const SOURCE_TYPES = Object.freeze(["base64", "text", "content"]); +// Refused beta names logged and returned, at most (our decision); the header +// is client-controlled. +const MAX_NAMED_BETAS = 10; +// How long an oversized upload is drained after its 413 before the socket is closed. +const DRAIN_MS = 10_000; +// Body fields the count_tokens preflight forwards. +// Pointer: https://platform.claude.com/docs/en/api/messages-count-tokens (Body parameters) +// As of: 2026-11-06. Recheck trigger: that section adds or removes a parameter. +const COUNT_TOKENS_FIELDS = Object.freeze(["messages", "model", "cache_control", "output_config", "speed", "system", "thinking", "tool_choice", "tools"]); +// Counted toward the cap. Cache reads and writes are counted in full: the cap +// is a token count, not a price (our decision). +const USAGE_FIELDS = ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"]; + +// Refusal statuses Claude Code does not retry. Every refusal carries +// `x-should-retry: false`, which Claude Code reads as not retryable. The cap +// refusal is a 429 shaped like a gateway spend limit, which Claude Code shows +// without retrying; a policy refusal is a 403 and an oversized body a 413, +// neither in the automatic-retry list (the 403 retry there needs an +// apiKeyHelper, which the driven session does not use). Not 400 or 422, which +// Claude Code may resend after once when it does not recognize the cause. +// An upstream failure (no answer, a connection dropped before any response +// byte, a stall) is the opposite: a 502 with `x-should-retry: true`, a server +// error before anything streamed, which Claude Code retries with backoff. +// Pointer: https://code.claude.com/docs/en/llm-gateway-protocol#response-headers (x-should-retry row), +// https://code.claude.com/docs/en/llm-gateway-protocol#retry-without-tool-search, +// https://code.claude.com/docs/en/errors#automatic-retries, +// https://code.claude.com/docs/en/errors#spend-limit-reached +// As of: 2026-11-06 (Claude Code 2.1.318). +// Recheck trigger: the automatic-retries lists, the x-should-retry row, the +// tool-search retry or the spend-limit section changes. +const refuse = (status, type, message) => ({ status, type, message }); +const policy = (message) => refuse(403, "permission_error", message); +const spendLimit = (what) => refuse(429, "rate_limit_error", `spend limit reached (${what})`); +const retryable = (message) => ({ ...refuse(502, "api_error", message), retry: true }); +const UPSTREAM_TIMEOUT = "UPSTREAM_TIMEOUT"; +const upstreamFailure = (err) => retryable(err?.code === UPSTREAM_TIMEOUT ? "upstream timed out" : "upstream unreachable"); +const clip = (v) => String(v).slice(0, 80); + +const stringList = (c, name) => { + if (!Array.isArray(c[name]) || !c[name].every((m) => typeof m === "string" && m)) throw new Error(`config ${name} must be a list of strings`); + return Object.freeze([...c[name]]); +}; + +export function loadConfig(raw, upstreamOverride) { + const c = typeof raw === "string" ? JSON.parse(raw) : raw; + const positiveInt = (name) => { + if (!Number.isInteger(c[name]) || c[name] <= 0) throw new Error(`config ${name} must be a positive integer`); + return c[name]; + }; + const nonEmpty = (name) => { + const list = stringList(c, name); + if (list.length === 0) throw new Error(`config ${name} must not be empty`); + return list; + }; + const upstream = new URL(upstreamOverride ?? c.upstream ?? DEFAULT_UPSTREAM); + if (upstream.protocol !== "https:" && upstream.protocol !== "http:") throw new Error("config upstream must be an http(s) URL"); + if (c.socketMode !== undefined && !/^[0-7]{3,4}$/.test(String(c.socketMode))) throw new Error("config socketMode must be an octal string"); + return Object.freeze({ + tokenCap: positiveInt("tokenCap"), + models: nonEmpty("models"), + maxTokensCeiling: positiveInt("maxTokensCeiling"), + maxBodyBytes: positiveInt("maxBodyBytes"), + maxInFlight: positiveInt("maxInFlight"), + maxCountTokensRequests: positiveInt("maxCountTokensRequests"), + upstreamTimeoutMs: positiveInt("upstreamTimeoutMs"), + betas: stringList(c, "betas"), + bodyKeys: nonEmpty("bodyKeys"), + blockTypes: nonEmpty("blockTypes"), + upstream, + socketMode: c.socketMode === undefined ? undefined : parseInt(String(c.socketMode), 8), + }); +} + +// Committed tokens (used, or charged on an abandoned response) plus tokens +// reserved by requests in flight. A reservation settles exactly once. +export function createBudget(cap) { + let committed = 0; + let reserved = 0; + return { + get cap() { return cap; }, + get committed() { return committed; }, + get reserved() { return reserved; }, + reserve(tokens) { + if (committed + reserved + tokens > cap) return null; + reserved += tokens; + let settled = false; + return { + tokens, + settle(used) { + if (settled) return; + settled = true; + reserved -= tokens; + committed += used; + }, + }; + }, + }; +} + +// Final usage of one response. message_delta usage is cumulative, so a later +// value replaces an earlier one field by field; message_start and +// message_delta are never added together. +// Pointer: https://platform.claude.com/docs/en/build-with-claude/streaming#event-types +// As of: 2026-11-06. Recheck trigger: that section changes what message_delta usage holds. +export function createUsageMeter(streaming) { + const usage = {}; + let seen = false; + let sawDelta = false; + let pending = ""; + let whole = []; + const take = (u) => { + if (!u || typeof u !== "object") return; + for (const f of USAGE_FIELDS) { + if (Number.isFinite(u[f])) { + usage[f] = u[f]; + seen = true; + } + } + }; + const line = (l) => { + if (!l.startsWith("data:")) return; + let event; + try { event = JSON.parse(l.slice(5)); } catch { return; } + if (event?.type === "message_start") take(event.message?.usage); + else if (event?.type === "message_delta") { + sawDelta = true; + take(event.usage); + } + }; + return { + feed(chunk) { + if (!streaming) { + whole.push(chunk); + return; + } + pending += chunk.toString("utf8"); + const lines = pending.split("\n"); + pending = lines.pop(); + for (const l of lines) line(l.replace(/\r$/, "")); + }, + end() { + if (streaming) { + if (pending) line(pending.replace(/\r$/, "")); + pending = ""; + } else if (whole.length) { + try { take(JSON.parse(Buffer.concat(whole).toString("utf8"))?.usage); } catch { /* not JSON: no usage */ } + whole = []; + } + }, + get seen() { return seen; }, + get sawDelta() { return sawDelta; }, + total() { return USAGE_FIELDS.reduce((sum, f) => sum + (usage[f] ?? 0), 0); }, + }; +} + +// Content blocks in messages and system, walked at every depth through a +// block's `content` and a content-type source's `content` (the nesting this +// proxy checks, our decision). We do not walk tool_use input or tool schemas: +// we treat them as data the model or tool definition supplies, and checking +// their `type` keys as block types would refuse ordinary JSON (our decision). +function contentRefusal(content, config) { + const stack = [content]; + while (stack.length) { + const list = stack.pop(); + if (typeof list === "string") continue; + if (!Array.isArray(list)) return policy("content must be a string or a list of blocks"); + for (const b of list) { + if (!b || typeof b !== "object" || !config.blockTypes.includes(b.type)) { + return policy(`content block type not allowed through this proxy: ${clip(b?.type)}`); + } + if (b.source !== undefined) { + if (!b.source || typeof b.source !== "object" || !SOURCE_TYPES.includes(b.source.type)) { + return policy(`content source type not allowed through this proxy: ${clip(b.source?.type)}`); + } + if (b.source.type === "content") stack.push(b.source.content); + } + if (b.content !== undefined) stack.push(b.content); + } + } + return null; +} + +const decoder = new TextDecoder("utf-8", { fatal: true }); + +// The ordered pipeline. Each check returns null (allow) or a refusal, or a +// promise of one. Size is enforced as the body arrives (see createProxy). +export const CHECKS = Object.freeze([ + function path(ctx) { + return ctx.method === "POST" && ALLOWED_PATHS.includes(ctx.path) ? null : refuse(404, "not_found_error", "not found"); + }, + function query(ctx) { + return ctx.query === undefined || ctx.query === ALLOWED_QUERY ? null : policy("query string not allowed through this proxy"); + }, + function parse(ctx) { + try { ctx.body = JSON.parse(decoder.decode(ctx.raw)); } catch { return refuse(400, "invalid_request_error", "request body is not UTF-8 JSON"); } + return ctx.body && typeof ctx.body === "object" && !Array.isArray(ctx.body) ? null : refuse(400, "invalid_request_error", "request body is not a JSON object"); + }, + function bodyKeys(ctx) { + const extra = Object.keys(ctx.body).find((k) => !ctx.config.bodyKeys.includes(k)); + return extra === undefined ? null : policy(`body field not allowed through this proxy: ${clip(extra)}`); + }, + function model(ctx) { + return ctx.config.models.includes(ctx.body.model) ? null : policy(`model not allowed through this proxy: ${clip(ctx.body.model)}`); + }, + function maxTokens(ctx) { + if (ctx.path === COUNT_TOKENS) return null; + const m = ctx.body.max_tokens; + if (!Number.isInteger(m) || m <= 0) return policy("max_tokens is required"); + return m > ctx.config.maxTokensCeiling ? policy(`max_tokens exceeds this proxy's ceiling of ${ctx.config.maxTokensCeiling}`) : null; + }, + function betas(ctx) { + const header = ctx.headers["anthropic-beta"]; + if (header === undefined) return null; + const unknown = [...new Set(String(header).split(",").map((b) => b.trim()).filter((b) => b && !ctx.config.betas.includes(b)))]; + if (unknown.length === 0) return null; + const named = unknown.slice(0, MAX_NAMED_BETAS).map(clip); + const more = unknown.length > named.length ? ` (+${unknown.length - named.length} more)` : ""; + return { + ...policy(`anthropic-beta values not allowed through this proxy: ${named.join(", ")}${more}; add them to the config betas list to allow them`), + log: { betas: named }, + }; + }, + // Server tools run inside the API with the held key, so a tools[] entry is + // allowed only as a custom tool (no type, or type "custom"), which fails + // closed on any new server tool type (our decision). + // Pointer: https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#the-server-tool-use-block + // As of: 2026-11-06. Recheck trigger: that section stops saying the API runs the tool. + function serverTools(ctx) { + const { body } = ctx; + if (body.mcp_servers !== undefined) return policy("mcp_servers is not allowed through this proxy"); + if (body.tools !== undefined && !Array.isArray(body.tools)) return policy("tools must be a list"); + for (const t of body.tools ?? []) { + if (!t || typeof t !== "object" || Array.isArray(t)) return policy("tools entries must be objects"); + if (t.type !== undefined && t.type !== "custom") return policy(`server tools are not allowed through this proxy: ${clip(t.type)}`); + } + return null; + }, + function content(ctx) { + const { body, config } = ctx; + if (!Array.isArray(body.messages)) return policy("messages must be a list"); + for (const m of body.messages) { + if (!m || typeof m !== "object") return policy("messages must be objects"); + const r = contentRefusal(m.content, config); + if (r) return r; + } + return body.system === undefined ? null : contentRefusal(body.system, config); + }, + // Client count_tokens is not counted toward the cap, since token counting + // is free, so it is limited per job and stops once the cap is spent, and + // cannot be used as an unmetered channel (our decision). + // Pointer: https://platform.claude.com/docs/en/build-with-claude/token-counting#pricing-and-rate-limits + // As of: 2026-11-06. Recheck trigger: that section stops calling token counting free. + function countTokensLimits(ctx) { + if (ctx.path !== COUNT_TOKENS) return null; + if (ctx.budget.committed >= ctx.budget.cap) return spendLimit("per-job token cap"); + if (ctx.state.countTokensRequests >= ctx.config.maxCountTokensRequests) return policy("count_tokens request limit reached for this job"); + ctx.state.countTokensRequests += 1; + return null; + }, + function inFlight(ctx) { + if (ctx.state.inFlight >= ctx.config.maxInFlight) return policy("too many requests in flight through this proxy"); + ctx.state.inFlight += 1; + let released = false; + ctx.release = () => { + if (released) return; + released = true; + ctx.state.inFlight -= 1; + }; + return null; + }, + async function cap(ctx) { + if (ctx.path === COUNT_TOKENS) return null; + const pre = await ctx.preflight(ctx); + // A failure the client would retry against the API itself (a 429 or a + // 5xx, relayed as sent; no answer, as a retryable 502) goes back to the + // client so Claude Code's own retry covers it; any other failure is a + // refusal it does not retry (our decision). See the refusal-status + // pointer above (errors#automatic-retries). + if (pre.relay) return { relay: pre.relay, status: pre.relay.status, type: "relayed" }; + if (pre.refusal) return pre.refusal; + const input = pre.input; + if (!Number.isInteger(input) || input < 0) return policy("token count preflight failed"); + ctx.reservation = ctx.budget.reserve(input + ctx.body.max_tokens); + return ctx.reservation ? null : spendLimit("per-job token cap"); + }, +]); + +export async function runChecks(ctx) { + for (const check of CHECKS) { + const r = await check(ctx); + if (r) return r; + } + return null; +} + +const sendRefusal = (res, r) => { + const body = JSON.stringify({ type: "error", error: { type: r.type, message: r.message } }); + res.writeHead(r.status, { "content-type": "application/json", "x-should-retry": r.retry ? "true" : "false", "content-length": Buffer.byteLength(body), ...(r.status === 413 ? { connection: "close" } : {}) }); + res.end(body); +}; + +const forwardHeaders = (incoming, key, length) => { + const out = {}; + for (const [name, value] of Object.entries(incoming)) { + if (FORWARD_NAMED.has(name) || FORWARD_PREFIX.test(name)) out[name] = value; + } + out["content-type"] = "application/json"; + out["accept-encoding"] = "identity"; + out["x-api-key"] = key; + out["content-length"] = String(length); + return out; +}; + +const relayHeaders = (incoming) => Object.fromEntries(Object.entries(incoming).filter(([name]) => RELAY_NAMED.has(name) || RELAY_PREFIX.test(name))); + +export function createProxy({ key, config, log = () => {} }) { + if (typeof key !== "string" || !key) throw new Error("key is required"); + const budget = createBudget(config.tokenCap); + const state = { inFlight: 0, countTokensRequests: 0 }; + const lib = config.upstream.protocol === "https:" ? https : http; + const basePath = config.upstream.pathname.replace(/\/$/, ""); + const upstreamPath = (ctx, path) => basePath + path + (ctx.query === ALLOWED_QUERY ? `?${ALLOWED_QUERY}` : ""); + // An upstream socket idle for upstreamTimeoutMs, before or during the + // response, is destroyed with an UPSTREAM_TIMEOUT error. + const upstreamRequest = (ctx, path, body, onResponse) => { + const req = lib.request({ + protocol: config.upstream.protocol, + hostname: config.upstream.hostname, + port: config.upstream.port || undefined, + method: "POST", + path: upstreamPath(ctx, path), + headers: forwardHeaders(ctx.headers, key, body.length), + timeout: config.upstreamTimeoutMs, + }, onResponse); + req.on("timeout", () => req.destroy(Object.assign(new Error("upstream timed out"), { code: UPSTREAM_TIMEOUT }))); + return req; + }; + + // The upstream's own input count for the checked request: { input }, or + // { relay } for a 429 or 5xx answer, { refusal } for no answer, or {} for + // any other failure. The first resolve wins. + const preflight = (ctx) => new Promise((resolve) => { + const subset = Object.fromEntries(COUNT_TOKENS_FIELDS.filter((f) => ctx.body[f] !== undefined).map((f) => [f, ctx.body[f]])); + const body = Buffer.from(JSON.stringify(subset)); + const failed = (err) => resolve({ refusal: upstreamFailure(err) }); + const req = upstreamRequest(ctx, COUNT_TOKENS, body, (res) => { + const chunks = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => { + const raw = Buffer.concat(chunks); + if (res.statusCode === 429 || res.statusCode >= 500) return resolve({ relay: { status: res.statusCode, headers: relayHeaders(res.headers), body: raw } }); + if (res.statusCode !== 200) return resolve({}); + try { resolve({ input: JSON.parse(raw.toString("utf8")).input_tokens }); } catch { resolve({}); } + }); + res.on("error", failed); + res.on("close", () => failed()); + }); + req.on("error", failed); + req.end(body); + }); + + const server = http.createServer((req, res) => { + const q = req.url.indexOf("?"); + const path = q < 0 ? req.url : req.url.slice(0, q); + const query = q < 0 ? undefined : req.url.slice(q + 1); + const chunks = []; + let bytes = 0; + let tooLarge = false; + let clientGone = false; + res.on("close", () => { clientGone = true; }); + const done = (status, extra = {}) => log({ method: req.method, path, status, ...extra }); + + req.on("data", (c) => { + if (tooLarge) return; + bytes += c.length; + if (bytes <= config.maxBodyBytes) { + chunks.push(c); + return; + } + tooLarge = true; + // Read and drop the rest, answering the 413 once the body ends: the server closes a + // `connection: close` socket when the response ends, so answering now would leave a client + // still uploading with a reset, which it retries. A client still sending after DRAIN_MS gets + // the 413 and the socket is closed (our decision: the drain stays bounded). + drainTimer = setTimeout(() => { refuseTooLarge(); req.destroy(); }, DRAIN_MS); + drainTimer.unref(); + }); + let drainTimer; + let answered = false; + const refuseTooLarge = () => { + if (answered) return; + answered = true; + clearTimeout(drainTimer); + sendRefusal(res, refuse(413, "request_too_large", "request body exceeds the proxy's size limit")); + done(413, { refused: "request_too_large" }); + }; + req.on("end", async () => { + if (tooLarge) return refuseTooLarge(); + const ctx = { method: req.method, path, query, headers: req.headers, raw: Buffer.concat(chunks), config, budget, state, preflight }; + try { + await handle(ctx); + } catch (err) { + // A throw here (a body that passes the checks but breaks re-serialization, or a bug in a + // check) must not end the process the whole capture job depends on. Nothing went upstream + // on this path, so the reservation is released (our decision). + ctx.reservation?.settle(0); + ctx.release?.(); + if (!clientGone && !res.headersSent) sendRefusal(res, refuse(400, "invalid_request_error", "the proxy could not process this request")); + else if (!res.writableEnded) res.destroy(); + done(400, { refused: "proxy_error", error: String(err?.name ?? "Error"), committed: budget.committed }); + } + }); + + async function handle(ctx) { + const refusal = await runChecks(ctx); + if (refusal) { + ctx.release?.(); + if (!clientGone && refusal.relay) { + res.writeHead(refusal.relay.status, { ...refusal.relay.headers, "content-length": refusal.relay.body.length }); + res.end(refusal.relay.body); + } else if (!clientGone) sendRefusal(res, refusal); + done(refusal.status, { refused: refusal.type, ...refusal.log, committed: budget.committed }); + return; + } + if (clientGone) { + ctx.reservation?.settle(0); + ctx.release(); + done(499, { committed: budget.committed }); + return; + } + forward(res, ctx, done); + } + }); + + function forward(res, ctx, done) { + const { reservation } = ctx; + const reserved = reservation?.tokens ?? 0; + let meter = null; + let finished = false; + const settle = (used) => { + reservation?.settle(used); + ctx.release(); + done(res.statusCode, { reserved, used, committed: budget.committed }); + }; + const abandoned = () => Math.max(reserved, meter?.total() ?? 0); + // Upstream sees exactly the object the checks passed. + const body = Buffer.from(JSON.stringify(ctx.body)); + + const upReq = upstreamRequest(ctx, ctx.path, body, (upRes) => { + const streaming = /^text\/event-stream/i.test(upRes.headers["content-type"] ?? ""); + meter = createUsageMeter(streaming); + res.writeHead(upRes.statusCode, relayHeaders(upRes.headers)); + res.flushHeaders(); + upRes.on("data", (c) => { + meter.feed(c); + res.write(c); + }); + upRes.on("end", () => { + finished = true; + meter.end(); + res.end(); + const ok = upRes.statusCode >= 200 && upRes.statusCode < 300; + // An error status with no usage commits nothing. A success commits + // its usage, except a stream that ended before its message_delta + // (an incomplete response) or a body with no usage: those commit at + // least the reservation (our decision). + if (!ok) settle(meter.total()); + else if (streaming ? !meter.sawDelta : !meter.seen) settle(abandoned()); + else settle(meter.total()); + }); + // Upstream dropped or stalled mid-response: drop the client too, so it + // sees a dropped connection rather than a stall, and commit as for a + // client disconnect (our decision). Claude Code's handling of a dropped + // connection: errors#automatic-retries, see the refusal-status pointer. + upRes.on("error", () => {}); + upRes.on("close", () => { + if (finished) return; + finished = true; + meter.end(); + res.destroy(); + settle(abandoned()); + }); + }); + + // No response byte relayed yet: a retryable answer either way. Once the + // body was fully written upstream, we assume generation may have run and + // be billed even though no response byte came back (our decision), and Claude Code + // resends a retryable failure, so the full reservation is committed; + // it is released only when the connection failed before the body was + // written (our decision). Bytes relayed: drop the client and commit as + // for a disconnect. + // Pointer: https://code.claude.com/docs/en/errors#automatic-retries + // As of: 2026-11-06. Recheck trigger: that section changes which + // failures before any streamed response Claude Code retries. + let bodySent = false; + upReq.on("finish", () => { bodySent = true; }); + upReq.on("error", (err) => { + if (finished) return; + finished = true; + if (!res.headersSent) { + sendRefusal(res, upstreamFailure(err)); + settle(bodySent ? reserved : 0); + } else { + meter?.end(); + res.destroy(); + settle(abandoned()); + } + }); + + // The client went away before the response finished: stop generation + // upstream and commit the reservation; an abandoned response counts as + // fully spent (our decision). + res.on("close", () => { + if (finished) return; + finished = true; + upReq.destroy(); + meter?.end(); + settle(abandoned()); + }); + + upReq.end(body); + } + + return { server, budget, state }; +} + +function argValue(argv, name) { + const i = argv.indexOf(name); + return i >= 0 ? argv[i + 1] : undefined; +} + +async function readStdin() { + const chunks = []; + for await (const c of process.stdin) chunks.push(c); + return Buffer.concat(chunks).toString("utf8").trim(); +} + +async function main(argv) { + const socket = argValue(argv, "--socket"); + const configPath = argValue(argv, "--config"); + if (!socket || !configPath) { + process.stderr.write("usage: key-proxy.mjs --socket --config [--upstream ] < key\n"); + return 2; + } + let config; + try { + config = loadConfig(readFileSync(configPath, "utf8"), argValue(argv, "--upstream")); + } catch (e) { + process.stderr.write(`key-proxy: bad config: ${e.message}\n`); + return 2; + } + const key = await readStdin(); + if (!key) { + process.stderr.write("key-proxy: no key on stdin\n"); + return 2; + } + const log = (entry) => process.stderr.write(`${JSON.stringify({ t: new Date().toISOString(), ...entry })}\n`); + const { server } = createProxy({ key, config, log }); + rmSync(socket, { force: true }); + await new Promise((resolve, reject) => server.once("error", reject).listen(socket, resolve)); + if (config.socketMode !== undefined) chmodSync(socket, config.socketMode); + log({ listening: socket, models: config.models, tokenCap: config.tokenCap }); + const stop = () => server.close(() => process.exit(0)); + process.on("SIGTERM", stop); + process.on("SIGINT", stop); + return null; +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + main(process.argv.slice(2)).then((code) => { + if (code !== null) process.exit(code); + }, (e) => { + process.stderr.write(`key-proxy: ${e.message}\n`); + process.exit(1); + }); +} diff --git a/.github/scripts/pr-verify/key-proxy.test.mjs b/.github/scripts/pr-verify/key-proxy.test.mjs new file mode 100644 index 00000000000..2ade95d0581 --- /dev/null +++ b/.github/scripts/pr-verify/key-proxy.test.mjs @@ -0,0 +1,769 @@ +// key-proxy.mjs, the only path from pr-verify's driven Claude Code to the +// API: each guarantee tested against a local stub upstream over a real unix +// socket, plus the stdin key and never-log guarantees of the script itself. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { statSync, writeFileSync } from "node:fs"; +import http from "node:http"; +import path from "node:path"; +import { after, test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { tempDir } from "../../../lib/test-tmp.mjs"; +import { createProxy, loadConfig } from "./key-proxy.mjs"; + +const SCRIPT = fileURLToPath(new URL("./key-proxy.mjs", import.meta.url)); +// Built at run time so no key-shaped literal sits in the file. +const KEY = `${"sk-ant-"}api03-${"K".repeat(40)}`; +const MODELS = ["model-main", "model-title"]; +// Measured from the driven session (Claude Code 2.1.318): its betas and +// top-level body keys. Block types are the ones a restricted session sends. +const MAIN_BETAS = "claude-code-20250219,interleaved-thinking-2025-05-14,context-management-2025-06-27,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24,thinking-display-updates-2026-08-18"; +const TITLE_BETAS = "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,context-management-2025-06-27,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,effort-2025-11-24,structured-outputs-2025-12-15"; +const BETAS = [...new Set(`${MAIN_BETAS},${TITLE_BETAS}`.split(","))]; +const BODY_KEYS = ["context_management", "max_tokens", "messages", "metadata", "model", "output_config", "stream", "system", "thinking", "tools"]; +const BLOCK_TYPES = ["text", "image", "document", "tool_use", "tool_result", "thinking", "redacted_thinking"]; +const BASE_CONFIG = { + tokenCap: 1_000_000, models: MODELS, maxTokensCeiling: 1000, maxBodyBytes: 100_000, maxInFlight: 8, + maxCountTokensRequests: 100, betas: BETAS, bodyKeys: BODY_KEYS, blockTypes: BLOCK_TYPES, + // Longer than any test holds an upstream idle; the timeout tests override it. + upstreamTimeoutMs: 10_000, +}; + +const servers = []; +after(() => { + for (const s of servers) { + s.closeAllConnections?.(); + s.close(); + } +}); + +// A stub upstream. /v1/messages requests go to `handler(req, body, res)` and +// are recorded in `seen`; count_tokens requests are recorded in `counts` and +// answered with `countTokens` input tokens (a function may answer instead). +async function stubUpstream(handler, { countTokens = 50 } = {}) { + const seen = []; + const counts = []; + const server = http.createServer((req, res) => { + const chunks = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", () => { + const body = Buffer.concat(chunks); + const entry = { method: req.method, url: req.url, headers: req.headers, body, closed: new Promise((r) => res.on("close", r)) }; + if (req.url.startsWith("/v1/messages/count_tokens")) { + counts.push(entry); + if (typeof countTokens === "function") return countTokens(res); + res.writeHead(200, { "content-type": "application/json" }); + return res.end(JSON.stringify({ input_tokens: countTokens })); + } + seen.push(entry); + handler(req, body, res, entry); + }); + }); + servers.push(server); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + return { url: `http://127.0.0.1:${server.address().port}`, seen, counts, server }; +} + +const okJson = (usage = { input_tokens: 1, output_tokens: 1 }) => (_req, _body, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ type: "message", content: [], usage })); +}; + +async function startProxy(upstream, overrides = {}) { + const config = loadConfig({ ...BASE_CONFIG, ...overrides }, upstream.url); + const logs = []; + const { server, budget } = createProxy({ key: KEY, config, log: (e) => logs.push(e) }); + servers.push(server); + const socket = path.join(tempDir("kp-"), "p.sock"); + await new Promise((r) => server.listen(socket, r)); + return { socket, budget, logs }; +} + +// One request over the proxy's socket; resolves with status, headers, body. +function call(socket, { method = "POST", url = "/v1/messages", headers = {}, body } = {}) { + const raw = body === undefined ? undefined : Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body)); + return new Promise((resolve, reject) => { + const req = http.request({ socketPath: socket, method, path: url, headers: { "content-type": "application/json", ...headers } }, (res) => { + const chunks = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks).toString("utf8") })); + }); + req.on("error", reject); + req.end(raw); + }); +} + +const message = (extra = {}) => ({ model: "model-main", max_tokens: 100, messages: [{ role: "user", content: "hi" }], ...extra }); +const countBody = (extra = {}) => ({ model: "model-main", messages: [{ role: "user", content: "hi" }], ...extra }); +const sse = (type, data) => `event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`; +const tick = () => new Promise((r) => setImmediate(r)); +async function until(cond) { + for (let i = 0; i < 500 && !cond(); i++) await new Promise((r) => setTimeout(r, 10)); + assert.ok(cond(), "condition not reached"); +} +const assertRefused = (res, status, type) => { + assert.equal(res.status, status); + assert.equal(res.headers["x-should-retry"], "false"); + assert.equal(JSON.parse(res.body).error.type, type); +}; + +// Opens a request whose response the test controls; resolves on the first +// response byte with the request and response. +function openStream(socket, body) { + return new Promise((resolve, reject) => { + const req = http.request({ socketPath: socket, method: "POST", path: "/v1/messages", headers: { "content-type": "application/json" } }, (res) => resolve({ req, res })); + req.on("error", reject); + req.end(JSON.stringify(body)); + }); +} + +test("path allowlist: only POST /v1/messages and /v1/messages/count_tokens reach upstream; everything else is 404", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + const refused = [ + { method: "GET", url: "/v1/messages" }, + { method: "HEAD", url: "/api/hello" }, + { url: "/v1/messages/batches", body: message() }, + { url: "/v1/messages/", body: message() }, + { url: "/v1/x/../messages", body: message() }, + { url: "/v1/complete", body: message() }, + ]; + for (const r of refused) assert.equal((await call(socket, r)).status, 404, `${r.method ?? "POST"} ${r.url}`); + assert.equal(up.seen.length + up.counts.length, 0); + + assert.equal((await call(socket, { body: message() })).status, 200); + assert.equal((await call(socket, { url: "/v1/messages/count_tokens", body: countBody() })).status, 200); + assert.deepEqual(up.seen.map((s) => `${s.method} ${s.url}`), ["POST /v1/messages"]); + assert.equal(up.counts.at(-1).url, "/v1/messages/count_tokens"); +}); + +test("query: exactly beta=true is forwarded; any other query is refused", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + assert.equal((await call(socket, { url: "/v1/messages?beta=true", body: message() })).status, 200); + assert.equal(up.seen[0].url, "/v1/messages?beta=true"); + for (const url of ["/v1/messages?beta=true&x=1", "/v1/messages?beta=false", "/v1/messages?", "/v1/messages/count_tokens?foo=1"]) { + assertRefused(await call(socket, { url, body: message() }), 403, "permission_error"); + } + assert.equal(up.seen.length, 1); +}); + +test("credential swap: the client's Authorization and x-api-key are stripped and x-api-key is the held key", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + await call(socket, { body: message(), headers: { authorization: "Bearer client-token", "x-api-key": "dummy-client-key" } }); + for (const r of [up.counts[0], up.seen[0]]) { + assert.equal(r.headers["x-api-key"], KEY); + assert.equal(r.headers.authorization, undefined); + } +}); + +test("request header allowlist: version, listed betas and x-claude-code-* pass; other headers are dropped; an unlisted beta is refused", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + const headers = { + "anthropic-version": "2023-06-01", "anthropic-beta": MAIN_BETAS, "x-claude-code-session-id": "s-1", + "x-stainless-os": "Linux", "accept-encoding": "gzip, br, zstd", cookie: "a=b", "anthropic-workspace-id": "w", + }; + assert.equal((await call(socket, { body: message(), headers })).status, 200); + const h = up.seen[0].headers; + assert.equal(h["anthropic-version"], "2023-06-01"); + assert.equal(h["anthropic-beta"], MAIN_BETAS); + assert.equal(h["x-claude-code-session-id"], "s-1"); + for (const dropped of ["x-stainless-os", "cookie", "anthropic-workspace-id"]) assert.equal(h[dropped], undefined, dropped); + // The client's gzip/br/zstd is replaced: both upstream requests ask for identity. + assert.equal(h["accept-encoding"], "identity"); + assert.equal(up.counts[0].headers["accept-encoding"], "identity"); + assert.equal((await call(socket, { body: message({ model: "model-title" }), headers: { "anthropic-beta": TITLE_BETAS } })).status, 200); + + assertRefused(await call(socket, { body: message(), headers: { "anthropic-beta": `${MAIN_BETAS},files-api-2025-04-14` } }), 403, "permission_error"); + assert.equal(up.seen.length, 2); +}); + +test("a beta refusal names each refused beta in the response body and the log line", async () => { + const up = await stubUpstream(okJson()); + const { socket, logs } = await startProxy(up); + const header = `${MAIN_BETAS},files-api-2025-04-14,mcp-client-2025-04-04,files-api-2025-04-14`; + const res = await call(socket, { body: message(), headers: { "anthropic-beta": header } }); + assertRefused(res, 403, "permission_error"); + const msg = JSON.parse(res.body).error.message; + assert.ok(msg.includes("files-api-2025-04-14, mcp-client-2025-04-04"), msg); + assert.ok(!msg.includes("claude-code-20250219"), "an allowed beta is not named"); + assert.deepEqual(logs.at(-1).betas, ["files-api-2025-04-14", "mcp-client-2025-04-04"]); + assert.equal(logs.at(-1).status, 403); + + // Twelve unknown betas: ten are named, the rest counted. + const many = Array.from({ length: 12 }, (_, i) => `x-beta-${i}`); + const capped = await call(socket, { body: message(), headers: { "anthropic-beta": many.join(",") } }); + assert.deepEqual(logs.at(-1).betas, many.slice(0, 10)); + assert.ok(JSON.parse(capped.body).error.message.includes("x-beta-9 (+2 more)")); + assert.equal(up.seen.length + up.counts.length, 0); +}); + +test("body canonicalization: upstream receives the checked object re-serialized, so a duplicate key cannot smuggle its first value", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + const raw = '{ "messages":[{"role":"user","content":"hi"}],\n "max_tokens" : 100, "model":"model-title", "metadata":{"z":1,"a":2} }'; + assert.equal((await call(socket, { body: raw })).status, 200); + assert.deepEqual(JSON.parse(up.seen[0].body), { messages: [{ role: "user", content: "hi" }], max_tokens: 100, model: "model-title", metadata: { z: 1, a: 2 } }); + assert.equal(up.seen[0].headers["content-type"], "application/json"); + assert.equal(Number(up.seen[0].headers["content-length"]), up.seen[0].body.length); + + const dup = '{"model":"model-main","max_tokens":100,"messages":[],"tools":[{"type":"web_fetch_20250910","name":"web_fetch"}],"tools":[]}'; + assert.equal((await call(socket, { body: dup })).status, 200); + assert.deepEqual(JSON.parse(up.seen[1].body), { model: "model-main", max_tokens: 100, messages: [], tools: [] }); + assert.ok(!up.seen[1].body.includes("web_fetch")); + + // A lone 0xff byte: a lenient decoder would turn it into U+FFFD and parse. + const badUtf8 = Buffer.concat([Buffer.from('{"model":"model-main","max_tokens":100,"messages":[{"role":"user","content":"'), Buffer.from([0xff]), Buffer.from('"}]}')]); + assert.equal((await call(socket, { body: badUtf8 })).status, 400); + assert.equal(up.seen.length, 2); +}); + +test("body key allowlist: the measured top-level keys pass and any other key is refused", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + const full = message({ context_management: {}, metadata: { user_id: "u" }, output_config: {}, stream: false, system: "s", thinking: { type: "adaptive" }, tools: [] }); + assert.equal((await call(socket, { body: full })).status, 200); + for (const extra of [{ container: "c" }, { mcp_servers: [] }, { service_tier: "auto" }]) { + assertRefused(await call(socket, { body: message(extra) }), 403, "permission_error"); + } + assert.equal(up.seen.length, 1); +}); + +test("SSE streams are relayed unbuffered, ping events included", { timeout: 10_000 }, async () => { + let release; + const released = new Promise((r) => (release = r)); + const up = await stubUpstream(async (_req, _body, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write(sse("message_start", { message: { usage: { input_tokens: 3, output_tokens: 1 } } })); + res.write(sse("ping", {})); + // The rest is sent only after the client has seen the ping: a proxy that + // buffers never delivers it, and the test fails on its timeout. + await released; + res.write(sse("message_delta", { delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } })); + res.end(sse("message_stop", {})); + }); + const { socket } = await startProxy(up); + const { res } = await openStream(socket, message({ stream: true })); + assert.equal(res.headers["content-type"], "text/event-stream"); + const text = await new Promise((resolve) => { + let got = ""; + res.on("data", (c) => { + got += c; + if (got.includes("event: ping")) release(); + }); + res.on("end", () => resolve(got)); + }); + assert.match(text, /event: message_start[\s\S]*event: ping[\s\S]*event: message_delta[\s\S]*event: message_stop/); +}); + +test("upstream errors keep their status and body; only the allowlisted response headers are relayed", async () => { + const errorBody = '{"type":"error","error":{"type":"invalid_request_error","message":"Unexpected value(s) `x-2026` for the `anthropic-beta` header"}}'; + const up = await stubUpstream((_req, _body, res) => { + res.writeHead(400, { + "content-type": "application/json", "x-should-retry": "true", "request-id": "req_1", "retry-after": "5", + "anthropic-ratelimit-unified-status": "allowed", "set-cookie": "s=1", "x-envoy-upstream-service-time": "9", server: "stub", + }); + res.end(errorBody); + }); + const { socket } = await startProxy(up); + const res = await call(socket, { body: message() }); + assert.equal(res.status, 400); + assert.equal(res.body, errorBody); + assert.equal(res.headers["x-should-retry"], "true"); + assert.equal(res.headers["request-id"], "req_1"); + assert.equal(res.headers["retry-after"], "5"); + assert.equal(res.headers["anthropic-ratelimit-unified-status"], "allowed"); + for (const dropped of ["set-cookie", "x-envoy-upstream-service-time", "server"]) assert.equal(res.headers[dropped], undefined, dropped); +}); + +test("a model allowlist of several models and a max_tokens ceiling", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up, { maxTokensCeiling: 1000 }); + assert.equal((await call(socket, { body: message({ model: "model-main" }) })).status, 200); + assert.equal((await call(socket, { body: message({ model: "model-title" }) })).status, 200); + assert.equal((await call(socket, { body: message({ max_tokens: 1000 }) })).status, 200); + const before = up.seen.length; + for (const body of [message({ model: "model-other" }), message({ max_tokens: 1001 }), message({ max_tokens: undefined })]) { + assertRefused(await call(socket, { body }), 403, "permission_error"); + } + assert.equal(up.seen.length, before); + // count_tokens takes no max_tokens, but its model is still checked. + // Pointer: https://platform.claude.com/docs/en/api/messages-count-tokens (Body parameters) + // As of: 2026-11-06. Recheck trigger: that section adds max_tokens. + assert.equal((await call(socket, { url: "/v1/messages/count_tokens", body: countBody({ model: "model-title" }) })).status, 200); + assertRefused(await call(socket, { url: "/v1/messages/count_tokens", body: countBody({ model: "model-other" }) }), 403, "permission_error"); +}); + +test("requests carrying server tools are refused", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up, { bodyKeys: [...BODY_KEYS, "mcp_servers"] }); + const custom = { name: "Read", description: "read", input_schema: { type: "object", properties: { path: { type: "string" } } } }; + assert.equal((await call(socket, { body: message({ tools: [custom, { ...custom, name: "Edit", type: "custom" }] }) })).status, 200); + const before = up.seen.length; + const refused = [ + message({ tools: [custom, { type: "web_search_20250305", name: "web_search" }] }), + message({ tools: [{ type: "web_fetch_20250910", name: "web_fetch" }] }), + message({ mcp_servers: [{ type: "url", url: "https://example.com/mcp", name: "x" }] }), + ]; + for (const body of refused) assertRefused(await call(socket, { body }), 403, "permission_error"); + assert.equal(up.seen.length, before); +}); + +test("a tools field that is not a list, or a tools entry that is not an object, is refused", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + const server = { type: "web_fetch_20250910", name: "web_fetch" }; + for (const tools of [server, { 0: server, length: 1 }, "web_fetch", null, ["web_fetch"], [[server]]]) { + assertRefused(await call(socket, { body: message({ tools }) }), 403, "permission_error"); + assertRefused(await call(socket, { url: "/v1/messages/count_tokens", body: countBody({ tools }) }), 403, "permission_error"); + } + assert.equal(up.seen.length + up.counts.length, 0); +}); + +test("content allowlist: block types outside the list and any source other than base64, text or content are refused at any depth", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up); + const base64 = { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgo=" } }; + const nested = { type: "tool_result", tool_use_id: "toolu_1", content: [{ type: "text", text: "see" }, base64] }; + // The proxy does not walk tool_use input, so a `type` key there is not checked. + const toolUse = { type: "tool_use", id: "toolu_1", name: "Write", input: { type: "url", source: { type: "url" } } }; + const textDoc = { type: "document", source: { type: "text", media_type: "text/plain", data: "d" } }; + const allowed = message({ messages: [{ role: "assistant", content: [toolUse] }, { role: "user", content: [nested, textDoc] }], system: [{ type: "text", text: "s" }] }); + assert.equal((await call(socket, { body: allowed })).status, 200); + const before = up.seen.length; + const url = (kind) => ({ type: kind, source: { type: "url", url: `https://example.com/${kind}` } }); + const user = (content) => message({ messages: [{ role: "user", content }] }); + const refused = [ + user([{ ...nested, content: [url("image")] }]), + user([url("document")]), + message({ system: [{ type: "text", text: "x" }, url("document")] }), + user([{ type: "document", source: { type: "file", file_id: "file_1" } }]), + user([{ type: "document", source: { type: "content", content: [url("image")] } }]), + message({ messages: [{ role: "assistant", content: [{ type: "server_tool_use", id: "srvtoolu_1", name: "web_search", input: {} }] }] }), + user([{ type: "web_fetch_tool_result", tool_use_id: "srvtoolu_1", content: {} }]), + user([{ type: "search_result", source: "s", title: "t", content: [] }]), + ]; + for (const body of refused) assertRefused(await call(socket, { body }), 403, "permission_error"); + assert.equal(up.seen.length, before); +}); + +test("usage is summed without double counting message_start and the cumulative message_delta", async () => { + // Token counts from the streaming doc's own example streams; message_delta + // usage is cumulative. + // Pointer: https://platform.claude.com/docs/en/build-with-claude/streaming#event-types + // As of: 2026-11-06. Recheck trigger: that section changes what message_delta usage holds. + const streams = [ + [sse("message_start", { message: { usage: { input_tokens: 25, output_tokens: 1 } } }), sse("ping", {}), sse("message_delta", { usage: { output_tokens: 15 } }), sse("message_stop", {})], + [sse("message_start", { message: { usage: { input_tokens: 2679, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 3 } } }), + sse("message_delta", { usage: { input_tokens: 10682, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 510 } }), sse("message_stop", {})], + ]; + let n = 0; + const up = await stubUpstream(async (_req, _body, res) => { + const joined = streams[n++].join(""); + res.writeHead(200, { "content-type": "text/event-stream" }); + // Split one event across two writes so the parser must join chunks. + res.write(joined.slice(0, 40)); + await tick(); + res.end(joined.slice(40)); + }); + const { socket, budget } = await startProxy(up); + await call(socket, { body: message({ stream: true }) }); + assert.equal(budget.committed, 40); // 25 input + 15 output; not 41 + await call(socket, { body: message({ stream: true }) }); + assert.equal(budget.committed, 11232); // 40 + 10682 input + 510 output + assert.equal(budget.reserved, 0); +}); + +test("non-streaming usage is read from the response body", async () => { + const up = await stubUpstream(okJson({ input_tokens: 7, cache_read_input_tokens: 5, output_tokens: 3 })); + const { socket, budget } = await startProxy(up); + await call(socket, { body: message() }); + assert.equal(budget.committed, 15); +}); + +test("a streaming 200 that ends with no message_delta commits the reservation", async () => { + const up = await stubUpstream((_req, _body, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(sse("message_start", { message: { usage: { input_tokens: 5, output_tokens: 1 } } })); + }, { countTokens: 50 }); + const { socket, budget } = await startProxy(up); + await call(socket, { body: message({ max_tokens: 100, stream: true }) }); + assert.equal(budget.committed, 150); // reservation 50 + 100, above the 6 seen +}); + +test("the reservation is the upstream count_tokens preflight of the checked body plus max_tokens", async () => { + let releaseHold; + const hold = new Promise((r) => (releaseHold = r)); + const up = await stubUpstream(async (_req, body, res) => { + await hold; + okJson()(_req, body, res); + }, { countTokens: 250 }); + const { socket, budget } = await startProxy(up); + const body = message({ max_tokens: 100, stream: true, metadata: { user_id: "u" }, context_management: {}, system: "s", thinking: { type: "adaptive" }, tools: [] }); + const pending = call(socket, { url: "/v1/messages?beta=true", body, headers: { "anthropic-beta": MAIN_BETAS, "x-api-key": "dummy" } }); + await until(() => up.seen.length === 1); + assert.equal(budget.reserved, 350); + const pre = up.counts[0]; + assert.equal(pre.url, "/v1/messages/count_tokens?beta=true"); + assert.equal(pre.headers["x-api-key"], KEY); + assert.equal(pre.headers["anthropic-beta"], MAIN_BETAS); + assert.deepEqual(JSON.parse(pre.body), { messages: [{ role: "user", content: "hi" }], model: "model-main", system: "s", thinking: { type: "adaptive" }, tools: [] }); + releaseHold(); + await pending; +}); + +test("a 529 preflight is relayed with its retry headers and body, takes no reservation and frees its slot", async () => { + const overloaded = '{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}'; + const up = await stubUpstream(okJson(), { + countTokens: (res) => res.writeHead(529, { "content-type": "application/json", "retry-after": "3", "x-should-retry": "true" }).end(overloaded), + }); + const { socket, budget } = await startProxy(up, { maxInFlight: 1 }); + for (let i = 0; i < 2; i++) { + // The second pass would get the in-flight 403 if the first kept its slot. + const res = await call(socket, { body: message() }); + assert.equal(res.status, 529); + assert.equal(res.body, overloaded); + assert.equal(res.headers["retry-after"], "3"); + assert.equal(res.headers["x-should-retry"], "true"); + } + assert.equal(up.seen.length, 0); + assert.equal(budget.reserved, 0); + assert.equal(budget.committed, 0); +}); + +test("a 400 preflight is refused with a status that is not retried", async () => { + const up = await stubUpstream(okJson(), { countTokens: (res) => res.writeHead(400, { "content-type": "application/json" }).end('{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}') }); + const { socket, budget } = await startProxy(up); + assertRefused(await call(socket, { body: message() }), 403, "permission_error"); + assert.equal(up.seen.length, 0); + assert.equal(budget.reserved, 0); +}); + +test("a 429 preflight is relayed with its retry headers and body, takes no reservation and frees its slot", async () => { + const limited = '{"type":"error","error":{"type":"rate_limit_error","message":"Number of requests has exceeded your rate limit"}}'; + const up = await stubUpstream(okJson(), { + countTokens: (res) => res.writeHead(429, { "content-type": "application/json", "retry-after": "7", "anthropic-ratelimit-requests-remaining": "0" }).end(limited), + }); + const { socket, budget } = await startProxy(up, { maxInFlight: 1 }); + for (let i = 0; i < 2; i++) { + const res = await call(socket, { body: message() }); + assert.equal(res.status, 429); + assert.equal(res.body, limited); + assert.equal(res.headers["retry-after"], "7"); + assert.equal(res.headers["anthropic-ratelimit-requests-remaining"], "0"); + } + assert.equal(up.seen.length, 0); + assert.equal(budget.reserved, 0); + assert.equal(budget.committed, 0); +}); + +test("a preflight whose connection drops is answered 502 with x-should-retry true, takes no reservation and frees its slot", async () => { + const up = await stubUpstream(okJson(), { countTokens: (res) => res.socket.destroy() }); + const { socket, budget } = await startProxy(up, { maxInFlight: 1 }); + for (let i = 0; i < 2; i++) { + const res = await call(socket, { body: message() }); + assert.equal(res.status, 502); + assert.equal(res.headers["x-should-retry"], "true"); + assert.equal(JSON.parse(res.body).error.type, "api_error"); + } + assert.equal(up.counts.length, 2); + assert.equal(up.seen.length, 0); + assert.equal(budget.reserved, 0); + assert.equal(budget.committed, 0); +}); + +test("a main request whose upstream drops after reading the body is a retryable 502 that commits its reservation and frees its slot", async () => { + let n = 0; + const up = await stubUpstream((req, body, res) => { + if (n++ === 0) return res.socket.destroy(); + okJson({ input_tokens: 1, output_tokens: 1 })(req, body, res); + }, { countTokens: 50 }); + const { socket, budget } = await startProxy(up, { maxInFlight: 1 }); + const res = await call(socket, { body: message({ max_tokens: 100 }) }); + assert.equal(res.status, 502); + assert.equal(res.headers["x-should-retry"], "true"); + assert.equal(JSON.parse(res.body).error.type, "api_error"); + assert.equal(budget.reserved, 0); + assert.equal(budget.committed, 150); // 50 counted + 100 max_tokens + assert.equal((await call(socket, { body: message({ max_tokens: 100 }) })).status, 200); + assert.equal(budget.committed, 152); // + 1 input + 1 output +}); + +test("a non-streaming request whose upstream takes the body and then stalls times out as a retryable 502 and commits its reservation", { timeout: 10_000 }, async () => { + const up = await stubUpstream(() => {}, { countTokens: 50 }); + const { socket, budget } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 600, maxInFlight: 1, upstreamTimeoutMs: 150 }); + const body = message({ max_tokens: 600 }); + const res = await call(socket, { body }); + assert.equal(res.status, 502); + assert.equal(res.headers["x-should-retry"], "true"); + assert.equal(JSON.parse(res.body).error.type, "api_error"); + await up.seen[0].closed; // the proxy aborted the stalled upstream request + assert.equal(budget.reserved, 0); + assert.equal(budget.committed, 650); // 50 counted + 600 max_tokens + // Another 650 fits under 1000 only if the first had been released; the + // 429 (not the in-flight 403) also shows the slot was freed. + assertRefused(await call(socket, { body }), 429, "rate_limit_error"); + assert.equal(up.seen.length, 1); +}); + +test("a connect failure before the body is written is a retryable 502 that releases its reservation", { timeout: 10_000 }, async () => { + // The preflight answers and closes its connection, then the upstream stops + // listening, so the main request's connect is refused. + const up = await stubUpstream(okJson(), { + countTokens: (res) => { + res.writeHead(200, { "content-type": "application/json", connection: "close" }).end(JSON.stringify({ input_tokens: 50 })); + up.server.close(); + }, + }); + const { socket, budget } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 600, maxInFlight: 1 }); + const res = await call(socket, { body: message({ max_tokens: 600 }) }); + assert.equal(res.status, 502); + assert.equal(res.headers["x-should-retry"], "true"); + assert.equal(up.counts.length, 1); + assert.equal(up.seen.length, 0); + assert.equal(budget.reserved, 0); + assert.equal(budget.committed, 0); +}); + +test("a count_tokens preflight that never answers times out as a retryable 502 and frees its slot", { timeout: 10_000 }, async () => { + const up = await stubUpstream(okJson(), { countTokens: () => {} }); + const { socket, budget } = await startProxy(up, { maxInFlight: 1, upstreamTimeoutMs: 150 }); + // The second pass would get the in-flight 403 if the first kept its slot. + for (let i = 0; i < 2; i++) { + const res = await call(socket, { body: message() }); + assert.equal(res.status, 502); + assert.equal(res.headers["x-should-retry"], "true"); + } + assert.equal(up.seen.length, 0); + assert.equal(budget.reserved, 0); +}); + +test("an in-flight reservation stops concurrent requests from passing the cap together", async () => { + let releaseA; + const holdA = new Promise((r) => (releaseA = r)); + const up = await stubUpstream(async (_req, body, res) => { + if (JSON.parse(body).metadata?.user_id === "A") await holdA; + okJson({ input_tokens: 10, output_tokens: 10 })(_req, body, res); + }, { countTokens: 100 }); + // Each request reserves 100 + 500 = 600; the cap of 1000 fits one, not two. + const { socket, budget } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 500 }); + const a = call(socket, { body: message({ max_tokens: 500, metadata: { user_id: "A" } }) }); + await until(() => up.seen.length === 1); + assertRefused(await call(socket, { body: message({ max_tokens: 500, metadata: { user_id: "B" } }) }), 429, "rate_limit_error"); + assert.equal(up.seen.length, 1); + releaseA(); + assert.equal((await a).status, 200); + assert.equal(budget.committed, 20); + assert.equal((await call(socket, { body: message({ max_tokens: 500, metadata: { user_id: "B" } }) })).status, 200); +}); + +test("maxInFlight caps concurrent forwarded requests, count_tokens included", async () => { + let releaseA; + const holdA = new Promise((r) => (releaseA = r)); + const up = await stubUpstream(async (_req, body, res) => { + await holdA; + okJson()(_req, body, res); + }); + const { socket } = await startProxy(up, { maxInFlight: 1 }); + const a = call(socket, { body: message() }); + await until(() => up.seen.length === 1); + assertRefused(await call(socket, { body: message() }), 403, "permission_error"); + assertRefused(await call(socket, { url: "/v1/messages/count_tokens", body: countBody() }), 403, "permission_error"); + releaseA(); + await a; + assert.equal((await call(socket, { url: "/v1/messages/count_tokens", body: countBody() })).status, 200); +}); + +test("client count_tokens is limited per job and refused once the cap is spent", async () => { + const up = await stubUpstream(okJson({ input_tokens: 600, output_tokens: 400 }), { countTokens: 10 }); + const limited = await startProxy(up, { maxCountTokensRequests: 2 }); + for (let i = 0; i < 2; i++) assert.equal((await call(limited.socket, { url: "/v1/messages/count_tokens", body: countBody() })).status, 200); + assertRefused(await call(limited.socket, { url: "/v1/messages/count_tokens", body: countBody() }), 403, "permission_error"); + + const capped = await startProxy(up, { tokenCap: 1000 }); + assert.equal((await call(capped.socket, { url: "/v1/messages/count_tokens", body: countBody() })).status, 200); + assert.equal((await call(capped.socket, { body: message() })).status, 200); // commits 1000 + assertRefused(await call(capped.socket, { url: "/v1/messages/count_tokens", body: countBody() }), 429, "rate_limit_error"); +}); + +test("a client that disconnects mid-stream has its reservation committed, not released", async () => { + const up = await stubUpstream((_req, _body, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write(sse("message_start", { message: { usage: { input_tokens: 5, output_tokens: 1 } } })); + // Then stall: no message_delta ever comes. + }, { countTokens: 50 }); + const { socket, budget } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 600 }); + const body = message({ max_tokens: 600, stream: true }); + const { req, res } = await openStream(socket, body); + await new Promise((r) => res.once("data", r)); + req.on("error", () => {}); + req.destroy(); + await up.seen[0].closed; // the proxy aborted the upstream request + await until(() => budget.reserved === 0); + assert.equal(budget.committed, 650); // 50 counted + 600 max_tokens + // A second request of the same size fits only if the first had been released. + assertRefused(await call(socket, { body }), 429, "rate_limit_error"); +}); + +test("an upstream that drops mid-stream drops the client and commits the reservation", { timeout: 10_000 }, async () => { + const up = await stubUpstream((_req, _body, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write(sse("message_start", { message: { usage: { input_tokens: 5, output_tokens: 1 } } }), () => setTimeout(() => res.socket.destroy(), 20)); + }, { countTokens: 50 }); + const { socket, budget } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 600 }); + const { req, res } = await openStream(socket, message({ max_tokens: 600, stream: true })); + req.on("error", () => {}); + const ended = await new Promise((resolve) => { + res.on("data", () => {}); + res.on("error", () => resolve("dropped")); + res.on("end", () => resolve("ended")); + res.on("close", () => resolve("closed")); + }); + assert.notEqual(ended, "ended"); // no clean end: the client must see a drop + await until(() => budget.reserved === 0); + assert.equal(budget.committed, 650); +}); + +test("an upstream that stalls mid-stream is aborted after the idle timeout: the client is dropped and the reservation committed", { timeout: 10_000 }, async () => { + const up = await stubUpstream((_req, _body, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write(sse("message_start", { message: { usage: { input_tokens: 5, output_tokens: 1 } } })); + // Then nothing: no ping, no message_delta. + }, { countTokens: 50 }); + const { socket, budget } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 600, upstreamTimeoutMs: 150 }); + const { req, res } = await openStream(socket, message({ max_tokens: 600, stream: true })); + req.on("error", () => {}); + const ended = await new Promise((resolve) => { + res.on("data", () => {}); + res.on("error", () => resolve("dropped")); + res.on("end", () => resolve("ended")); + res.on("close", () => resolve("closed")); + }); + assert.notEqual(ended, "ended"); // no clean end: the client must see a drop + await up.seen[0].closed; + await until(() => budget.reserved === 0); + assert.equal(budget.committed, 650); // 50 counted + 600 max_tokens +}); + +test("an oversized body gets a 413 that is not retried, and never reaches upstream", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up, { maxBodyBytes: 2000 }); + const res = await call(socket, { body: message({ messages: [{ role: "user", content: "x".repeat(2000) }] }) }); + assertRefused(res, 413, "request_too_large"); + assert.equal(up.seen.length + up.counts.length, 0); +}); + +test("an oversized body still uploading in chunks is drained to its end, with no socket error", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up, { maxBodyBytes: 2000 }); + let res; + let writeError = null; + let written = 0; + await new Promise((resolve) => { + const req = http.request({ socketPath: socket, method: "POST", path: "/v1/messages", headers: { "content-type": "application/json" } }, (r) => { + const chunks = []; + r.on("data", (c) => chunks.push(c)); + r.on("end", () => { res = { status: r.statusCode, headers: r.headers, body: Buffer.concat(chunks).toString("utf8") }; }); + }); + req.on("error", (e) => { writeError = e; resolve(); }); + req.on("close", resolve); + // 40 chunks of 64 KiB, 5 ms apart: more than a socket buffer holds, so the client is still + // writing when the limit trips on the first chunk. Over TCP (the socat bridge) a socket closed + // with unread data answers the remaining writes with a reset. + const next = (err) => { + if (err) return; + if (written === 40) return req.end(); + written++; + req.write("x".repeat(65536), (e) => setTimeout(() => next(e), 5)); + }; + next(); + }); + assert.equal(writeError, null); + assert.equal(written, 40); + assertRefused(res, 413, "request_too_large"); + assert.equal(up.seen.length + up.counts.length, 0); +}); + +test("a body that breaks re-serialization gets a 400 and the proxy keeps serving", async () => { + const up = await stubUpstream(okJson()); + const { socket } = await startProxy(up, { maxBodyBytes: 1_000_000 }); + // tool_use input is not walked, so 50000 nested arrays pass the checks and then overflow the + // stack when the proxy re-serializes the body. Written by hand: JSON.stringify would overflow here. + const deep = "[".repeat(50000) + "]".repeat(50000); + const raw = `{"model":"model-main","max_tokens":100,"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Write","input":{"a":${deep}}}]}]}`; + const bad = await call(socket, { body: Buffer.from(raw) }); + assertRefused(bad, 400, "invalid_request_error"); + const next = await call(socket, { body: message() }); + assert.equal(next.status, 200); + assert.equal(up.seen.length, 1); +}); + +test("past the cap the refusal is a 429 spend limit with x-should-retry false", async () => { + const up = await stubUpstream(okJson({ input_tokens: 450, output_tokens: 450 }), { countTokens: 10 }); + // The first request commits 900; the second reserves 10 + 100 more. + const { socket } = await startProxy(up, { tokenCap: 1000, maxTokensCeiling: 100 }); + assert.equal((await call(socket, { body: message() })).status, 200); + const res = await call(socket, { body: message() }); + assertRefused(res, 429, "rate_limit_error"); + // The documented spend-limit wording. + // Pointer: https://code.claude.com/docs/en/errors#spend-limit-reached + // As of: 2026-11-06. Recheck trigger: that section changes the message wording. + assert.match(JSON.parse(res.body).error.message, /^spend limit reached/); + assert.equal(up.seen.length, 1); +}); + +// Runs the script as the workflow will. +function spawnProxy(args, stdin) { + const child = spawn(process.execPath, [SCRIPT, ...args], { stdio: ["pipe", "pipe", "pipe"], env: { PATH: process.env.PATH } }); + const out = { stdout: "", stderr: "" }; + child.stdout.on("data", (c) => (out.stdout += c)); + child.stderr.on("data", (c) => (out.stderr += c)); + child.stdin.end(stdin); + const exited = new Promise((r) => child.on("exit", (code) => r(code))); + return { child, out, exited }; +} + +test("the script reads the key from stdin, never argv or env, and logs neither the key nor a request body", async () => { + const sentinel = "BODY-SENTINEL-7f3a"; + const up = await stubUpstream(okJson()); + const dir = tempDir("kp-"); + const config = path.join(dir, "config.json"); + writeFileSync(config, JSON.stringify({ ...BASE_CONFIG, socketMode: "660" })); + const socket = path.join(dir, "p.sock"); + const p = spawnProxy(["--socket", socket, "--config", config, "--upstream", up.url], `${KEY}\n`); + try { + await until(() => p.out.stderr.includes('"listening"')); + assert.equal(statSync(socket).mode & 0o777, 0o660); + const res = await call(socket, { body: message({ messages: [{ role: "user", content: sentinel }] }), headers: { "x-api-key": "dummy" } }); + assert.equal(res.status, 200); + assert.equal(up.seen[0].headers["x-api-key"], KEY); + await until(() => p.out.stderr.includes('"status":200')); + } finally { + p.child.kill("SIGTERM"); + await p.exited; + } + for (const stream of [p.out.stdout, p.out.stderr]) { + assert.ok(!stream.includes(KEY), "key logged"); + assert.ok(!stream.includes(sentinel), "body logged"); + } + assert.ok(!p.child.spawnargs.some((a) => a.includes(KEY))); +}); + +test("the script exits non-zero on a missing key or a bad config", async () => { + const dir = tempDir("kp-"); + const good = path.join(dir, "good.json"); + writeFileSync(good, JSON.stringify(BASE_CONFIG)); + const bad = path.join(dir, "bad.json"); + writeFileSync(bad, JSON.stringify({ ...BASE_CONFIG, tokenCap: 0, models: [] })); + const noBodyKeys = path.join(dir, "nokeys.json"); + writeFileSync(noBodyKeys, JSON.stringify({ ...BASE_CONFIG, bodyKeys: undefined })); + assert.equal(await spawnProxy(["--socket", path.join(dir, "a.sock"), "--config", good], "").exited, 2); + assert.equal(await spawnProxy(["--socket", path.join(dir, "b.sock"), "--config", bad], KEY).exited, 2); + assert.equal(await spawnProxy(["--socket", path.join(dir, "c.sock"), "--config", noBodyKeys], KEY).exited, 2); + const noTimeout = path.join(dir, "notimeout.json"); + writeFileSync(noTimeout, JSON.stringify({ ...BASE_CONFIG, upstreamTimeoutMs: undefined })); + assert.equal(await spawnProxy(["--socket", path.join(dir, "d.sock"), "--config", noTimeout], KEY).exited, 2); + assert.equal(await spawnProxy(["--config", good], KEY).exited, 2); +});