Files
clean-architecture-frontend…/tests/platform/telemetry/redact-telemetry.test.ts
T
DongHyeonkaandClaude Opus 5.5 4e0745c569 fix(telemetry): redact credentials anywhere in a string, URL secrets and emails (R-9.3)
The value check was anchored with ^, so "request failed: Authorization:
Bearer abc" passed through, as did ?access_token=... in a URL and email
addresses. The key deny-list also missed pwd/pass/auth/otp/pin.

Changes in src/platform/telemetry/redact-telemetry.ts:
- Bearer/Basic credentials and JWTs are masked wherever they occur; only
  the match is replaced with [redacted], the rest of the message stays.
  A JWT cut short still matches.
- URL query/fragment parameters (?, &, #) are masked when the name is a
  secret key (isSecretTelemetryKey) or one of the URL-only names code,
  key, sig. Non-secret parameters (limit, cursor, state) are kept.
- Email addresses are masked, including one cut in half by truncation.
- Keys: pwd, pass, auth, otp, pin match as whole key tokens (camelCase,
  snake, kebab, PINCode split), so spinner/author/compass/isPinned are
  kept; passcode and passphrase are added as fragments.
- Strings are truncated before the patterns run, so the scan is bounded
  by maxStringLength. No regex lookbehind (Vite's default target includes
  Safari 16.0).
Public exports and signatures are unchanged.

Pinned first (passed before and after): "keeps legitimate telemetry values
and innocent keys untouched" (enum codes, ULID/UUID/hex ids, route ids,
numbers, booleans, BASIC_PLAN, react@19.1.0, a URL without secrets,
code=... in prose, keys spinner/author/code/key).

RED before fix:
- "redacts the short secret key %s as a whole key token" (11 cases, key
  kept)
- "redacts credentials in the middle of a string" (values unchanged)
- "masks secret URL query and fragment parameters" (tokens kept)
- "masks email addresses" (email kept)
- "does not leak a secret cut in half by truncation" (partial secrets kept)

