fix(runtime): preserve origin-domain access for retired windows

This commit is contained in:
ldm0
2026-11-22 02:01:52 +08:00
parent 137a4fc66e
commit 6e2ecccbd8
17 changed files with 477 additions and 67 deletions
@@ -8056,11 +8056,9 @@ html/webappapis/dynamic-markup-insertion/opening-the-input-stream/016.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document-open-cancels-javascript-url-navigation.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-02.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-03.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/event-listeners.window.js?moli-wpt-script=window
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/form-control-state.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/location-set-and-document-open.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/origin-check-in-document-open-basic.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url.window.js?moli-wpt-script=window
html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-documentfragment.html
html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-no-parent.html
html/webappapis/microtask-queuing/queue-microtask-cross-realm-callback-report-exception.html
@@ -421,6 +421,14 @@ impl PageScriptHost {
),
resource_authority,
);
if matches!(
owner_transition.local_window_owner_transition(),
FrameLocalWindowOwnerTransition::Preserved { .. }
) {
// Reusing the initial inner global still gives it the newly
// committed Document's origin and mutable domain state.
self.refresh_child_default_world_security_token(scope, handle);
}
// A preserved initial LocalWindow may already have a history surface
// without running realm bootstrap again. Commit its Document seed here;
// subsequent view refreshes must never replay this history transition.
@@ -104,6 +104,13 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn rebind_child_
};
validate_registered_realm(host, scope, init)?;
let snapshot = capture_child_window_realm_snapshot(host, init)?;
let context = scope.get_current_context();
host.install_window_context_security_origin(
scope,
context,
OwnerDispatchScope::Child(init.handle),
init.world.access_policy(),
);
rebind_child_window_document_environment(scope, global, rebind.handle)?;
bind_window_name(scope, global, &snapshot.window_name);
@@ -667,45 +667,42 @@ pub(crate) fn contexts_can_script_access<'s>(
return true;
}
let Some((accessing_host_ptr, accessing_identity)) = (|| {
let host_ptr = crate::util::context_host_ptr_from_context_slot(accessing_context)?;
let identity = unsafe { &*host_ptr }
.window_execution_context_identity_for_access_check(accessing_context);
Some((host_ptr, identity))
})() else {
let Some(accessing_host_ptr) =
crate::util::context_host_ptr_from_context_slot(accessing_context)
else {
return false;
};
let Some((accessed_host_ptr, accessed_identity)) = (|| {
let host_ptr = crate::util::context_host_ptr_from_context_slot(accessed_context)?;
let identity = unsafe { &*host_ptr }
.window_execution_context_identity_for_access_check(accessed_context)?;
Some((host_ptr, identity))
})() else {
let Some(accessed_host_ptr) = crate::util::context_host_ptr_from_context_slot(accessed_context)
else {
return false;
};
let host = unsafe { &*accessing_host_ptr };
let Some(accessing_identity) = accessing_identity
.filter(|identity| host.window_execution_context_identity_is_current(*identity))
else {
return accessing_context
.get_slot::<super::super::WindowEnvironmentSettings>()
.is_some_and(|settings| {
settings.can_access_current_window(
host,
unsafe { &*accessed_host_ptr },
accessed_identity,
)
});
};
if accessing_host_ptr != accessed_host_ptr {
return host.window_execution_context_can_access_other_host(
accessing_identity,
unsafe { &*accessed_host_ptr },
accessed_identity,
);
let accessed_host = unsafe { &*accessed_host_ptr };
let accessing_identity = host
.window_execution_context_identity_for_access_check(accessing_context)
.filter(|identity| host.window_execution_context_identity_is_current(*identity));
let accessed_identity = accessed_host
.window_execution_context_identity_for_access_check(accessed_context)
.filter(|identity| accessed_host.window_execution_context_identity_is_current(*identity));
if let (Some(accessing), Some(accessed)) = (accessing_identity, accessed_identity) {
return if accessing_host_ptr == accessed_host_ptr {
host.window_execution_context_can_access(accessing, accessed)
} else {
host.window_execution_context_can_access_other_host(accessing, accessed_host, accessed)
};
}
host.window_execution_context_can_access(accessing_identity, accessed_identity)
if accessing_host_ptr == accessed_host_ptr {
// Domain state survives execution retirement, without granting a task route.
return host.window_context_origins_allow_access(accessing_context, accessed_context);
}
accessing_identity.is_none()
&& accessed_identity.is_some_and(|accessed| {
accessing_context
.get_slot::<super::super::WindowEnvironmentSettings>()
.is_some_and(|settings| {
settings.can_access_current_window(host, accessed_host, accessed)
})
})
}
pub(crate) fn caller_can_access_window<'s>(
@@ -67,7 +67,7 @@ pub(super) struct ChildBrowsingContextEntry {
performance_time_origin: ChildPerformanceTimeOrigin,
pending_document_load_id: Option<u64>,
classic_script_document_state: classic_scripts::ChildClassicScriptDocumentState,
document_domain_override: Rc<RefCell<Option<String>>>,
document_domain_override: super::DocumentDomainState,
credentialless: bool,
service_worker_client_id: Option<ServiceWorkerClientId>,
pending_service_worker_client_id: Option<ServiceWorkerClientId>,
@@ -123,20 +123,18 @@ impl ChildBrowsingContextEntry {
self.clear_document_domain_override();
}
pub(super) fn document_domain_override(&self) -> Option<String> {
self.document_domain_override.borrow().clone()
}
pub(super) fn shared_document_domain_override(&self) -> Rc<RefCell<Option<String>>> {
pub(super) fn document_domain_state(&self) -> super::DocumentDomainState {
self.document_domain_override.clone()
}
pub(super) fn set_document_domain_override(&mut self, domain: String) {
*self.document_domain_override.borrow_mut() = Some(domain);
self.document_domain_override.set(domain);
}
pub(super) fn clear_document_domain_override(&mut self) {
self.document_domain_override = Rc::new(RefCell::new(None));
// A new Document gets its own mutable domain. Retained realms keep
// the previous origin, including any inherited references to it.
self.document_domain_override = super::DocumentDomainState::default();
}
pub(super) fn window_name(&self) -> &str {
@@ -61,7 +61,7 @@ impl PageScriptHost {
inherited_document_domain: Option<&str>,
policy: &crate::document_runtime::DocumentPolicyContainer,
) -> crate::frame_owner_model::FrameDocumentLocalWindowTransition {
let same_origin = self.document_domain_override.borrow().as_deref()
let same_origin = self.document_domain_override.get().as_deref()
== inherited_document_domain
&& (inherited_opaque_origin_matches
|| moli_url::WebOrigin::from_serialized(&self.main_document_security_origin())
@@ -431,7 +431,7 @@ impl PageScriptHost {
#[cfg(test)]
force_reused_isolated_proxy_bootstrap_failure: std::cell::Cell::new(false),
child_browsing_context_document_handles: HashMap::new(),
document_domain_override: Rc::new(RefCell::new(None)),
document_domain_override: DocumentDomainState::default(),
next_child_document_load_id: 0,
next_child_classic_script_load_id: 0,
pending_child_document_navigations: HashMap::new(),
@@ -4,17 +4,17 @@ use std::net::IpAddr;
use url::{Host, Url};
impl PageScriptHost {
pub(crate) fn inherit_document_domain_override(&mut self, domain: Rc<RefCell<Option<String>>>) {
pub(crate) fn inherit_document_domain_override(&mut self, domain: DocumentDomainState) {
self.document_domain_override = domain;
}
pub(crate) fn inherited_document_domain(
&self,
child: Option<DomHandle>,
) -> Rc<RefCell<Option<String>>> {
) -> DocumentDomainState {
match child.and_then(|handle| self.child_browsing_context_security_origin_owner(handle)) {
Some(ChildSecurityOriginOwner::Child(owner)) => {
self.child_browsing_contexts[&owner].shared_document_domain_override()
self.child_browsing_contexts[&owner].document_domain_state()
}
Some(ChildSecurityOriginOwner::Main) | None => self.document_domain_override.clone(),
}
@@ -27,8 +27,7 @@ impl PageScriptHost {
if document_handle == self.document_handle() {
return self
.document_domain_override
.borrow()
.clone()
.get()
.unwrap_or_else(|| self.main_document_domain_host().unwrap_or_default());
}
if let Some(child_handle) =
@@ -65,7 +64,7 @@ impl PageScriptHost {
if !document_domain_is_allowed_for_host(&current_host, &domain) {
return false;
}
*self.document_domain_override.borrow_mut() = Some(domain);
self.document_domain_override.set(domain);
return true;
}
let Some(child_handle) =
@@ -84,12 +83,19 @@ impl PageScriptHost {
&self,
handle: DomHandle,
) -> Option<String> {
self.child_document_domain_state(handle)?.get()
}
pub(super) fn child_document_domain_state(
&self,
handle: DomHandle,
) -> Option<DocumentDomainState> {
match self.child_browsing_context_security_origin_owner(handle)? {
ChildSecurityOriginOwner::Main => self.document_domain_override.borrow().clone(),
ChildSecurityOriginOwner::Main => Some(self.document_domain_override.clone()),
ChildSecurityOriginOwner::Child(owner) => self
.child_browsing_contexts
.get(&owner)
.and_then(|entry| entry.document_domain_override()),
.map(|entry| entry.document_domain_state()),
}
}
@@ -132,9 +138,7 @@ impl PageScriptHost {
return false;
};
match origin_owner {
ChildSecurityOriginOwner::Main => {
*self.document_domain_override.borrow_mut() = Some(domain);
}
ChildSecurityOriginOwner::Main => self.document_domain_override.set(domain),
ChildSecurityOriginOwner::Child(owner) => {
let Some(entry) = self.child_browsing_contexts.get_mut(&owner) else {
return false;
@@ -179,6 +179,7 @@ mod window_execution_context;
mod window_security_tokens;
mod window_world;
mod workers;
pub(crate) use window_security_tokens::DocumentDomainState;
pub(crate) use window_security_tokens::set_window_security_token;
#[cfg(test)]
@@ -931,7 +932,7 @@ pub(crate) struct PageScriptHost {
#[cfg(test)]
force_reused_isolated_proxy_bootstrap_failure: std::cell::Cell<bool>,
child_browsing_context_document_handles: HashMap<DomHandle, DomHandle>,
document_domain_override: Rc<RefCell<Option<String>>>,
document_domain_override: DocumentDomainState,
next_child_document_load_id: u64,
next_child_classic_script_load_id: u64,
pending_child_document_navigations: HashMap<u64, PendingChildDocumentNavigation>,
@@ -105,7 +105,7 @@ impl WindowEnvironmentSettings {
} = &mut origin
{
if self.domain_owner_document == host.document_handle() {
*document_domain = host.document_domain_override.borrow().clone();
*document_domain = host.document_domain_override.get();
} else if let Some(handle) =
host.child_browsing_context_handle_for_stored_document(self.domain_owner_document)
{
@@ -135,7 +135,7 @@ impl WindowEnvironmentSettings {
} = &mut origin
{
if self.domain_owner_document == host.document_handle() {
*document_domain = host.document_domain_override.borrow().clone();
*document_domain = host.document_domain_override.get();
} else if let Some(handle) =
host.child_browsing_context_handle_for_stored_document(self.domain_owner_document)
{
@@ -1,13 +1,96 @@
use super::{
OwnerDispatchScope, PageScriptHost, WindowEnvironmentSettings, WindowExecutionContextIdentity,
OwnerDispatchScope, PageScriptHost, WindowEnvironmentSettings,
WindowExecutionContextAccessPolicy, WindowExecutionContextIdentity,
WindowExecutionContextOwner,
child_frames::{ChildAncestorOriginsReferrerPolicy, ChildBrowsingContextEntry},
};
use crate::document_runtime::DomHandle;
use std::{cell::RefCell, rc::Rc};
const WINDOW_SECURITY_TOKEN_PREFIX: &str = "moli-window-origin-v1:";
const WINDOW_ISOLATED_WORLD_SECURITY_TOKEN_PREFIX: &str = "moli-window-isolated-origin-v1:";
#[derive(Clone, Default)]
pub(crate) struct DocumentDomainState(Rc<DocumentDomainStateData>);
#[derive(Default)]
struct DocumentDomainStateData {
value: RefCell<Option<String>>,
contexts: RefCell<Vec<v8::Weak<v8::Context>>>,
}
impl std::fmt::Debug for DocumentDomainState {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_tuple("DocumentDomainState")
.field(&self.get())
.finish()
}
}
impl DocumentDomainState {
pub(crate) fn get(&self) -> Option<String> {
self.0.value.borrow().clone()
}
pub(super) fn set(&self, domain: String) {
*self.0.value.borrow_mut() = Some(domain);
}
fn register_context(
&self,
scope: &mut v8::PinScope<'_, '_, ()>,
context: v8::Local<'_, v8::Context>,
) {
let mut contexts = self.0.contexts.borrow_mut();
contexts.retain(|weak| {
weak.to_local(scope)
.is_some_and(|current| current != context)
});
contexts.push(v8::Weak::new(scope, context));
}
fn invalidate_context_tokens(&self, scope: &mut v8::PinScope<'_, '_>) {
// Inherited origins can still be shared with a retired realm. Its old
// tuple token must not bypass the changed origin-domain check. Weak
// handles keep this propagation independent of execution registrations.
self.0.contexts.borrow_mut().retain(|weak| {
let Some(context) = weak.to_local(scope) else {
return false;
};
let shares_domain = context
.get_slot::<WindowContextSecurityOrigin>()
.as_deref()
.and_then(|origin| origin.domain.as_ref())
.is_some_and(|domain| Rc::ptr_eq(&self.0, &domain.0));
if shares_domain {
context.use_default_security_token();
}
shares_domain
});
}
}
struct WindowContextSecurityOrigin {
origin: WindowAccessOrigin,
domain: Option<DocumentDomainState>,
access_policy: WindowExecutionContextAccessPolicy,
}
impl WindowContextSecurityOrigin {
fn current_origin(&self) -> WindowAccessOrigin {
let mut origin = self.origin.clone();
if let WindowAccessOrigin::Tuple {
document_domain, ..
} = &mut origin
&& let Some(domain) = &self.domain
{
*document_domain = domain.get();
}
origin
}
}
impl PageScriptHost {
/// Static pure APIs use their concrete function realm, including retained
/// Document settings, without reading author-visible Window properties.
@@ -70,6 +153,50 @@ impl PageScriptHost {
))
}
pub(crate) fn install_window_context_security_origin(
&self,
scope: &mut v8::PinScope<'_, '_, ()>,
context: v8::Local<'_, v8::Context>,
dispatch_scope: OwnerDispatchScope,
access_policy: WindowExecutionContextAccessPolicy,
) {
let Some(origin) = self.window_access_origin_for_dispatch_scope(dispatch_scope) else {
context.remove_slot::<WindowContextSecurityOrigin>();
return;
};
let domain = match dispatch_scope {
OwnerDispatchScope::Top => Some(self.document_domain_override.clone()),
OwnerDispatchScope::Child(handle) => self.child_document_domain_state(handle),
// Popups currently alias their opener's concrete realm.
OwnerDispatchScope::LightweightPopup(_) => return,
};
if let Some(domain) = &domain {
domain.register_context(scope, context);
}
context.set_slot(Rc::new(WindowContextSecurityOrigin {
origin,
domain,
access_policy,
}));
}
pub(in crate::native_bridge::context_host) fn window_context_origins_allow_access(
&self,
accessing_context: v8::Local<'_, v8::Context>,
accessed_context: v8::Local<'_, v8::Context>,
) -> bool {
let Some(accessing) = accessing_context.get_slot::<WindowContextSecurityOrigin>() else {
return false;
};
let Some(accessed) = accessed_context.get_slot::<WindowContextSecurityOrigin>() else {
return false;
};
accessing.access_policy == WindowExecutionContextAccessPolicy::Universal
|| accessing
.current_origin()
.can_access(&accessed.current_origin())
}
pub(in crate::native_bridge::context_host) fn child_ancestor_origins_referrer_policy_from_owner_attribute(
&self,
handle: DomHandle,
@@ -148,7 +275,7 @@ impl PageScriptHost {
return None;
}
let origin = self.main_document_security_origin();
if self.document_domain_override.borrow().is_some() {
if self.document_domain_override.get().is_some() {
return None;
}
window_security_token_key(origin)
@@ -177,7 +304,7 @@ impl PageScriptHost {
}
window_isolated_world_security_token_key(
self.main_document_security_origin(),
self.document_domain_override.borrow().is_some(),
self.document_domain_override.get().is_some(),
)
}
@@ -209,6 +336,15 @@ impl PageScriptHost {
return 0;
}
let domain = if target_is_main {
Some(self.document_domain_override.clone())
} else {
target_child.and_then(|handle| self.child_document_domain_state(handle))
};
if let Some(domain) = domain {
domain.invalidate_context_tokens(scope);
}
let mut dispatch_scopes = vec![OwnerDispatchScope::Top];
dispatch_scopes.extend(
self.child_browsing_context_handles_in_document_order()
@@ -324,6 +460,12 @@ impl PageScriptHost {
let Some((_, context)) = self.window_execution_context(scope, owner, dispatch_scope) else {
return false;
};
self.install_window_context_security_origin(
scope,
context,
dispatch_scope,
WindowExecutionContextAccessPolicy::EnforceWebOrigin,
);
set_window_security_token(
scope,
context,
@@ -630,7 +772,7 @@ impl PageScriptHost {
}
WindowAccessOrigin::from_serialized_origin(
serialized_origin,
self.document_domain_override.borrow().clone(),
self.document_domain_override.get(),
)
}
+1 -1
View File
@@ -9,7 +9,7 @@ mod current_input;
#[cfg(feature = "devtools")]
pub(crate) use context_host::MouseReleaseFollowUp;
pub(crate) use context_host::{
ChildDocumentFetch, PageScriptHost, PageScriptHostTaskCapabilities,
ChildDocumentFetch, DocumentDomainState, PageScriptHost, PageScriptHostTaskCapabilities,
PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner,
SharedResourceTimingBufferRegistry,
};
+1 -1
View File
@@ -2005,7 +2005,7 @@ impl ScriptVm {
pub(crate) struct ScriptVmInitialDocumentEnvironment {
security_token: Option<v8::Global<v8::Value>>,
opaque_origin: Option<std::sync::Arc<crate::structured_clone::RuntimeMessageOpaqueOrigin>>,
document_domain_override: Rc<RefCell<Option<String>>>,
document_domain_override: crate::native_bridge::DocumentDomainState,
origin: String,
pub(crate) policy_container: crate::document_runtime::DocumentPolicyContainer,
fallback_base_url: Option<url::Url>,
@@ -32,7 +32,7 @@ impl ScriptVm {
false
};
let inherited_domain =
inherited.map(|environment| environment.document_domain_override.borrow());
inherited.map(|environment| environment.document_domain_override.get());
Ok(self
._context_host
.borrow()
@@ -318,6 +318,24 @@ impl ScriptVmContextBootstrap {
child_handle: None, ..
} => unsafe { &*host_ptr }.main_isolated_world_security_token_key(),
};
let dispatch_scope = match mode {
WindowContextBootstrapMode::ChildDefault { child_handle, .. }
| WindowContextBootstrapMode::Isolated {
child_handle: Some(child_handle),
..
} => crate::native_bridge::OwnerDispatchScope::Child(child_handle),
_ => crate::native_bridge::OwnerDispatchScope::Top,
};
let access_policy = match mode {
WindowContextBootstrapMode::Isolated { access_policy, .. } => access_policy,
_ => crate::native_bridge::WindowExecutionContextAccessPolicy::EnforceWebOrigin,
};
unsafe { &*host_ptr }.install_window_context_security_origin(
scope,
local_context,
dispatch_scope,
access_policy,
);
if !crate::native_bridge::set_window_security_token(
scope,
local_context,
@@ -43,7 +43,7 @@ impl ScriptVmDefaultWorldBootstrap {
Some(ScriptVmInitialDocumentEnvironment {
security_token: None,
opaque_origin,
document_domain_override: Rc::default(),
document_domain_override: Default::default(),
fallback_base_url: None,
storage_key: None,
origin: inherited_origin.clone(),
@@ -1,5 +1,139 @@
use super::*;
#[cfg(feature = "devtools")]
#[tokio::test(flavor = "current_thread")]
async fn retained_child_window_origin_rebinds_default_and_isolated_realms() {
let server = StaticHttpServer::spawn_with_bodies(vec![
"<!doctype html><script>document.domain = 'example.test';</script>".to_owned(),
])
.await;
let loader = static_http_loader([server.resolve_entry("www.example.test")]);
let parent_url = server.url_for_host("www.example.test", "/page.html");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);
vm.exec(
r#"
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
globalThis.frame = document.createElement('iframe');
body.append(frame);
globalThis.heldWindow = frame.contentWindow;
"#,
None,
)
.unwrap();
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 16)
.await
.expect("initial child realm should materialize through Page tasks");
let child_realm = vm
.live_child_default_runtime_realm_inventory()
.into_iter()
.next()
.expect("initial child realm");
let child_context_id = child_realm.context_id;
let frame_id = child_realm.frame_id.expect("initial child frame id");
for (name, universal) in [("enforcedRead", false), ("universalRead", true)] {
let context_id = vm
.create_isolated_world_for_frame(&frame_id, name, universal)
.expect("initial child isolated world");
vm.eval_in_isolated_context(
context_id,
&format!(
"parent.{name} = ((target) => () => {{ try {{ return target.status; }} catch (error) {{ return error.name; }} }})(parent); 'installed'"
),
)
.expect("retain a callback from the initial isolated realm");
}
vm.exec(
"globalThis.loaded = false; frame.onload = () => { loaded = true; }; frame.src = '/child.html';",
None,
)
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(loaded)",
"true",
"network document should replace the initial about:blank document",
)
.await;
assert_eq!(
vm.live_child_default_runtime_realm_inventory()[0].context_id,
child_context_id,
"the first same-origin navigation must reuse the initial realm"
);
const PROBE: &str = r#"JSON.stringify([
(() => { try { return heldWindow.status; } catch (error) { return error.name; } })(),
enforcedRead(),
universalRead()
])"#;
let expected = r#"["SecurityError","SecurityError",""]"#;
assert_eq!(vm.eval(PROBE).unwrap(), expected);
vm.eval("frame.remove()").unwrap();
assert_eq!(vm.child_frame_realm_store.len(), 0);
assert_eq!(vm.page_isolated_world_contexts.len(), 0);
assert_eq!(
vm.eval(PROBE).unwrap(),
expected,
"retired realms must keep the committed origin and their own access policy"
);
assert_eq!(server.finish_targets().await, vec!["/child.html"]);
}
#[tokio::test(flavor = "current_thread")]
async fn retained_child_windows_keep_shared_origin_domain_access() {
const BODY: &str = r#"<!doctype html><body><script>
const domain = new URL(location.href).searchParams.get('domain');
if (domain) document.domain = domain;
</script></body>"#;
let server = StaticHttpServer::spawn_with_bodies(vec![BODY.to_owned(); 26]).await;
let second_server = StaticHttpServer::spawn_with_bodies(vec![BODY.to_owned()]).await;
let loader = static_http_loader([
server.resolve_entry("www.example.test"),
server.resolve_entry("sub.example.test"),
server.resolve_entry("other.test"),
second_server.resolve_entry("www.example.test"),
]);
let parent_url = server.url_for_host("www.example.test", "/page.html");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);
let script = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/retained-document-domain.js"
));
vm.exec(
&format!(
r#"
if (!document.documentElement) document.appendChild(document.createElement('html'));
if (!document.body) document.documentElement.appendChild(document.createElement('body'));
globalThis.__retainedDomainResult = null;
({script})({port}).then(
result => {{ globalThis.__retainedDomainResult = result; }},
error => {{ globalThis.__retainedDomainResult = {{error: String(error)}}; }}
);
"#,
port = second_server.base_url().port().unwrap(),
),
None,
)
.expect("retained origin-domain probe should start");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(__retainedDomainResult !== null)",
"true",
"retained origin-domain probe should finish",
)
.await;
let result: serde_json::Value = serde_json::from_str(
&vm.eval("JSON.stringify(__retainedDomainResult)")
.expect("retained origin-domain observations"),
)
.unwrap();
assert_eq!(result["checks"], 85, "{result}");
assert_eq!(result["failures"], serde_json::json!([]), "{result}");
assert_eq!(server.finish_targets().await.len(), 26);
assert_eq!(second_server.finish_targets().await.len(), 1);
}
#[test]
fn retained_child_window_survives_context_retirement() {
for materialized in [false, true] {
@@ -0,0 +1,103 @@
(async (otherPort) => {
const result = {checks: 0, failures: [], observations: []};
const check = (name, actual, expected) => {
result.checks++;
if (actual !== expected) result.failures.push({name, actual, expected});
};
const exercise = async config => {
const observations = [];
const documentDiagnostics = [];
const read = action => {
try { return action(); } catch (error) { return error.name; }
};
const record = (name, action, expected) => observations.push([name, read(action), expected]);
const observeDocument = (name, action, expected) => documentDiagnostics.push([name, read(action), expected]);
const peerRead = parent.Function('target', 'try { return target.status; } catch (error) { return error.name; }');
const frame = document.createElement('iframe');
if (config.sandbox) frame.sandbox = 'allow-scripts';
if (config.inherit === 'srcdoc') frame.srcdoc = '<!doctype html><body>inherited</body>';
else if (!config.inherit) {
const childURL = new URL('/domain-fixture.html', location.href);
if (config.childHost) childURL.hostname = config.childHost;
if (config.childPort) childURL.port = config.childPort;
if (config.childDomain) childURL.searchParams.set('domain', config.childDomain);
frame.src = childURL.href;
}
const loaded = new Promise(resolve => frame.onload = resolve);
document.body.append(frame);
await loaded;
const view = frame.contentWindow;
if (config.parentDomain) document.domain = config.parentDomain;
record('live-access', () => view.status, config.allow ? '' : 'SecurityError');
const doc = config.allow ? view.document : null;
const reverse = config.allow ? view.Function('other', 'return () => other.document.domain;')(window) : null;
frame.remove();
if (config.afterDomain) document.domain = config.afterDomain;
const allowedAfter = config.allowAfter ?? config.allow;
record('removed-access', () => view.status, allowedAfter ? '' : 'SecurityError');
const childDomainAfter = config.inherit ? (config.afterDomain || config.parentDomain) : config.childDomain;
const peerAllowed = !config.sandbox && !childDomainAfter && !config.childPort
&& (!config.childHost || config.childHost === location.hostname);
record('independent-peer-access', () => peerRead(view), peerAllowed ? '' : 'SecurityError');
if (doc) {
const expectedDomain = config.inherit
? (config.afterDomain || config.parentDomain || location.hostname)
: (config.childDomain || config.childHost || location.hostname);
observeDocument('retained-document-domain', () => doc.domain, expectedDomain);
record('retained-document-view', () => doc.defaultView, null);
record('retained-document-setter', () => { doc.domain = expectedDomain; return 'accepted'; }, 'SecurityError');
observeDocument('cloned-document-domain', () => doc.cloneNode(false).domain, expectedDomain);
}
if (reverse) record('retired-caller', reverse, allowedAfter ? document.domain : 'SecurityError');
if (config.reinsert) {
const newURL = new URL('/domain-fixture.html', location.href);
newURL.searchParams.set('domain', location.hostname);
const reloaded = new Promise(resolve => frame.onload = resolve);
frame.src = newURL.href;
document.body.append(frame);
await reloaded;
record('old-window-after-reinsert', () => view.status, '');
record('replacement-remains-one-sided', () => frame.contentWindow.status, 'SecurityError');
observeDocument('old-document-domain-after-reinsert', () => doc.domain, config.childDomain);
}
return {observations, documentDiagnostics, late: () => read(() => view.status), allowedAfter};
};
const host = location.hostname;
const relaxed = 'example.test';
const scenarios = [
{name: 'tuple', allow: true},
{name: 'exact-domain', parentDomain: host, childDomain: host, allow: true},
{name: 'relaxed-domain', parentDomain: relaxed, childDomain: relaxed, allow: true},
{name: 'subdomain', childHost: 'sub.example.test', parentDomain: relaxed, childDomain: relaxed, allow: true},
{name: 'port', childPort: otherPort, parentDomain: relaxed, childDomain: relaxed, allow: true},
{name: 'parent-only', parentDomain: relaxed, allow: false},
{name: 'child-only', childDomain: relaxed, allow: false},
{name: 'cross-origin', childHost: 'other.test', allow: false},
{name: 'opaque', sandbox: true, allow: false},
{name: 'parent-changes', allow: true, afterDomain: relaxed, allowAfter: false},
{name: 'parent-catches-up', childDomain: relaxed, allow: false, afterDomain: relaxed, allowAfter: true},
{name: 'inherited-blank', inherit: 'blank', allow: true, afterDomain: relaxed},
{name: 'inherited-srcdoc', inherit: 'srcdoc', allow: true, afterDomain: relaxed},
{name: 'reinsert', parentDomain: relaxed, childDomain: relaxed, allow: true, reinsert: true},
];
for (const config of scenarios) {
const outer = document.createElement('iframe');
const loaded = new Promise(resolve => outer.onload = resolve);
outer.src = '/domain-fixture.html';
document.body.append(outer);
await loaded;
try {
const observed = await outer.contentWindow.eval('(' + exercise.toString() + ')(' + JSON.stringify(config) + ')');
result.observations.push({scenario: config.name, document: observed.documentDiagnostics});
for (const [name, actual, expected] of observed.observations) check(config.name + ':' + name, actual, expected);
outer.remove();
await new Promise(resolve => setTimeout(resolve, 0));
check(config.name + ':both-retired', observed.late(), observed.allowedAfter ? '' : 'SecurityError');
} catch (error) {
check(config.name + ':setup', error.name + ': ' + error.message, 'no exception');
} finally {
outer.remove();
}
}
return result;
})