From 7b3fb897c0868c198b7c92b1a413c0535240ea8d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:57:36 -0500 Subject: [PATCH] test(browser): consolidate source-map and deadline contracts (#13220) --- src/application/BrowserEvidence.test.ts | 79 ++++++-- .../browser/webDeadlineBehavior.test.ts | 168 ------------------ .../browser/webSourceMapFetcher.test.ts | 51 +++--- .../webSourceMapOriginalDependencies.test.ts | 87 --------- .../webSourceMapSourceLanguage.test.ts | 65 +++++-- 5 files changed, 151 insertions(+), 299 deletions(-) delete mode 100644 tests/boundary/browser/webDeadlineBehavior.test.ts delete mode 100644 tests/boundary/browser/webSourceMapOriginalDependencies.test.ts diff --git a/src/application/BrowserEvidence.test.ts b/src/application/BrowserEvidence.test.ts index fe1d755456..c3a9d2777d 100644 --- a/src/application/BrowserEvidence.test.ts +++ b/src/application/BrowserEvidence.test.ts @@ -2,6 +2,8 @@ import { jsonValueSchema } from "../domain/jsonValue.js"; import { describe, expect, it } from "vitest"; import { createBrowserEvidence } from "./BrowserEvidence.js"; +import { listBrowserTargetsInputSchema } from "../domain/browserObservation.js"; +import { browserTargetListSchema } from "../domain/browserObservationSchemas.js"; import { analyzeWebBundleInputSchema, webBundleAnalysisSchema, @@ -40,16 +42,25 @@ const result = webBundleAnalysisSchema.parse({ limitations: [], }); +const bundleInput = { + cdp_endpoint: "http://127.0.0.1:9222", + target_id: "page-1", + observation_ms: 0, +}; const input = (allowedOrigins: string[]) => analyzeWebBundleInputSchema.parse({ - cdp_endpoint: "http://127.0.0.1:9222", - target_id: "page-1", - observation_ms: 0, + ...bundleInput, allowed_origins: allowedOrigins, }); -describe("web bundle Evidence origin scope", () => { - it("records the captured target origin when the request uses the default scope", () => { +const deadlines = { + command_timeout_ms: 1_500, + discovery_timeout_ms: 15_000, + source_map_fetch_timeout_ms: 1_750, +}; + +describe("web bundle Evidence scope", () => { + it("records the captured target origin and leaves implicit deadlines omitted", () => { const evidence = createBrowserEvidence( "analyze_web_bundle", input([]), @@ -60,19 +71,27 @@ describe("web bundle Evidence origin scope", () => { expect(evidence.parameters.allowed_origins).toEqual([ "https://app.example.test", ]); + for (const deadline of Object.keys(deadlines)) + expect(evidence.parameters).not.toHaveProperty(deadline); }); - it("preserves an explicit caller origin scope", () => { + it("preserves the caller's explicit origin scope and independent deadlines", () => { const evidence = createBrowserEvidence( "analyze_web_bundle", - input(["https://explicit.example.test"]), + analyzeWebBundleInputSchema.parse({ + ...bundleInput, + allowed_origins: ["https://explicit.example.test"], + fetch_source_maps: true, + ...deadlines, + }), { source: jsonValueSchema.parse(result), facts: result }, provider, ); - expect(evidence.parameters.allowed_origins).toEqual([ - "https://explicit.example.test", - ]); + expect(evidence.parameters).toMatchObject({ + allowed_origins: ["https://explicit.example.test"], + ...deadlines, + }); }); it("does not infer an origin from a URL without one", () => { @@ -134,3 +153,43 @@ it.each([undefined, {}, { decoded_records: 1024 }])( else expect(evidence.parameters.source_map_limits).toEqual(selection); }, ); + +const targetList = browserTargetListSchema.parse({ + browser: { + product: "fixture", + protocol_version: "1.3", + revision: "fake-revision", + user_agent: "FakeChrome", + js_version: "13.0", + }, + targets: [], + excluded: { disallowed_origin: 0, unsupported_url: 0, non_page: 0 }, + limitations: [], +}); + +it("records only the caller-selected discovery deadline on target listing", () => { + const cdp_endpoint = "ws://127.0.0.1:9222/devtools/browser/fake"; + const observation = { + source: jsonValueSchema.parse(targetList), + facts: targetList, + }; + const explicit = createBrowserEvidence( + "list_browser_targets", + listBrowserTargetsInputSchema.parse({ + cdp_endpoint, + discovery_timeout_ms: 25_000, + }), + observation, + provider, + ); + expect(explicit.parameters.discovery_timeout_ms).toBe(25_000); + expect(explicit.parameters).not.toHaveProperty("command_timeout_ms"); + const omitted = createBrowserEvidence( + "list_browser_targets", + listBrowserTargetsInputSchema.parse({ cdp_endpoint }), + observation, + provider, + ); + expect(omitted.parameters).not.toHaveProperty("discovery_timeout_ms"); + expect(omitted.parameters).not.toHaveProperty("command_timeout_ms"); +}); diff --git a/tests/boundary/browser/webDeadlineBehavior.test.ts b/tests/boundary/browser/webDeadlineBehavior.test.ts deleted file mode 100644 index 4717f3b713..0000000000 --- a/tests/boundary/browser/webDeadlineBehavior.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { jsonValueSchema } from "../../../src/domain/jsonValue.js"; -import { expect, it } from "vitest"; - -import { createBrowserEvidence } from "../../../src/application/BrowserEvidence.js"; -import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/providerIdentities.js"; -import { listBrowserTargetsInputSchema } from "../../../src/domain/browserObservation.js"; -import { browserTargetListSchema } from "../../../src/domain/browserObservationSchemas.js"; -import { - analyzeWebBundleInputSchema, - webBundleAnalysisSchema, -} from "../../../src/domain/webBundleAnalysis.js"; - -const targetList = browserTargetListSchema.parse({ - browser: { - product: "FakeChrome/1.0", - protocol_version: "1.3", - revision: "fake-revision", - user_agent: "FakeChrome", - js_version: "13.0", - }, - targets: [], - excluded: { disallowed_origin: 0, unsupported_url: 0, non_page: 0 }, - limitations: [], -}); - -const bundle = webBundleAnalysisSchema.parse({ - capture: { - target_url: "https://example.test/", - target_origin: "https://example.test", - scripts_observed: 0, - scripts_analyzed: 0, - source_artifacts: [], - }, - observations: { - chunks: { nodes: [], edges: [] }, - routes: [], - endpoints: [], - webmcp_declarations: [], - source_maps: { - status: "not_requested", - requested: 0, - processed: 0, - items: [], - }, - }, - inferences: [], - unknowns: [], - completeness: { - status: "complete", - parsed_scripts: 0, - parse_failures: 0, - visited_ast_nodes: 0, - }, - limitations: [], -}); - -it("records an explicit command deadline and omits the default", () => { - const base = { - cdp_endpoint: "http://127.0.0.1:9222", - target_id: "page", - fetch_source_maps: false, - }; - const explicit = createBrowserEvidence( - "analyze_web_bundle", - analyzeWebBundleInputSchema.parse({ - ...base, - command_timeout_ms: 1_500, - }), - { source: jsonValueSchema.parse(bundle), facts: bundle }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(explicit.parameters.command_timeout_ms).toBe(1_500); - const omitted = createBrowserEvidence( - "analyze_web_bundle", - analyzeWebBundleInputSchema.parse(base), - { source: jsonValueSchema.parse(bundle), facts: bundle }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(omitted.parameters).not.toHaveProperty("command_timeout_ms"); -}); - -it("rejects a command deadline on target listing and leaves it out of Evidence", () => { - expect( - listBrowserTargetsInputSchema.safeParse({ - cdp_endpoint: "http://127.0.0.1:9222", - command_timeout_ms: 1_500, - }).success, - ).toBe(false); - const evidence = createBrowserEvidence( - "list_browser_targets", - listBrowserTargetsInputSchema.parse({ - cdp_endpoint: "http://127.0.0.1:9222", - }), - { source: jsonValueSchema.parse(targetList), facts: targetList }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(evidence.parameters).not.toHaveProperty("command_timeout_ms"); -}); - -it("records an explicit discovery deadline and omits the default", () => { - const explicitListing = createBrowserEvidence( - "list_browser_targets", - listBrowserTargetsInputSchema.parse({ - cdp_endpoint: "ws://127.0.0.1:9222/devtools/browser/fake", - discovery_timeout_ms: 25_000, - }), - { source: jsonValueSchema.parse(targetList), facts: targetList }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(explicitListing.parameters.discovery_timeout_ms).toBe(25_000); - const omittedListing = createBrowserEvidence( - "list_browser_targets", - listBrowserTargetsInputSchema.parse({ - cdp_endpoint: "ws://127.0.0.1:9222/devtools/browser/fake", - }), - { source: jsonValueSchema.parse(targetList), facts: targetList }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(omittedListing.parameters).not.toHaveProperty("discovery_timeout_ms"); - - const baseBundle = { - cdp_endpoint: "http://127.0.0.1:9222", - target_id: "page", - fetch_source_maps: false, - }; - const explicitBundle = createBrowserEvidence( - "analyze_web_bundle", - analyzeWebBundleInputSchema.parse({ - ...baseBundle, - discovery_timeout_ms: 15_000, - }), - { source: jsonValueSchema.parse(bundle), facts: bundle }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(explicitBundle.parameters.discovery_timeout_ms).toBe(15_000); - const omittedBundle = createBrowserEvidence( - "analyze_web_bundle", - analyzeWebBundleInputSchema.parse(baseBundle), - { source: jsonValueSchema.parse(bundle), facts: bundle }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(omittedBundle.parameters).not.toHaveProperty("discovery_timeout_ms"); -}); - -it("records an explicit source-map fetch deadline and omits the default", () => { - const base = { - cdp_endpoint: "http://127.0.0.1:9222", - target_id: "page", - fetch_source_maps: true, - }; - const explicit = createBrowserEvidence( - "analyze_web_bundle", - analyzeWebBundleInputSchema.parse({ - ...base, - source_map_fetch_timeout_ms: 1_500, - }), - { source: jsonValueSchema.parse(bundle), facts: bundle }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(explicit.parameters.source_map_fetch_timeout_ms).toBe(1_500); - const omitted = createBrowserEvidence( - "analyze_web_bundle", - analyzeWebBundleInputSchema.parse(base), - { source: jsonValueSchema.parse(bundle), facts: bundle }, - CDP_BROWSER_PROVIDER_IDENTITY, - ); - expect(omitted.parameters).not.toHaveProperty("source_map_fetch_timeout_ms"); -}); diff --git a/tests/boundary/browser/webSourceMapFetcher.test.ts b/tests/boundary/browser/webSourceMapFetcher.test.ts index f55e8bb7c4..ec909d59fa 100644 --- a/tests/boundary/browser/webSourceMapFetcher.test.ts +++ b/tests/boundary/browser/webSourceMapFetcher.test.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { createServer } from "node:http"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { phaseArrival } from "../../support/lifecycleHarness.js"; import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs"; @@ -555,16 +555,19 @@ describe("source-map declared URL policy", () => { }); describe("web source-map fetching and validation: enforcing fetch limits and validating responses", () => { - it("settles an endless unique-URL redirect chain at the selected fetch deadline", async () => { - let calls = 0; + it("aborts a paused HTTP redirect chain at the selected fetch deadline", async () => { + const stalled = phaseArrival(); + const requests: number[] = []; const server = createServer((incoming, response) => { - calls += 1; - const next = - Number( - new URL(incoming.url ?? "/", "http://local").searchParams.get("n") ?? - "0", - ) + 1; - response.writeHead(302, { location: `/map?n=${String(next)}` }).end(); + const hop = Number( + new URL(incoming.url ?? "/", "http://local").searchParams.get("n"), + ); + requests.push(hop); + if (hop === 8) stalled.arrive(hop); + else + response + .writeHead(302, { location: `/map?n=${String(hop + 1)}` }) + .end(); }); try { await new Promise((resolve, reject) => { @@ -576,37 +579,45 @@ describe("web source-map fetching and validation: enforcing fetch limits and val throw new TypeError("Expected a TCP listener address"); const localOrigin = `http://127.0.0.1:${String(address.port)}`; const url = `${localOrigin}/map?n=0`; - const result = await fetchWebSourceMapsOk( + const deadline = 13_700; + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const capture = fetchWebSourceMapsOk( [{ ...request, fetchUrl: url, declaredUrl: url }], input({ allowed_origins: [localOrigin], - source_map_fetch_timeout_ms: 250, + source_map_fetch_timeout_ms: deadline, }), - AbortSignal.timeout(2_000), - { fetch }, + AbortSignal.timeout(4_000), ); - expect(calls).toBeGreaterThan(1); - expect(result).toMatchObject({ + await stalled.reached( + capture, + "ninth HTTP request in an approved redirect chain", + ); + expect(requests).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]); + await vi.advanceTimersByTimeAsync(deadline); + expect(await capture).toMatchObject({ status: "unavailable", processed: 1, items: [ { status: "fetch_failed", + effective_url: `${localOrigin}/map?n=7`, artifact: null, limitation: expect.stringContaining( - "250 ms source_map_fetch_timeout_ms deadline", + `${String(deadline)} ms source_map_fetch_timeout_ms deadline`, ), }, ], }); } finally { + vi.useRealTimers(); server.closeAllConnections(); if (server.listening) - await new Promise((resolve, reject) => { + await new Promise((resolve, reject) => server.close((error) => error === undefined ? resolve() : reject(error), - ); - }); + ), + ); } }); diff --git a/tests/boundary/browser/webSourceMapOriginalDependencies.test.ts b/tests/boundary/browser/webSourceMapOriginalDependencies.test.ts deleted file mode 100644 index 5623e99d1a..0000000000 --- a/tests/boundary/browser/webSourceMapOriginalDependencies.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { createHash } from "node:crypto"; -import { createServer } from "node:http"; - -import { expect, it } from "vitest"; - -import { fetchWebSourceMapsOk } from "../../fixtures/fetchWebSourceMapsOk.js"; -import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js"; - -it("retains literal dependencies from HTTP source-map originals", async () => { - const source = [ - '// import "./comment.js";', - String.raw`const quoted = "require(\"./string.js\")";`, - "const template = `import './template-comment.js'`;", - `export { value } from "./it's-real.js";`, - 'import "package-name";', - 'import("./dynamic.js");', - "import(`./dep.js`);", - "import(`./dep.${name}.js`);", - 'require("./normal.cjs");', - "require(`./templated.cjs`);", - "require(`./${name}.cjs`);", - 'require?.("./optional.cjs");', - 'function local(require) { require?.("./shadowed.cjs"); }', - "require?.(selectedModule);", - ].join("\n"); - const text = JSON.stringify({ - version: 3, - names: [], - mappings: "AAAA", - sources: ["main.cjs"], - sourcesContent: [source], - }); - const server = createServer((_request, response) => response.end(text)); - try { - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - const address = server.address(); - if (address === null || typeof address === "string") - throw new TypeError("Expected a TCP listener address"); - const origin = `http://127.0.0.1:${String(address.port)}`; - const url = `${origin}/app.js.map`; - const result = await fetchWebSourceMapsOk( - [{ scriptKey: `scr_${"1".repeat(64)}`, declaredUrl: url, fetchUrl: url }], - analyzeWebBundleInputSchema.parse({ - cdp_endpoint: origin, - target_id: "fixture", - allowed_origins: [origin], - fetch_source_maps: true, - }), - ); - expect(result.items[0]).toMatchObject({ - status: "included", - artifact: { - text, - bytes: Buffer.byteLength(text), - sha256: createHash("sha256").update(text).digest("hex"), - }, - original_sources: [{ artifact: { text: source } }], - mappings: [{ generated_line: 1, source: `${origin}/main.cjs` }], - original_module_edges: [ - { specifier: "./it's-real.js", kind: "static_import" }, - { specifier: "package-name", kind: "static_import" }, - { specifier: "./dynamic.js", kind: "dynamic_import" }, - { specifier: "./dep.js", kind: "dynamic_import" }, - { specifier: "./normal.cjs", kind: "require" }, - { specifier: "./templated.cjs", kind: "require" }, - { specifier: "./optional.cjs", kind: "require" }, - ].map(({ kind, specifier }) => ({ - from_source: `${origin}/main.cjs`, - kind, - specifier, - resolved_source: - specifier === "package-name" ? null : new URL(specifier, origin).href, - })), - }); - } finally { - server.closeAllConnections(); - if (server.listening) - await new Promise((resolve, reject) => { - server.close((error) => - error === undefined ? resolve() : reject(error), - ); - }); - } -}); diff --git a/tests/boundary/browser/webSourceMapSourceLanguage.test.ts b/tests/boundary/browser/webSourceMapSourceLanguage.test.ts index 84aa4b6666..f52cfc0cde 100644 --- a/tests/boundary/browser/webSourceMapSourceLanguage.test.ts +++ b/tests/boundary/browser/webSourceMapSourceLanguage.test.ts @@ -10,7 +10,40 @@ import { fetchWebSourceMapsOk } from "../../fixtures/fetchWebSourceMapsOk.js"; const typescriptContent = 'import "./dep.ts"; const value = 1;'; const annotatedContent = 'import "./dep.ts"; const value: number = 1;'; const javascriptContent = 'import "./dep.ts"; const value = 1;'; +const commonJsContent = [ + '// import "./comment.js";', + String.raw`const quoted = "require(\"./string.js\")";`, + "const template = `import './template-comment.js'`;", + `export { value } from "./it's-real.js";`, + 'import "package-name";', + 'import("./dynamic.js");', + "import(`./dep.js`);", + "import(`./dep.${name}.js`);", + 'require("./normal.cjs");', + "require(`./templated.cjs`);", + "require(`./${name}.cjs`);", + 'require?.("./optional.cjs");', + 'function local(require) { require?.("./shadowed.cjs"); }', + "require?.(selectedModule);", +].join("\n"); + +const commonJsEdges = [ + ["static_import", "./it's-real.js"], + ["static_import", "package-name"], + ["dynamic_import", "./dynamic.js"], + ["dynamic_import", "./dep.js"], + ["require", "./normal.cjs"], + ["require", "./templated.cjs"], + ["require", "./optional.cjs"], +] as const; + const declarations = [ + { + path: "main.cjs", + mediaType: "text/javascript", + content: commonJsContent, + edges: commonJsEdges, + }, { path: "plain.ts?revision=2#view.tsx", mediaType: "text/typescript", @@ -117,7 +150,11 @@ it("selects the language of HTTP map originals and retains exact URLs and depend expect(result.items[0]).toMatchObject({ status: "included", limitation: null, - artifact: { text }, + artifact: { + text, + bytes: Buffer.byteLength(text), + sha256: createHash("sha256").update(text).digest("hex"), + }, original_sources: sources.map(({ source, content, mediaType }) => ({ source, artifact: { @@ -132,22 +169,22 @@ it("selects the language of HTTP map originals and retains exact URLs and depend source, })), original_module_edges: sources.flatMap( - ({ source, requires = [] }, declaration_index) => [ - { + ({ source, edges, requires = [] }, declaration_index) => { + const imports = edges ?? [ + ["static_import", "./dep.ts"] as const, + ...requires.map((specifier) => ["require", specifier] as const), + ]; + return imports.map(([kind, specifier]) => ({ declaration_index, from_source: source, - kind: "static_import", - specifier: "./dep.ts", - resolved_source: `${origin}/maps/dep.ts`, - }, - ...requires.map((specifier) => ({ - declaration_index, - from_source: source, - kind: "require", + kind, specifier, - resolved_source: new URL(specifier, source).href, - })), - ], + resolved_source: + specifier === "package-name" + ? null + : new URL(specifier, source).href, + })); + }, ), }); } finally {