// The API key never leaves the x-api-key header: not in a log, an error, an // event, a transcript or a request body — on success, a 401, a 400, retry // exhaustion, a network failure, a tool error and a bad key file. The key is // recognisable, and the servers below echo it back in their errors (worse than // the real API does) to prove the redaction. import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { inspect } from "node:util"; import { FAKE_KEY, errorTurn, startFakeAnthropic, textTurn, toolTurn, turn, toolUseBlock } from "../../testing/llm/fakeAnthropic.mjs"; import { AnthropicClient, type AnthropicConfig } from "./anthropic"; import { runAgent, type AgentEvent, type AgentTool } from "./agent"; import { Meter } from "./meter"; import { structuredAnswer } from "./structured"; const KEY = FAKE_KEY; function capture(seen: string[], v: unknown) { if (v instanceof Error) { seen.push(v.message, String(v.stack), String(v), inspect(v, { depth: 5 }), JSON.stringify({ ...v })); if (v.cause) capture(seen, v.cause); } else seen.push(typeof v === "string" ? v : (JSON.stringify(v) ?? String(v)), inspect(v, { depth: 8 })); } test("the key appears in no log, error, event, transcript or request body", async () => { const seen: string[] = []; const methods = ["log", "info", "warn", "error", "debug"] as const; const saved = methods.map((m) => console[m]); for (const m of methods) console[m] = (...args: unknown[]) => void seen.push(args.map((a) => inspect(a)).join(" ")); const echo = `invalid request (key ${KEY})`; const api = await startFakeAnthropic({ turns: [ // 1. success: a tool loop with a tool that errors, then an answer toolTurn("lookup", { q: "oven" }), textTurn("done"), // 2. structured answer, success turn([toolUseBlock("answer", { ok: true })]), // 3. a 400 that echoes the key errorTurn(400, "invalid_request_error", echo), // 4. retry exhaustion, every attempt echoing the key errorTurn(529, "overloaded_error", echo), errorTurn(529, "overloaded_error", echo), errorTurn(529, "overloaded_error", echo), ], }); const wrong = await startFakeAnthropic({ key: "another-key-for-the-401", turns: [] }); const dir = await mkdtemp(path.join(os.tmpdir(), "llm-leak-")); try { const env = { ANTHROPIC_API_KEY: KEY }; const cfg: AnthropicConfig = { baseUrl: api.url, env, sleep: async () => {}, maxRetries: 2 }; const events: AgentEvent[] = []; const failing: AgentTool = { name: "lookup", description: "d", inputSchema: { type: "object", properties: {} }, run: async () => { throw new Error("the index is offline"); }, }; // 1. const r = await runAgent({ llm: { anthropic: cfg }, model: "claude-sonnet-5-5", system: "s", user: "u", tools: [failing], meter: new Meter(), onEvent: (e) => events.push(e), }); assert.equal(r.stopReason, "end_turn"); capture(seen, r); capture(seen, events); // 2. capture(seen, await structuredAnswer({ llm: { anthropic: cfg }, model: "claude-sonnet-5", system: "s", user: "u", schema: { type: "object", properties: { ok: { type: "boolean" } } } })); // 3. + 4. const client = new AnthropicClient(cfg); const body = { model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }; for (let i = 0; i < 2; i++) { const err = await client.messages(body).then( () => assert.fail("expected an error"), (e: unknown) => e, ); capture(seen, err); } capture(seen, client); // 5. a 401 (the server knows another key) — through the agent, so its events too const err401 = await runAgent({ llm: { anthropic: { ...cfg, baseUrl: wrong.url } }, model: "claude-sonnet-5", system: "s", user: "u", tools: [], meter: new Meter(), onEvent: (e) => events.push(e), }).then( () => assert.fail("expected a 401"), (e: unknown) => e, ); assert.match(String(err401), /401/); capture(seen, err401); // 6. a network failure (nothing listens there) const closed = await startFakeAnthropic(); const closedUrl = closed.url; await closed.close(); capture( seen, await new AnthropicClient({ ...cfg, baseUrl: closedUrl }).messages(body).catch((e: unknown) => e), ); // 7. bad key files: readable by others, and no key line const open = path.join(dir, "open.env"); await writeFile(open, `ANTHROPIC_API_KEY=${KEY}\n`); await chmod(open, 0o644); const noLine = path.join(dir, "noline.env"); await writeFile(noLine, `ANTHROPIC_KEY=${KEY}\n`); await chmod(noLine, 0o600); for (const file of [open, noLine]) { const e = await new AnthropicClient({ baseUrl: api.url, env: {}, apiKeyFile: file }).messages(body).catch((x: unknown) => x); assert.ok(e instanceof Error); capture(seen, e); } // The key was used — and only in the header. assert.ok(api.requestHeaders.length >= 6); for (const h of api.requestHeaders) assert.equal(h["x-api-key"], KEY); capture(seen, api.requests); capture(seen, wrong.requests); const all = seen.join("\n"); assert.ok(all.length > 1000, "captured something"); assert.ok(all.includes("[redacted]"), "the echoed key was redacted"); assert.ok(all.includes("the index is offline"), "the tool error was captured"); assert.equal(all.includes(KEY), false, "the key leaked"); for (let i = 0; i + 16 <= KEY.length; i += 4) assert.equal(all.includes(KEY.slice(i, i + 16)), false, `a piece of the key leaked: ${i}`); } finally { methods.forEach((m, i) => (console[m] = saved[i])); await api.close(); await wrong.close(); await rm(dir, { recursive: true, force: true }); } });