fix(web): require root identity in CDP session and runtime captures (#13186)

This commit is contained in:
morluto authored and GitHub committed 2026-11-21 18:55:15 +00:00
1 parent 006581b838
commit 4807b31749
4 files changed
+258 -286

No files matched your search

+10 -9
View File
@@ -23,6 +23,7 @@ import {
import { classifyCdpFrameUrl } from "./CdpCaptureDocuments.js";
import { selectCdpFrameIdentity } from "./CdpFrameIdentity.js";
import { CdpTargetDocument } from "./CdpTargetDocument.js";
import { cdpRootDocument } from "./CdpTargetSession.js";
import type { CdpCommandResult } from "./protocol/CdpCommands.js";
import { observedFrameUrl, reportedFrameUrl } from "./protocol/CdpFrameTree.js";
import {
@@ -75,15 +76,11 @@ export const observeCdpSession = async (
allowedOrigins,
operation: "observe_web_session",
});
const initialUrl = observedFrameUrl(initial.root.url) ?? "";
const mainFrameId = initial.root.facts.frameId;
if (mainFrameId === null)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
const document = CdpTargetDocument.watch(context, {
frameId: mainFrameId,
loaderId: initial.root.facts.loaderId,
url: observedFrameUrl(initial.root.url),
});
const selected = cdpRootDocument(initial);
if (selected === undefined)
throw new BrowserObservationError("observe_web_session", "protocol_error");
const initialUrl = selected.url ?? "";
const document = CdpTargetDocument.watch(context, selected);
const capture = new TimelineCapture(allowedOrigins, document, initialUrl);
let removeListener = (): void => {};
const removeDisconnectListener = context.connection.onDisconnect(() =>
@@ -777,6 +774,10 @@ const captureFinalUrl = async (
context.signal,
);
if (capture.scopeExcluded) return "target_left_scope";
if (cdpRootDocument(tree) === undefined) {
capture.invalidateFinalUrl();
return "window_elapsed";
}
const observation = tree.root.url;
const facts = classifyCdpFrameUrl(observation, allowedOrigins);
if (observation.kind !== "observed") capture.invalidateFinalUrl();
+7 -11
View File
@@ -15,10 +15,7 @@ import {
} from "../../domain/browserDeadline.js";
import { CdpTargetSessionOwner } from "../CdpTargetSessionOwner.js";
import { classifyCdpFrameUrl } from "../CdpCaptureDocuments.js";
import {
observedFrameUrl,
type CdpFrameTree,
} from "../protocol/CdpFrameTree.js";
import type { CdpFrameTree } from "../protocol/CdpFrameTree.js";
import type {
CdpDomainWith,
CdpCommand,
@@ -38,6 +35,7 @@ import {
type CdpEndpointDiscovery,
} from "../CdpEndpoint.js";
import {
cdpRootDocument,
openCdpTargetSession,
type CdpTargetSession,
} from "../CdpTargetSession.js";
@@ -138,8 +136,8 @@ export class CdpRuntimeSession {
target_id: target.id,
initial_url: url.url,
origin: url.origin,
frame_id: frame.id,
loader_id: frame.loaderId ?? null,
frame_id: frame.document.frameId,
loader_id: frame.document.loaderId ?? null,
},
allowedOrigins,
operation,
@@ -374,16 +372,14 @@ const runtimeMainFrame = (
allowedOrigins: ReadonlySet<string>,
operation: BrowserObservationOperation,
) => {
const { frameId, loaderId, loaderIssue } = tree.root.facts;
if (frameId === null || loaderIssue !== null)
const document = cdpRootDocument(tree);
if (document === undefined)
throw new BrowserObservationError(operation, "protocol_error", {
detail:
"CDP Page.getFrameTree did not identify the selected main frame's document.",
});
return {
id: frameId,
loaderId,
document: { frameId, loaderId, url: observedFrameUrl(tree.root.url) },
document,
...classifyCdpFrameUrl(tree.root.url, allowedOrigins),
};
};
@@ -42,101 +42,136 @@ const run = async (
}
};
it.each(
operations.flatMap((operation) =>
["about:blank", "about:srcdoc", "file:///local.html", "not a URL"].flatMap(
(url) =>
[7, "bad-fragment"].map((urlFragment) => ({
operation,
url,
urlFragment,
})),
),
),
)(
"retries uncertain initial $url/$urlFragment before $operation authorizes",
async ({ operation, url, urlFragment }) => {
let reads = 0;
const browser = await startRuntimeBrowser({
commandResult: ({ method }) => {
if (method !== "Page.getFrameTree" || ++reads > 2) return undefined;
return {
frameTree: { frame: { id: "runtime-main", url, urlFragment } },
};
},
});
trackBrowser(browser);
const result = await run(browser, operation);
expect(result.ok).toBe(true);
expect(reads).toBeGreaterThan(2);
},
);
const frameReads = (browser: FakeCdpBrowser) =>
browser.commands.filter(({ method }) => method === "Page.getFrameTree");
it.each(
operations.flatMap((operation) =>
[false, true].flatMap((foreign) =>
[7, "bad-fragment"].map((urlFragment) => ({
operation,
foreign,
urlFragment,
})),
),
),
)(
"rejects known $foreign scope with malformed $urlFragment immediately for $operation",
async ({ operation, foreign, urlFragment }) => {
let reads = 0;
const protectedDomain = {
inspect: "Network.enable",
session: "Network.enable",
runtime: "Debugger.enable",
} satisfies Record<Operation, string>;
const selectedFrame = (url: string, fields: Record<string, unknown> = {}) => ({
frameTree: {
frame: { id: "runtime-main", loaderId: "document-1", url, ...fields },
},
});
const startFrameBrowser = async (
reply: (origin: string, reads: number) => Record<string, unknown> | undefined,
) => {
const browser = await startRuntimeBrowser({
commandResult: ({ method }, origin, reads) =>
method === "Page.getFrameTree" ? reply(origin, reads) : undefined,
});
trackBrowser(browser);
return browser;
};
it.each(operations)(
"authorizes %s only after the main frame is readable",
async (operation) => {
const startupFrames = [
{ id: "runtime-main" },
{ id: "runtime-main", url: "about:blank" },
{ id: "runtime-main", url: "about:srcdoc", urlFragment: 7 },
{
id: "runtime-main",
url: "file:///local.html",
urlFragment: "bad-fragment",
},
{ id: "runtime-main", url: "not a URL", urlFragment: 7 },
];
let readsAtEnable: number | undefined;
const browser = await startRuntimeBrowser({
commandResult: ({ method }, origin) => {
commandResult: ({ method }, _origin, reads) => {
if (method === protectedDomain[operation]) readsAtEnable ??= reads;
if (method !== "Page.getFrameTree") return undefined;
reads += 1;
return {
frameTree: {
frame: {
id: "runtime-main",
url: foreign ? "https://foreign.example/page" : `${origin}/app`,
urlFragment,
},
},
};
const frame = startupFrames[reads - 1];
if (frame !== undefined) return { frameTree: { frame } };
return undefined;
},
});
trackBrowser(browser);
const result = await run(browser, operation);
expect(result).toMatchObject({
ok: false,
error: { reason: foreign ? "target_not_allowed" : "protocol_error" },
if (!result.ok) throw result.error;
expect(result.value.target).toMatchObject({
target_id: "allowed-page",
[operation === "inspect" ? "url" : "initial_url"]:
`${browser.allowedOrigin}/app`,
});
if (foreign && !result.ok)
expect(projectAnalysisError(result.error)).toMatchObject({
code: "target_unavailable",
message: expect.stringContaining("permitted HTTP(S) origin scope"),
remediation: { action: expect.stringContaining("allowed_origins") },
details: { reason: "target_not_allowed" },
});
expect(reads).toBe(1);
expect(readsAtEnable).toBe(startupFrames.length + 1);
},
);
// A reply without a frame tree is a protocol failure, not 80 retries that end
// in an origin refusal.
it.each(
operations.flatMap((operation) =>
[{}, { frameTree: null }, { frameTree: [] }].map((reply) => ({
operation,
reply,
})),
),
)(
"rejects a malformed frame tree reply $reply once for $operation",
async ({ operation, reply }) => {
const browser = await startRuntimeBrowser({
commandResult: ({ method }) =>
method === "Page.getFrameTree" ? reply : undefined,
});
trackBrowser(browser);
it.each([
{ operation: "inspect", fragment: undefined },
{ operation: "session", fragment: 7 },
{ operation: "runtime", fragment: "bad-fragment" },
] as const)(
"refuses outside-policy $operation before enabling capture",
async ({ operation, fragment }) => {
const browser = await startFrameBrowser(() =>
selectedFrame("https://foreign.example/page", { urlFragment: fragment }),
);
const result = await run(browser, operation);
expect(result).toMatchObject({
if (result.ok) throw new Error("Expected origin scope refusal");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "target_unavailable",
remediation: { action: expect.stringContaining("allowed_origins") },
details: { reason: "target_not_allowed" },
});
expect(frameReads(browser)).toHaveLength(1);
expect(browser.commands.map(({ method }) => method)).not.toContain(
protectedDomain[operation],
);
},
);
const child = { parentId: "enclosing-frame" };
it.each([
{
operation: "inspect",
defect: "numeric fragment",
fields: { urlFragment: 7 },
},
{
operation: "runtime",
defect: "fragment missing delimiter",
fields: { urlFragment: "bad-fragment" },
},
...operations.map((operation) => ({
operation,
defect: "parent on root",
fields: child,
})),
] as const)(
"refuses $operation before capture for $defect",
async ({ operation, fields }) => {
const browser = await startFrameBrowser((origin) =>
selectedFrame(`${origin}/app`, fields),
);
expect(await run(browser, operation)).toMatchObject({
ok: false,
error: { reason: "protocol_error" },
});
expect(frameReads(browser)).toHaveLength(1);
expect(browser.commands.map(({ method }) => method)).not.toContain(
protectedDomain[operation],
);
},
);
it.each([
{ operation: "inspect", reply: {} },
{ operation: "session", reply: { frameTree: null } },
{ operation: "runtime", reply: { frameTree: [] } },
] as const)(
"rejects a malformed frame tree reply once for $operation",
async ({ operation, reply }) => {
const browser = await startFrameBrowser(() => reply);
expect(await run(browser, operation)).toMatchObject({
ok: false,
error: {
reason: "protocol_error",
@@ -144,26 +179,28 @@ it.each(
pointer: "/frameTree",
},
});
expect(
browser.commands.filter(({ method }) => method === "Page.getFrameTree"),
).toHaveLength(1);
expect(frameReads(browser)).toHaveLength(1);
},
);
it("bounds unsupported malformed frame retries without authorizing execution", async () => {
let reads = 0;
const browser = await startRuntimeBrowser({
commandResult: ({ method }) => {
if (method !== "Page.getFrameTree") return undefined;
reads += 1;
return {
frameTree: {
frame: { id: "runtime-main", url: "about:blank", urlFragment: 7 },
},
};
},
it("withholds the final session URL when the proposed root has a parent", async () => {
const browser = await startFrameBrowser((origin, reads) =>
reads > 1 ? selectedFrame(`${origin}/child`, child) : undefined,
);
const result = await run(browser, "session");
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
target: { initial_url: `${browser.allowedOrigin}/app`, final_url: null },
window: { end_reason: "window_elapsed" },
completeness: { unavailable_sections: ["timeline"] },
});
trackBrowser(browser);
expect(frameReads(browser)).toHaveLength(2);
});
it("bounds unsupported malformed frame retries without authorizing execution", async () => {
const browser = await startFrameBrowser(() =>
selectedFrame("about:blank", { urlFragment: 7 }),
);
const result = await run(browser, "runtime");
expect(result).toMatchObject({
ok: false,
@@ -173,7 +210,7 @@ it("bounds unsupported malformed frame retries without authorizing execution", a
expect(JSON.stringify(projectAnalysisError(result.error))).not.toContain(
"outside the permitted HTTP(S) origin scope",
);
expect(reads).toBe(80);
expect(frameReads(browser)).toHaveLength(80);
expect(browser.commands.map(({ method }) => method)).not.toContain(
"Debugger.enable",
);
@@ -181,18 +218,10 @@ it("bounds unsupported malformed frame retries without authorizing execution", a
it("preserves cancellation while an unsupported malformed frame awaits authorization", async () => {
const controller = new AbortController();
const browser = await startRuntimeBrowser({
commandResult: ({ method }) => {
if (method !== "Page.getFrameTree") return undefined;
setTimeout(() => controller.abort("caller stopped authorization"), 5);
return {
frameTree: {
frame: { id: "runtime-main", url: "about:blank", urlFragment: 7 },
},
};
},
const browser = await startFrameBrowser(() => {
setTimeout(() => controller.abort("caller stopped authorization"), 5);
return selectedFrame("about:blank", { urlFragment: 7 });
});
trackBrowser(browser);
expect(await run(browser, "inspect", controller.signal)).toMatchObject({
ok: false,
error: {
@@ -200,51 +229,5 @@ it("preserves cancellation while an unsupported malformed frame awaits authoriza
cause: "caller stopped authorization",
},
});
expect(
browser.commands.filter(({ method }) => method === "Page.getFrameTree"),
).toHaveLength(1);
expect(frameReads(browser)).toHaveLength(1);
});
// Ordinary startup uncertainty and known policy exits keep their existing semantics.
it.each(
operations.flatMap((operation) =>
["unsupported", "missing", "foreign"].map((kind) => ({ operation, kind })),
),
)(
"preserves $kind authorization behavior for $operation",
async ({ operation, kind }) => {
let reads = 0;
const browser = await startRuntimeBrowser({
commandResult: ({ method }) => {
if (method !== "Page.getFrameTree" || ++reads > 2) return undefined;
return {
frameTree: {
frame: {
id: "runtime-main",
...(kind === "missing"
? {}
: {
url:
kind === "foreign"
? "https://foreign.example/page"
: "about:blank",
}),
},
},
};
},
});
trackBrowser(browser);
const result = await run(browser, operation);
if (kind === "foreign") {
expect(result).toMatchObject({
ok: false,
error: { reason: "target_not_allowed" },
});
expect(reads).toBe(1);
} else {
expect(result.ok).toBe(true);
expect(reads).toBeGreaterThan(2);
}
},
);
@@ -1,4 +1,3 @@
import { BrowserObservationError } from "../../../src/domain/browserObservationError.js";
import { expect, it } from "vitest";
import { CdpWebRuntimeProvider } from "../../../src/browser/execution/CdpWebRuntimeProvider.js";
import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution.js";
@@ -30,119 +29,94 @@ const run = async (
);
};
it.each(
actions.flatMap((action) =>
[false, true].flatMap((loader) =>
["split", "clear", "inline", "credentials"].map((kind) => ({
action,
loader,
kind,
})),
),
),
)(
"preserves full $kind frame identity in $action evidence with loader=$loader",
async ({ action, loader, kind }) => {
const documentId = "document-1";
const query = "/app?caller=retained";
const frameTree = (url: string, fields: Record<string, unknown> = {}) => ({
frameTree: {
frame: { id: "runtime-main", loaderId: documentId, url, ...fields },
},
});
it.each([
["execution", "#details", "#details", documentId, false],
["listeners", "", "", undefined, false],
["execution", undefined, "#old", undefined, false],
["listeners", "#details", "#details", documentId, true],
] as const)(
"preserves reported %s identity with split fragment %s",
async (action, splitFragment, fragment, loaderId, credentials) => {
const browser = await startRuntimeBrowser({
commandResult: ({ method }, origin) =>
method === "Page.getFrameTree"
? {
frameTree: {
frame: {
id: "runtime-main",
...(loader ? { loaderId: "document-1" } : {}),
url: `${kind === "credentials" ? origin.replace("://", "://user:password@") : origin}/app?caller=retained#old`,
...(kind === "inline"
? {}
: { urlFragment: kind === "clear" ? "" : "#details" }),
},
},
}
: undefined,
commandResult: ({ method }, origin) => {
if (method !== "Page.getFrameTree") return undefined;
const host = credentials
? origin.replace("://", "://user:password@")
: origin;
return frameTree(`${host}${query}#old`, {
loaderId,
urlFragment: splitFragment,
});
},
});
trackBrowser(browser);
const result = await run(browser, action);
if (!result.ok) throw result.error;
expect(result.value.target).toMatchObject({
initial_url: `${browser.allowedOrigin}/app?caller=retained${kind === "inline" ? "#old" : kind === "clear" ? "" : "#details"}`,
frame_id: "runtime-main",
initial_url: `${browser.allowedOrigin}${query}${fragment}`,
origin: browser.allowedOrigin,
loader_id: loader ? "document-1" : null,
loader_id: loaderId ?? null,
});
},
);
const transitions = [
{ kind: "equivalent", loader: false, reason: null },
{ kind: "fragment-change", loader: false, reason: "target_changed" },
{ kind: "fragment-change", loader: true, reason: null },
{ kind: "malformed", loader: false, reason: "protocol_error" },
{ kind: "malformed", loader: true, reason: "protocol_error" },
{ kind: "foreign-malformed", loader: true, reason: "target_not_allowed" },
{ kind: "foreign-loader-change", loader: true, reason: "target_changed" },
{ kind: "foreign", loader: false, reason: "target_not_allowed" },
{ kind: "foreign", loader: true, reason: "target_not_allowed" },
{ kind: "missing", loader: true, reason: "protocol_error" },
{ kind: "frame-change", loader: true, reason: "target_changed" },
{ kind: "loader-change", loader: true, reason: "target_changed" },
{ kind: "unsupported", loader: false, reason: "target_not_allowed" },
{ kind: "unsupported", loader: true, reason: "target_not_allowed" },
] as const;
it.each(
actions.flatMap((action) => transitions.map((item) => ({ action, ...item }))),
)(
"checks parsed $kind final identity in $action with loader=$loader",
async ({ action, kind, loader, reason }) => {
const foreign = { url: "https://foreign.example/app" };
const badFragment = { urlFragment: 7 };
const changedFragment = { urlFragment: "#changed" };
const changedLoader = { loaderId: "replacement" };
const changed = "target_changed";
const refused = "target_not_allowed";
const invalid = "protocol_error";
it.each([
["execution", "equivalent inline fragment", false, "inline", null],
["listeners", "fragment change, no loader", false, changedFragment, changed],
["execution", "fragment change, same loader", true, changedFragment, null],
["listeners", "malformed fragment", true, badFragment, invalid],
[
"listeners",
"malformed foreign",
true,
{ ...foreign, ...badFragment },
refused,
],
[
"execution",
"foreign with new loader",
true,
{ ...foreign, ...changedLoader },
changed,
],
["execution", "foreign with same loader", true, foreign, refused],
["execution", "missing URL", true, { url: undefined }, invalid],
["listeners", "different frame", true, { id: "replacement" }, changed],
["execution", "different loader", true, changedLoader, changed],
["listeners", "unsupported base", false, { url: "about:blank" }, refused],
] as const)(
"checks %s document with %s",
async (action, _label, loader, change, reason) => {
const browser = await startRuntimeBrowser({
commandResult: ({ method }, origin, reads) => {
if (method !== "Page.getFrameTree") return undefined;
const changed = reads > 1;
const url = `${origin}/app?caller=retained`;
return {
frameTree: {
frame: {
id:
changed && kind === "frame-change"
? "replacement"
: "runtime-main",
...(loader
? {
loaderId:
changed &&
(kind === "loader-change" ||
kind === "foreign-loader-change")
? "replacement"
: "document-1",
}
: {}),
...(changed && kind === "missing"
? {}
: {
url:
changed &&
(kind === "foreign-malformed" ||
kind === "foreign" ||
kind === "foreign-loader-change")
? "https://foreign.example/app"
: changed && kind === "unsupported"
? "about:blank"
: changed && kind === "equivalent"
? `${url}#details`
: url,
}),
...(changed && kind === "equivalent"
? {}
: {
urlFragment:
changed &&
(kind === "malformed" || kind === "foreign-malformed")
? 7
: changed && kind === "fragment-change"
? "#changed"
: "#details",
}),
},
},
};
const url = `${origin}${query}`;
const updated =
change === "inline"
? { url: `${url}#details`, urlFragment: undefined }
: change;
return frameTree(url, {
loaderId: loader ? documentId : undefined,
urlFragment: "#details",
...(reads > 1 ? updated : {}),
});
},
});
trackBrowser(browser);
@@ -150,20 +124,38 @@ it.each(
if (reason === null) {
if (!result.ok) throw result.error;
expect(result.value.target.initial_url).toBe(
`${browser.allowedOrigin}/app?caller=retained#details`,
`${browser.allowedOrigin}${query}#details`,
);
} else {
expect(result).toMatchObject({ ok: false, error: { reason } });
if (kind === "foreign" && loader && !result.ok) {
if (!(result.error instanceof BrowserObservationError))
throw result.error;
expect(result.error.detail).toBe(
`Selected target allowed-page moved to an unselected origin during ${result.error.operation}.`,
);
}
}
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("Debugger.disable");
expect(methods).toContain("Target.detachFromTarget");
},
);
it.each(actions)(
"refuses a child root after collecting %s evidence",
async (action) => {
let sourceRead = false;
let returnedChild = false;
const browser = await startRuntimeBrowser({
commandResult: ({ method }, origin) => {
if (method === "Debugger.getScriptSource") sourceRead = true;
if (method !== "Page.getFrameTree" || !sourceRead) return undefined;
returnedChild = true;
return frameTree(`${origin}/app`, { parentId: "enclosing-frame" });
},
});
trackBrowser(browser);
expect(await run(browser, action)).toMatchObject({
ok: false,
error: { reason: "protocol_error" },
});
expect(returnedChild).toBe(true);
expect(browser.commands.map(({ method }) => method)).toEqual(
expect.arrayContaining(["Debugger.disable", "Target.detachFromTarget"]),
);
},
);