From 3c7ea1ce850c20c067add363ffcddbc1d48f2aac Mon Sep 17 00:00:00 2001 From: Abhishek Sharma <78235887+abhisheksharma001@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:12:13 +0530 Subject: [PATCH] feat(browser): count credential-named members in HAR capture inspection (#8708) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(browser): count credential-named members in HAR capture inspection inspect_web_network_capture now runs the credential-name scan that environment-build already applies over the selected HAR records and reports matches as limitations by pointer, never by value, together with the bodies the scan could not read. Values the decoder already excluded are not counted, and nothing is excluded on a name. Refs #8207 Co-Authored-By: Claude Fable 5.1 * fix(browser): bound the listed credential-name pointers The limitation lists the pointers that fit within 1 KiB of text and says how many counted names are not listed, so one long body member name cannot inflate the limitation that summaries and record pages repeat. Co-Authored-By: Claude Fable 5.1 * fix(environment): bound the credential scan's values before parsing a body A body under the scan's 4 MiB text limit could still expand into millions of JSON values or form fields when parsed in the application process, and the inspection now runs the scan on every HAR capture. The scan counts the characters that can start a value (`[`, `{`, `,` for JSON, `&` for forms) before parsing and skips a body that could hold more than 524288, reporting it like a body over the text limit. Both consumers' messages and docs name the bound. Co-Authored-By: Claude Fable 5.1 * fix(web): charge every body and name/value list to one credential-scan budget The credential-name scan bounded each body's values on its own, so a capture of many compact bodies still expanded millions of values in the application process, and HAR header, query and form-parameter lists were copied twice without any bound. One 524288-value budget now covers the whole scan: a body's values are bounded from its text before it is parsed and a list is charged by its length before it is read in place, so what would pass the budget is reported as not scanned instead. Co-Authored-By: Claude Fable 5.1 * fix(web): read credential names in place and charge nothing for empty text The credential-name scan split each member, header and query name with two regex replacements, a lowercase copy and a split into a segment array before matching. A near-4 MiB alternating-case member name (`x-aAaA…`) therefore expanded into about two million segments: more than 192 MiB of heap in the application process after the decoder's containment had ended. `credentialNamed` now reads the name once in place with the same segmentation (case changes, digits, separators, and `toLowerCase`'s KELVIN SIGN and dotted capital I), keeping at most two segments no longer than the longest credential word, so a name of any length allocates no copies. `valueBound` started every text at one value, so an empty query, a bare `?`, an empty form and whitespace-only JSON were each charged a value they do not hold; once earlier content spent the budget, they were reported as unscanned in `credential-scan-incomplete`. JSON now holds its first value only after a non-whitespace character, and a form holds one field per non-empty `&`-separated piece after an optional leading `?`, as `URLSearchParams` and the query reader split it. Co-Authored-By: Claude Opus 5.5 * docs(browser): point the environment build link at the physical guide The guide lives at docs/agent-environments.md, so the relative link from docs/guides/web must climb two levels. The Documentation job failed on the dead link; vitepress build now completes. Co-Authored-By: Claude Sonnet 5.5 * test: drop the hard-coded timeout from the heap-bound name test The test finishes in about half a second, so the shared test deadline is enough, and a literal 60_000 bypasses the CI and coverage deadline scaling. Co-Authored-By: Claude Sonnet 5.5 * fix(web-network-capture): name an unavailable response source in the scan limitation The credential-name scan counts a response body whose retained source is unavailable as not scanned, and WebNetworkCaptureService reuses that scan. Its limitation text still listed only a cut body, text over 4 MiB, or past the value budget, so CLI and MCP reports gave none of those reasons for such a body. Name the unavailable source in the text, matching the environment-build warning, and cover it with a test that fails on the old wording. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Fable 5.1 --- docs/agent-environments.md | 20 +- docs/guides/web/web-network-captures.md | 18 ++ .../WebNetworkCaptureService.test.ts | 227 +++++++++++++++ src/application/WebNetworkCaptureService.ts | 49 ++++ .../environmentBuildReport.test.ts | 221 ++++++++++++++ .../environment/environmentBuildReport.ts | 272 +++++++++++++----- .../webNetworkCaptureToolContracts.ts | 2 +- .../browser/historicalWebCapture.test.ts | 97 +++++++ 8 files changed, 825 insertions(+), 81 deletions(-) diff --git a/docs/agent-environments.md b/docs/agent-environments.md index 58d85c8fcc..8fab6650bf 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -202,14 +202,18 @@ scanned by event (`event 4 response /token` names `normalized_result.events.items[4]`): every retained request and response content event, including a response whose request began before the browser was attached and a transaction no record represents, and each transaction URL's -query once. Bodies larger than 4 MiB of UTF-8 text are not -scanned. A retained HAR base64 body must match its declared source text and -representation before replay or state extraction; HAR's admitted ASCII whitespace -differences do not change source identity. A mismatched or missing retained source -is not promoted and is counted as unscanned, while its original Evidence is retained. -`credential-scan-incomplete` counts these unavailable sources and oversized -bodies, listing up to 20 record or event pointers, including base64 bodies whose -decoded scan was cut. An empty name +query once. The scan reads at most 524288 values in all: a body's values are +bounded from its text before it is parsed, and a header list or query string +is charged by its length before it is read, so a body larger than 4 MiB of +UTF-8 text, or any body, header list or query string that would take the scan +past its budget, is not scanned. A retained HAR base64 body must match its +declared source text and representation before replay or state extraction; +HAR's admitted ASCII whitespace differences do not change source identity. A +mismatched or missing retained source is not promoted and is counted as +unscanned, while its original Evidence is retained. +`credential-scan-incomplete` counts these unavailable sources and the bodies, +header lists and query strings the scan did not read, and lists up to 20 record +or event pointers, including base64 bodies whose decoded scan was cut. An empty name warning does not establish that these bodies were checked. A browser scenario's saved values (`save` and `save_response`) named like credentials but not marked `secret: true` are recorded unredacted; `credential-named-saved-values` lists up diff --git a/docs/guides/web/web-network-captures.md b/docs/guides/web/web-network-captures.md index 5f49655f87..8236267cf0 100644 --- a/docs/guides/web/web-network-captures.md +++ b/docs/guides/web/web-network-captures.md @@ -388,6 +388,24 @@ global, per-record and Evidence explanations added during projection. Contract field names, typed discriminators and exact decoder identities keep their canonical meanings; declarations do not rename formats or providers. +A HAR capture's header names, query parameter names and JSON or form body +member names that look like credentials (whole name segments such as `token`, +`secret`, `password`, `api_key`, `authorization` or `session`) and hold a +retained value are counted in a limitation that lists up to 20 of them by +record and pointer (`record 3 request header X-Api-Key`) within about 1 KiB +of text, says how many are not listed, and never names a value; the +[environment build](../../agent-environments.md) runs the same scan as its +`credential-named-members` warning. Values already excluded, such as the +standard authentication headers or declared sensitive values, are not counted. +The scan reads at most 524288 values in all across the selected records: a +body's values are bounded from its text before it is parsed, and a header +list, query string or form-parameter list is charged by its length before it +is read, so a body larger than 4 MiB of UTF-8 text, or any of these that would +take the scan past its budget, is not scanned, and a second limitation counts +them by record and side. Names do not establish sensitivity, so nothing is excluded on +them; declare the values as sensitive to exclude them. Other capture formats +are not scanned. + Historical evidence does not prove runtime attribution, execution or deployment authenticity. Mitmproxy messages are upstream-assembled messages, not recovered wire fragments. Native dictionary duplicate keys have the unchanged upstream diff --git a/src/application/WebNetworkCaptureService.test.ts b/src/application/WebNetworkCaptureService.test.ts index 76ba31e198..7a42c8af1c 100644 --- a/src/application/WebNetworkCaptureService.test.ts +++ b/src/application/WebNetworkCaptureService.test.ts @@ -650,3 +650,230 @@ it("rejects relative descriptor paths before starting a capture decoder", async }, }); }); + +/** HAR-shaped record whose credential-named members hold values the decoder retains. */ +const credentialNamedReport = (): WebNetworkCapture => { + const report = fixture(); + report.records[0]!.reported = { + request: { + method: "POST", + url: "https://example.test/login?api_key=demo-key", + headers: [ + { name: "Authorization", value: null }, + { name: "X-Demo-Token", value: "demo-token" }, + { name: "Accept", value: "application/json" }, + ], + queryString: [{ name: "api_key", value: "demo-key" }], + postData: { + mimeType: "application/json", + text: '{"user":"demo","password":"demo-pass"}', + }, + }, + response: { + status: 200, + headers: [{ name: "Set-Cookie", value: null }], + content: { + mimeType: "application/json", + text: '{"session_token":"demo-session"}', + }, + }, + }; + return report; +}; + +const credentialNameLimitation = (limitations: readonly string[]) => + limitations.filter((text) => text.includes("look like credentials")); + +it("counts credential-named members that hold a retained value, by pointer and never by value", async () => { + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(credentialNamedReport())), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + const [limitation, ...others] = credentialNameLimitation( + result.value.limitations, + ); + expect(others).toEqual([]); + expect(limitation).toMatch(/^4 /); + for (const pointer of [ + "record 0 request header X-Demo-Token", + "record 0 request query api_key", + "record 0 request /password", + "record 0 response /session_token", + ]) + expect(limitation).toContain(pointer); + // Redacted standard credentials and ordinary names are not counted. + expect(limitation).not.toContain("Authorization"); + expect(limitation).not.toContain("Accept"); + for (const value of ["demo-token", "demo-key", "demo-pass", "demo-session"]) + expect(limitation).not.toContain(value); + expect(result.value.normalized_result).toMatchObject({ + limitations: expect.arrayContaining([limitation]), + }); + expect(parseEvidence(result.value)).toEqual(result.value); +}); + +it("bounds the listed pointers so a long member name cannot inflate the limitation", async () => { + const report = credentialNamedReport(); + const long = "k".repeat(2048); + report.records[0]!.reported = { + request: { + method: "POST", + url: "https://example.test/login", + postData: { + mimeType: "application/json", + text: JSON.stringify({ + [long]: { token: "demo-token" }, + password: "p", + }), + }, + }, + response: { status: 204 }, + }; + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(report)), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + const [limitation] = credentialNameLimitation(result.value.limitations); + expect(limitation).toMatch(/^2 /); + expect(limitation).toContain("record 0 request /password"); + expect(limitation).toContain("1 more not listed"); + expect(limitation).not.toContain(long); + expect(limitation!.length).toBeLessThan(1024 + 400); +}); + +it("adds no credential-name limitation when no counted name holds a value", async () => { + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(fixture())), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + expect(credentialNameLimitation(result.value.limitations)).toEqual([]); +}); + +it("scans only HAR records for credential names", async () => { + const report = credentialNamedReport(); + report.format = "mitmproxy"; + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(report)), + }).inspect({ capture_path: "/capture.har", format: "mitmproxy" }); + if (!result.ok) throw result.error; + expect(credentialNameLimitation(result.value.limitations)).toEqual([]); +}); + +it("reports a body whose values would expand past the credential-name scan's bound", async () => { + const report = credentialNamedReport(); + report.records[0]!.reported = { + request: { method: "GET", url: "https://example.test/expansive" }, + response: { + status: 200, + content: { + mimeType: "application/json", + text: `[${"[],".repeat(300_000)}{"password":"x"}]`, + }, + }, + }; + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(report)), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + expect(credentialNameLimitation(result.value.limitations)).toEqual([]); + const skipped = result.value.limitations.filter((text) => + text.includes("were not scanned"), + ); + expect(skipped).toHaveLength(1); + expect(skipped[0]).toMatch(/^1 /); + expect(skipped[0]).toContain("record 0 response"); +}); + +it("shares the credential-name scan's value budget across the selected records", async () => { + const expansive = (path: string) => ({ + request: { method: "GET", url: `https://example.test/${path}` }, + response: { + status: 200, + content: { + mimeType: "application/json", + text: `[${"1,".repeat(300_000)}{"password":"x"}]`, + }, + }, + }); + const base = credentialNamedReport(); + const first = { ...base.records[0]!, reported: expansive("first") }; + const report: WebNetworkCapture = { + ...base, + total_records: 2, + records: [ + first, + { + ...first, + ordinal: 1, + location: { kind: "json-pointer", pointer: "/log/entries/1" }, + reported: expansive("second"), + }, + ], + }; + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(report)), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + const [found] = credentialNameLimitation(result.value.limitations); + expect(found).toMatch(/^1 /); + expect(found).toContain("record 0 response /300000/password"); + const skipped = result.value.limitations.filter((text) => + text.includes("were not scanned"), + ); + expect(skipped).toHaveLength(1); + expect(skipped[0]).toMatch(/^1 /); + expect(skipped[0]).toContain("record 1 response"); +}); + +it("reports a response body whose retained source is unavailable", async () => { + const report = credentialNamedReport(); + // A base64 body with no retained binary field has no source to decode. + report.records[0]!.reported = { + request: { method: "GET", url: "https://example.test/unretained" }, + response: { + status: 200, + content: { + mimeType: "application/json", + text: "eyJwYXNzd29yZCI6IngifQ==", + encoding: "base64", + }, + }, + }; + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(report)), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + expect(credentialNameLimitation(result.value.limitations)).toEqual([]); + const skipped = result.value.limitations.filter((text) => + text.includes("were not scanned"), + ); + expect(skipped).toHaveLength(1); + expect(skipped[0]).toMatch(/^1 /); + expect(skipped[0]).toContain("record 0 response"); + expect(skipped[0]).toContain("retained source is unavailable"); +}); + +it("reports bodies the credential-name scan could not read", async () => { + const report = credentialNamedReport(); + report.records[0]!.reported = { + request: { method: "GET", url: "https://example.test/large" }, + response: { + status: 200, + content: { + mimeType: "application/json", + text: `{"password":"${"x".repeat(4 * 1024 * 1024)}"}`, + }, + }, + }; + const result = await new WebNetworkCaptureService({ + inspect: () => Promise.resolve(ok(report)), + }).inspect({ capture_path: "/capture.har", format: "har" }); + if (!result.ok) throw result.error; + expect(credentialNameLimitation(result.value.limitations)).toEqual([]); + const skipped = result.value.limitations.filter((text) => + text.includes("were not scanned"), + ); + expect(skipped).toHaveLength(1); + expect(skipped[0]).toMatch(/^1 /); + expect(skipped[0]).toContain("record 0 response"); +}); diff --git a/src/application/WebNetworkCaptureService.ts b/src/application/WebNetworkCaptureService.ts index 9b20775694..42979cdaba 100644 --- a/src/application/WebNetworkCaptureService.ts +++ b/src/application/WebNetworkCaptureService.ts @@ -23,6 +23,7 @@ import { type WebNetworkCapture, } from "../domain/webNetworkCapture.js"; import { completeProviderEvidence } from "./ProviderOperationExecution.js"; +import { scanCredentialNames } from "./environment/environmentBuildReport.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; const OPERATION = "inspect_web_network_capture"; @@ -200,6 +201,9 @@ export class WebNetworkCaptureService { "The explicitly sensitive artifact path is excluded; its size remains available.", ] : []), + ...(safeValue.format === "har" + ? credentialNameLimitations(scanCredentialNames(records)) + : []), ].map(redactText); const parameters = jsonObjectSchema.parse({ capture_path: safePath, @@ -291,6 +295,51 @@ export class WebNetworkCaptureService { } } +/** A count with its first pointers, as the credential-name scan tallies them. */ +type ScanTally = { + readonly count: number; + readonly pointers: readonly string[]; +}; + +/** Listed pointers stay within this many characters, so one long member name cannot inflate a limitation. */ +const LISTED_POINTER_CHARACTERS = 1024; + +/** The pointers that fit the sample in order, then how many of the counted names are not listed. */ +const listedPointers = (tally: ScanTally): string => { + const listed: string[] = []; + let length = 0; + for (const pointer of tally.pointers) { + const added = pointer.length + (listed.length > 0 ? 2 : 0); + if (length + added > LISTED_POINTER_CHARACTERS) break; + length += added; + listed.push(pointer); + } + const unlisted = tally.count - listed.length; + if (unlisted === 0) return listed.join(", "); + const rest = `${String(unlisted)} ${listed.length > 0 ? "more " : ""}not listed`; + return listed.length > 0 ? `${listed.join(", ")}; ${rest}` : rest; +}; + +/** + * The credential-name scan environment-build runs over selected HAR records, + * as limitations: counts and pointers to names that hold a retained value, + * never the values, and what the scan did not read. + */ +const credentialNameLimitations = ( + scan: ReturnType, +): string[] => [ + ...(scan.count > 0 + ? [ + `${String(scan.count)} recorded header, query parameter or body member names look like credentials and hold a retained value (${listedPointers(scan)}); names do not establish sensitivity, so declare the values as explicitly sensitive to exclude them.`, + ] + : []), + ...(scan.skipped.count > 0 + ? [ + `${String(scan.skipped.count)} recorded bodies, header lists or query strings were not scanned: each is cut, over 4 MiB of text, past the 524288 values the credential-name scan reads in all, or a response body whose retained source is unavailable (${listedPointers(scan.skipped)}).`, + ] + : []), +]; + const isCapturePartialCandidate = (value: unknown): boolean => { if (typeof value !== "object" || value === null || Array.isArray(value)) return false; diff --git a/src/application/environment/environmentBuildReport.test.ts b/src/application/environment/environmentBuildReport.test.ts index cec10448b5..5c89bf2aab 100644 --- a/src/application/environment/environmentBuildReport.test.ts +++ b/src/application/environment/environmentBuildReport.test.ts @@ -1,3 +1,5 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; import { createHash } from "node:crypto"; @@ -47,6 +49,8 @@ const record = ( /** Every body of these records was small enough to scan. */ const NONE_SKIPPED = { count: 0, pointers: [] }; +const execFileAsync = promisify(execFile); + describe("credentialNamed", () => { it("matches whole name segments, not substrings", () => { for (const name of [ @@ -69,6 +73,67 @@ describe("credentialNamed", () => { for (const name of ["author", "authority_level", "keyboard", "tokenizer"]) expect(credentialNamed(name), name).toBe(false); }); + + it("splits case changes, digits and lowercasing as toLowerCase does", () => { + for (const name of [ + "SSHKey", + "API2Token", + "AUTHORIZATION", + "x-Session-ID", + // KELVIN SIGN lowercases to `k`. + "toKen", + "İİ-token", + ]) + expect(credentialNamed(name), name).toBe(true); + for (const name of [ + "authorizations", + "xToken2", + "apiXKey", + // U+0130 lowercases to `i` and a combining dot, which ends the segment. + "sessionİd", + ]) + expect(credentialNamed(name), name).toBe(false); + }); +}); + +describe("scanCredentialNames name reading", () => { + it("reads a near-4 MiB alternating-case member name in place within a 64 MiB heap", async () => { + const reportUrl = new URL("./environmentBuildReport.ts", import.meta.url) + .href; + // `x-aAaA…` names no credential, so every character is read; splitting it + // into its two million segments took more than 192 MiB of heap. + const program = ` + const { scanCredentialNames } = await import(${JSON.stringify(reportUrl)}); + const text = JSON.stringify({ ["x-" + "aA".repeat(2_000_000)]: "v", token: "t" }); + const record = { + ordinal: 1, + reported: { + request: { method: "GET", url: "http://127.0.0.1/api" }, + response: { status: 200, content: { mimeType: "application/json", text } }, + }, + redactions: [], + binary_fields: [], + }; + process.stdout.write(JSON.stringify(scanCredentialNames([record]))); + `; + const { stdout } = await execFileAsync( + process.execPath, + [ + "--max-old-space-size=64", + "--import", + import.meta.resolve("tsx"), + "--input-type=module", + "-e", + program, + ], + { encoding: "utf8" }, + ); + expect(JSON.parse(stdout)).toEqual({ + count: 1, + pointers: ["record 1 response /token"], + skipped: NONE_SKIPPED, + }); + }); }); describe("scanCredentialNames", () => { @@ -199,6 +264,96 @@ describe("scanCredentialNames body formats", () => { }); }); + it("skips a body holding more values than the scan reads, bounded before it is parsed", () => { + const skipped = { count: 1, pointers: ["record 3 request"] }; + // 300001 empty arrays: under 1 MiB of text, over the value bound. + expect( + scanCredentialNames([ + posted("application/json", `[${"[],".repeat(300_000)}[]]`), + ]), + ).toEqual({ count: 0, pointers: [], skipped }); + expect( + scanCredentialNames([posted(FORM, `${"a=&".repeat(524_288)}token=t`)]), + ).toEqual({ count: 0, pointers: [], skipped }); + expect( + scanCredentialNames([ + posted("application/json", `[${"1,".repeat(200_000)}{"token":"t"}]`), + ]), + ).toEqual({ + count: 1, + pointers: ["record 3 request /200000/token"], + skipped: NONE_SKIPPED, + }); + }); + + it("charges every body and name/value list to one budget before reading it", () => { + const named = ( + ordinal: number, + request: Record, + ): WebNetworkCaptureRecord => { + const scanned = record(ordinal, undefined, undefined); + Object.assign( + (scanned.reported as { request: Record }).request, + request, + ); + return scanned; + }; + // Each body bounds to 300003 values: the first fits, the second would pass the budget. + const body = `[${"1,".repeat(300_000)}{"token":"t"}]`; + const post = { mimeType: "application/json", text: body }; + expect( + scanCredentialNames([ + named(3, { postData: post }), + named(4, { postData: post }), + ]), + ).toEqual({ + count: 1, + pointers: ["record 3 request /300000/token"], + skipped: { count: 1, pointers: ["record 4 request"] }, + }); + // A list is charged by its length before it is read; one past the budget is skipped unread and charges nothing. + const list = (name: string, length: number) => { + const entry = { name, value: "v" }; + return Array.from({ length }, () => entry); + }; + const one = named(6, { headers: list("X-Demo-Token", 1) }); + expect( + scanCredentialNames([ + named(5, { + headers: list("X-Demo-Token", 524_289), + queryString: list("token", 524_289), + postData: { + mimeType: "multipart/form-data", + params: list("api_key", 524_289), + }, + }), + one, + ]), + ).toEqual({ + count: 1, + pointers: ["record 6 request header X-Demo-Token"], + skipped: { + count: 3, + pointers: [ + "record 5 request headers", + "record 5 request query", + "record 5 request", + ], + }, + }); + // Once the budget is spent, one more header is skipped rather than read. + expect( + scanCredentialNames([ + named(7, { headers: list("Accept", 524_288) }), + one, + ]), + ).toEqual({ + count: 0, + pointers: [], + skipped: { count: 1, pointers: ["record 6 request headers"] }, + }); + }); + it("finds nothing in plain text that is not a form", () => { for (const mimeType of ["text/plain", ""]) for (const text of ["token=abc to sign in", "Use token=abc", ""]) @@ -209,6 +364,51 @@ describe("scanCredentialNames body formats", () => { }); }); +describe("scanCredentialNames empty text", () => { + it("charges nothing for text that holds no value, so it is never reported unread", () => { + const entry = { name: "Accept", value: "v" }; + const spent = record(7, undefined, undefined); + (spent.reported as { request: Record }).request[ + "headers" + ] = Array.from({ length: 524_288 }, () => entry); + const bodies = ( + ordinal: number, + request: string, + response?: string, + ): WebNetworkCaptureRecord => { + const scanned = record(ordinal, undefined, undefined); + const reported = scanned.reported as { + request: { postData?: unknown }; + response: { content: unknown }; + }; + reported.request.postData = { + mimeType: "application/x-www-form-urlencoded", + text: request, + }; + reported.response.content = { + mimeType: "application/json", + text: response, + }; + return scanned; + }; + // The headers spend the whole budget; empty forms, a bare `?` and + // whitespace-only JSON hold nothing, so only the later field is unread. + expect( + scanCredentialNames([ + spent, + bodies(8, "", ""), + bodies(9, "?", " \n"), + bodies(10, "&&", "\t"), + bodies(11, "a=1"), + ]), + ).toEqual({ + count: 0, + pointers: [], + skipped: { count: 1, pointers: ["record 11 request"] }, + }); + }); +}); + describe("scanCredentialNames over structured form parameters", () => { it.each([undefined, null])( "scans each structured form parameter with absent text: %s", @@ -273,6 +473,27 @@ describe("scanScenarioCredentialNames", () => { expect(JSON.stringify(scanned)).not.toContain("k-2"); }); + it("charges nothing for a URL without a query once the budget is spent", () => { + const capture = scenarioCaptureFixture([ + { + method: "GET", + url: "/api/a", + status: 200, + mediaType: "application/json", + // Bounds to exactly the 524288 values the scan reads. + body: `[${"1,".repeat(524_286)}1]`, + }, + { method: "GET", url: "/api/b", status: 204 }, + { method: "GET", url: "/api/c?", status: 204 }, + { method: "GET", url: "/api/d?page=1", status: 204 }, + ]); + expect(scanScenarioCredentialNames(capture.events.items)).toEqual({ + count: 0, + pointers: [], + skipped: { count: 1, pointers: ["event 7 request query"] }, + }); + }); + it("scans each content event of a phase the capture recorded twice", () => { const capture = scenarioCaptureFixture([ { diff --git a/src/application/environment/environmentBuildReport.ts b/src/application/environment/environmentBuildReport.ts index 87869ee1d2..85dfa510d1 100644 --- a/src/application/environment/environmentBuildReport.ts +++ b/src/application/environment/environmentBuildReport.ts @@ -61,27 +61,81 @@ const CREDENTIAL_PAIRS = new Set([ "ssh key", ]); -/** Split a member name into lowercase segments at case changes and separators. */ -const nameSegments = (name: string): string[] => - name - .replaceAll(/([a-z0-9])([A-Z])/gu, "$1 $2") - .replaceAll(/([A-Z]+)([A-Z][a-z])/gu, "$1 $2") - .toLowerCase() - .split(/[^a-z0-9]+/u) - .filter((segment) => segment.length > 0); +/** A segment longer than every credential word matches none, so it is not kept. */ +const LONGEST_SEGMENT = Math.max( + ...[ + ...CREDENTIAL_SEGMENTS, + ...[...CREDENTIAL_PAIRS].join(" ").split(" "), + ].map((segment) => segment.length), +); -/** Whether a member, header or query name looks like it holds a credential. */ +const upper = (code: number): boolean => code >= 0x41 && code <= 0x5a; +const lower = (code: number): boolean => code >= 0x61 && code <= 0x7a; +const digit = (code: number): boolean => code >= 0x30 && code <= 0x39; + +/** + * Whether a member, header or query name looks like it holds a credential: a + * lowercase segment, split at separators and case changes (`apiKey`, + * `APIToken`, `api_key`), is a credential word, or follows the segment it + * pairs with. The name is read once in place, keeping at most two short + * segments, so a name of any length allocates no copies or segment list. + * Lowercasing follows `toLowerCase`: U+212A KELVIN SIGN reads as `k`, and + * U+0130 as `i` followed by a combining dot that ends the segment. + */ export const credentialNamed = (name: string): boolean => { - const segments = nameSegments(name); - return segments.some( - (segment, index) => - CREDENTIAL_SEGMENTS.has(segment) || - (index > 0 && CREDENTIAL_PAIRS.has(`${segments[index - 1]} ${segment}`)), - ); + /** The segment before this one, or null when there is none or it was too long. */ + let previous: string | null = null; + let segment = ""; + let open = false; + let long = false; + const close = (): boolean => { + if (!open) return false; + const word = long ? null : segment; + const found = + word !== null && + (CREDENTIAL_SEGMENTS.has(word) || + (previous !== null && CREDENTIAL_PAIRS.has(`${previous} ${word}`))); + previous = word; + segment = ""; + open = false; + long = false; + return found; + }; + const append = (letter: string): void => { + open = true; + if (long) return; + if (segment.length === LONGEST_SEGMENT) { + long = true; + segment = ""; + } else segment += letter; + }; + for (let index = 0; index < name.length; index++) { + const code = name.charCodeAt(index); + if (upper(code)) { + // `aB` and `1B` start a segment at `B`; so does `C` in `ABCd`. + const before = name.charCodeAt(index - 1); + if ( + (lower(before) || + digit(before) || + (upper(before) && lower(name.charCodeAt(index + 1)))) && + close() + ) + return true; + append(String.fromCharCode(code + 0x20)); + } else if (lower(code) || digit(code)) append(name[index]!); + else if (code === 0x212a) append("k"); + else if (code === 0x130) { + append("i"); + if (close()) return true; + } else if (close()) return true; + } + return close(); }; /** Bodies larger than this are not scanned. */ const SCAN_BODY_LIMIT_BYTES = 4 * 1024 * 1024; +/** Values one scan reads in all, over every body and name/value list; each is charged before it is parsed or read. */ +const SCAN_VALUE_BUDGET = 524_288; /** Pointers the report lists; the count covers every match. */ const REPORTED_POINTERS = 20; @@ -96,13 +150,14 @@ const member = (value: unknown, name: string): unknown => ? Reflect.get(value, name) : undefined; -/** A recorded body: JSON or form fields to walk, or a body the scan could not examine. */ +/** A recorded body: text the scan parses as JSON or as form fields (in order, every occurrence kept, as headers and query strings are) once it fits the budget, or text too large or cut to scan. */ type ScannedBody = - | { readonly kind: "json"; readonly value: unknown } - | { readonly kind: "form"; readonly fields: readonly [string, string][] } + | { readonly kind: "json" | "form"; readonly text: string } | { readonly kind: "skipped" }; const FORM_MEDIA_TYPE = "application/x-www-form-urlencoded"; +/** Space, tab, line feed and carriage return, the only whitespace JSON allows around a value. */ +const JSON_WHITESPACE = new Set([0x20, 0x09, 0x0a, 0x0d]); /** The parser a recorded media type names; otherwise JSON by its first character, or a form when it has `=` and no whitespace, which form encoding never leaves raw. */ const bodyFormat = ( @@ -118,8 +173,45 @@ const bodyFormat = ( return text.includes("=") && !/\s/u.test(text) ? "form" : undefined; }; -/** A recorded body as JSON or form fields, skipped when it is cut or over the limit, or undefined when it is neither. */ -const parsedBody = ( +/** + * An upper bound on the values the text holds, counted no further than one + * past `limit`. JSON text holds its first value only once it has a + * non-whitespace character, and each later `[`, `{` and `,` starts at most one + * more; one inside a string only loosens the bound. A form holds one field per + * non-empty `&`-separated piece after an optional leading `?`, exactly as + * `URLSearchParams` and the query reader split it. The count bounds the parse + * before it allocates, and text that holds nothing, such as an empty query or + * a bare `?`, charges nothing. + */ +const valueBound = ( + text: string, + format: "json" | "form", + limit: number, +): number => { + let values = 0; + let pieceStart = true; + for ( + let index = format === "form" && text.startsWith("?") ? 1 : 0; + index < text.length && values <= limit; + index++ + ) { + const code = text.charCodeAt(index); + if (format === "form") { + if (code === 0x26) pieceStart = true; + else if (pieceStart) { + values++; + pieceStart = false; + } + continue; + } + if (values === 0 && !JSON_WHITESPACE.has(code)) values++; + if (code === 0x5b || code === 0x7b || code === 0x2c) values++; + } + return values; +}; + +/** A recorded body the scan may parse, skipped when it is cut or over the text limit, or undefined when it is neither JSON nor a form. */ +const scannableBody = ( text: unknown, mediaType: unknown, cut = false, @@ -127,15 +219,8 @@ const parsedBody = ( if (typeof text !== "string") return undefined; if (cut || Buffer.byteLength(text, "utf8") > SCAN_BODY_LIMIT_BYTES) return { kind: "skipped" }; - const format = bodyFormat(text, mediaType); - if (format === "form") - return { kind: "form", fields: [...new URLSearchParams(text)] }; - if (format === undefined) return undefined; - try { - return { kind: "json", value: JSON.parse(text) }; - } catch { - return undefined; - } + const kind = bodyFormat(text, mediaType); + return kind === undefined ? undefined : { kind, text }; }; /** Unproven body sources remain unscanned; binary bytes hold no JSON or form text. */ @@ -147,18 +232,7 @@ const decodedBody = ( ? { kind: "skipped" } : body.bodyEncoding === "base64" ? undefined - : parsedBody(body.bodyText, mediaType, body.bodyCut === true); - -/** Name/value pairs such as HAR headers and query strings. */ -const namedValues = (value: unknown): (readonly [string, unknown])[] => - Array.isArray(value) - ? value.flatMap((entry: unknown) => { - const name = member(entry, "name"); - return typeof name === "string" - ? [[name, member(entry, "value")] as const] - : []; - }) - : []; + : scannableBody(body.bodyText, mediaType, body.bodyCut === true); /** A count of matches and the first of their pointers. */ interface ScanTally { @@ -177,15 +251,50 @@ const tallied = (tally: ScanTally, pointer: string): void => { /** * The tallies both capture readers fill: a named value counts when its name - * looks like a credential and it holds a value. The body walk keeps its own - * stack, so nesting depth cannot overflow it. + * looks like a credential and it holds a value. One value budget covers the + * whole scan: every body and name/value list is charged to it before it is + * parsed or read, so the scan's work stays bounded however many records are + * selected, and what does not fit is tallied as skipped. The body walk keeps + * its own stack, so nesting depth cannot overflow it. */ const credentialTally = () => { const matches: ScanTally = { count: 0, pointers: [] }; const skipped: ScanTally = { count: 0, pointers: [] }; + let remaining = SCAN_VALUE_BUDGET; + /** Whether `values` more fit the budget, charging them; otherwise the label is tallied as skipped. */ + const charge = (values: number, label: string): boolean => { + if (values > remaining) { + tallied(skipped, label); + return false; + } + remaining -= values; + return true; + }; const field = (pointer: string, name: string, value: unknown): void => { if (credentialNamed(name) && holdsValue(value)) tallied(matches, pointer); }; + /** Name/value entries such as HAR headers, query strings and form params, read in place once their count fits the budget. */ + const entries = ( + items: unknown, + label: string, + each: (name: string, value: unknown) => void, + ): void => { + if (!Array.isArray(items) || !charge(items.length, label)) return; + for (const entry of items as unknown[]) { + const name = member(entry, "name"); + if (typeof name === "string") each(name, member(entry, "value")); + } + }; + /** Form-encoded text such as a transaction URL's query, read field by field once its bound fits the budget. */ + const query = ( + text: string, + label: string, + each: (name: string, value: string) => void, + ): void => { + if (!charge(valueBound(text, "form", remaining), label)) return; + for (const [name, value] of iterateUrlQueryParameters(text)) + each(name, value); + }; const walk = (root: unknown, label: string): void => { const stack: [unknown, string][] = [[root, ""]]; while (stack.length > 0) { @@ -206,14 +315,28 @@ const credentialTally = () => { } }; const body = (scanned: ScannedBody | undefined, label: string): void => { - if (scanned?.kind === "skipped") tallied(skipped, label); - else if (scanned?.kind === "json") walk(scanned.value, label); - else if (scanned?.kind === "form") - for (const [name, value] of scanned.fields) + if (scanned === undefined) return; + if (scanned.kind === "skipped") { + tallied(skipped, label); + return; + } + if (!charge(valueBound(scanned.text, scanned.kind, remaining), label)) + return; + if (scanned.kind === "form") { + for (const [name, value] of new URLSearchParams(scanned.text)) field(`${label} /${escapeJsonPointerToken(name)}`, name, value); + return; + } + try { + walk(JSON.parse(scanned.text), label); + } catch { + // Text that does not parse as JSON holds no members to scan. + } }; return { field, + entries, + query, body, result: (): CredentialScan => ({ ...matches, skipped }), }; @@ -222,7 +345,8 @@ const credentialTally = () => { /** * Credential-named members that hold a value in recorded JSON and form * bodies, headers and query strings: a count and the first pointers, never - * values, and the bodies too large to scan by record and side. + * values, and the bodies, header lists and query strings it did not read, + * by record and side. */ export const scanCredentialNames = ( records: readonly WebNetworkCaptureRecord[], @@ -236,27 +360,28 @@ export const scanCredentialNames = ( ["request", request], ["response", response], ] as const) - for (const [name, value] of namedValues(member(message, "headers"))) - scan.field(`record ${ordinal} ${side} header ${name}`, name, value); - for (const [name, value] of namedValues(member(request, "queryString"))) - scan.field(`record ${ordinal} request query ${name}`, name, value); + scan.entries( + member(message, "headers"), + `record ${ordinal} ${side} headers`, + (name, value) => + scan.field(`record ${ordinal} ${side} header ${name}`, name, value), + ); + scan.entries( + member(request, "queryString"), + `record ${ordinal} request query`, + (name, value) => + scan.field(`record ${ordinal} request query ${name}`, name, value), + ); const postData = member(request, "postData"); const text = member(postData, "text"); + const label = `record ${ordinal} request`; // A HAR may record form fields only as structured params; each occurrence counts, as in a form body. - scan.body( - typeof text !== "string" - ? { - kind: "form", - fields: namedValues(member(postData, "params")).flatMap( - ([name, value]) => - typeof value === "string" - ? [[name, value] as [string, string]] - : [], - ), - } - : parsedBody(text, member(postData, "mimeType")), - `record ${ordinal} request`, - ); + if (typeof text !== "string") + scan.entries(member(postData, "params"), label, (name, value) => { + if (typeof value === "string") + scan.field(`${label} /${escapeJsonPointerToken(name)}`, name, value); + }); + else scan.body(scannableBody(text, member(postData, "mimeType")), label); scan.body( decodedBody( readRecordedResponseBody(record, SCAN_BODY_LIMIT_BYTES), @@ -284,8 +409,9 @@ export const scanScenarioCredentialNames = ( if (event.kind === "network-content") { const side = `${label} ${event.phase}`; if (event.headers.state === "captured") - for (const { name, value } of event.headers.items) - scan.field(`${side} header ${name}`, name, value); + scan.entries(event.headers.items, `${side} headers`, (name, value) => + scan.field(`${side} header ${name}`, name, value), + ); if (event.body.state === "captured") scan.body( decodedBody( @@ -302,14 +428,16 @@ export const scanScenarioCredentialNames = ( const { query } = parseRecordedTransportUrl(event.url.url, { includeQuery: true, }); - for (const [name, value] of iterateUrlQueryParameters(query ?? "")) - scan.field(`${label} ${event.kind} query ${name}`, name, value); + if (typeof query === "string") + scan.query(query, `${label} ${event.kind} query`, (name, value) => + scan.field(`${label} ${event.kind} query ${name}`, name, value), + ); } } return scan.result(); }; -/** The credential-name scan's warnings: what it found, and the bodies it could not scan. */ +/** The credential-name scan's warnings: what it found, and what it could not read. */ export const credentialScanWarnings = (capture: { readonly records: readonly WebNetworkCaptureRecord[]; readonly scenarioEvents: readonly BrowserScenarioEvent[] | null; @@ -328,7 +456,7 @@ export const credentialScanWarnings = (capture: { if (scanned.skipped.count > 0) warnings.push({ code: "credential-scan-incomplete", - message: `${String(scanned.skipped.count)} recorded bodies could not be completely scanned for credential-like names (4 MiB limit or unavailable response-body source); evidence.json ships their retained representation, so review it before sharing.`, + message: `${String(scanned.skipped.count)} recorded bodies, header lists or query strings were not scanned: each is cut, over 4 MiB of text, past the 524288 values the credential-name scan reads in all, or a response body whose retained source is unavailable; evidence.json ships what was retained, so review it before sharing.`, pointers: scanned.skipped.pointers, }); return warnings; diff --git a/src/contracts/webNetworkCaptureToolContracts.ts b/src/contracts/webNetworkCaptureToolContracts.ts index 36fa18f4e5..efe61ed050 100644 --- a/src/contracts/webNetworkCaptureToolContracts.ts +++ b/src/contracts/webNetworkCaptureToolContracts.ts @@ -24,7 +24,7 @@ export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [ }), ), description: - "Inspect a saved local HAR 1.2, mitmproxy, Fiddler SAZ or supported aioquic qlog capture without contacting recorded URLs. Returns source-linked records, preserved producer fields, precise numbers, exposed bytes and explicit coverage/limitations; transport credentials and explicitly marked sensitive values are excluded. Use inspect_web_page for a live CDP page. Preserve capture_path exactly as supplied; it names a path on the REA host, not a path to rebase onto the client workspace. Select format; record_ordinals selects records after full decoding and also decodes recognized protobuf/gRPC bodies. Optional protobuf selects body_pointers, framing and a local FileDescriptorSet/message_type; native gRPC and gRPC-web remain distinct, ambiguous readings stay candidates and compressed payloads stay unknown. Default complete delivery is inline. detail summary retains Evidence for inspect_analysis_view kind capture (preview/complete), protobuf (bodies/frames/fields), or qlog; large text/schema values require explicit fields. Qlog supports aioquic 1.5.0 JSON qlog 0.3 and reports STREAM interval unions/endpoint loss declarations, not recovered bodies or proved network loss. SAZ preserves encoded bytes without replay/HAR conversion; encrypted archives are unsupported. Mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Malformed or oversized captures return no partial success; browser transaction attribution and HAR text’s original bytes remain unknown.", + "Inspect a saved local HAR 1.2, mitmproxy, Fiddler SAZ or supported aioquic qlog capture without contacting recorded URLs. Returns source-linked records, preserved producer fields, precise numbers, exposed bytes and explicit coverage/limitations; transport credentials and explicitly marked sensitive values are excluded; HAR header, query and body member names that look like credentials and hold a retained value are counted in a limitation by pointer, never by value. Use inspect_web_page for a live CDP page. Preserve capture_path exactly as supplied; it names a path on the REA host, not a path to rebase onto the client workspace. Select format; record_ordinals selects records after full decoding and also decodes recognized protobuf/gRPC bodies. Optional protobuf selects body_pointers, framing and a local FileDescriptorSet/message_type; native gRPC and gRPC-web remain distinct, ambiguous readings stay candidates and compressed payloads stay unknown. Default complete delivery is inline. detail summary retains Evidence for inspect_analysis_view kind capture (preview/complete), protobuf (bodies/frames/fields), or qlog; large text/schema values require explicit fields. Qlog supports aioquic 1.5.0 JSON qlog 0.3 and reports STREAM interval unions/endpoint loss declarations, not recovered bodies or proved network loss. SAZ preserves encoded bytes without replay/HAR conversion; encrypted archives are unsupported. Mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Malformed or oversized captures return no partial success; browser transaction attribution and HAR text’s original bytes remain unknown.", kind: "application", inputSchema: inspectWebNetworkCaptureInputSchema.extend({ detail: analysisDetailSchema, diff --git a/tests/boundary/browser/historicalWebCapture.test.ts b/tests/boundary/browser/historicalWebCapture.test.ts index fc4e6ce8ab..7f8097f82d 100644 --- a/tests/boundary/browser/historicalWebCapture.test.ts +++ b/tests/boundary/browser/historicalWebCapture.test.ts @@ -392,3 +392,100 @@ it("reports the actual HAR decoder nesting constraint as a typed selected-input }, }); }); + +it("counts credential-named HAR members by pointer, excluding values the decoder removed", async () => { + const root = await createTestTempDirectory("rea-har-credential-names-"); + const path = join(root, "capture.har"); + const fixture = historicalHar(); + const entry = fixture.log.entries[0]!; + await writeFile( + path, + JSON.stringify({ + log: { + ...fixture.log, + entries: [ + { + ...entry, + request: { + ...entry.request, + method: "POST", + url: "https://example.test/login?api_key=demo-key", + headers: [ + { name: "Authorization", value: "Bearer demo-bearer" }, + { name: "X-Demo-Token", value: "demo-token" }, + { name: "Accept", value: "application/json" }, + ], + queryString: [{ name: "api_key", value: "demo-key" }], + postData: { + mimeType: "application/json", + text: '{"user":"demo","password":"demo-pass"}', + }, + }, + response: { + ...entry.response, + content: { + size: 32, + mimeType: "application/json", + text: '{"session_token":"demo-session"}', + }, + }, + }, + ], + }, + }), + ); + const { call } = await connectLocalToolsMcp(); + for (const sensitive of [[], ["demo-token", "demo-pass"]]) { + const fromCli = await cli( + path, + "har", + sensitive.flatMap((value) => ["--sensitive-value", value]), + ); + expect(fromCli.ok, fromCli.stdout).toBe(true); + const cliEvidence = parseEvidence(JSON.parse(fromCli.stdout)); + const response = await call("inspect_web_network_capture", { + capture_path: path, + format: "har", + sensitive_values: sensitive, + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + const evidence = parseEvidence(response.structuredContent); + expect(evidence.limitations).toEqual(cliEvidence.limitations); + const [limitation, ...others] = evidence.limitations.filter((text) => + text.includes("look like credentials"), + ); + expect(others).toEqual([]); + const expected = + sensitive.length === 0 + ? [ + "record 0 request header X-Demo-Token", + "record 0 request query api_key", + "record 0 request /password", + "record 0 response /session_token", + ] + : [ + "record 0 request query api_key", + "record 0 response /session_token", + ]; + expect(limitation).toMatch(new RegExp(`^${String(expected.length)} `)); + for (const pointer of expected) expect(limitation).toContain(pointer); + // The decoder already excluded the standard credential and declared values. + expect(limitation).not.toContain("Authorization"); + expect(limitation).not.toContain("Accept"); + if (sensitive.length > 0) { + expect(limitation).not.toContain("X-Demo-Token"); + expect(limitation).not.toContain("/password"); + } + for (const value of [ + "demo-bearer", + "demo-token", + "demo-key", + "demo-pass", + "demo-session", + ]) + expect(limitation).not.toContain(value); + expect(evidence.normalized_result).toMatchObject({ + limitations: expect.arrayContaining([limitation]), + }); + } +});