diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bc1f5f8..9c94ebac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,6 +78,10 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 - 입력의 실패 보고: `result.error.kind !== "REQUEST_ABORTED"`를 `!isAbortFailure(result.error)`(`src/contracts/errors.ts`)로 바꾼다. - 목록의 개수: `message(…resultCount, { count: number(query.data.total) })`처럼 `useLocale().number`로 넘긴다. - 옮긴 뒤 확인: 그 기능의 시험과 `scripts/verify.sh merge`. +- telemetry payload 예산 `TelemetryPayloadBudget`(`src/platform/telemetry/redact-telemetry.ts`)에 필수 필드 `maxNodes`가 생긴다. + - 옮기기 전: 그 타입 값을 직접 만들어 `createTelemetryPipeline`의 `budget.payload`에 넘기면 `check:types`가 `maxNodes`가 없다며 실패한다. + - 옮기는 법: `{ ...DEFAULT_TELEMETRY_PAYLOAD_BUDGET, … }`로 만들거나 `maxNodes`를 적는다(기본 512). 양의 안전 정수가 아니면 `createTelemetryPipeline`이 `TypeError`를 던진다. + - 옮긴 뒤 확인: `scripts/verify.sh script check:types`. ### 보안·계약 변경 @@ -113,6 +117,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | [계약] | `dependency-cache` 단계를 main job(`main_gate`)에도 둔다. 키·경로·main run만 저장·frozen install은 merge job과 같다. release·promotion·provider job은 그대로 거절한다. 위 `7ed0af3d` 행의 「merge job 셋에만」을 바꾼다(decisions.md FE-7) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md` | `d254d70a` | | [계약] | FE-GATE-005의 명령이 `test:coverage`·`check:scale:pr` 둘이 된다. `tests/unit`·`tests/contract`의 JUnit 증거(`unit.xml`·`contract.xml`, 이름·형식 그대로)는 coverage 실행 안의 reporter가 쓰고, 두 증거의 producer는 `test-coverage`다. 한 폴더에서 시험 파일이 하나도 돌지 않거나 보고서가 그 폴더에서 돈 파일과 다른 파일을 담으면 그 실행이 실패한다. unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. FE-GATE-004·006·007은 자기 실행을 그대로 둔다(decisions.md FE-4) | `config/ci/gates.json`, `package.json`, `scripts/lib/coverage-bundle-junit-reporter.ts`, `scripts/lib/feature-scaffold-drill.ts`, `tests/unit/coverage-bundle-junit-reporter.test.ts`, `docs/operations/ci-quality-gates.md` | `6cba1f50` | | [계약] | `check:ci:gating`(FE-GATE-029)이 Playwright 실행의 `--grep`·`--grep-invert`·파일 필터를 읽는다. testDir은 필터 없는 gated 실행이 있거나, `--grep-invert P` 실행마다 같은 testDir을 `--grep P`(같은 글자)로 도는 gated 실행이 있을 때만 게이트 안으로 센다. 파일 필터가 있는 실행, `--grep`·`--grep-invert`를 합쳐 둘 이상 쓴 실행, 설정(또는 그 설정이 import한 설정)에 `grep`·`grepInvert`가 있는 실행은 부분 실행으로 센다. 그 testDir의 게이트 밖 파일은 testDir·실행·빠진 짝을 대는 한 줄로 실패한다. 전에는 009의 Playwright 실행을 빼도 통과해, 시험이 모두 `@a11y`인 `tests/e2e/accessibility.spec.ts`가 어느 게이트에서도 돌지 않았다. `-c X`·`-cX`·`--config=X`로 고른 설정도 이제 읽는다(전에는 e2e 설정의 testDir로 셌다). 위 "먼저 할 일" | `scripts/lib/playwright-test-args.ts`, `scripts/lib/ungated-tests.ts`, `scripts/check-ci-gating.ts`, `playwright.a11y.config.ts`, `tests/unit/playwright-test-args.test.ts`, `tests/unit/ungated-tests.test.ts`, `tests/unit/playwright-result-paths.test.ts`, `docs/operations/ci-quality-gates.md` | `32982e55` | +| [보안] | telemetry payload 정제가 복사하는 값의 총수를 `maxNodes`(기본 512)로 막는다. 같은 객체를 여러 key가 가리키는 payload(정규화된 엔티티 graph 등)를 경로마다 따로 복사해, `emit` 한 번이 호출 스택을 수 초 막거나 heap OOM으로 탭을 죽였다. 여러 경로가 가리키는 객체의 key는 한 번만 읽는다. 순회가 너비 우선이 되어 상한이 차면 얕은 필드가 남고 깊은 값이 `[truncated]`가 된다. 복사본 객체의 key 순서가 원본 순서가 된다(전에는 거꾸로, fingerprint는 그대로). 깊이 제한 시험이 잘린 모양과 순환 payload를 단언한다 | `src/platform/telemetry/redact-telemetry.ts`, `src/platform/telemetry/telemetry-pipeline.ts`, `tests/platform/telemetry/redact-telemetry.test.ts`, `config/scale/feature-shape-ceilings.json` | `d406c10b`, `0190b631` | ### 그 밖의 변경 diff --git a/config/scale/feature-shape-ceilings.json b/config/scale/feature-shape-ceilings.json index c4e412a1..38d15aba 100644 --- a/config/scale/feature-shape-ceilings.json +++ b/config/scale/feature-shape-ceilings.json @@ -45,11 +45,11 @@ } ], "initialJavascript": { - "gzipBytes": 194339, + "gzipBytes": 194610, "files": 15, - "firstFeatureGzipBytes": 6221, - "perFeatureGzipBytes": 521, - "perContextGzipBytes": 7 + "firstFeatureGzipBytes": 6210, + "perFeatureGzipBytes": 546, + "perContextGzipBytes": 2 }, "serviceWorkerPrecache": { "assets": 22, diff --git a/src/platform/telemetry/redact-telemetry.ts b/src/platform/telemetry/redact-telemetry.ts index 9cc55159..a584c5fe 100644 --- a/src/platform/telemetry/redact-telemetry.ts +++ b/src/platform/telemetry/redact-telemetry.ts @@ -5,12 +5,26 @@ * preserves prototypes and never invokes getters or `toJSON` on untrusted * payloads. Traversal is iterative and capped by a structural budget, so an * adversarial payload cannot make telemetry itself unbounded. + * + * The per-value caps (depth, keys, array items, string length) do not bound + * the copy on their own: an object reached from many keys is copied once per + * path, so 4 levels of 64 keys pointing at one shared object copy 16.8 million + * values. `maxNodes` caps the whole copy. Values are visited breadth first, so + * when that cap runs out the shallow fields are kept and the deeper ones become + * `TRUNCATED`. Each copied value is one visit, and an object's own keys are + * listed once however many paths reach it, so the work is at most `maxNodes` + * visits plus one key listing per distinct object. */ export type TelemetryPayloadBudget = Readonly<{ maxDepth: number; maxKeys: number; maxArrayItems: number; maxStringLength: number; + /** + * Values in the whole copy: objects, arrays, leaves and `TRUNCATED` markers. + * A positive safe integer (the pipeline rejects anything else). + */ + maxNodes: number; }>; export const DEFAULT_TELEMETRY_PAYLOAD_BUDGET: TelemetryPayloadBudget = @@ -19,6 +33,7 @@ export const DEFAULT_TELEMETRY_PAYLOAD_BUDGET: TelemetryPayloadBudget = maxKeys: 64, maxArrayItems: 32, maxStringLength: 256, + maxNodes: 512, }); export const REDACTED = "[redacted]"; @@ -127,12 +142,44 @@ type Pending = Readonly<{ assign: (value: unknown) => void; }>; +type Child = readonly [slot: string | number, value: unknown]; + +type Copy = unknown[] | Record; + +function place(copy: Copy, slot: string | number, value: unknown): void { + if (Array.isArray(copy)) copy[Number(slot)] = value; + else copy[String(slot)] = value; +} + +/** The own data values a copy of `source` keeps, before the node budget. */ +function childrenOf(source: object, budget: TelemetryPayloadBudget): Child[] { + const children: Child[] = []; + if (Array.isArray(source)) { + const length = Math.min(source.length, budget.maxArrayItems); + for (let index = 0; index < length; index += 1) { + const item = readOwnData(source, String(index)); + children.push([index, item.ok ? item.value : null]); + } + return children; + } + for (const key of Object.keys(source).slice(0, budget.maxKeys)) { + if (key === "__proto__" || key === "constructor" || key === "prototype") { + continue; + } + if (isSecretTelemetryKey(key)) continue; + const entry = readOwnData(source, key); + if (entry.ok) children.push([key, entry.value]); + } + return children; +} + export function redactTelemetryPayload( payload: unknown, budget: TelemetryPayloadBudget = DEFAULT_TELEMETRY_PAYLOAD_BUDGET, ): unknown { let result: unknown = null; - const stack: Pending[] = [ + // A queue, not a stack: breadth first, so a spent node budget cuts the deepest values. + const queue: Pending[] = [ { source: payload, depth: 0, @@ -141,8 +188,12 @@ export function redactTelemetryPayload( }, }, ]; - while (stack.length > 0) { - const { source, depth, assign } = stack.pop() as Pending; + // Every queued entry becomes exactly one value of the copy. + let nodes = 1; + // A shared object is reached from many paths; list its own keys once. + const listed = new WeakMap(); + for (let head = 0; head < queue.length; head += 1) { + const { source, depth, assign } = queue[head] as Pending; if (source === null || typeof source !== "object") { assign(source === undefined ? null : sanitizeLeaf(source, budget)); continue; @@ -151,37 +202,34 @@ export function redactTelemetryPayload( assign(TRUNCATED); continue; } - if (Array.isArray(source)) { - const length = Math.min(source.length, budget.maxArrayItems); - const copy: unknown[] = new Array(length).fill(null); - assign(copy); - for (let index = 0; index < length; index += 1) { - const item = readOwnData(source, String(index)); - if (!item.ok) continue; - stack.push({ - source: item.value, - depth: depth + 1, - assign: (value) => { - copy[index] = value; - }, - }); - } + let children = listed.get(source); + if (children === undefined) { + children = childrenOf(source, budget); + listed.set(source, children); + } + const room = budget.maxNodes - nodes; + if (children.length > 0 && room <= 0) { + assign(TRUNCATED); continue; } - const copy: Record = {}; + // Without room for every child, the last slot that fits holds the marker. + const kept = Math.min(children.length, room); + nodes += kept; + const copy: Copy = Array.isArray(source) ? new Array(kept).fill(null) : {}; assign(copy); - for (const key of Object.keys(source).slice(0, budget.maxKeys)) { - if (key === "__proto__" || key === "constructor" || key === "prototype") { - continue; + for (let index = 0; index < kept; index += 1) { + const [slot, value] = children[index] as Child; + if (kept < children.length && index === kept - 1) { + place(copy, slot, TRUNCATED); + break; } - if (isSecretTelemetryKey(key)) continue; - const entry = readOwnData(source, key); - if (!entry.ok) continue; - stack.push({ - source: entry.value, + // Holds the key's place so the copy keeps the source's key order. + place(copy, slot, null); + queue.push({ + source: value, depth: depth + 1, - assign: (value) => { - copy[key] = value; + assign: (copied) => { + place(copy, slot, copied); }, }); } diff --git a/src/platform/telemetry/telemetry-pipeline.ts b/src/platform/telemetry/telemetry-pipeline.ts index 37d11dff..af9039ae 100644 --- a/src/platform/telemetry/telemetry-pipeline.ts +++ b/src/platform/telemetry/telemetry-pipeline.ts @@ -25,6 +25,11 @@ import { createDeterministicSampler } from "./telemetry-sampler.ts"; * * Every stage has an explicit ceiling, and no stage can throw or reject into * the business caller: internal failures become dropped-event counters. + * Redaction runs inside `emit` on the caller's stack, so its ceiling is the + * payload budget's `maxNodes` (values in the whole copy, plus one own-key + * listing per distinct object), not the byte ceiling that applies after it: a + * payload whose objects share references would otherwise be copied once per + * path before any byte count is taken. * * A duplicate inside the dedup window is not sent on its own. Its count is held * per fingerprint and delivered as `occurrences` on the next flush, or on a @@ -153,6 +158,7 @@ export function createTelemetryPipeline( assertPositive("maxBatchEvents", budget.maxBatchEvents); assertPositive("maxSendsPerMinute", budget.maxSendsPerMinute); const payloadBudget = budget.payload ?? DEFAULT_TELEMETRY_PAYLOAD_BUDGET; + assertPositive("payload.maxNodes", payloadBudget.maxNodes); const now = options.now ?? (() => performance.now()); const schedule = options.schedule ?? queueMicrotask; const setTimer = diff --git a/tests/platform/telemetry/redact-telemetry.test.ts b/tests/platform/telemetry/redact-telemetry.test.ts index 108528d5..0b346c23 100644 --- a/tests/platform/telemetry/redact-telemetry.test.ts +++ b/tests/platform/telemetry/redact-telemetry.test.ts @@ -6,6 +6,35 @@ import { 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([ @@ -161,13 +190,89 @@ describe("redactTelemetryPayload", () => { ); 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 }, + { maxDepth: 4, maxKeys: 10, maxArrayItems: 5, maxStringLength: 16, maxNodes: 512 }, ) as Record; - expect(JSON.stringify(result)).toContain(TRUNCATED); + // `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"] as string).length).toBeLessThanOrEqual(16 + TRUNCATED.length); + expect(result["text"]).toBe(`${"x".repeat(16)}${TRUNCATED}`); + }); + + it("stops a self-referencing payload at the depth limit", () => { + const cycle: Record = { 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; + + 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", () => { @@ -188,3 +293,42 @@ describe("redactTelemetryPayload", () => { ).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 => ({ 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); + }); +});