Skip to content

The headless browser for AI agents and web scraping

fix(js): honour postMessage targetOrigin to stop cross-origin leaks

Andrey Mnatsakanov15bf567e603f
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index e1aa4ae6..52f56442 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -1084,10 +1084,12 @@ impl Page {
for message in pending {
let escaped_data = serde_json::to_string(&message.data_json).unwrap_or_default();
let escaped_origin = serde_json::to_string(&message.origin).unwrap_or_default();
+ let escaped_target_origin =
+ serde_json::to_string(&message.target_origin).unwrap_or_default();
if message.target_frame_id == 0 {
let Some(js) = self.js.as_mut() else { continue };
let script = format!(
- "globalThis.__obscura_deliverMessage({escaped_data}, {escaped_origin}, {});",
+ "globalThis.__obscura_deliverMessage({escaped_data}, {escaped_origin}, {}, {escaped_target_origin});",
message.source_frame_id,
);
if let Err(error) = js.execute_script("<frame-message>", &script) {
@@ -1111,6 +1113,7 @@ impl Page {
&message.data_json,
&message.origin,
message.source_frame_id,
+ &message.target_origin,
) {
tracing::debug!("message to frame {} failed: {error}", message.target_frame_id);
}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index d7e69040..db0c010e 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -11904,7 +11904,23 @@ function _realmOrigin() {
try { return new URL(_domParse('document_url')).origin; } catch (_) { return 'null'; }
}
-function _sendRealmMessage(targetFrameId, data) {
+// Whether a postMessage restricted to `targetOrigin` may be delivered to a
+// realm whose current origin is `receiverOrigin`, given the sender's origin.
+// Mirrors the browser check done at delivery time: '*' (or an unspecified '')
+// allows any origin; '/' requires the receiver to be same-origin as the sender;
+// anything else must equal the receiver's own origin.
+function _targetOriginAllows(targetOrigin, receiverOrigin, senderOrigin) {
+ if (!targetOrigin || targetOrigin === '*') return true;
+ let expected;
+ if (targetOrigin === '/') {
+ expected = senderOrigin;
+ } else {
+ try { expected = new URL(targetOrigin).origin; } catch (_) { expected = targetOrigin; }
+ }
+ return receiverOrigin === expected;
+}
+
+function _sendRealmMessage(targetFrameId, data, targetOrigin) {
let json;
// Structured clone cannot cross realms here. JSON carries what postMessage is
// actually used for; anything else throws the same DataCloneError a browser
@@ -11915,8 +11931,11 @@ function _sendRealmMessage(targetFrameId, data) {
throw new DOMException('The object could not be cloned.', 'DataCloneError');
}
if (json === undefined) json = '{"v":null}';
+ // An unspecified targetOrigin stays permissive (empty string); the receiver
+ // enforces a specified one against its own origin in __obscura_deliverMessage.
+ const to = (targetOrigin === undefined || targetOrigin === null) ? '' : String(targetOrigin);
Deno.core.ops.op_post_frame_message(
- targetFrameId >>> 0, globalThis.__obscura_frameId >>> 0, _realmOrigin(), json);
+ targetFrameId >>> 0, globalThis.__obscura_frameId >>> 0, _realmOrigin(), to, json);
}
// The frame's own window and document, when this page is allowed to touch
@@ -11948,8 +11967,8 @@ function _frameWindowFor(frameId) {
if (!real) return existing || null;
if (existing && existing.__obscura_wrapsRealm) return existing;
- const post = _markNative(function (data, _targetOrigin, _transfer) {
- _sendRealmMessage(frameId, data);
+ const post = _markNative(function (data, targetOrigin, _transfer) {
+ _sendRealmMessage(frameId, data, targetOrigin);
});
const win = new Proxy(real, {
get(target, prop) {
@@ -11968,7 +11987,11 @@ function _frameWindowFor(frameId) {
}
// The host calls this inside the target realm.
-globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId) {
+globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId, targetOrigin) {
+ // Enforce postMessage's targetOrigin against THIS (the receiving) realm's
+ // origin, the same check a real browser does at delivery time. A mismatch
+ // drops the message silently.
+ if (!_targetOriginAllows(targetOrigin, _realmOrigin(), origin)) return;
let data = null;
try { data = JSON.parse(dataJson).v; } catch (_) {}
// Who to reply to: the frame above, or one of the frames below.
@@ -11998,7 +12021,7 @@ class _RemoteWindow {
constructor(frameId) {
Object.defineProperty(this, '_frameId', { value: frameId, enumerable: false });
}
- postMessage(data, _targetOrigin, _transfer) { _sendRealmMessage(this._frameId, data); }
+ postMessage(data, targetOrigin, _transfer) { _sendRealmMessage(this._frameId, data, targetOrigin); }
get self() { return this; }
get window() { return this; }
get frames() { return this; }
@@ -12087,13 +12110,13 @@ class _IframeWindow {
return proxy;
}
- postMessage(data, _targetOrigin, _transfer) {
+ postMessage(data, targetOrigin, _transfer) {
// Into the frame's own realm, through the host. This used to dispatch the
// event on the *parent's* window, so a page could never actually talk to
// the document inside its iframe. A frame that has not loaded yet has no
// browsing context to receive anything.
if (!this._frameId) return;
- _sendRealmMessage(this._frameId, data);
+ _sendRealmMessage(this._frameId, data, targetOrigin);
}
setTimeout(fn, ms) { return globalThis.setTimeout(fn, ms); }
@@ -13091,7 +13114,7 @@ globalThis.stop = function() {}; _markNative(globalThis.stop);
// that posted to itself and waited for the `message` event waited forever.
// Same realm, so this needs no host round trip; it is queued as a task because
// postMessage never delivers synchronously.
-globalThis.postMessage = function(data, _targetOrigin, _transfer) {
+globalThis.postMessage = function(data, targetOrigin, _transfer) {
let clone = data;
// Match the cross-realm path: a value postMessage cannot carry is rejected
// at the call, not delivered as something else.
@@ -13101,6 +13124,9 @@ globalThis.postMessage = function(data, _targetOrigin, _transfer) {
throw new DOMException('The object could not be cloned.', 'DataCloneError');
}
const origin = _realmOrigin();
+ // A self-post honours targetOrigin too: sender and receiver are this realm,
+ // so a targetOrigin naming a different origin drops the message.
+ if (!_targetOriginAllows(targetOrigin, origin, origin)) return;
setTimeout(() => {
try {
globalThis.dispatchEvent(globalThis.__obscura_markTrusted(
diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rs
index a5ef00f3..3f62d638 100644
--- a/crates/obscura-js/src/frame.rs
+++ b/crates/obscura-js/src/frame.rs
@@ -148,13 +148,15 @@ impl FrameRealm {
data_json: &str,
origin: &str,
source_frame_id: u32,
+ target_origin: &str,
) -> Result<(), String> {
self.execute_script(
parent,
&format!(
- "globalThis.__obscura_deliverMessage({}, {}, {source_frame_id});",
+ "globalThis.__obscura_deliverMessage({}, {}, {source_frame_id}, {});",
encode_json_argument(data_json),
encode_json_argument(origin),
+ encode_json_argument(target_origin),
),
)
}
@@ -802,6 +804,74 @@ mod tests {
);
}
+ /// SEC-001 / #704 — postMessage must honour `targetOrigin`. A message
+ /// restricted to a specific origin must be dropped when the receiving realm
+ /// has a different origin, and delivered when the origins match. Before the
+ /// fix the argument was discarded end-to-end, so the first message leaked.
+ #[test]
+ fn post_message_honours_target_origin() {
+ let mut parent = page("https://parent.example/", "<html><body></body></html>");
+ parent
+ .execute_script(
+ "p",
+ "globalThis.got = [];\
+ addEventListener('message', (e) => globalThis.got.push([e.data, e.origin]));",
+ )
+ .unwrap();
+ let frame = FrameRealm::new(
+ &mut parent,
+ 1,
+ 0,
+ "https://child.example/f",
+ "<html><body></body></html>",
+ )
+ .expect("frame realm");
+
+ // Deliver the way `Page` does, now carrying the queued targetOrigin.
+ let deliver = |parent: &mut ObscuraJsRuntime, m: &crate::ops::PendingFrameMessage| {
+ let script = format!(
+ "globalThis.__obscura_deliverMessage({}, {}, {}, {});",
+ serde_json::to_string(&m.data_json).unwrap(),
+ serde_json::to_string(&m.origin).unwrap(),
+ m.source_frame_id,
+ serde_json::to_string(&m.target_origin).unwrap(),
+ );
+ parent.execute_script("<frame-message>", &script).unwrap();
+ };
+
+ // Restricted to an origin the parent does NOT have -> must be dropped.
+ frame
+ .execute_script(
+ &mut parent,
+ "parent.postMessage({token: 'secret'}, 'https://attacker.example');",
+ )
+ .unwrap();
+ let queued = parent.take_pending_frame_messages();
+ assert_eq!(queued.len(), 1);
+ assert_eq!(queued[0].target_origin, "https://attacker.example");
+ deliver(&mut parent, &queued[0]);
+ assert_eq!(
+ parent.evaluate("globalThis.got").unwrap(),
+ serde_json::json!([]),
+ "a message whose targetOrigin does not match the receiver must be dropped",
+ );
+
+ // Restricted to the parent's real origin -> must be delivered.
+ frame
+ .execute_script(
+ &mut parent,
+ "parent.postMessage({token: 'ok'}, 'https://parent.example');",
+ )
+ .unwrap();
+ let queued = parent.take_pending_frame_messages();
+ deliver(&mut parent, &queued[0]);
+ assert_eq!(
+ parent.evaluate("globalThis.got").unwrap(),
+ serde_json::json!([[{"token": "ok"}, "https://child.example"]]),
+ "a message whose targetOrigin matches the receiver must be delivered",
+ );
+ }
+
/// `parent === window` is how a document decides it is top-level, so a
/// framed realm must not see itself as the top.
#[test]
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 7597a997..7115acc1 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -271,6 +271,12 @@ pub struct PendingFrameMessage {
pub source_frame_id: u32,
/// The sender's origin, for `event.origin`.
pub origin: String,
+ /// The origin the sender restricted delivery to (postMessage's
+ /// `targetOrigin`). `"*"` means any origin; `"/"` means the receiver must be
+ /// same-origin as the sender; anything else is matched against the
+ /// receiver's own origin, and a mismatch drops the message. An empty string
+ /// means the sender did not specify one and delivery stays permissive.
+ pub target_origin: String,
/// The payload, JSON encoded. Structured clone is not available across
/// realms here, and JSON covers what postMessage is used for in practice:
/// a widget reporting a result. Anything it cannot encode is rejected by
@@ -3546,6 +3552,7 @@ fn op_post_frame_message(
target_frame_id: u32,
source_frame_id: u32,
#[string] origin: &str,
+ #[string] target_origin: &str,
#[string] data_json: &str,
) {
let gs = state.borrow::<SharedState>().clone();
@@ -3569,6 +3576,7 @@ fn op_post_frame_message(
target_frame_id,
source_frame_id,
origin: origin.to_string(),
+ target_origin: target_origin.to_string(),
data_json: data_json.to_string(),
});
}
diff --git a/crates/obscura/tests/child_frame_scripts.rs b/crates/obscura/tests/child_frame_scripts.rs
index e850b202..a2922b33 100644
--- a/crates/obscura/tests/child_frame_scripts.rs
+++ b/crates/obscura/tests/child_frame_scripts.rs
@@ -267,6 +267,34 @@ async fn window_post_message_delivers_to_the_same_window() {
assert_eq!(page.evaluate("window.__syncGot").as_f64(), Some(0.0));
}
+/// SEC-001 / #704 — a self-post must honour targetOrigin: a message restricted
+/// to a different origin is dropped, while the page's own origin and "/" are
+/// delivered.
+#[tokio::test]
+async fn window_post_message_honours_target_origin() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let base = spawn_server(
+ r#"<!doctype html><html><body><script>
+ window.__got = [];
+ window.addEventListener('message', (e) => window.__got.push(String(e.data)));
+ window.postMessage('LEAK', 'https://other.example'); // mismatched -> dropped
+ window.postMessage('OK', window.location.origin); // exact origin -> delivered
+ window.postMessage('SLASH', '/'); // same-origin as sender -> delivered
+</script></body></html>"#,
+ );
+
+ let browser = Browser::new().unwrap();
+ let mut page = browser.new_page().await.unwrap();
+ page.goto(&base).await.unwrap();
+ page.settle(1000).await;
+
+ assert_eq!(
+ page.evaluate("window.__got"),
+ serde_json::json!(["OK", "SLASH"]),
+ "a self-post with a non-matching targetOrigin must be dropped; matching ones delivered",
+ );
+}
+
/// A parser-created `<iframe src>` never goes through the `src` setter, so
/// nothing used to start its load at all.
#[tokio::test]