Your agent's error logging leaks the API key: plant canary secrets and fail the build when one shows up
A Vitest test, a scrubbing logger and a call-site fix that stop an agent-written API client from writing credentials into your logs. About 15 minutes to try.

Ask an agent for an API client with decent error handling and the result usually looks great in review. A try/catch, a descriptive message, and a log.error call that includes everything you’d want at 3am: the URL, the headers, the config, the error. Everything includes the credentials.
Nothing fails when this ships. The tests pass, because they check that the function throws. The first sign is a secret sitting in a log aggregator that forty people can search, or a vendor email asking why a key was used from an unfamiliar place. Reading the diff doesn’t reliably catch it, because the leak is rarely in the line that looks suspicious. It’s in an error message that interpolates a URL three functions away.
The fix is a test that plants fake secrets, forces every failure path, and fails if any of them appear in the log output. It takes one file and runs in any test setup. Below it’s built against a small TypeScript client, then tightened until it passes. The technique, the prompt and the check work with any coding agent that can read files and run a shell, so none of it depends on one tool.
The code under test
Here’s the kind of client an agent writes without being told otherwise. It fetches an invoice from a partner API that takes the key in the query string and a token in a header:
import type { Logger } from "./logger.js";
export interface PartnerConfig {
baseUrl: string;
apiKey: string;
token: string;
webhookSecret: string;
}
export async function fetchInvoice(id: string, cfg: PartnerConfig, log: Logger) {
const url = `${cfg.baseUrl}/invoices/${id}?api_key=${cfg.apiKey}`;
const headers = { Authorization: `Bearer ${cfg.token}`, "X-Request-Id": crypto.randomUUID() };
try {
const res = await fetch(url, { headers });
if (!res.ok) throw new Error(`Partner API returned ${res.status} for ${url}`);
return (await res.json()) as { id: string; total: number };
} catch (err) {
log.error("invoice fetch failed", { id, url, headers, cfg, err });
throw err;
}
}
And the logger it sits on, which turns Error objects into something JSON can carry, because JSON.stringify on an Error gives {}:
export type Sink = (line: string) => void;
export interface Logger {
error(message: string, fields?: Record<string, unknown>): void;
}
function describeError(err: Error): Record<string, unknown> {
return { name: err.name, message: err.message, stack: err.stack, cause: err.cause instanceof Error ? describeError(err.cause) : err.cause };
}
export function createLogger(sink: Sink): Logger {
return {
error(message, fields = {}) {
const replacer = (_k: string, v: unknown) => (v instanceof Error ? describeError(v) : v);
sink(JSON.stringify({ level: "error", message, ...fields }, replacer));
},
};
}
Both files are ordinary. The sink is injected, which is what makes the log testable: production passes a function that writes to stdout, the test passes one that pushes onto an array.
Plant the canaries
A canary secret is a made-up value that’s obviously fake, unique and greppable. Give the config three of them, one per way a credential tends to travel (query string, header, signing secret):
export const CANARIES = {
apiKey: "CANARY-apikey-7f3a91c2",
token: "CANARY-token-b81d44e0",
webhookSecret: "CANARY-whsec-0c5e92aa",
};
Real values would work too, but a canary has two advantages. It’s safe to commit and paste into a failure report, and it can’t be mistaken for anything else. When the output contains CANARY-token-b81d44e0, there’s one explanation.
The test also needs a server that fails on demand. A local node:http server with three modes (500, 401, and a 200 with invalid JSON) covers the failures a real partner produces, and port 1 on localhost covers connection refused:
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
export async function startPartner() {
let mode: "500" | "401" | "badjson" = "500";
const server: Server = createServer((_req, res) => {
if (mode === "500") { res.statusCode = 500; res.end("boom"); }
else if (mode === "401") { res.statusCode = 401; res.end("no"); }
else { res.statusCode = 200; res.end("{not json"); }
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const { port } = server.address() as AddressInfo;
return {
baseUrl: `http://127.0.0.1:${port}`,
setMode: (m: typeof mode) => { mode = m; },
close: () => new Promise<void>((r) => server.close(() => r())),
};
}
The test
One test, run once per failure path with it.each. It checks every canary in four spellings, because secrets leak in transformed form as often as raw: as-is, URL-encoded, base64, and base64 as the second half of a user:secret pair (which is what HTTP Basic auth sends):
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createLogger } from "../src/logger.js";
import { fetchInvoice, type PartnerConfig } from "../src/partner.js";
import { CANARIES, startPartner } from "./helpers.js";
const variants = (s: string) => [
...new Set([s, encodeURIComponent(s), Buffer.from(s).toString("base64"), Buffer.from(`svc:${s}`).toString("base64")]),
];
let partner: Awaited<ReturnType<typeof startPartner>>;
beforeAll(async () => { partner = await startPartner(); });
afterAll(async () => { await partner.close(); });
const scenarios = [
["server error", "500"],
["unauthorised", "401"],
["bad json", "badjson"],
["connection refused", "refused"],
] as const;
describe("failure paths never write a secret to the log", () => {
it.each(scenarios)("%s", async (_name, mode) => {
const lines: string[] = [];
const log = createLogger((l) => lines.push(l));
const cfg: PartnerConfig = { baseUrl: partner.baseUrl, ...CANARIES };
if (mode === "refused") cfg.baseUrl = "http://127.0.0.1:1";
else partner.setMode(mode);
await expect(fetchInvoice("inv_1", cfg, log)).rejects.toBeDefined();
expect(lines.length).toBeGreaterThan(0); // the failure was logged at all
const output = lines.join("\n");
const leaks = Object.entries(CANARIES).flatMap(([name, secret]) =>
variants(secret).filter((v) => output.includes(v)).map((v) => `${name} as ${v}`));
expect(leaks).toEqual([]);
});
});
Two details matter. The lines.length assertion stops the test passing vacuously: a logger that swallows everything has no leaks, and a test that can’t fail is worse than none. And the leak list is an array compared with toEqual([]), so a failure names the secret and the spelling instead of printing “expected false to be true”.
Watch it fail
Run npx vitest run against the client as written:
× server error
× unauthorised
× bad json
× connection refused
Tests 4 failed (4)
+ "apiKey as CANARY-apikey-7f3a91c2",
+ "token as CANARY-token-b81d44e0",
+ "webhookSecret as CANARY-whsec-0c5e92aa",
All four fail, and the whole config is in the log, which is what you’d expect from a call site that passes cfg. That’s the obvious bug. A reviewer would likely catch it, and so would the agent if you asked it to fix the failing test.
The next part is the useful one. Take the obvious patch, the one an agent (or a person in a hurry) makes first: drop headers and cfg from the log call.
log.error("invoice fetch failed", { id, url, err });
Run it again:
× server error
× unauthorised
× bad json
× connection refused
Tests 4 failed (4)
+ "apiKey as CANARY-apikey-7f3a91c2",
Still four failures, one canary. The key is in the query string, so url carries it, and in the 500 and 401 cases the thrown message interpolates the same URL. The agent’s patch removed the two leaks that were easy to see and left the one that reads like harmless context. A review that approves “removed credentials from the log” would have passed this. The canary test doesn’t, and it names the exact value that’s still there.
Fix it in two layers
Neither layer alone is enough, and the reasons differ.
The first layer is at the call site: log the path, not the URL, and keep credentials out of error messages. This removes the leak at its source:
if (!res.ok) throw new Error(`Partner API returned ${res.status} for /invoices/${id}`);
// ...
log.error("invoice fetch failed", { id, path: `/invoices/${id}`, err });
The second layer is the logger, which makes the next careless call site harmless. It does two things: it redacts by key name, and it scrubs known secret values from the finished line:
export interface LoggerOptions {
/** Exact secret values. Every one is scrubbed from the finished line, in any common encoding. */
secrets?: string[];
}
const SECRET_KEYS = /^(authorization|cookie|set-cookie|password|token|api[_-]?key|secret)$/i;
function encodings(secret: string): string[] {
const json = JSON.stringify(secret).slice(1, -1);
return [...new Set([
secret,
json,
encodeURIComponent(secret),
Buffer.from(secret).toString("base64"),
])].filter((s) => s.length >= 8); // very short values would shred ordinary text
}
export function createLogger(sink: Sink, options: LoggerOptions = {}): Logger {
const needles = (options.secrets ?? []).flatMap(encodings);
const replacer = (key: string, v: unknown) => {
if (SECRET_KEYS.test(key)) return "[redacted]";
return v instanceof Error ? describeError(v) : v;
};
return {
error(message, fields = {}) {
let line = JSON.stringify({ level: "error", message, ...fields }, replacer);
for (const needle of needles) line = line.replaceAll(needle, "[redacted]");
sink(line);
},
};
}
Key-name redaction catches Authorization and api_key fields wherever they nest, but it can’t see a secret inside a string, such as a URL or an error message. That’s what value scrubbing is for. It runs on the serialised line, after Error objects have been expanded to include message, stack and cause, so a secret buried in a cause chain is covered too. It’s applied last, so nothing can reintroduce a value after it runs.
The encodings list includes the JSON-escaped form because the scrub runs on JSON text. A secret containing a quote or backslash appears escaped in the line, and a plain includes would miss it. The length floor keeps a short value like 1234 from replacing every 1234 in a log line, which makes logs useless and hides the real problem.
Wire the secrets in where the logger is built, from the same config that holds them (createLogger(sink, { secrets: [cfg.apiKey, cfg.token, cfg.webhookSecret] })), and add the same option in the test’s createLogger call. Run the suite:
Tests 4 passed (4)
To confirm the second layer works on its own, put the leaky call site back ({ id, url, headers, err } and the URL in the message) and run again. It still passes with four of four, and the line it writes looks like this (trimmed):
{"level":"error","message":"invoice fetch failed","id":"inv_1","url":"http://127.0.0.1:1/invoices/inv_1?api_key=[redacted]","headers":{"Authorization":"[redacted]","X-Request-Id":"726fc1c1-c5d0-4812-99dc-1bdaddc23b39"},"err":{"name":"TypeError","message":"fetch failed","stack":"TypeError: fetch failed\n at node:internal/deps/undici/undici:15456:13\n ...
So the call-site fix removes the leak, and the scrubber is the net under it. Keep both. A scrubber without the call-site fix still logs more than it should, and a call-site fix without the scrubber depends on every future edit being careful.
The prompt that closes the loop
The point of the test is that an agent can run it. Give it this, with the file path adjusted:
Add a canary-secret test for every module that logs and holds credentials.
Plant three fake secrets with a CANARY- prefix in the config. Force every
failure path the module has (HTTP errors, timeouts, refused connections,
malformed bodies, validation errors). Capture the log through an injected
sink and fail if any canary appears raw, URL-encoded or base64-encoded.
Run it, show me the failing output, then fix the code until it passes.
Do not weaken the test or filter the output to get green.
Then read the first failing run before the agent fixes anything. If the test doesn’t fail on code you know is leaky, the test is wrong, and no fix will tell you that.
Make it yours
Every setup differs in where the log goes and what the secrets look like. Three adaptations cover most of them.
For an ASP.NET Core service, the same shape works with ILogger and a test ILoggerProvider that collects formatted messages, including the exception text and every structured property. Plant the canaries in IOptions<T>, drive the failures through WebApplicationFactory, and assert on the collected output. Don’t forget the exception’s ToString(), since that’s what the console provider writes.
For a service with many clients, put the canary values in one shared fixture and run the same assertion in every module’s failure tests. The marginal cost is a function call, and the day somebody adds a new client with a new log line is the day it pays off.
For a pipeline that already has a secret scanner, keep both. Scanners recognise the shapes of real credentials, so they miss a bespoke partner key. A canary test knows exactly what to look for in exactly the code you wrote, so it misses anything you didn’t plant. The two cover different holes.
What goes wrong
The test only finds leaks along paths it exercises. A failure that only happens against the real partner, say a redirect with the key in the Location header, isn’t there until a scenario forces it. Add a scenario when an incident teaches you a new path, and have the agent write it.
Value scrubbing only knows values you register and encodings you list. A derived value, such as an HMAC signature, a JWT signed with the secret, or a hash, isn’t the secret and isn’t scrubbed, though it may be just as sensitive. Those need key-name redaction or call-site discipline. The base64 variant in the test (svc: plus the secret) catches Basic auth headers, but it won’t catch every encoding someone invents.
Logs aren’t the only sink. Error trackers, traces, metrics labels, and the message that comes back to the caller in an HTTP response can all carry the same values. If your error tracker captures request data on its own, test its serialisation path with the same canaries, or turn that capture off. OWASP’s logging guidance lists access tokens and session identifiers among the values that should usually be removed, masked, sanitised, hashed or encrypted before they reach a log, and that applies to every one of those sinks.
Don’t bother if the module never logs and never builds an error message from its inputs. And don’t treat a passing run as proof the code is clean: it proves that the paths you drove, with the secrets you planted, produced no copy of them. That’s a narrower claim than “no leaks”, and a useful one.
First 15 minutes
Pick one module that holds a credential and catches errors. Plant the canaries in its config, inject the log sink, and write the single it.each over its failure paths. Run it before changing any code, and read what it reports.
If it passes on the first run, break it on purpose by adding cfg to a log call. A canary test you’ve never seen fail isn’t ready to trust.