The headless browser for AI agents and web scraping
//! Child frame realms.
//!
//! An iframe is a separate browsing context: its own JavaScript realm, its own
//! DOM tree, and its own origin. Without this, a frame's HTML is fetched and its
//! body dropped into a detached document in the *parent's* realm, so no script
//! inside a frame ever runs (issue #600).
//!
//! A frame realm is a second `v8::Context` in the page's isolate. Three things
//! make that practical:
//!
//! - The startup snapshot already contains the whole bootstrap, so a restored
//! context arrives with every DOM class installed. A realm costs a context
//! restore, not a re-parse.
//! - The realm's op table is filled from the page realm's, so every shim in the
//! frame can call ops.
//! - Each realm registers its document in `RealmStates`, and an op looks up the
//! realm that called it. Making a realm current around the host's calls into
//! it is not enough, because a frame's timers and settled promises re-enter
//! JavaScript straight from the event loop.
//!
//! Staying in one isolate is what lets same-origin frames share objects with
//! their parent, the way `iframe.contentWindow.document` does in a browser. A
//! second isolate could never do that.
use std::rc::Rc;
use obscura_dom::parse_html;
use crate::ops::{ObscuraState, RealmStates};
use crate::runtime::ObscuraJsRuntime;
/// One child browsing context: its own realm, document and origin, living in
/// the page's isolate.
pub struct FrameRealm {
context: deno_core::v8::Global<deno_core::v8::Context>,
/// Held so the frame's entry can be taken out again when the frame dies.
realms: Rc<std::cell::RefCell<RealmStates>>,
frame_id: u32,
parent_frame_id: u32,
url: String,
origin: String,
}
impl Drop for FrameRealm {
fn drop(&mut self) {
self.realms.borrow_mut().forget(&self.context);
}
}
impl FrameRealm {
/// Builds a frame realm around an already-fetched document.
///
/// The frame inherits the page's browser identity and its shared resources,
/// by copying them from the parent rather than by being told them, so the
/// two cannot drift apart.
pub fn new(
parent: &mut ObscuraJsRuntime,
frame_id: u32,
parent_frame_id: u32,
url: &str,
html: &str,
) -> Option<Self> {
let realms = parent.realm_states();
let existing = realms.borrow().context(frame_id);
if let Some(context) = existing {
let state = realms.borrow().by_frame_id(frame_id)?;
let origin = state.borrow().inherited_origin.clone().unwrap_or_else(|| origin_of(url));
return Some(Self {
context,
realms,
frame_id,
parent_frame_id,
url: url.to_string(),
origin,
});
}
if realms.borrow().live_count() >= crate::ops::max_live_frames() {
return None;
}
let context = parent.create_realm_context()?;
if !parent.share_ops_with_realm(&context) {
return None;
}
parent.copy_identity_to_realm(&context);
// A snapshot-created realm has null deno_core per-context state slots, so
// a promise rejection or dynamic import() in the frame would segfault in
// deno_core's global callbacks (#850, #841). Alias the main realm's state.
parent.share_deno_context_state_with_realm(&context);
// Only a same-origin frame is reachable from the page. Cross-origin
// keeps its own security token, so V8 answers `undefined` for any
// property the page tries to read out of it, and nothing about it is
// published below.
let (scripting_enabled, sandbox_opaque_origin) = realms.borrow().by_frame_id(parent_frame_id)
.map(|creator| {
let creator = creator.borrow();
(creator.scripting_enabled, creator.sandbox_opaque_origin)
}).unwrap_or((true, false));
let origin = if sandbox_opaque_origin { "null".to_string() } else { origin_of(url) };
let same_origin = origin != "null" && origin == parent.page_origin();
if same_origin {
parent.share_security_token_with_realm(&context);
}
let mut state = ObscuraState::new();
state.navigation_timing.record("domLoading");
state.dom = Some(parse_html(html));
state.url = url.to_string();
state.frame_id = frame_id;
state.parent_frame_id = parent_frame_id;
state.scripting_enabled = scripting_enabled;
state.sandbox_opaque_origin = sandbox_opaque_origin;
if sandbox_opaque_origin { state.inherited_origin = Some("null".to_string()); }
parent.share_resources_with(&mut state);
let realms = parent.realm_states();
realms.borrow_mut().register(
context.clone(),
frame_id,
Rc::new(std::cell::RefCell::new(state)),
);
let realm = FrameRealm {
context,
realms,
frame_id,
parent_frame_id,
url: url.to_string(),
origin,
};
// Both ids before init, not after: init is what installs `parent` and
// `top`, and a document that runs even one script believing it is
// top-level has already taken the wrong branch.
let watchdog = parent.arm_watchdog(std::time::Duration::from_secs(5));
let initialized = realm.run(parent, &format!(
"globalThis.__obscura_frameId = {frame_id};\
globalThis.__obscura_parentFrameId = {parent_frame_id};\
globalThis.__obscura_init();"
));
parent.disarm_watchdog(watchdog);
initialized.ok()?;
// Only after init, so the document the page reaches through
// `contentDocument` is the initialized one.
if same_origin {
parent.publish_realm_objects(&realm.context, frame_id);
}
Some(realm)
}
/// Fires the frame document's lifecycle events, in spec order.
///
/// The page's own document gets these; a frame's did not, and a document
/// that is never told it finished loading will not run any of the work
/// scripts defer until then. That is most of what a widget does: a frame
/// can talk to its parent perfectly and still never build its interface,
/// which looks like a rendering problem and is a lifecycle one.
pub fn dispatch_load_events(&self, parent: &mut ObscuraJsRuntime) -> Result<(), String> {
let state = self.realms.borrow().by_frame_id(self.frame_id)
.ok_or_else(|| "Frame no longer exists".to_string())?;
{
let mut state = state.borrow_mut();
state.navigation_timing.record("domInteractive");
state.navigation_timing.record("domContentLoadedEventStart");
}
self.execute_script(
parent,
"globalThis.__documentReadyState__ = 'interactive';\
try { document.dispatchEvent(new Event('DOMContentLoaded', \
{ bubbles: false, cancelable: false })); } catch (_) {}\
try { window.dispatchEvent(new Event('DOMContentLoaded', \
{ bubbles: false, cancelable: false })); } catch (_) {}",
)?;
{
let mut state = state.borrow_mut();
state.navigation_timing.record("domContentLoadedEventEnd");
state.navigation_timing.record("domComplete");
state.navigation_timing.record("loadEventStart");
}
let result = self.execute_script(
parent,
"globalThis.__documentReadyState__ = 'complete';\
try { document.dispatchEvent(new Event('readystatechange')); } catch (_) {}\
try { const loadEvent = new Event('load', \
{ bubbles: false, cancelable: false }); \
if (typeof window.onload === 'function') { try { window.onload.call(window, loadEvent); } catch (_) {} } \
try { window.dispatchEvent(loadEvent); } catch (_) {} } catch (_) {}",
);
if result.is_ok() {
state.borrow_mut().navigation_timing.record("loadEventEnd");
}
result
}
/// Delivers a `postMessage` that another realm sent to this one.
pub fn deliver_message(
&self,
parent: &mut ObscuraJsRuntime,
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}, {});",
encode_json_argument(data_json),
encode_json_argument(origin),
encode_json_argument(target_origin),
),
)
}
/// Delivers a queued message without losing a retired sender's Window identity.
pub fn deliver_queued_message(
&self,
parent: &mut ObscuraJsRuntime,
message: &crate::ops::PendingFrameMessage,
) -> Result<(), String> {
self.execute_script(parent, &format!(
"globalThis.__obscura_deliverMessage({}, {}, {}, {}, {});",
encode_json_argument(&message.data_json),
encode_json_argument(&message.origin),
message.source_frame_id,
encode_json_argument(&message.target_origin),
message.source_context_id.map_or(-1i64, i64::from),
))
}
pub fn frame_id(&self) -> u32 {
self.frame_id
}
/// Sets the frame document's viewport before any of its scripts run.
pub fn set_viewport(
&self,
parent: &mut ObscuraJsRuntime,
width: f64,
height: f64,
) -> Result<(), String> {
let width = if width.is_finite() && width > 0.0 {
width
} else {
300.0
};
let height = if height.is_finite() && height > 0.0 {
height
} else {
150.0
};
#[cfg(feature = "render")]
{
let state = self.realms.borrow().by_frame_id(self.frame_id)
.ok_or_else(|| "could not resize frame: missing realm".to_string())?;
state.borrow_mut().set_viewport(width, height);
}
self.execute_script(
parent,
&format!(
"globalThis.innerWidth={width};globalThis.innerHeight={height};\
if(globalThis.visualViewport){{\
globalThis.visualViewport.width={width};\
globalThis.visualViewport.height={height};\
}}"
),
)
}
pub fn parent_frame_id(&self) -> u32 {
self.parent_frame_id
}
pub fn url(&self) -> &str {
&self.url
}
/// The frame's origin, or `"null"` for a document with an opaque origin.
pub fn origin(&self) -> &str {
&self.origin
}
/// Whether script from `other_origin` may reach into this frame's DOM. Two
/// opaque origins are never same-origin, which is why `"null"` never
/// matches.
pub fn is_same_origin_as(&self, other_origin: &str) -> bool {
self.origin != "null" && self.origin == other_origin
}
/// Runs `source` in the frame's realm. Ops called from it find the frame's
/// document by looking up the realm they were called from.
fn run(&self, parent: &mut ObscuraJsRuntime, source: &str) -> Result<String, String> {
parent.eval_in_realm(&self.context, source)
}
/// Runs a script inside the frame, reporting a script error as `Err`.
pub fn execute_script(
&self,
parent: &mut ObscuraJsRuntime,
source: &str,
) -> Result<(), String> {
self.run(parent, source).map(|_| ())
}
/// Evaluates an expression inside the frame and decodes it as JSON.
pub fn evaluate(
&self,
parent: &mut ObscuraJsRuntime,
expression: &str,
) -> Result<serde_json::Value, String> {
let json = self.run(parent, &format!("JSON.stringify({expression})"))?;
serde_json::from_str(&json).map_err(|error| error.to_string())
}
/// Runs the frame document's classic scripts, in document order.
///
/// `load_external` resolves a `src=` script to its source text; returning
/// `None` skips it, which is what a failed subresource fetch looks like to
/// the page. One script throwing does not stop the ones after it, matching
/// how a browser treats separate classic scripts.
///
/// Module scripts are skipped and reported: they need the frame's own module
/// loader, which is not wired up yet.
///
/// Returns one message per script that failed or was skipped.
pub fn run_document_scripts(
&self,
parent: &mut ObscuraJsRuntime,
load_external: impl Fn(&str) -> Option<String>,
) -> Vec<String> {
let scripts = match self.list_scripts() {
Ok(scripts) => scripts,
Err(error) => return vec![error],
};
let mut problems = Vec::new();
for (index, script) in scripts.iter().enumerate() {
if !script.is_classic() {
if script.type_attribute == "module" {
problems.push(format!("frame module script {index} skipped: not supported"));
}
continue;
}
let (name, source) = if script.src.is_empty() {
(format!("inline {index}"), script.text.clone())
} else {
let resolved = self.resolve(&script.src);
match load_external(&resolved) {
Some(source) => (resolved, source),
None => {
problems.push(format!("frame script {resolved} could not be loaded"));
continue;
}
}
};
if source.trim().is_empty() {
continue;
}
if let Err(error) = self.execute_script(parent, &source) {
problems.push(format!("frame script {name} failed: {error}"));
}
}
problems
}
/// Absolute URLs of the frame's `src=` classic scripts, in document order.
///
/// A caller that fetches over the network needs the list before running
/// anything, because `run_document_scripts` resolves sources synchronously.
pub fn external_script_urls(&self, _parent: &mut ObscuraJsRuntime) -> Vec<String> {
self.list_scripts()
.unwrap_or_default()
.iter()
.filter(|script| script.is_classic() && !script.src.is_empty())
.map(|script| self.resolve(&script.src))
.collect()
}
/// Resolves a subresource URL against the frame's own document URL, not the
/// parent's. A relative `src` in a frame is relative to the frame.
fn resolve(&self, src: &str) -> String {
if self.url == "about:srcdoc" {
if let Some(base) = self.realms.borrow().by_frame_id(self.frame_id)
.and_then(|state| crate::ops::document_base_url(&state.borrow()))
{
return url::Url::parse(&base).and_then(|base| base.join(src))
.map(|url| url.to_string()).unwrap_or_else(|_| src.to_string());
}
}
url::Url::parse(&self.url)
.and_then(|base| base.join(src))
.map(|url| url.to_string())
.unwrap_or_else(|_| src.to_string())
}
fn list_scripts(&self) -> Result<Vec<DocumentScript>, String> {
// Browser-owned discovery must not execute script-overridden DOM APIs.
let state = self.realms.borrow().by_frame_id(self.frame_id)
.ok_or_else(|| "could not list frame scripts: missing realm".to_string())?;
let state = state.borrow();
if !state.scripting_enabled { return Ok(Vec::new()); }
let dom = state.dom.as_ref()
.ok_or_else(|| "could not list frame scripts: missing document".to_string())?;
let nodes = dom.query_selector_all("script")?;
Ok(nodes.into_iter().filter_map(|id| {
let text = dom.text_content(id);
dom.with_node(id, |node| DocumentScript {
src: node.get_attribute("src").unwrap_or("").to_string(),
type_attribute: node.get_attribute("type").unwrap_or("").to_lowercase(),
text,
})
}).collect())
}
}
struct DocumentScript {
src: String,
type_attribute: String,
text: String,
}
impl DocumentScript {
/// An empty type, or a JavaScript MIME type, is a classic script. Anything
/// else is data or a module.
fn is_classic(&self) -> bool {
self.type_attribute.is_empty()
|| matches!(
self.type_attribute.as_str(),
"text/javascript" | "application/javascript" | "text/ecmascript"
)
}
}
/// Embeds a string in JavaScript source as a literal, so a payload holding
/// quotes or newlines cannot end the literal and be read as code.
fn encode_json_argument(value: &str) -> String {
serde_json::to_string(value).unwrap_or_else(|_| "\"\"".to_string())
}
/// Serializes an origin the way `location.origin` does, using `"null"` for
/// schemes that have no tuple origin.
fn origin_of(url: &str) -> String {
match url::Url::parse(url) {
Ok(parsed) => {
let origin = parsed.origin();
if origin.is_tuple() {
origin.ascii_serialization()
} else {
"null".to_string()
}
}
Err(_) => "null".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
fn page(url: &str, html: &str) -> ObscuraJsRuntime {
let mut runtime = ObscuraJsRuntime::new();
runtime.set_dom(parse_html(html));
runtime.set_url(url);
runtime.run_page_init();
runtime
}
#[test]
fn frame_shadow_root_append_uses_its_own_document() {
let mut parent = page("https://parent.example/",
"<html><body><div id='host'>Parent</div></body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://child.example/",
"<html><body><div id='host'>Child</div></body></html>").unwrap();
let result = frame.evaluate(&mut parent, r#"(() => {
const host = document.getElementById('host');
const root = host.attachShadow({ mode: 'open' });
const child = document.createElement('span');
child.textContent = 'shadow child';
root.appendChild(child);
return [
host.shadowRoot === root,
root.host === host,
root.ownerDocument === document,
child.parentNode === root,
root.textContent
];
})()"#).unwrap();
assert_eq!(result, serde_json::json!([true, true, true, true, "shadow child"]));
assert_eq!(parent.evaluate(
"document.getElementById('host').shadowRoot === null").unwrap(),
serde_json::json!(true));
}
#[test]
fn frame_shadow_root_lookup_does_not_read_parent() {
let mut parent = page("https://parent.example/",
"<html><body><div id='host'>Parent</div></body></html>");
parent.execute_script("parent-shadow", r#"
document.getElementById('host').attachShadow({ mode: 'open' })
.innerHTML = '<span>parent shadow</span>';
"#).unwrap();
let frame = FrameRealm::new(&mut parent, 1, 0, "https://child.example/",
"<html><body><div id='host'>Child</div></body></html>").unwrap();
let result = frame.evaluate(&mut parent,
"document.getElementById('host').shadowRoot === null").unwrap();
assert_eq!(result, serde_json::json!(true));
assert_eq!(parent.evaluate(
"document.getElementById('host').shadowRoot.textContent").unwrap(),
serde_json::json!("parent shadow"));
}
#[test]
fn initial_frame_shadow_root_uses_its_own_document() {
let mut parent = page("https://parent.example/",
"<html><body><div id='host'>Parent</div></body></html>");
let result = parent.evaluate(r#"(() => {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const childDocument = frame.contentDocument;
const host = childDocument.createElement('div');
childDocument.body.appendChild(host);
const root = host.attachShadow({ mode: 'open' });
const child = childDocument.createElement('span');
child.textContent = 'initial frame shadow';
root.appendChild(child);
return [
host.shadowRoot === root,
root.ownerDocument === childDocument,
child.parentNode === root,
root.textContent,
document.getElementById('host').shadowRoot === null
];
})()"#).unwrap();
assert_eq!(result,
serde_json::json!([true, true, true, "initial frame shadow", true]));
}
#[test]
fn frame_closed_shadow_root_stays_private_and_rejects_duplicate_attach() {
let mut parent = page("https://parent.example/",
"<html><body><div id='host'>Parent</div></body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://child.example/",
"<html><body><div id='host'>Child</div></body></html>").unwrap();
let result = frame.evaluate(&mut parent, r#"(() => {
const host = document.getElementById('host');
const root = host.attachShadow({ mode: 'closed' });
const child = document.createElement('span');
child.textContent = 'closed frame shadow';
root.appendChild(child);
return [host.shadowRoot === null, root.mode, root.textContent];
})()"#).unwrap();
let error = frame.evaluate(&mut parent,
"document.getElementById('host').attachShadow({ mode: 'open' })").unwrap_err();
assert_eq!(result, serde_json::json!([true, "closed", "closed frame shadow"]));
assert!(error.contains("NotSupportedError"), "{error}");
assert_eq!(parent.evaluate(
"document.getElementById('host').shadowRoot === null").unwrap(),
serde_json::json!(true));
}
#[test]
fn borrowed_form_getters_keep_the_owning_document() {
let mut parent = page("https://parent.example/",
"<html><body><form id='same'><input id='parent'></form></body></html>");
let _frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",
"<html><body><form id='same'><input id='inside'></form><input id='outside' form='same'></body></html>").unwrap();
assert_eq!(parent.evaluate(r#"(() => {
const doc = globalThis.__obscura_frameObjects[1].document;
const form = doc.querySelector('form'), outside = doc.getElementById('outside');
const elements = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'elements').get;
const owner = Object.getOwnPropertyDescriptor(Element.prototype, 'form').get;
return [owner.call(outside) === form, elements.call(form)[1] === outside,
Array.from(elements.call(form), n => n.id).join(','),
document.querySelector('form').elements[0].id];
})()"#).unwrap(), serde_json::json!([true,true,"inside,outside","parent"]));
}
#[test]
fn html_interface_brands_stay_in_the_creation_realm() {
let mut parent = page("https://parent.example/",
"<html><body><div id='parent'>Parent</div></body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",
"<html><body><div id='child'>Child</div><span></span></body></html>").unwrap();
assert_eq!(frame.evaluate(&mut parent, r#"(() => {
HTMLDivElement.prototype.__brandProbe = 'child';
const node = document.getElementById('child');
return [node.constructor === HTMLDivElement, node instanceof HTMLDivElement,
!(node instanceof HTMLSpanElement), document.createElement('div').__brandProbe,
document.querySelector('span').__brandProbe === undefined];
})()"#).unwrap(), serde_json::json!([true,true,true,"child",true]));
assert_eq!(parent.evaluate(r#"(() => {
const child = globalThis.__obscura_frameObjects[1].document.getElementById('child');
const node = document.getElementById('parent');
return [child.constructor.name, child.__brandProbe, child instanceof HTMLDivElement,
node.constructor === HTMLDivElement, node.__brandProbe === undefined,
document.createElement('div').__brandProbe === undefined];
})()"#).unwrap(), serde_json::json!(["HTMLDivElement","child",false,true,true,true]));
}
#[test]
fn borrowed_select_and_option_methods_keep_the_owning_dom() {
let mut parent = page("https://parent.example/",
"<html><body><select id='parent'><option>Parent</option></select></body></html>");
let _frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",
"<html><body><select><option id='a'>A</option><optgroup><option id='b'>B</option></optgroup></select></body></html>").unwrap();
assert_eq!(parent.evaluate(r#"(() => {
const select = globalThis.__obscura_frameObjects[1].document.querySelector('select');
const length = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'length');
const index = Object.getOwnPropertyDescriptor(HTMLOptionElement.prototype, 'index').get;
const item = HTMLSelectElement.prototype.item.call(select, 1);
const named = HTMLSelectElement.prototype.namedItem.call(select, 'b');
const initial = [length.get.call(select), item.id, named === item, index.call(item)];
length.set.call(select, 3);
HTMLSelectElement.prototype.remove.call(select, 0);
const changed = [select.length, select.item(0).id, index.call(item)];
const div = select.ownerDocument.createElement('div');
const rejected = [() => length.get.call(div), () => length.set.call(div, 1),
() => HTMLSelectElement.prototype.item.call(div, 0),
() => HTMLSelectElement.prototype.namedItem.call(div, ''),
() => HTMLSelectElement.prototype.remove.call(div), () => index.call(div)].map(call => {
try { call(); return false; } catch (error) { return error instanceof TypeError; }
});
HTMLSelectElement.prototype.remove.call(select);
return {initial, changed, rejected, childConnected:select.isConnected,
parent:[document.getElementById('parent').length, document.querySelector('option').textContent]};
})()"#).unwrap(), serde_json::json!({
"initial":[2,"b",true,1], "changed":[2,"b",0], "rejected":[true,true,true,true,true,true],
"childConnected":false,
"parent":[1,"Parent"],
}));
}
#[test]
fn borrowed_style_getter_keeps_the_elements_declaration() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let _frame = FrameRealm::new(&mut parent, 1, 0,
"https://parent.example/frame", "<html><body style='color: red'>Child</body></html>")
.expect("frame realm");
assert_eq!(parent.evaluate(r#"(() => {
const element = globalThis.__obscura_frameObjects[1].document.body;
const getter = Object.getOwnPropertyDescriptor(Element.prototype, 'style').get;
const borrowed = getter.call(element);
const same = borrowed === element.style;
element.setAttribute('style', 'color: blue');
return [same, borrowed.color, element.style.color];
})()"#).unwrap(), serde_json::json!([true, "blue", "blue"]));
}
#[test]
fn borrowed_content_type_getter_reads_the_frame_document() {
let mut parent = ObscuraJsRuntime::new();
parent.set_dom(parse_html("<html><body></body></html>"));
parent.set_url("https://parent.example/page");
parent.set_content_type("text/plain");
parent.run_page_init();
let _frame = FrameRealm::new(&mut parent, 1, 0,
"https://parent.example/frame", "<html><body>Child</body></html>")
.expect("frame realm");
assert_eq!(parent.evaluate(r#"(function(){
const child = globalThis.__obscura_frameObjects[1].document;
const get = Object.getOwnPropertyDescriptor(Document.prototype, 'contentType').get;
return [get.call(child), child.contentType, document.contentType];
})()"#).unwrap(), serde_json::json!(["text/html", "text/html", "text/plain"]));
}
#[test]
fn fetched_frame_contexts_survive_runtime_teardown_under_gc_stress() {
crate::set_v8_flags("--stress-compaction --stress-marking=1");
for _ in 0..10 {
let mut parent = page("https://parent.example/page", "<html><body>Parent</body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",
"<html><body>Child</body></html>").expect("frame realm");
assert_eq!(frame.evaluate(&mut parent, "document.body.textContent").unwrap(),
serde_json::json!("Child"));
drop(frame);
drop(parent);
}
}
#[test]
fn frame_has_its_own_realm_dom_and_origin() {
let mut parent = page(
"https://parent.example/page",
"<html><body><h1>Parent</h1></body></html>",
);
parent
.execute_script("p", "globalThis.marker = 'parent';")
.unwrap();
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/frame",
"<html><body><h1>Child</h1></body></html>",
)
.expect("frame realm");
frame
.execute_script(&mut parent, "globalThis.marker = 'child';")
.unwrap();
// Separate realm: own globals, own DOM, own URL.
assert_eq!(
frame
.evaluate(&mut parent, "document.querySelector('h1').textContent")
.unwrap(),
serde_json::json!("Child")
);
assert_eq!(
frame.evaluate(&mut parent, "globalThis.marker").unwrap(),
serde_json::json!("child")
);
assert_eq!(
frame.evaluate(&mut parent, "location.href").unwrap(),
serde_json::json!("https://child.example/frame")
);
// The parent keeps its own document and globals throughout.
assert_eq!(
parent
.evaluate("document.querySelector('h1').textContent")
.unwrap(),
serde_json::json!("Parent")
);
assert_eq!(
parent.evaluate("globalThis.marker").unwrap(),
serde_json::json!("parent")
);
assert_eq!(frame.origin(), "https://child.example");
assert_eq!(frame.frame_id(), 1);
assert!(!frame.is_same_origin_as("https://parent.example"));
assert!(frame.is_same_origin_as("https://child.example"));
}
#[test]
fn initial_frame_adoption_preserves_the_realm_and_inherited_base() {
let mut parent = page("https://parent.example/pages/index.html", "<html><body></body></html>");
parent.execute_script("initial-frame", r#"
globalThis.frameElementProbe = document.createElement('iframe');
document.body.appendChild(frameElementProbe);
globalThis.initialWindowProbe = frameElementProbe.contentWindow;
initialWindowProbe.eval('globalThis.marker = 42; document.body.textContent = "child"');
"#).unwrap();
let pending = parent.take_pending_frames().pop().expect("initial frame queued");
let frame = FrameRealm::new(&mut parent, pending.frame_id, pending.parent_frame_id,
&pending.url, &pending.html).expect("adopt initial realm");
assert_eq!(frame.origin(), "https://parent.example");
assert_eq!(frame.evaluate(&mut parent,
"[marker, document.body.textContent, document.URL, document.baseURI]").unwrap(),
serde_json::json!([42, "child", "about:blank", "https://parent.example/pages/index.html"]));
assert_eq!(parent.evaluate(
"[initialWindowProbe === frameElementProbe.contentWindow, initialWindowProbe.parent === window, typeof marker, document.body.textContent]").unwrap(),
serde_json::json!([true, true, "undefined", ""]));
}
#[tokio::test(flavor = "current_thread")]
async fn initial_frame_messages_keep_the_calling_realm_as_sender() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
parent.execute_script("initial-frame", r#"
globalThis.frameElementProbe = document.createElement('iframe');
document.body.appendChild(frameElementProbe);
globalThis.initialWindowProbe = frameElementProbe.contentWindow;
initialWindowProbe.postMessage('from-parent', '*');
"#).unwrap();
let pending = parent.take_pending_frames().pop().unwrap();
let frame = FrameRealm::new(&mut parent, pending.frame_id, 0,
&pending.url, &pending.html).unwrap();
frame.execute_script(&mut parent,
"parent.postMessage('from-child', '*'); postMessage('to-self', '*');").unwrap();
let messages = parent.take_pending_frame_messages();
assert_eq!(messages.iter().map(|message| (
message.target_frame_id, message.source_frame_id, message.origin.as_str()
)).collect::<Vec<_>>(), vec![
(frame.frame_id(), 0, "https://parent.example"),
(0, frame.frame_id(), "https://parent.example"),
(frame.frame_id(), frame.frame_id(), "https://parent.example"),
]);
}
#[test]
fn nested_message_source_parent_keeps_the_intermediate_frame() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let _child = FrameRealm::new(&mut parent, 1, 0,
"https://parent.example/child", "<html><body></body></html>").unwrap();
let _grandchild = FrameRealm::new(&mut parent, 2, 1,
"https://parent.example/grandchild", "<html><body></body></html>").unwrap();
parent.execute_script("nested-message-parent", r#"
globalThis.sources = [];
addEventListener('message', event => sources.push(event.source));
__obscura_deliverMessage('{"v":"child"}', 'https://parent.example', 1, '*');
__obscura_deliverMessage('{"v":"grandchild"}', 'https://parent.example', 2, '*');
sources[1].parent.postMessage('reply', '*');
"#).unwrap();
assert_eq!(parent.evaluate(
"[sources[1].parent === sources[0], sources[1].parent.parent === window, sources[1].top === window]"
).unwrap(), serde_json::json!([true, true, true]));
let messages = parent.take_pending_frame_messages();
assert_eq!(messages.iter().map(|message| (
message.target_frame_id, message.source_frame_id,
)).collect::<Vec<_>>(), vec![(1, 0)]);
}
#[test]
fn message_source_parent_stays_opaque_across_origins() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let _child = FrameRealm::new(&mut parent, 1, 0,
"https://other.example/child", "<html><body></body></html>").unwrap();
let _grandchild = FrameRealm::new(&mut parent, 2, 1,
"https://parent.example/grandchild", "<html><body></body></html>").unwrap();
parent.execute_script("opaque-message-parent", r#"
addEventListener('message', event => { globalThis.sourceParent = event.source.parent; });
__obscura_deliverMessage('{"v":"grandchild"}', 'https://parent.example', 2, '*');
sourceParent.postMessage('reply', '*');
"#).unwrap();
assert_eq!(parent.evaluate("[sourceParent !== window, (() => { try { sourceParent.document; return false; } catch (e) { return e.name === 'SecurityError'; } })()]").unwrap(),
serde_json::json!([true, true]));
let messages = parent.take_pending_frame_messages();
assert_eq!(messages.iter().map(|message| (
message.target_frame_id, message.source_frame_id,
)).collect::<Vec<_>>(), vec![(1, 0)]);
}
#[test]
fn nested_initial_frame_uses_its_owner_document_not_the_entered_page() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
parent.execute_script("nested-initial-frame", r#"
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const child = iframe.contentWindow;
const nested = child.document.createElement('iframe');
child.document.body.appendChild(nested);
globalThis.nestedWindowProbe = nested.contentWindow;
"#).unwrap();
let pending = parent.take_pending_frames();
assert_eq!(pending.len(), 2);
assert_eq!(pending[0].parent_frame_id, 0);
assert_eq!(pending[1].parent_frame_id, pending[0].frame_id);
}
#[test]
fn initial_frame_script_discovery_does_not_read_the_parent_after_prototype_remap() {
let mut parent = page("https://parent.example/",
"<html><body><script src='/parent.js'></script></body></html>");
parent.execute_script("initial-frame", r#"
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const child = iframe.contentWindow;
Object.setPrototypeOf(child.document, Document.prototype);
"#).unwrap();
let pending = parent.take_pending_frames().pop().unwrap();
let frame = FrameRealm::new(&mut parent, pending.frame_id, 0,
&pending.url, &pending.html).unwrap();
assert!(frame.external_script_urls(&mut parent).is_empty(),
"initial frame must not replay its parent's author scripts");
}
#[test]
fn initial_frame_script_discovery_ignores_overridden_dom_methods() {
let mut parent = page("https://parent.example/",
"<html><body><script src='/parent.js'></script></body></html>");
parent.execute_script("initial-frame", r#"
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const child = iframe.contentWindow;
const parentScripts = document.querySelectorAll('script');
child.document.querySelectorAll = () => parentScripts;
"#).unwrap();
let pending = parent.take_pending_frames().pop().unwrap();
let frame = FrameRealm::new(&mut parent, pending.frame_id, 0,
&pending.url, &pending.html).unwrap();
assert!(frame.external_script_urls(&mut parent).is_empty(),
"author script discovery must use the actual frame DOM");
}
#[tokio::test(flavor = "current_thread")]
async fn frame_uses_its_embedding_viewport() {
let mut parent = page(
"https://parent.example/page",
"<html><body><iframe style='width:300px;height:65px'></iframe></body></html>",
);
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/frame",
"<html><body></body></html>",
)
.expect("frame realm");
frame.set_viewport(&mut parent, 300.0, 65.0).unwrap();
assert_eq!(
frame
.evaluate(
&mut parent,
"[innerWidth,innerHeight,visualViewport.width,visualViewport.height]",
)
.unwrap(),
serde_json::json!([300, 65, 300, 65]),
);
}
#[cfg(feature = "render")]
#[test]
fn frame_renderer_viewport_changes_do_not_resize_the_page() {
let mut parent = page("https://parent.example/",
"<html><head><style>body{margin:0}#page{width:100vw;height:100vh}</style></head><body><div id='page'></div></body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://child.example/",
"<html><head><style>body{margin:0}div{width:50vw;height:25vh}</style></head><body><div id='box'></div></body></html>").unwrap();
frame.set_viewport(&mut parent, 300.0, 80.0).unwrap();
assert_eq!(frame.evaluate(&mut parent, r#"(() => {
const r = document.getElementById('box').getBoundingClientRect();
globalThis.savedStyle = getComputedStyle(document.getElementById('box'));
return [r.width, r.height, savedStyle.width, savedStyle.height];
})()"#).unwrap(), serde_json::json!([150, 20, "150px", "20px"]));
frame.set_viewport(&mut parent, 200.0, 120.0).unwrap();
assert_eq!(frame.evaluate(&mut parent, r#"(() => {
const r = document.getElementById('box').getBoundingClientRect();
const fresh = getComputedStyle(document.getElementById('box'));
return [r.width, r.height, savedStyle.width, savedStyle.height,
fresh.width, fresh.height];
})()"#).unwrap(), serde_json::json!([100, 30, "100px", "30px", "100px", "30px"]));
assert_eq!(parent.evaluate(r#"(() => {
const r = document.getElementById('page').getBoundingClientRect();
return [r.width, r.height];
})()"#).unwrap(), serde_json::json!([1280, 720]));
}
/// A frame must not look like a different browser than its parent. Anti-bot
/// code fingerprints inside the frame and compares it with the top document.
#[tokio::test(flavor = "current_thread")]
async fn frame_inherits_the_parent_browser_identity() {
let user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) TestAgent/150.0.0.0";
let mut parent = ObscuraJsRuntime::new();
parent.set_user_agent(user_agent);
parent.set_platform("Win32", "Windows", "19.0.0");
parent.set_dom(parse_html("<html><body></body></html>"));
parent.set_url("https://parent.example/");
parent.run_page_init();
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
for surface in [
"navigator.userAgent",
"navigator.platform",
"navigator.userAgentData.platform",
] {
assert_eq!(
frame.evaluate(&mut parent, surface).unwrap(),
parent.evaluate(surface).unwrap(),
"frame and parent disagree on {surface}"
);
}
assert_eq!(
frame.evaluate(&mut parent, "navigator.userAgent").unwrap(),
serde_json::json!(user_agent)
);
}
/// The capability the frame realm exists for: scripts that arrived with the
/// frame's document run, in order, against the frame's own DOM.
#[test]
fn frame_runs_its_document_scripts_in_order() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/dir/page",
r#"<html><body><div id="out"></div>
<script>window.log = ['inline1'];</script>
<script src="first.js"></script>
<script src="/second.js"></script>
<script>window.log.push('inline2');
document.getElementById('out').textContent = window.log.join(',');</script>
</body></html>"#,
)
.expect("frame realm");
let requested = RefCell::new(Vec::new());
let problems = frame.run_document_scripts(&mut parent, |url| {
requested.borrow_mut().push(url.to_string());
match url {
"https://child.example/dir/first.js" => Some("window.log.push('ext1');".into()),
"https://child.example/second.js" => Some("window.log.push('ext2');".into()),
_ => None,
}
});
assert!(problems.is_empty(), "unexpected problems: {problems:?}");
// Relative and root-relative src resolve against the frame's URL, not
// the parent's.
assert_eq!(
requested.into_inner(),
vec![
"https://child.example/dir/first.js".to_string(),
"https://child.example/second.js".to_string(),
]
);
assert_eq!(
frame
.evaluate(&mut parent, "document.getElementById('out').textContent")
.unwrap(),
serde_json::json!("inline1,ext1,ext2,inline2")
);
// The frame's document writes never touch the parent's DOM.
assert_eq!(
parent.evaluate("document.body.innerHTML").unwrap(),
serde_json::json!("")
);
}
#[tokio::test(flavor = "current_thread")]
async fn frame_posted_task_runs_in_its_creation_realm() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
"<html><body><output id='result'>pending</output></body></html>",
)
.expect("frame realm");
frame
.execute_script(
&mut parent,
"globalThis.__obscura_frameId = 0;\
scheduler.postTask(() => {\
document.getElementById('result').textContent = location.origin;\
});",
)
.unwrap();
parent.run_event_loop_bounded(100).await.unwrap();
assert_eq!(
frame
.evaluate(
&mut parent,
"document.getElementById('result').textContent",
)
.unwrap(),
serde_json::json!("https://child.example"),
);
assert_eq!(
parent.evaluate("document.body.innerHTML").unwrap(),
serde_json::json!("")
);
}
#[tokio::test(flavor = "current_thread")]
async fn dropping_frame_cancels_its_queued_posted_task() {
let mut parent = page(
"https://parent.example/",
"<html><body data-owner='parent'></body></html>",
);
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://parent.example/child",
"<html><body data-owner='frame'></body></html>",
)
.expect("frame realm");
frame
.execute_script(
&mut parent,
"const staleController = new AbortController();\
globalThis.__staleController = staleController;\
staleController.signal.removeEventListener = () => {\
document.body.setAttribute('data-stale-cleanup', 'ran');\
parent.postMessage('stale-cleanup', '*');\
};\
scheduler.postTask(() => {\
document.body.setAttribute('data-stale-task', 'ran');\
parent.postMessage('stale-posted-task', '*');\
}, { signal: staleController.signal });\
setTimeout(() => scheduler.postTask(() => {\
document.body.setAttribute('data-delayed-stale-task', 'ran');\
parent.postMessage('delayed-stale-posted-task', '*');\
}), 1);",
)
.unwrap();
drop(frame);
parent.run_event_loop_bounded(100).await.unwrap();
assert!(
parent.take_pending_frame_messages().is_empty(),
"a posted task from the detached frame still executed",
);
assert_eq!(
parent.evaluate("document.body.getAttribute('data-owner')").unwrap(),
serde_json::json!("parent"),
);
assert_eq!(
parent
.evaluate("document.body.getAttribute('data-stale-task')")
.unwrap(),
serde_json::Value::Null,
);
assert_eq!(
parent
.evaluate("document.body.getAttribute('data-delayed-stale-task')")
.unwrap(),
serde_json::Value::Null,
);
assert_eq!(
parent
.evaluate("document.body.getAttribute('data-stale-cleanup')")
.unwrap(),
serde_json::Value::Null,
);
assert_eq!(
parent
.evaluate(
"(function(){\
const window = globalThis.__obscura_frameObjects[1]?.window;\
const controller = window?.__staleController;\
return [typeof window, typeof controller,\
controller?.signal?._listeners?.length];\
})()",
)
.unwrap(),
serde_json::json!(["object", "object", 0]),
"the retained frame realm did not discard its scheduler listener",
);
}
#[test]
fn frame_navigation_timing_records_its_own_event_boundaries() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",
"<html><body></body></html>").unwrap();
frame.execute_script(&mut parent, r#"
globalThis.samples = [];
function sample() {
samples.push([performance.timing.domContentLoadedEventStart,
performance.timing.domContentLoadedEventEnd,
performance.timing.loadEventStart, performance.timing.loadEventEnd]);
}
document.addEventListener('DOMContentLoaded', sample);
window.addEventListener('load', sample);
Date.now = () => 0;
"#).unwrap();
frame.dispatch_load_events(&mut parent).unwrap();
assert_eq!(frame.evaluate(&mut parent, r#"(() => {
const [dom, load] = samples;
return [dom[0] > 0 && dom[1] === 0, load[2] > 0 && load[3] === 0,
performance.timing.domContentLoadedEventEnd >= dom[0],
performance.timing.loadEventEnd >= load[2]];
})()"#).unwrap(), serde_json::json!([true, true, true, true]));
assert_eq!(parent.evaluate("performance.timing.loadEventEnd").unwrap().as_f64(), Some(0.0));
}
#[test]
fn frame_navigation_timing_terminated_load_does_not_record_completion() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://parent.example/frame",
"<html><body></body></html>").unwrap();
frame.execute_script(&mut parent,
"window.addEventListener('load',()=>{globalThis.entered=true;while(true){}});").unwrap();
let token = parent.arm_watchdog(std::time::Duration::from_millis(250));
let result = frame.dispatch_load_events(&mut parent);
let fired = parent.disarm_watchdog(token);
assert!(fired && result.is_err(), "the infinite load handler must be terminated");
assert_eq!(frame.evaluate(&mut parent, "globalThis.entered === true").unwrap(), serde_json::json!(true));
assert_eq!(frame.evaluate(&mut parent, "performance.timing.loadEventEnd").unwrap().as_f64(), Some(0.0));
}
#[test]
fn frame_body_onload_content_attribute_reflects_to_window() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
r#"<html><body onload="
globalThis.__frameBodyOnload = [this === window, event.type];
throw new Error('frame body onload failure');
"><script>
globalThis.__frameBodyOnload = null;
globalThis.__frameLoadListenerCalls = 0;
window.addEventListener('load', () => __frameLoadListenerCalls++);
</script></body></html>"#,
)
.expect("frame realm");
assert!(frame
.run_document_scripts(&mut parent, |_| None)
.is_empty());
frame
.dispatch_load_events(&mut parent)
.expect("frame load events");
assert_eq!(
frame
.evaluate(
&mut parent,
"[globalThis.__frameBodyOnload, globalThis.__frameLoadListenerCalls]",
)
.unwrap(),
serde_json::json!([[true, "load"], 1]),
);
}
#[test]
fn one_bad_frame_script_does_not_stop_the_rest() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
r#"<html><body>
<script>window.log = ['a'];</script>
<script>throw new Error('boom');</script>
<script src="missing.js"></script>
<script type="module">window.log.push('module');</script>
<script>window.log.push('b');</script>
</body></html>"#,
)
.expect("frame realm");
let problems = frame.run_document_scripts(&mut parent, |_| None);
assert_eq!(
frame.evaluate(&mut parent, "window.log.join(',')").unwrap(),
serde_json::json!("a,b")
);
assert_eq!(problems.len(), 3, "problems: {problems:?}");
assert!(problems.iter().any(|p| p.contains("boom")), "{problems:?}");
assert!(
problems.iter().any(|p| p.contains("missing.js")),
"{problems:?}"
);
assert!(problems.iter().any(|p| p.contains("module")), "{problems:?}");
}
#[tokio::test(flavor = "current_thread")]
async fn many_frames_can_be_alive_at_once() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frames: Vec<FrameRealm> = (0..4)
.map(|index| {
FrameRealm::new(
&mut parent,
// Frame ids start at 1: 0 names the page itself, which is
// what a DOM call from an unframed realm reports.
index + 1,
0,
&format!("https://f{index}.example/"),
&format!("<html><body><h1>{index}</h1></body></html>"),
)
.expect("frame realm")
})
.collect();
for (index, frame) in frames.iter().enumerate() {
frame
.execute_script(&mut parent, &format!("globalThis.n = {index};"))
.unwrap();
}
// Out-of-order access must be safe: each frame carries its own state.
for (index, frame) in frames.iter().enumerate().rev() {
assert_eq!(
frame.evaluate(&mut parent, "globalThis.n").unwrap().as_f64(),
Some(index as f64)
);
assert_eq!(
frame
.evaluate(&mut parent, "document.querySelector('h1').textContent")
.unwrap(),
serde_json::json!(index.to_string())
);
}
}
/// The hard case. A frame's deferred work re-enters JavaScript from the
/// event loop, long after the host last called into the frame, so nothing
/// can have made the frame "current" for it. It has to find its own
/// document anyway.
#[tokio::test(flavor = "current_thread")]
async fn a_frames_deferred_work_still_sees_the_frames_document() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
"<html><body></body></html>",
)
.expect("frame realm");
// 50ms, not 0: a zero delay drains as a microtask while the host is
// still inside the frame, which would hide the bug this guards.
frame
.execute_script(
&mut parent,
"setTimeout(() => { document.body.setAttribute('data-who', location.href); }, 50);",
)
.unwrap();
parent.run_event_loop_bounded(300).await.unwrap();
assert_eq!(
frame
.evaluate(&mut parent, "document.body.getAttribute('data-who')")
.unwrap(),
serde_json::json!("https://child.example/"),
"the frame's timer did not write to the frame's own document"
);
assert_eq!(
parent
.evaluate("document.body.getAttribute('data-who')")
.unwrap(),
serde_json::Value::Null,
"the frame's timer wrote to the parent's document"
);
}
/// A frame's timers cannot go through deno_core's queue: `op_timer_queue`
/// reads per-context state that only a deno_core-created context carries,
/// and queueing from a snapshot realm dereferences uninitialized memory,
/// which aborts the process rather than failing a test. This is the guard
/// against that path ever being restored.
#[tokio::test(flavor = "current_thread")]
async fn a_frame_timer_fires_without_deno_cores_timer_queue() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(&mut parent, "setTimeout(() => { globalThis.fired = 1; }, 50);")
.unwrap();
parent.run_event_loop_bounded(300).await.unwrap();
assert_eq!(
frame.evaluate(&mut parent, "globalThis.fired || 0").unwrap(),
serde_json::json!(1),
"the frame's timer callback never ran"
);
}
/// Frame timers run on a separate queue from the page's, so cancelling one
/// has its own path and its own way to go wrong.
#[tokio::test(flavor = "current_thread")]
async fn clear_timeout_cancels_a_frame_timer() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(
&mut parent,
"globalThis.kept = 0;\
const cancelled = setTimeout(() => { globalThis.kept = 1; }, 50);\
setTimeout(() => { globalThis.kept = 2; }, 50);\
clearTimeout(cancelled);",
)
.unwrap();
parent.run_event_loop_bounded(300).await.unwrap();
assert_eq!(
frame.evaluate(&mut parent, "globalThis.kept").unwrap(),
serde_json::json!(2),
"clearTimeout did not cancel exactly the frame timer it was given"
);
}
/// V8 reports the frame as the microtask context, so a promise continuation
/// resolves ops against the frame without any help from the host.
#[tokio::test(flavor = "current_thread")]
async fn a_frames_promise_continuation_sees_the_frames_document() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(
&mut parent,
"Promise.resolve().then(() => { \
document.body.setAttribute('data-who', location.href); });",
)
.unwrap();
parent.run_event_loop_bounded(300).await.unwrap();
assert_eq!(
frame
.evaluate(&mut parent, "document.body.getAttribute('data-who')")
.unwrap(),
serde_json::json!("https://child.example/"),
);
}
// #850 / #841 — a promise rejection or dynamic import() inside a frame realm
// used to null-deref deno_core's global callbacks (which read per-context
// state from V8 embedder slots) and segfault the whole process. The realm
// must now alias the main realm's state so these run without crashing.
#[test]
fn a_frame_rejection_does_not_crash_the_process() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://parent.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
// Reaching this line at all (no SIGSEGV) is the regression check.
frame
.execute_script(&mut parent, "Promise.reject(new Error('boom')); 'ok'")
.unwrap();
}
#[test]
fn a_frame_dynamic_import_does_not_crash_the_process() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://parent.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(
&mut parent,
"import('data:text/javascript,export default 1').catch(() => {}); 'ok'",
)
.unwrap();
}
/// A frame posting to `parent` must reach the page, arrive trusted, and
/// carry the frame's origin. Turnstile and every widget like it drop an
/// untrusted message silently, so an untrusted delivery is not a cosmetic
/// difference, it is the widget hanging forever.
#[test]
fn a_frame_posts_to_its_parent_as_a_trusted_message() {
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, e.isTrusted]));",
)
.unwrap();
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(&mut parent, "parent.postMessage({token: 'ok'}, '*');")
.unwrap();
// The host is the transport, exactly as `Page` does between turns.
let queued = parent.take_pending_frame_messages();
assert_eq!(queued.len(), 1);
assert_eq!(queued[0].target_frame_id, 0);
assert_eq!(queued[0].source_frame_id, 1);
let script = format!(
"globalThis.__obscura_deliverMessage({}, {}, {});",
serde_json::to_string(&queued[0].data_json).unwrap(),
serde_json::to_string(&queued[0].origin).unwrap(),
queued[0].source_frame_id,
);
parent.execute_script("<frame-message>", &script).unwrap();
assert_eq!(
parent.evaluate("globalThis.got").unwrap(),
serde_json::json!([[{"token": "ok"}, "https://child.example", true]]),
);
}
/// 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",
);
}
/// SEC-001 / #704 — verifies the targetOrigin gate does NOT break legitimate
/// delivery *into* a frame (the "about:blank / empty origin" regression a
/// reviewer warned about): an explicit origin that matches the loaded frame
/// is delivered, the wildcard is always delivered (including to an opaque
/// about:blank frame), and only a genuine mismatch is dropped.
#[test]
fn post_message_into_a_frame_does_not_over_drop() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
// A loaded, same-origin child frame.
let child = FrameRealm::new(
&mut parent,
1,
0,
"https://parent.example/child",
"<html><body></body></html>",
)
.expect("frame realm");
child
.execute_script(
&mut parent,
"globalThis.got = [];\
addEventListener('message', (e) => globalThis.got.push(String(e.data)));",
)
.unwrap();
// Explicit matching origin -> delivered (the case that must not break).
child
.deliver_message(&mut parent, "{\"v\":\"m1\"}", "https://parent.example", 0, "https://parent.example")
.unwrap();
// Wildcard -> always delivered.
child
.deliver_message(&mut parent, "{\"v\":\"m2\"}", "https://parent.example", 0, "*")
.unwrap();
// Explicit non-matching origin -> dropped.
child
.deliver_message(&mut parent, "{\"v\":\"m3\"}", "https://parent.example", 0, "https://evil.example")
.unwrap();
assert_eq!(
child.evaluate(&mut parent, "globalThis.got").unwrap(),
serde_json::json!(["m1", "m2"]),
"matching origin and wildcard must deliver into the frame; only a real mismatch drops",
);
// An opaque (about:blank) frame: the wildcard must still deliver, so the
// common widget case never breaks even when the frame origin is 'null'.
let blank = FrameRealm::new(
&mut parent,
2,
0,
"about:blank",
"<html><body></body></html>",
)
.expect("blank frame realm");
blank
.execute_script(
&mut parent,
"globalThis.got = [];\
addEventListener('message', (e) => globalThis.got.push(String(e.data)));",
)
.unwrap();
blank
.deliver_message(&mut parent, "{\"v\":\"w\"}", "https://parent.example", 0, "*")
.unwrap();
assert_eq!(
blank.evaluate(&mut parent, "globalThis.got").unwrap(),
serde_json::json!(["w"]),
"the wildcard must still deliver to an about:blank (opaque-origin) frame",
);
}
/// `parent === window` is how a document decides it is top-level, so a
/// framed realm must not see itself as the top.
#[test]
fn a_framed_realm_does_not_look_top_level() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
2,
0,
"https://child.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
assert_eq!(
frame
.evaluate(&mut parent, "[parent === window, top === window]")
.unwrap(),
serde_json::json!([false, false]),
);
// The page itself really is the top and must still say so.
assert_eq!(
parent.evaluate("[parent === window, top === window]").unwrap(),
serde_json::json!([true, true]),
);
}
/// Script can post in a synchronous loop while the host only drains between
/// event loop turns, and this queue is on the process heap rather than
/// V8's, where the heap-limit guard would never see it.
#[test]
fn a_flood_of_messages_cannot_grow_the_queue_without_bound() {
std::env::set_var("OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES", "64");
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://child.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(
&mut parent,
"for (let i = 0; i < 5000; i++) parent.postMessage(i, '*');",
)
.unwrap();
let queued = parent.take_pending_frame_messages();
assert_eq!(queued.len(), 64, "the queue was not capped");
// The messages kept are the earliest, which is the half of a handshake
// that matters.
assert_eq!(queued[0].data_json, r#"{"v":0}"#);
std::env::remove_var("OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES");
}
/// The page realm holds the frame's window and document, so a discarded
/// frame leaves the page naming objects from a context the host no longer
/// holds. Reading one must be safe. A regression here is an access
/// violation that takes the process down, not a failed assertion.
///
/// It must also not read as anything: V8 severs a global proxy when its
/// context goes, which is the same thing a browser does to a WindowProxy
/// when it discards a browsing context.
#[test]
fn a_discarded_realm_leaves_the_page_safe_to_run() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
{
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://parent.example/child",
"<html><body><h1>Child</h1></body></html>",
)
.expect("frame realm");
frame
.execute_script(&mut parent, "globalThis.marker = 'child';")
.unwrap();
// Reachable from the page while the frame is alive.
assert_eq!(
parent
.evaluate("globalThis.__obscura_frameObjects[1].window.marker")
.unwrap(),
serde_json::json!("child"),
);
}
// Dropping the realm does not free it, and must not make touching it
// unsafe: the page still names its window, so V8 keeps the context
// alive and the read still answers. This is exactly why a discarded
// frame has to have its entry removed rather than merely dropped, and
// what `Page::release_detached_frames` is for.
assert_eq!(
parent
.evaluate("globalThis.__obscura_frameObjects[1].window.marker")
.unwrap(),
serde_json::json!("child"),
);
// The page's own DOM work still resolves against the page.
assert_eq!(
parent.evaluate("document.body.innerHTML").unwrap(),
serde_json::json!(""),
);
// Dropping the page's reference is what lets the frame be collected.
parent
.execute_script("p", "delete globalThis.__obscura_frameObjects[1];")
.unwrap();
assert_eq!(
parent
.evaluate("globalThis.__obscura_frameObjects[1] === undefined")
.unwrap(),
serde_json::json!(true),
);
}
/// A DOM call names the realm it belongs to, so the page reading the
/// frame's document gets the frame's document. Resolving from the running
/// context instead would silently answer with the page's own.
#[test]
fn the_page_reads_the_frames_document_through_its_own_object() {
let mut parent = page(
"https://parent.example/",
"<html><head><title>parent</title></head><body></body></html>",
);
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://parent.example/child",
"<html><head><title>BEFORE</title></head><body><p>child</p></body></html>",
)
.expect("frame realm");
frame
.execute_script(&mut parent, "document.title = 'RAN-IN-CHILD';")
.unwrap();
// Read the frame's document from the *page's* realm.
assert_eq!(
parent
.evaluate("globalThis.__obscura_frameObjects[1].document.title")
.unwrap(),
serde_json::json!("RAN-IN-CHILD"),
);
assert_eq!(
parent
.evaluate("globalThis.__obscura_frameObjects[1].document.querySelector('p').textContent")
.unwrap(),
serde_json::json!("child"),
);
// The page's own title is untouched by any of that.
assert_eq!(
parent.evaluate("document.title").unwrap(),
serde_json::json!("parent"),
);
}
/// A cross-origin frame must stay opaque. Nothing about it is published to
/// the page, and V8's own access check answers `undefined` for anything the
/// page reaches for, because the two realms keep different security tokens.
#[test]
fn a_cross_origin_frame_is_not_reachable_from_the_page() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"https://other.example/f",
"<html><body></body></html>",
)
.expect("frame realm");
frame
.execute_script(&mut parent, "globalThis.secret = 'do-not-leak';")
.unwrap();
assert_eq!(
parent
.evaluate("globalThis.__obscura_frameObjects[1] === undefined")
.unwrap(),
serde_json::json!(true),
"a cross-origin frame was published to the page"
);
// The frame still works on its own side.
assert_eq!(
frame.evaluate(&mut parent, "globalThis.secret").unwrap(),
serde_json::json!("do-not-leak"),
);
}
#[test]
fn remote_dom_nodes_preserve_foreign_document_identity_and_reject_stale_frames() {
let mut parent = page("https://example.com/", "<div id=parent>parent</div>");
let frame = FrameRealm::new(&mut parent, 1, 0, "https://example.com/child",
"<base href='/assets/'><span id=child>child</span>").unwrap();
let info = parent.store_object_with_meta(
"globalThis.__obscura_frameObjects[1].document.getElementById('child')").unwrap();
let object_id = info.object_id.unwrap();
let description = parent.with_remote_dom_node(&object_id, |dom, node, frame, url, base| {
(frame, url.to_string(), base.to_string(), dom.outer_html(node))
}).unwrap();
assert_eq!(description, (1, "https://example.com/child".into(),
"https://example.com/assets/".into(), "<span id=\"child\">child</span>".into()));
frame.execute_script(&mut parent, "history.pushState({},'', '/changed');").unwrap();
assert_eq!(parent.with_remote_dom_node(&object_id, |_, _, _, url, base| {
(url.to_string(), base.to_string())
}).unwrap(), ("https://example.com/changed".into(), "https://example.com/assets/".into()));
let document = parent.store_object_with_meta(
"globalThis.__obscura_frameObjects[1].document").unwrap().object_id.unwrap();
assert_eq!(parent.with_remote_dom_node(&document, |dom, node, frame, _, _| {
(node == dom.document(), frame)
}).unwrap(), (true, 1));
let forged = parent.store_object_with_meta("({_nid:0})").unwrap().object_id.unwrap();
parent.execute_script("override", "Map.prototype.get=function(){return this};").unwrap();
assert!(parent.with_remote_dom_node(&forged, |_, _, _, _, _| ()).is_err());
assert_eq!(parent.with_remote_dom_node(&document, |_, _, frame, _, _| frame).unwrap(), 1);
parent.forget_frame_state(frame.frame_id());
assert!(parent.with_remote_dom_node(&document, |_, _, _, _, _| ()).is_err());
}
#[test]
fn opaque_origin_frames_are_never_same_origin() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
let frame = FrameRealm::new(
&mut parent,
1,
0,
"about:blank",
"<html><body></body></html>",
)
.expect("frame realm");
assert_eq!(frame.origin(), "null");
assert!(!frame.is_same_origin_as("null"));
assert!(!frame.is_same_origin_as("https://parent.example"));
}
#[test]
fn file_list_global_exists_and_input_files_is_instance() {
// Issue #1232: `typeof FileList` was `undefined`, crashing apps that
// reference it while booting.
let mut rt = page(
"https://example.com/",
"<html><body><input type=file id=f></body></html>",
);
assert_eq!(
rt.evaluate("typeof FileList").unwrap(),
serde_json::json!("function")
);
assert_eq!(
rt.evaluate("Object.prototype.toString.call(document.getElementById('f').files)")
.unwrap(),
serde_json::json!("[object FileList]")
);
assert_eq!(
rt.evaluate("document.getElementById('f').files instanceof FileList")
.unwrap(),
serde_json::json!(true)
);
assert_eq!(
rt.evaluate("document.getElementById('f').files.length").unwrap(),
serde_json::json!(0.0)
);
assert_eq!(
rt.evaluate("(() => { try { new FileList(); return 'no-throw'; } catch (e) { return e.name + ': ' + e.message; } })()").unwrap(),
serde_json::json!("TypeError: Illegal constructor")
);
}
#[test]
fn file_list_iteration_preserves_uploaded_files() {
let mut rt = page(
"https://example.com/",
"<html><body><input type=file id=f multiple></body></html>",
);
let result = rt.evaluate(r#"(() => {
const input = document.getElementById('f');
const empty = [...input.files].length;
__obscura_setInputFiles(input, [
{name: 'first.txt', type: 'text/plain', b64: 'YQ=='},
{name: 'second.txt', type: 'text/plain', b64: 'Yg=='}
]);
const files = input.files;
const names = [];
for (const file of files) names.push(file.name);
const iterator = files[Symbol.iterator]();
return {
empty,
spread: [...files].map(file => file.name),
names,
sameFile: [...files][0] === files.item(0),
iterableIterator: iterator[Symbol.iterator]() === iterator
};
})()"#).unwrap();
assert_eq!(result, serde_json::json!({
"empty": 0,
"spread": ["first.txt", "second.txt"],
"names": ["first.txt", "second.txt"],
"sameFile": true,
"iterableIterator": true
}));
}
#[tokio::test(flavor = "current_thread")]
async fn parsed_frame_metadata_exists_without_eager_realms_or_started_loads() {
let mut parent = page("https://parent.example/",
"<html><body><iframe name='a' src='https://other.example/a'></iframe>\
<iframe name='b' src='https://other.example/b'></iframe></body></html>");
assert_eq!(parent.evaluate("frames.length").unwrap().as_f64(), Some(2.0));
assert_eq!(parent.realm_states().borrow().live_count(), 0);
assert!(parent.take_pending_frames().is_empty());
assert_eq!(parent.evaluate(
"[frames.a === frames[0], frames.b === frames[1], frames[0] !== frames[1]]"
).unwrap(), serde_json::json!([true, true, true]));
}
#[tokio::test(flavor = "current_thread")]
async fn unowned_frame_realms_do_not_alias_connected_frame_owners() {
let mut parent = page(
"https://parent.example/",
"<html><body>\
<iframe name=\"a\" src=\"https://other.example/a\"></iframe>\
<iframe name=\"b\" src=\"https://other.example/b\"></iframe>\
</body></html>",
);
parent.evaluate_script("__obscura_init_frames();").unwrap();
let frame_a = FrameRealm::new(
&mut parent,
1,
0,
"https://other.example/a",
"<html><body></body></html>",
).unwrap();
let frame_b = FrameRealm::new(
&mut parent,
2,
0,
"https://other.example/b",
"<html><body></body></html>",
).unwrap();
let result_a = frame_a.evaluate(&mut parent, r#"
[
parent.frames.length,
parent.length,
parent.frames[0] === window,
parent.frames[1] === window,
typeof parent.frames.b,
parent.frames.a !== window,
parent.frames.b !== window,
parent.parent === parent,
parent.top === parent,
]
"#).unwrap();
assert_eq!(result_a, serde_json::json!([
2, 2, false, false, "object", true, true, true, true
]));
let result_b = frame_b.evaluate(&mut parent, r#"
[
parent.frames.length,
parent.length,
parent.frames[0] === window,
parent.frames[1] === window,
parent.frames.b === window,
typeof parent.frames.a,
]
"#).unwrap();
assert_eq!(result_b, serde_json::json!([
2, 2, false, false, false, "object"
]));
frame_a.execute_script(&mut parent, r#"
parent.frames.b.postMessage('hello from a', '*');
"#).unwrap();
assert!(parent.take_pending_frame_messages().is_empty(),
"an unowned realm must not receive a pending owner's message");
let frame_c = FrameRealm::new(
&mut parent,
3,
1,
"https://other.example/c",
"<html><body></body></html>",
).unwrap();
let result_c = frame_c.evaluate(&mut parent, r#"
[
parent.parent === top,
parent.parent.frames.length,
parent.parent.frames.a === parent,
]
"#).unwrap();
assert_eq!(result_c, serde_json::json!([true, 2, false]));
}
}