diff --git a/src/browser/CdpLargeBase64.test.ts b/src/browser/CdpLargeBase64.test.ts index 86a894bb53..effcd8095b 100644 --- a/src/browser/CdpLargeBase64.test.ts +++ b/src/browser/CdpLargeBase64.test.ts @@ -1,56 +1,13 @@ -import { createHash } from "node:crypto"; - -import { expect, it, vi } from "vitest"; +import { expect, it } from "vitest"; import { inspectWebPageInputSchema } from "../domain/browserObservation.js"; import { CdpCaptureEvents } from "./CdpCaptureEvents.js"; -import { captureStorageFingerprints } from "./CdpCaptureStorageFingerprints.js"; -import type { CdpConnection } from "./CdpConnection.js"; import { receiveCdpEvent } from "./CdpConnection.js"; const ORIGIN = "https://example.test"; const CDP_ENDPOINT = "http://127.0.0.1:9222"; const BODY_BYTES = 4 * 1024 * 1024; -const captureCacheFingerprint = async (encodedBody: string) => { - const send = vi.fn(async (method: string) => { - if (method === "Network.getCookies") return { cookies: [] }; - if (method === "CacheStorage.requestEntries") - return { - cacheDataEntries: [ - { - requestURL: `${ORIGIN}/cached`, - requestMethod: "GET", - requestHeaders: [], - }, - ], - returnCount: 1, - }; - if (method === "CacheStorage.requestCachedResponse") - return { response: { body: encodedBody } }; - throw new Error(`Unexpected CDP command ${method}`); - }); - const input = inspectWebPageInputSchema.parse({ - cdp_endpoint: CDP_ENDPOINT, - allowed_origins: [ORIGIN], - target_id: "page", - }); - return captureStorageFingerprints({ - context: { - connection: { send } as unknown as CdpConnection, - sessionId: "page-session", - input, - }, - origin: ORIGIN, - cookieUrl: `${ORIGIN}/`, - local: { items: [], complete: true }, - session: { items: [], complete: true }, - indexedDbNames: [], - caches: [{ name: "cache", id: "cache-id" }], - limitations: [], - }); -}; - const createEvents = (includeJsonBodyShapes = true): CdpCaptureEvents => new CdpCaptureEvents( inspectWebPageInputSchema.parse({ @@ -93,17 +50,6 @@ const startJsonResponse = ( ); }; -it("fingerprints valid cached bytes with nonzero pad bits and rejects invalid bytes", async () => { - const padBits = await captureCacheFingerprint("e31="); - expect(padBits.items[0]?.value_sha256).toBe( - createHash("sha256").update("{}").digest("hex"), - ); - - const malformed = await captureCacheFingerprint("%%%not-base64%%%"); - expect(malformed.complete).toBe(false); - expect(malformed.items[0]?.value_sha256).toBeNull(); -}); - it("decodes large JSON response bodies and accepts nonzero pad bits", () => { const events = createEvents(); startJsonResponse(events, "large-json", "/large.json"); diff --git a/tests/boundary/browser/cdpBrowserProvider.responseUtf8.test.ts b/tests/boundary/browser/cdpBrowserProvider.responseUtf8.test.ts index 173627b63a..a83383cccb 100644 --- a/tests/boundary/browser/cdpBrowserProvider.responseUtf8.test.ts +++ b/tests/boundary/browser/cdpBrowserProvider.responseUtf8.test.ts @@ -7,152 +7,149 @@ import { trackBrowser } from "./cdpBrowserProvider.support.js"; it.each([ { - name: "invalid UTF-8 property name", - body: Buffer.from([123, 34, 255, 34, 58, 116, 114, 117, 101, 125]), - property: null, + name: "malformed UTF-8", + cases: [ + ["invalid-key", Buffer.from('{"\xff":true}', "latin1"), null], + ["invalid-value", Buffer.from('{"k":"\xff"}', "latin1"), null], + ["overlong-key", Buffer.from('{"\xc0\xaf":true}', "latin1"), null], + ], }, { - name: "invalid UTF-8 string value", - body: Buffer.from([123, 34, 107, 34, 58, 34, 255, 34, 125]), - property: null, + name: "valid UTF-8", + cases: [ + ["accented-key", Buffer.from('{"é":true}'), "é"], + ["replacement-key", Buffer.from('{"�":true}'), "�"], + ], }, - { - name: "overlong UTF-8 property name", - body: Buffer.from([123, 34, 192, 175, 34, 58, 116, 114, 117, 101, 125]), - property: null, - }, - { - name: "valid UTF-8 property name", - body: Buffer.from('{"é":true}'), - property: "é", - }, - { - name: "literal replacement-character property name", - body: Buffer.from('{"�":true}'), - property: "�", - }, -])("preserves JSON-shape uncertainty for $name", async ({ body, property }) => { - const browser = await startFakeCdpBrowser({ - eventsBeforeReply: ["Network.enable"], - commandEvents(command, origin) { - if (command.method !== "Network.enable") return []; - const session = - command.sessionId === undefined ? {} : { sessionId: command.sessionId }; - return [false, true].flatMap((hasRequestShape) => { - const requestId = hasRequestShape - ? "request-and-response" - : "response-only"; - const url = `${origin}/${requestId}`; - return [ - { - ...session, - method: "Network.requestWillBeSent", - params: { - requestId, - request: { - url, - method: hasRequestShape ? "POST" : "GET", - ...(hasRequestShape +] as const)( + "keeps $name response body facts tied to their request", + async ({ cases }) => { + const exchanges = cases.flatMap(([id, body, property]) => + [false, true].map((hasRequestShape) => ({ + requestId: `${id}-${hasRequestShape ? "post" : "get"}`, + body, + property, + hasRequestShape, + })), + ); + const browser = await startFakeCdpBrowser({ + eventsBeforeReply: ["Network.enable"], + commandEvents(command, origin) { + if (command.method !== "Network.enable") return []; + return exchanges.flatMap(({ requestId, body, hasRequestShape }) => { + const url = `${origin}/${requestId}`; + return [ + { + sessionId: command.sessionId, + method: "Network.requestWillBeSent", + params: { + requestId, + request: hasRequestShape ? { + url, + method: "POST", headers: { "Content-Type": "application/json" }, postData: '{"request":true}', } - : {}), + : { url, method: "GET" }, + initiator: { type: "other" }, }, - initiator: { type: "other" }, }, - }, - { - ...session, - method: "Network.responseReceived", - params: { - requestId, - response: { url, status: 200, mimeType: "application/json" }, - }, - }, - { - ...session, - method: "Network.loadingFinished", - params: { requestId, encodedDataLength: body.length }, - }, - ]; - }); - }, - commandResult(command) { - return command.method === "Network.getResponseBody" - ? { body: body.toString("base64"), base64Encoded: true } - : undefined; - }, - }); - trackBrowser(browser); - const result = await new CdpBrowserProvider().inspectPage( - inspectWebPageInputSchema.parse({ - cdp_endpoint: browser.endpoint, - allowed_origins: [browser.allowedOrigin], - target_id: "allowed-page", - observation_ms: 0, - include_json_body_shapes: true, - }), - ); - if (!result.ok) throw result.error; - const requests = result.value.network.requests; - expect(requests).toHaveLength(2); - for (const request of requests) { - const hasRequestShape = request.request_id === "request-and-response"; - expect(request).toMatchObject({ - url: `${browser.allowedOrigin}/${request.request_id}`, - status: 200, - mime_type: "application/json", - encoded_data_length: body.length, - body_shapes: { - status: - property === null - ? hasRequestShape - ? "partial" - : "unavailable" - : "included", - request: hasRequestShape ? expect.any(Object) : null, - response: - property === null - ? null - : { - root_type: "object", - node_count: 2, - max_depth_observed: 1, - properties: [ - { - path: [{ kind: "property", name: property }], - types: ["boolean"], - observations: 1, - }, - ], + { + sessionId: command.sessionId, + method: "Network.responseReceived", + params: { + requestId, + response: { url, status: 200, mimeType: "application/json" }, }, + }, + { + sessionId: command.sessionId, + method: "Network.loadingFinished", + params: { requestId, encodedDataLength: body.length }, + }, + ]; + }); + }, + commandResult(command) { + if (command.method !== "Network.getResponseBody") return undefined; + const exchange = exchanges.find( + ({ requestId }) => requestId === command.params.requestId, + ); + if (exchange === undefined) throw new Error("Unexpected body request"); + return { body: exchange.body.toString("base64"), base64Encoded: true }; }, }); - } - expect( - browser.commands.filter( - (command) => command.method === "Network.getResponseBody", - ), - ).toHaveLength(2); - if (property === null) { - expect(result.value.completeness.unavailable_sections).toContain( - "json_body_shapes", + trackBrowser(browser); + const result = await new CdpBrowserProvider().inspectPage( + inspectWebPageInputSchema.parse({ + cdp_endpoint: browser.endpoint, + allowed_origins: [browser.allowedOrigin], + target_id: "allowed-page", + observation_ms: 0, + include_json_body_shapes: true, + }), ); - expect(result.value.completeness.excluded).toContainEqual({ + if (!result.ok) throw result.error; + + expect(result.value.network.requests).toEqual( + exchanges.map(({ requestId, body, property, hasRequestShape }) => + expect.objectContaining({ + request_id: requestId, + url: `${browser.allowedOrigin}/${requestId}`, + status: 200, + mime_type: "application/json", + encoded_data_length: body.length, + body_shapes: { + status: + property === null + ? hasRequestShape + ? "partial" + : "unavailable" + : "included", + request: hasRequestShape + ? expect.objectContaining({ root_type: "object" }) + : null, + response: + property === null + ? null + : { + root_type: "object", + node_count: 2, + max_depth_observed: 1, + properties: [ + { + path: [{ kind: "property", name: property }], + types: ["boolean"], + observations: 1, + }, + ], + }, + }, + }), + ), + ); + expect( + browser.commands + .filter(({ method }) => method === "Network.getResponseBody") + .map(({ params }) => params.requestId), + ).toEqual(exchanges.map(({ requestId }) => requestId)); + + const unavailable = cases.some(([, , property]) => property === null); + expect( + result.value.completeness.unavailable_sections.includes( + "json_body_shapes", + ), + ).toBe(unavailable); + const bodyGap = { section: "json_body_shapes", reason: "provider_unavailable", count: null, - }); - } else { - expect(result.value.completeness.unavailable_sections).not.toContain( - "json_body_shapes", - ); - } - expect(result.value.completeness.excluded).not.toContainEqual( - expect.objectContaining({ - section: "json_body_shapes", - reason: "invalid_protocol_value", - }), - ); -}); + }; + expect( + result.value.completeness.excluded.filter( + ({ section }) => section === "json_body_shapes", + ), + ).toEqual(unavailable ? [bodyGap] : []); + }, +); diff --git a/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts b/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts index 5675f7cf19..c6752d475a 100644 --- a/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts +++ b/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; + import { describe, expect, it } from "vitest"; import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js"; @@ -192,47 +194,103 @@ describe("CdpBrowserProvider: page cookie scope", () => { }); }); -describe("CdpBrowserProvider: complete storage fingerprints", () => { - it("fingerprints cache bodies above 64 KiB", async () => { - const body = "x".repeat(64 * 1_024 + 1); - const browser = await startFakeCdpBrowser({ cachedResponseBody: body }); - trackBrowser(browser); - const result = await new CdpBrowserProvider().inspectPage( - inspectWebPageInputSchema.parse({ - cdp_endpoint: browser.endpoint, - allowed_origins: [browser.allowedOrigin], - target_id: "allowed-page", - observation_ms: 0, - include_storage_keys: true, - include_storage_fingerprints: true, - }), - ); - - if (!result.ok) throw result.error; - expect(result.value.storage.fingerprints_complete).toBe(true); - expect( - result.value.storage.content_fingerprints.find( - ({ scope }) => scope === "cache_entry", - ), - ).toMatchObject({ complete: true, value_sha256: expect.any(String) }); - expect(JSON.stringify(result.value)).not.toContain(body); - // The storage capture always writes its fingerprint facts. - for (const omit of [ - "content_fingerprints", - "fingerprint_algorithm", - "fingerprints_complete", - ]) - expect( - webPageInspectionSchema.safeParse({ - ...result.value, - storage: Object.fromEntries( - Object.entries(result.value.storage).filter( - ([key]) => key !== omit, - ), - ), - }).success, - ).toBe(false); +it("fingerprints decoded cache bytes and leaves malformed cache entries incomplete", async () => { + const body = "x".repeat(64 * 1_024 + 1); + const validEntries = [ + { + path: "/large", + encoded: Buffer.from(body).toString("base64"), + decoded: body, + }, + { path: "/pad-bits", encoded: "e31=", decoded: "{}" }, + ]; + const malformed = { path: "/malformed", encoded: "e%30=", decoded: null }; + let entries: readonly { + path: string; + encoded: string; + decoded: string | null; + }[] = validEntries; + const browser = await startFakeCdpBrowser({ + commandResult(command, origin) { + if (command.method === "CacheStorage.requestEntries") + return { + cacheDataEntries: entries.map(({ path }) => ({ + requestURL: origin + path, + requestMethod: "GET", + requestHeaders: [], + })), + returnCount: entries.length, + }; + if (command.method !== "CacheStorage.requestCachedResponse") + return undefined; + const entry = entries.find( + ({ path }) => command.params.requestURL === origin + path, + ); + if (entry === undefined) throw new Error("Unexpected cache body request"); + return { response: { body: entry.encoded } }; + }, }); + trackBrowser(browser); + const input = inspectWebPageInputSchema.parse({ + cdp_endpoint: browser.endpoint, + allowed_origins: [browser.allowedOrigin], + target_id: "allowed-page", + observation_ms: 0, + include_storage_keys: true, + include_storage_fingerprints: true, + }); + const capture = async () => { + const result = await new CdpBrowserProvider().inspectPage(input); + if (!result.ok) throw result.error; + const cacheEntries = result.value.storage.content_fingerprints.filter( + ({ scope }) => scope === "cache_entry", + ); + expect(cacheEntries).toHaveLength(entries.length); + expect(cacheEntries).toEqual( + expect.arrayContaining( + entries.map(({ path, decoded }) => + expect.objectContaining({ + identity_sha256: createHash("sha256") + .update( + JSON.stringify({ + cache: "assets-v1", + requestHeaders: [], + requestMethod: "GET", + requestURL: browser.allowedOrigin + path, + }), + ) + .digest("hex"), + complete: decoded !== null, + value_sha256: + decoded === null + ? null + : createHash("sha256").update(decoded).digest("hex"), + }), + ), + ), + ); + expect(JSON.stringify(result.value)).not.toContain(body); + return result.value; + }; + + const before = await capture(); + expect(before.storage.fingerprints_complete).toBe(true); + entries = [...validEntries, malformed]; + expect((await capture()).storage.fingerprints_complete).toBe(false); + + for (const omit of [ + "content_fingerprints", + "fingerprint_algorithm", + "fingerprints_complete", + ]) + expect( + webPageInspectionSchema.safeParse({ + ...before, + storage: Object.fromEntries( + Object.entries(before.storage).filter(([key]) => key !== omit), + ), + }).success, + ).toBe(false); }); describe("CdpBrowserProvider: explicitly requested text and payload shapes", () => { diff --git a/tests/fixtures/fakeCdpBrowserResults.ts b/tests/fixtures/fakeCdpBrowserResults.ts index 82a4455461..33a570829e 100644 --- a/tests/fixtures/fakeCdpBrowserResults.ts +++ b/tests/fixtures/fakeCdpBrowserResults.ts @@ -63,7 +63,7 @@ export const resultFor = ( case "CacheStorage.requestEntries": return cacheEntriesResult(port); case "CacheStorage.requestCachedResponse": - return cachedResponseResult(options); + return cachedResponseResult(); case "Page.enable": case "Page.disable": case "Page.setLifecycleEventsEnabled": @@ -257,11 +257,9 @@ const cacheEntriesResult = (port: number) => ({ returnCount: 1, }); -const cachedResponseResult = (options: FakeOptions) => ({ +const cachedResponseResult = () => ({ response: { - body: Buffer.from( - options.cachedResponseBody ?? "cache-body-secret", - ).toString("base64"), + body: Buffer.from("cache-body-secret").toString("base64"), }, }); diff --git a/tests/fixtures/fakeCdpBrowserTypes.ts b/tests/fixtures/fakeCdpBrowserTypes.ts index c5e8e10d91..95af218aae 100644 --- a/tests/fixtures/fakeCdpBrowserTypes.ts +++ b/tests/fixtures/fakeCdpBrowserTypes.ts @@ -105,7 +105,6 @@ export interface FakeOptions { readonly sensitiveShapes?: boolean; /** Deliver a console argument the protocol spells as `{ type: "object", subtype: "null" }`. */ readonly nullConsoleArgument?: boolean; - readonly cachedResponseBody?: string; readonly webMcpTools?: boolean; /** Replaces the primary tool's registration stack; returning `undefined` omits it. */ readonly webMcpStackTrace?: (origin: string) => JsonValue | undefined;