Files
clean-architecture-frontend…/tests/platform/telemetry/redact-telemetry.test.ts
T

98 lines
3.0 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
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("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 });
});
});