Skip to content

The headless browser for AI agents and web scraping

fix(cdp): embed objectId as a JSON literal at every lookup site

aleekaza17015207a0c
diff --git a/crates/obscura-cdp/src/domains/dom.rs b/crates/obscura-cdp/src/domains/dom.rs
index eeb3c154..519f7989 100644
--- a/crates/obscura-cdp/src/domains/dom.rs
+++ b/crates/obscura-cdp/src/domains/dom.rs
@@ -4,17 +4,6 @@ use serde_json::{json, Value};
use crate::dispatch::CdpContext;
-/// Escape a client-supplied objectId for interpolation into a single-quoted JS
-/// string literal (`__obscura_objects['<here>']`). Backslashes must be escaped
-/// before single quotes, otherwise an id ending in `\` turns the closing quote
-/// into `\'` and produces a syntax error. All three objectId lookup sites route
-/// through this so they cannot diverge; not an injection vector (every `'` stays
-/// escaped, so the worst case is an unterminated string -> clean resolution
-/// failure), but a robustness fix.
-fn escape_object_id(oid: &str) -> String {
- oid.replace('\\', "\\\\").replace('\'', "\\'")
-}
-
/// Resolve a DOM `nodeId` from CDP params. Honors `nodeId`, `backendNodeId`,
/// and `objectId` in that order. Playwright commonly passes only `objectId`
/// (returned by a prior `DOM.resolveNode`); without this fallback those
@@ -28,9 +17,9 @@ fn resolve_node_id(page: &mut Page, params: &Value) -> Result<u64, String> {
}
if let Some(oid) = params.get("objectId").and_then(|v| v.as_str()) {
let code = format!(
- "(function() {{ var o = globalThis.__obscura_objects && globalThis.__obscura_objects['{}']; \
+ "(function() {{ var o = globalThis.__obscura_objects && globalThis.__obscura_objects[{}]; \
return (o && typeof o._nid === 'number') ? o._nid : -1; }})()",
- escape_object_id(oid)
+ crate::util::object_id_literal(oid)
);
let result = page.evaluate(&code);
let nid = result.as_f64().map(|n| n as i64).unwrap_or(-1);
@@ -151,10 +140,9 @@ pub async fn handle(
{
nid
} else if let Some(oid) = params.get("objectId").and_then(|v| v.as_str()) {
- let escaped_oid = escape_object_id(oid);
let code = format!(
- "(function() {{ var o = globalThis.__obscura_objects['{}']; if (!o) return -1; return (typeof o._nid === 'number') ? o._nid : -1; }})()",
- escaped_oid
+ "(function() {{ var o = globalThis.__obscura_objects[{}]; if (!o) return -1; return (typeof o._nid === 'number') ? o._nid : -1; }})()",
+ crate::util::object_id_literal(oid)
);
let result = page.evaluate(&code);
result.as_f64().map(|n| n as u64).unwrap_or(0)
@@ -175,8 +163,8 @@ pub async fn handle(
nid
} else if let Some(oid) = params.get("objectId").and_then(|v| v.as_str()) {
let code = format!(
- "(function() {{ var o = globalThis.__obscura_objects['{}']; return (o && typeof o._nid === 'number') ? o._nid : -1; }})()",
- escape_object_id(oid)
+ "(function() {{ var o = globalThis.__obscura_objects[{}]; return (o && typeof o._nid === 'number') ? o._nid : -1; }})()",
+ crate::util::object_id_literal(oid)
);
let result = page.evaluate(&code);
result.as_f64().map(|n| n as u64).unwrap_or(0)
@@ -524,16 +512,10 @@ mod tests {
use super::*;
use crate::dispatch::CdpContext;
- #[test]
- fn escape_object_id_escapes_backslash_before_quote() {
- // A trailing backslash must be doubled so it cannot escape the closing
- // quote of __obscura_objects['...']; the old resolve_node_id path escaped
- // only the quote, producing ['x\'] (syntax error) for the id `x\`.
- assert_eq!(escape_object_id(r"x\"), r"x\\");
- assert_eq!(escape_object_id("a'b"), r"a\'b");
- assert_eq!(escape_object_id(r"a\'b"), r"a\\\'b");
- assert_eq!(escape_object_id("plain"), "plain");
- }
+ // The escaping this file used to own now lives in `util::object_id_literal`,
+ // which is where its tests went with it: the three lookup sites here embed
+ // the id as a JSON literal rather than splicing it into a single-quoted
+ // string, so there is no per-domain escaping left to assert on.
#[tokio::test]
async fn dom_focus_sets_active_element() {
diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rs
index a6abfc90..6edd68e3 100644
--- a/crates/obscura-cdp/src/domains/runtime.rs
+++ b/crates/obscura-cdp/src/domains/runtime.rs
@@ -239,10 +239,15 @@ pub async fn handle(
let page = ctx
.get_session_page_mut(session_id)
.ok_or("No page")?;
- let escaped_oid = oid.replace('\\', "\\\\").replace('\'', "\\'");
+ // The child ids minted below are `<parent>::<key>` and the key
+ // is a property name off a page object, so the page decides
+ // what ends up inside this literal. A JSON literal covers the
+ // C0 controls a manual quote/backslash pair leaves alone; see
+ // `util::object_id_literal`.
+ let oid_literal = crate::util::object_id_literal(oid);
let code = format!(
"(function() {{\
- var obj = globalThis.__obscura_objects['{oid}'];\
+ var obj = globalThis.__obscura_objects[{oid}];\
if (!obj || typeof obj !== 'object') return [];\
var keys = Object.keys(obj);\
return keys.map(function(k) {{\
@@ -251,7 +256,7 @@ pub async fn handle(
var item = {{ name: k, type: t }};\
if (v === null) {{ item.value = null; return item; }}\
if (t !== 'object' && t !== 'function') {{ item.value = v; return item; }}\
- var childOid = '{oid}::' + k;\
+ var childOid = {oid} + '::' + k;\
globalThis.__obscura_objects[childOid] = v;\
item.childOid = childOid;\
if (typeof v.nodeType === 'number') {{\
@@ -269,7 +274,7 @@ pub async fn handle(
return item;\
}});\
}})()",
- oid = escaped_oid,
+ oid = oid_literal,
);
let result = page.evaluate(&code);
if let serde_json::Value::Array(props) = result {
diff --git a/crates/obscura-cdp/src/util.rs b/crates/obscura-cdp/src/util.rs
index e08d26ea..97af88bb 100644
--- a/crates/obscura-cdp/src/util.rs
+++ b/crates/obscura-cdp/src/util.rs
@@ -18,6 +18,32 @@ pub(crate) fn url_is_file_scheme(raw: &str) -> bool {
})
}
+/// Embed an objectId as a JS string literal, quotes included.
+///
+/// objectIds are interpolated into generated snippets that look up
+/// `__obscura_objects[<here>]`. Escaping `\` and `'` by hand covers the two
+/// characters that close a single-quoted literal and leaves every C0 control
+/// alone - and a raw newline ends a JS string literal just as a stray quote
+/// does. The snippet is then a syntax error, the lookup yields nothing, and
+/// the caller is told nothing: `Runtime.getProperties` answers with an empty
+/// property list and `DOM.describeNode` falls back to node 0, so a client is
+/// handed the document where it asked for an element.
+///
+/// Not an injection vector, and it never was: the worst case is an
+/// unterminated string, i.e. a clean resolution failure. What makes it worth
+/// removing is that the failure is invisible from the outside.
+///
+/// The ids are not all ours to shape. `Runtime.getProperties` mints child ids
+/// as `parentId + "::" + key`, and the key is a property name off a page
+/// object, so the page decides what ends up inside the literal.
+///
+/// JSON string syntax is a subset of JavaScript's, so serialising the id gives
+/// a double-quoted literal that escapes `"`, `\` and every C0 control at once.
+/// Callers interpolate the result *without* adding quotes of their own.
+pub(crate) fn object_id_literal(oid: &str) -> String {
+ serde_json::to_string(oid).unwrap_or_else(|_| "\"\"".to_string())
+}
+
/// Truncate `s` to at most `max` bytes, never splitting a UTF-8 character.
///
/// `&s[..max]` panics when `max` lands inside a multi-byte character, and the
@@ -78,6 +104,53 @@ mod tests {
assert!(!url_is_file_scheme("http://file/"));
}
+ #[test]
+ fn object_id_literal_quotes_and_escapes_what_the_hand_rolled_pair_did() {
+ // The pair this replaced was
+ // oid.replace('\\', "\\\\").replace('\'', "\\'")
+ // feeding a single-quoted '{}'. A double-quoted JSON literal needs no
+ // escape for `'` and adds one for `"`, so both quote characters are
+ // covered rather than one.
+ assert_eq!(object_id_literal("plain"), r#""plain""#);
+ assert_eq!(object_id_literal(r"x\"), r#""x\\""#);
+ assert_eq!(object_id_literal("a'b"), r#""a'b""#);
+ assert_eq!(object_id_literal("a\"b"), r#""a\"b""#);
+ // Carried over from the dom.rs helper this replaces: the backslash has
+ // to be doubled before the quote is looked at, or `a\'b` comes out with
+ // the escape attached to the wrong character.
+ assert_eq!(object_id_literal(r"a\'b"), r#""a\\'b""#);
+ }
+
+ #[test]
+ fn object_id_literal_escapes_the_controls_the_hand_rolled_pair_missed() {
+ // A raw LF or CR terminates a JS string literal, so these produced a
+ // syntax error and a silent resolution failure rather than a lookup.
+ // NUL parses but truncates the id against anything C-string shaped.
+ assert_eq!(object_id_literal("a\nb"), r#""a\nb""#);
+ assert_eq!(object_id_literal("a\rb"), r#""a\rb""#);
+ assert_eq!(object_id_literal("a\tb"), r#""a\tb""#);
+ assert_eq!(object_id_literal("a\0b"), r#""a\u0000b""#);
+ }
+
+ #[test]
+ fn object_id_literal_survives_the_shape_the_runtime_actually_mints() {
+ // Ids are JSON documents themselves, so the literal has to carry a
+ // second round of quoting without losing the id.
+ let oid = r#"{"injectedScriptId":1,"id":7}"#;
+ assert_eq!(
+ object_id_literal(oid),
+ r#""{\"injectedScriptId\":1,\"id\":7}""#
+ );
+
+ // And a getProperties child id is that, plus `::`, plus a page-chosen
+ // property name - the input this helper exists for.
+ let child = format!("{oid}::lf\nx");
+ assert_eq!(
+ object_id_literal(&child),
+ r#""{\"injectedScriptId\":1,\"id\":7}::lf\nx""#
+ );
+ }
+
#[test]
fn truncate_never_splits_a_multibyte_char() {
// 199 ASCII bytes + '€' (3 bytes, occupying indices 199..=201): byte 200
diff --git a/crates/obscura-cdp/tests/runtime_get_properties_objectid_escaping.rs b/crates/obscura-cdp/tests/runtime_get_properties_objectid_escaping.rs
new file mode 100644
index 00000000..f4744000
--- /dev/null
+++ b/crates/obscura-cdp/tests/runtime_get_properties_objectid_escaping.rs
@@ -0,0 +1,230 @@
+//! `Runtime.getProperties` mints a child objectId as `parentOid + '::' + key`
+//! and interpolates it straight back into a generated
+//! `__obscura_objects['<oid>']` lookup on the next call. The key comes from the
+//! page, so the page - not the client - decides which characters land inside
+//! that single-quoted JS literal (issue #709).
+//!
+//! Escaping only `\` and `'` leaves every C0 control alone, and a raw newline
+//! ends a JS string literal exactly as a stray quote does. The generated
+//! snippet is then a syntax error, `page.evaluate` yields no array, and the
+//! handler falls through to `result: []`. That is the part worth a regression
+//! test: the call still answers without an error and with an empty property
+//! list, so a client walking a nested object sees an object that has no
+//! properties rather than a failure, and nothing anywhere reports one.
+
+use obscura_cdp::dispatch::{dispatch, CdpContext};
+use obscura_cdp::types::CdpRequest;
+use serde_json::{json, Value};
+
+async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, session_id: &str) -> Value {
+ let resp = dispatch(
+ &CdpRequest {
+ id,
+ method: method.to_string(),
+ params,
+ session_id: Some(session_id.to_string()),
+ },
+ ctx,
+ )
+ .await;
+ assert!(resp.error.is_none(), "CDP {method} failed: {:?}", resp.error);
+ resp.result.unwrap_or_else(|| json!({}))
+}
+
+/// The `objectId` of the property descriptor named `name`.
+fn child_object_id(props: &Value, name: &str) -> Option<String> {
+ props
+ .get("result")?
+ .as_array()?
+ .iter()
+ .find(|d| d.get("name").and_then(|v| v.as_str()) == Some(name))
+ .and_then(|d| d.pointer("/value/objectId"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+}
+
+/// The string value of the property descriptor named `name`.
+fn string_property(props: &Value, name: &str) -> Option<String> {
+ props
+ .get("result")?
+ .as_array()?
+ .iter()
+ .find(|d| d.get("name").and_then(|v| v.as_str()) == Some(name))
+ .and_then(|d| d.pointer("/value/value"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+}
+
+// The keys are assembled with String.fromCharCode so this expression carries no
+// backslash of its own: the characters under test are exactly the four below
+// and not an artefact of how the literal was written. A page is free to define
+// every one of them, and a client cannot sanitise them away - it never sees the
+// key until getProperties has already built an objectId out of it.
+const SETUP: &str = r#"(function () {
+ var LF = String.fromCharCode(10);
+ var CR = String.fromCharCode(13);
+ var NUL = String.fromCharCode(0);
+ var BACKSLASH = String.fromCharCode(92);
+ var o = {};
+ o["lf" + LF + "x"] = { mark: "lf" };
+ o["cr" + CR + "x"] = { mark: "cr" };
+ o["nul" + NUL + "x"] = { mark: "nul" };
+ o["quote'" + BACKSLASH + "x"] = { mark: "quote" };
+ globalThis.__t = o;
+ return o;
+})()"#;
+
+#[tokio::test(flavor = "current_thread")]
+async fn get_properties_walks_into_a_child_whose_key_holds_a_control_character() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session_id = "session-1";
+ ctx.sessions.insert(session_id.to_string(), page_id.clone());
+
+ cdp(
+ &mut ctx,
+ 1,
+ "Page.navigate",
+ json!({"url": "about:blank", "waitUntil": "load"}),
+ session_id,
+ )
+ .await;
+
+ // returnByValue omitted, so the result is a handle rather than a copy.
+ let root = cdp(
+ &mut ctx,
+ 2,
+ "Runtime.evaluate",
+ json!({"expression": SETUP}),
+ session_id,
+ )
+ .await;
+ let root_oid = root
+ .pointer("/result/objectId")
+ .and_then(|v| v.as_str())
+ .expect("Runtime.evaluate must hand back an objectId for an object result")
+ .to_string();
+
+ let top = cdp(
+ &mut ctx,
+ 3,
+ "Runtime.getProperties",
+ json!({"objectId": root_oid}),
+ session_id,
+ )
+ .await;
+
+ // The last pair is the case the hand-rolled escaping already covered. It is
+ // here so a regression in either direction shows up in one run: a fix that
+ // traded the quote handling for control-character handling would pass the
+ // first three and fail this one.
+ let cases = [
+ ("lf\nx", "lf"),
+ ("cr\rx", "cr"),
+ ("nul\0x", "nul"),
+ ("quote'\\x", "quote"),
+ ];
+
+ for (id, (key, mark)) in cases.iter().enumerate() {
+ let child_oid = child_object_id(&top, key).unwrap_or_else(|| {
+ panic!("no child objectId for key {key:?}; descriptors were {top:#?}")
+ });
+
+ let child = cdp(
+ &mut ctx,
+ 10 + id as u64,
+ "Runtime.getProperties",
+ json!({"objectId": child_oid}),
+ session_id,
+ )
+ .await;
+
+ assert_eq!(
+ string_property(&child, "mark").as_deref(),
+ Some(*mark),
+ "walking into the child keyed {key:?} must reach its properties, \
+ not fall through to an empty list; got {child:#?}"
+ );
+ }
+}
+
+// The same page-minted objectId does not stay inside Runtime. Puppeteer's `$$`
+// flow is evaluate -> getProperties -> asElement, and asElement handles go on to
+// DOM.describeNode / DOM.resolveNode, which interpolate the id into the same kind
+// of lookup. dom.rs used to do that through its own `escape_object_id` - the
+// helper #709 cites as already robust - but that was the same two `replace` calls
+// and so had the same hole. Here the fallback was worse than an empty list:
+// describeNode's `unwrap_or(0)` answers with node 0, so the client was handed a
+// description of the wrong element rather than a failure.
+//
+// Both call sites now share `util::object_id_literal`, which is what keeps this
+// test and the one above from drifting apart.
+const SETUP_NODES: &str = r#"(function () {
+ var LF = String.fromCharCode(10);
+ var o = {};
+ o["plain"] = document.getElementById("a");
+ o["lf" + LF + "x"] = document.getElementById("b");
+ globalThis.__n = o;
+ return o;
+})()"#;
+
+#[tokio::test(flavor = "current_thread")]
+async fn describe_node_resolves_a_child_handle_whose_key_holds_a_control_character() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session_id = "session-1";
+ ctx.sessions.insert(session_id.to_string(), page_id.clone());
+
+ cdp(
+ &mut ctx,
+ 1,
+ "Page.navigate",
+ json!({"url": "data:text/html,<div id=a></div><p id=b></p>", "waitUntil": "load"}),
+ session_id,
+ )
+ .await;
+
+ let root = cdp(
+ &mut ctx,
+ 2,
+ "Runtime.evaluate",
+ json!({"expression": SETUP_NODES}),
+ session_id,
+ )
+ .await;
+ let root_oid = root
+ .pointer("/result/objectId")
+ .and_then(|v| v.as_str())
+ .expect("Runtime.evaluate must hand back an objectId for an object result")
+ .to_string();
+
+ let top = cdp(
+ &mut ctx,
+ 3,
+ "Runtime.getProperties",
+ json!({"objectId": root_oid}),
+ session_id,
+ )
+ .await;
+
+ for (id, (key, node_name)) in [("plain", "DIV"), ("lf\nx", "P")].iter().enumerate() {
+ let child_oid = child_object_id(&top, key).unwrap_or_else(|| {
+ panic!("no child objectId for key {key:?}; descriptors were {top:#?}")
+ });
+
+ let described = cdp(
+ &mut ctx,
+ 20 + id as u64,
+ "DOM.describeNode",
+ json!({"objectId": child_oid}),
+ session_id,
+ )
+ .await;
+
+ assert_eq!(
+ described.pointer("/node/nodeName").and_then(|v| v.as_str()),
+ Some(*node_name),
+ "the handle keyed {key:?} must describe its own element; got {described:#?}"
+ );
+ }
+}