Gates: check:architecture, check:types:app, check:types:test, lint,
test:component, check:release-coherence, test:platform pass. test:unit
passes except tests/unit/removal-fixture.test.ts, which needs generated
release evidence under artifacts/ that a fresh worktree does not have
(unrelated to this change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 12:18:23 +09:00

191 lines
6.1 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
DEFAULT_TELEMETRY_PAYLOAD_BUDGET,
REDACTED,
redactTelemetryPayload,
TRUNCATED,
} from "../../../src/platform/telemetry/redact-telemetry.ts";
describe("redactTelemetryPayload", () => {
it.each([
"password",
"authorization",
"cookie",
"accessToken",
"refreshToken",
"access_token",
"Set-Cookie",
"apiKey",
"clientSecret",
])("redacts %s recursively", (secretKey) => {
const input = { nested: { [secretKey]: "secret", safe: "ok" } };
const result = redactTelemetryPayload(input);
expect(JSON.stringify(result)).not.toContain("secret");
expect(result).toMatchObject({ nested: { safe: "ok" } });
});
it("redacts credential-shaped values under innocent keys", () => {
const result = redactTelemetryPayload({
note: "Bearer abc.def.ghi",
jwt: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.sig",
list: ["Basic dXNlcjpwYXNz"],
});
expect(result).toEqual({ note: REDACTED, jwt: REDACTED, list: [REDACTED] });
});
it("keeps legitimate telemetry values and innocent keys untouched", () => {
const legitimate = {
reason: "REQUEST_TIMEOUT",
operation: "LIST_REFERENCE_RESOURCES",
routeId: "reference.resources.detail",
featureId: "reference-feature",
resourceId: "01J8Z3K7Q9W4N2B6C5D1E0F7GH",
uuid: "3f2a9c1e-5b7d-4e8f-9a0b-1c2d3e4f5a6b",
traceHex: "4bf92f3577b34da6a3ce929d0e0e4736",
plan: "BASIC_PLAN",
dependency: "react@19.1.0",
path: "/api/resources?limit=20&cursor=c1#top",
message: "error code=REQUEST_TIMEOUT after 3 attempts",
status: 404,
durationMs: 12.5,
retried: false,
spinner: "visible",
author: "system",
compass: "north",
opinion: "none",
shipping: "standard",
isPinned: true,
code: "E_CONFLICT",
key: "sort-order",
};
expect(redactTelemetryPayload(legitimate)).toEqual(legitimate);
});
it.each([
"pwd",
"pass",
"auth",
"otp",
"pin",
"userPwd",
"pin_code",
"PINCode",
"x-otp",
"authHeader",
"passcode",
])("redacts the short secret key %s as a whole key token", (secretKey) => {
const result = redactTelemetryPayload({ [secretKey]: "s3cr3t", safe: "ok" });
expect(result).toEqual({ safe: "ok" });
});
it("redacts credentials in the middle of a string", () => {
expect(
redactTelemetryPayload({
header: "request failed: Authorization: Bearer abc",
basic: "proxy said Basic dXNlcjpwYXNz was rejected",
jwt: "retry with eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl now",
}),
).toEqual({
header: `request failed: Authorization: ${REDACTED}`,
basic: `proxy said ${REDACTED} was rejected`,
jwt: `retry with ${REDACTED} now`,
});
});
it("masks secret URL query and fragment parameters", () => {
expect(
redactTelemetryPayload(
"GET https://api.example.com/cb?code=abc123&state=xyz&access_token=tok456&key=k1#id_token=jwt789",
),
).toBe(
`GET https://api.example.com/cb?code=${REDACTED}&state=xyz&access_token=${REDACTED}&key=${REDACTED}#id_token=${REDACTED}`,
);
expect(redactTelemetryPayload("/login?user=a&password=hunter2&otp=123456")).toBe(
`/login?user=a&password=${REDACTED}&otp=${REDACTED}`,
);
});
it("masks email addresses", () => {
expect(
redactTelemetryPayload({ note: "invite failed for jane.doe+test@example.co.uk twice" }),
).toEqual({ note: `invite failed for ${REDACTED} twice` });
});
it("does not leak a secret cut in half by truncation", () => {
const budget = { ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxStringLength: 32 };
const cut = redactTelemetryPayload(
{
email: `${"x".repeat(20)} jane.doe@example.com`,
query: `/cb${"x".repeat(10)}?access_token=abcdefghijklmnopqrstuvwxyz`,
bearer: `${"x".repeat(20)} Bearer abcdefghijklmnopqrstuvwxyz`,
},
budget,
);
expect(JSON.stringify(cut)).not.toMatch(/jane|abcd/u);
expect(JSON.stringify(cut)).toContain(TRUNCATED);
});
it("never invokes getters, toJSON or foreign prototypes", () => {
let invoked = false;
class Carrier {
visible = "kept";
toJSON() {
invoked = true;
return { leaked: true };
}
}
const hostile = Object.defineProperty(new Carrier(), "computed", {
enumerable: true,
get() {
invoked = true;
return "computed";
},
});
const result = redactTelemetryPayload({ hostile });
expect(invoked).toBe(false);
expect(result).toEqual({ hostile: { visible: "kept" } });
expect(Object.getPrototypeOf((result as { hostile: object }).hostile)).toBe(
Object.prototype,
);
});
it("bounds depth, width, array length and string length", () => {
let deep: unknown = "leaf";
for (let depth = 0; depth < 50; depth += 1) deep = { next: deep };
const wide = Object.fromEntries(
Array.from({ length: 500 }, (_, index) => [`k${index}`, index]),
);
const result = redactTelemetryPayload(
{ deep, wide, list: Array.from({ length: 1_000 }, (_, i) => i), text: "x".repeat(5_000) },
{ maxDepth: 4, maxKeys: 10, maxArrayItems: 5, maxStringLength: 16 },
) as Record<string, unknown>;
expect(JSON.stringify(result)).toContain(TRUNCATED);
expect(Object.keys(result["wide"] as object).length).toBeLessThanOrEqual(10);
expect(result["list"]).toHaveLength(5);
expect((result["text"] as string).length).toBeLessThanOrEqual(16 + TRUNCATED.length);
});
it("does not let prototype keys pollute the copy", () => {
const payload = JSON.parse('{"__proto__":{"polluted":true},"ok":1}') as unknown;
const result = redactTelemetryPayload(payload) as Record<string, unknown>;
expect(result).toEqual({ ok: 1 });
expect(({} as Record<string, unknown>)["polluted"]).toBeUndefined();
});
it("normalizes non-JSON leaves", () => {
expect(
redactTelemetryPayload({
n: Number.NaN,
f: () => 1,
u: undefined,
b: 10n,
}),
).toEqual({ n: null, f: null, u: null, b: null });
});
});