redactTelemetryPayload의 상한은 값 하나마다(깊이 6, key 64, 배열 32)였다. 같은 객체를 여러 key가 가리키면 경로마다 따로 복사하므로, 객체 4개가 key 64개로 다음 객체를 가리키는 payload 하나가 1,680만 개 값을 만들었다 (약 18초). 서로를 16개씩 가리키는 엔티티 50개는 emit 한 번이 1.5초, 24개면 heap OOM이었다. emit은 호출한 쪽 스택에서 동기로 정제하고, 이 비용은 256 KB 바이트 상한보다 먼저 들며 OOM은 emit의 try/catch가 못 잡는다. TelemetryPayloadBudget에 maxNodes(기본 512, 양의 안전 정수)를 더한다. 큐에 넣는 값마다 하나씩 센다. 자식이 있는데 자리가 하나도 없으면 그 값이 TRUNCATED다(빈 객체·배열은 그대로라 예산에 딱 맞는 payload도 값이 같다). 자식을 다 넣을 자리가 없으면 들어가는 마지막 자리에 TRUNCATED를 둔다. 그래서 복사본의 값 수는 maxNodes를 넘지 않는다. 여러 경로가 가리키는 객체의 자식 목록은 WeakMap에 두고 한 번만 만든다. 그래서 일의 양은 방문 maxNodes 번과 서로 다른 객체마다 key 목록 한 번이다. 순회를 스택에서 큐로 바꿔 너비 우선으로 돈다. 상한이 차면 얕은 필드가 남고 깊은 값이 잘린다. key 자리를 먼저 잡아 두어 복사본 객체의 key 순서가 원본 순서가 된다(전에는 거꾸로). fingerprint는 key를 정렬하므로 같다. createTelemetryPipeline은 payload.maxNodes가 양의 안전 정수가 아니면 다른 예산처럼 TypeError를 던진다. 버린 안: WeakSet으로 본 객체를 [circular]로 바꾸는 안은 서로 다른 객체의 넓은 트리가 여전히 곱으로 돌고, 같은 값을 두 번 넣은 정상 payload의 fingerprint가 바뀐다. maxKeys·maxDepth만 낮추는 안도 곱 꼴 증가가 남는다. 값 수를 꺼낼 때 세는 안(bounded-json.ts 방식)은 이미 큐에 든 자식이 TRUNCATED로 남아 복사본이 maxNodes x maxKeys까지 커진다. 위험·한계: TelemetryPayloadBudget을 직접 만든 코드는 maxNodes를 더해야 typecheck가 통과한다. 서로 다른 큰 객체(예: 큰 typed array 여러 개)는 객체마다 Object.keys가 key 전부를 읽는다. 그 비용은 payload가 실제로 든 메모리 크기에 비례한다. 시험: 공유 사슬(4단계 x key 64)의 복사본 값 수 <= maxNodes와 최상위 key 64개 유지, 상한이 찬 자리의 TRUNCATED, 너비 우선과 key 순서, 공유 객체의 key 목록 1회(Proxy ownKeys로 센다), 예산에 딱 맞는 payload의 빈 객체· 배열 유지, 파이프라인에 엔티티 50개 x 16 graph를 넣으면 accepted 1, dropped 0, batch 1개, payload에 entities 배열, 값 수 <= maxNodes, 잘못된 maxNodes 거절. 시간은 단언하지 않는다. RED·GREEN은 PR 본문에 적는다. 기준선: 정제 코드가 초기 번들에 들어가 initial JavaScript가 gzip +271 B (194339 -> 194610)다. config/scale/feature-shape-ceilings.json의 initialJavascript를 손으로 고치지 않고 measure-feature-shape-growth.ts --initial-baseline --write로 다시 썼다(.claude/rules/gates-and-budgets.md 기준선 기록 줄). 예산 206848 B, 기능 하나 1 KiB, context 하나 512 B 상한은 그대로이고 새 값(firstFeature 6210, perFeature 546, perContext 2)은 그 안이다. Refs: REV-FE-0029
335 lines
12 KiB
TypeScript
335 lines
12 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
DEFAULT_TELEMETRY_PAYLOAD_BUDGET,
|
|
REDACTED,
|
|
redactTelemetryPayload,
|
|
TRUNCATED,
|
|
} from "../../../src/platform/telemetry/redact-telemetry.ts";
|
|
import {
|
|
createTelemetryPipeline,
|
|
DEFAULT_TELEMETRY_PIPELINE_BUDGET,
|
|
} from "../../../src/platform/telemetry/telemetry-pipeline.ts";
|
|
import type { TelemetryBatchItem } from "../../../src/platform/telemetry/telemetry-pipeline.ts";
|
|
|
|
/** Values in a copied tree: objects, arrays and leaves. */
|
|
function countNodes(value: unknown): number {
|
|
let count = 0;
|
|
const pending: unknown[] = [value];
|
|
while (pending.length > 0) {
|
|
const current = pending.pop();
|
|
count += 1;
|
|
if (current !== null && typeof current === "object") {
|
|
for (const child of Object.values(current)) pending.push(child);
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
|
|
/** `levels` objects, each pointing at the next one from `width` keys. */
|
|
function sharedChain(levels: number, width: number): unknown {
|
|
let next: unknown = "leaf";
|
|
for (let level = 0; level < levels; level += 1) {
|
|
const target = next;
|
|
next = Object.fromEntries(Array.from({ length: width }, (_, key) => [`k${key}`, target]));
|
|
}
|
|
return next;
|
|
}
|
|
|
|
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_ORDER_ITEMS",
|
|
routeId: "orders.items.detail",
|
|
featureId: "order-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, maxNodes: 512 },
|
|
) as Record<string, unknown>;
|
|
|
|
// `deep` sits at depth 1, so maxDepth 4 copies three objects and cuts the fourth.
|
|
expect(result["deep"]).toEqual({ next: { next: { next: TRUNCATED } } });
|
|
expect(Object.keys(result["wide"] as object).length).toBeLessThanOrEqual(10);
|
|
expect(result["list"]).toHaveLength(5);
|
|
expect(result["text"]).toBe(`${"x".repeat(16)}${TRUNCATED}`);
|
|
});
|
|
|
|
it("stops a self-referencing payload at the depth limit", () => {
|
|
const cycle: Record<string, unknown> = { id: 1 };
|
|
cycle["self"] = cycle;
|
|
|
|
let expected: unknown = TRUNCATED;
|
|
for (let depth = 0; depth < DEFAULT_TELEMETRY_PAYLOAD_BUDGET.maxDepth; depth += 1) {
|
|
expected = { id: 1, self: expected };
|
|
}
|
|
expect(redactTelemetryPayload(cycle)).toEqual(expected);
|
|
});
|
|
|
|
it("bounds the whole copy when many keys share one object", () => {
|
|
// 4 objects, each pointing at the next from 64 keys: 16.8 million paths.
|
|
const result = redactTelemetryPayload(sharedChain(4, 64)) as Record<string, unknown>;
|
|
|
|
expect(countNodes(result)).toBeLessThanOrEqual(DEFAULT_TELEMETRY_PAYLOAD_BUDGET.maxNodes);
|
|
// Breadth first: every top-level key survives the cut.
|
|
expect(Object.keys(result)).toHaveLength(64);
|
|
});
|
|
|
|
it("marks the slot where the node budget runs out", () => {
|
|
const budget = { ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxNodes: 4 };
|
|
expect(redactTelemetryPayload({ list: [1, 2, 3, 4, 5] }, budget)).toEqual({
|
|
list: [1, TRUNCATED],
|
|
});
|
|
expect(redactTelemetryPayload({ a: 1, b: 2, c: 3, d: 4 }, budget)).toEqual({
|
|
a: 1,
|
|
b: 2,
|
|
c: TRUNCATED,
|
|
});
|
|
expect(redactTelemetryPayload({ a: { b: { c: 1 } }, d: 2 }, { ...budget, maxNodes: 3 })).toEqual({
|
|
a: TRUNCATED,
|
|
d: 2,
|
|
});
|
|
});
|
|
|
|
it("spends the node budget breadth first and keeps the source key order", () => {
|
|
// Depth first would copy b.d.e and cut a: { a: TRUNCATED, b: { d: { e: TRUNCATED } } }.
|
|
const result = redactTelemetryPayload(
|
|
{ a: { c: 1 }, b: { d: { e: { f: 1 } } } },
|
|
{ ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxNodes: 5 },
|
|
);
|
|
expect(result).toEqual({ a: { c: 1 }, b: { d: TRUNCATED } });
|
|
|
|
const cut = redactTelemetryPayload(
|
|
{ a: 1, b: 2, c: 3, d: 4 },
|
|
{ ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxNodes: 4 },
|
|
);
|
|
expect(JSON.stringify(cut)).toBe(`{"a":1,"b":2,"c":"${TRUNCATED}"}`);
|
|
});
|
|
|
|
it("lists a shared object's keys once however many paths reach it", () => {
|
|
let listings = 0;
|
|
const counted = new Proxy(
|
|
{ x: 1 },
|
|
{
|
|
ownKeys(target) {
|
|
listings += 1;
|
|
return Reflect.ownKeys(target);
|
|
},
|
|
},
|
|
);
|
|
|
|
redactTelemetryPayload({ list: Array.from({ length: 32 }, () => counted) });
|
|
expect(listings).toBe(1);
|
|
});
|
|
|
|
it("copies a payload that fills the node budget exactly as it is", () => {
|
|
// c spends the last slot, so the empty a and b are visited with no room left.
|
|
const payload = { c: { d: 1 }, a: {}, b: [] };
|
|
expect(redactTelemetryPayload(payload, { ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxNodes: 5 })).toEqual(
|
|
payload,
|
|
);
|
|
});
|
|
|
|
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 });
|
|
});
|
|
});
|
|
|
|
describe("redaction inside the telemetry pipeline", () => {
|
|
it("admits an entity graph that shares references in one bounded emit", async () => {
|
|
// 50 entities, each pointing at the next 16: a normalized graph with cycles.
|
|
const entities = Array.from({ length: 50 }, (_, id): Record<string, unknown> => ({ id }));
|
|
for (const [id, entity] of entities.entries()) {
|
|
for (let link = 1; link <= 16; link += 1) entity[`peer${link}`] = entities[(id + link) % 50];
|
|
}
|
|
const batches: TelemetryBatchItem[][] = [];
|
|
const pipeline = createTelemetryPipeline({
|
|
transport: { send: (batch) => void batches.push([...batch]) },
|
|
});
|
|
|
|
await pipeline.emit({ kind: "graph.loaded", severity: "error", payload: { entities } });
|
|
await pipeline.flush();
|
|
|
|
// emit redacts on the caller's stack: one visit per copied value and one
|
|
// key listing per distinct object, so the node count bounds its work
|
|
// without a wall-clock assertion.
|
|
expect(pipeline.stats()).toMatchObject({ accepted: 1, dropped: 0 });
|
|
expect(batches).toHaveLength(1);
|
|
expect(batches[0]?.[0]?.event.payload).toMatchObject({ entities: expect.any(Array) });
|
|
expect(countNodes(batches[0]?.[0]?.event.payload)).toBeLessThanOrEqual(
|
|
DEFAULT_TELEMETRY_PAYLOAD_BUDGET.maxNodes,
|
|
);
|
|
});
|
|
|
|
it.each([0, -1, 2.5, Number.NaN])("rejects a payload maxNodes of %s", (maxNodes) => {
|
|
expect(() =>
|
|
createTelemetryPipeline({
|
|
transport: { send: () => {} },
|
|
budget: {
|
|
...DEFAULT_TELEMETRY_PIPELINE_BUDGET,
|
|
payload: { ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, maxNodes },
|
|
},
|
|
}),
|
|
).toThrow(/payload\.maxNodes/u);
|
|
});
|
|
});
|