diff --git a/moli-renderer-v8/src/agent_cluster.rs b/moli-renderer-v8/src/agent_cluster.rs new file mode 100644 index 00000000000..f5d6d82ffda --- /dev/null +++ b/moli-renderer-v8/src/agent_cluster.rs @@ -0,0 +1,70 @@ +use crate::{resource_owner::ResourceOwnerId, runtime::RendererStoragePartitionIdentity}; +use std::sync::Arc; + +/// Native identity shared by Window access checks and shared-memory cloning. +/// Permissions Policy controls API exposure separately from this identity. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct AgentClusterIdentity(Arc); + +#[derive(Debug, Eq, PartialEq)] +enum AgentClusterKey { + Window { + partition: RendererStoragePartitionIdentity, + origin: String, + isolation: WindowAgentClusterIsolation, + }, + Worker(ResourceOwnerId), +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum WindowAgentClusterIsolation { + CoopCoep { isolation_origin: String }, + DocumentIsolation, +} + +impl AgentClusterIdentity { + pub(crate) fn window( + partition: RendererStoragePartitionIdentity, + origin: String, + isolation: WindowAgentClusterIsolation, + ) -> Self { + Self(Arc::new(AgentClusterKey::Window { + partition, + origin, + isolation, + })) + } + + pub(crate) fn worker(owner: ResourceOwnerId) -> Self { + Self(Arc::new(AgentClusterKey::Worker(owner))) + } + + pub(crate) fn window_security_token_key(&self, prefix: &str) -> Option { + let AgentClusterKey::Window { + partition, + origin, + isolation, + } = self.0.as_ref() + else { + return None; + }; + let (kind, common_origin) = match isolation { + WindowAgentClusterIsolation::CoopCoep { isolation_origin } => { + ("coop-coep", isolation_origin.as_str()) + } + WindowAgentClusterIsolation::DocumentIsolation => ("document", origin.as_str()), + }; + let browser = partition.browser_context_id(); + let profile = partition.profile_partition_id(); + // Lengths make the representation injective even for arbitrary native + // partition identifiers. The caller supplies a distinct world namespace. + Some(format!( + "{prefix}{}:{browser}{}:{profile}{}:{origin}{}:{kind}{}:{common_origin}", + browser.len(), + profile.len(), + origin.len(), + kind.len(), + common_origin.len(), + )) + } +} diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/origin.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/origin.rs index 4ad3702a992..7f6d8a97757 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_runtime/origin.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/origin.rs @@ -35,9 +35,18 @@ pub(super) fn refresh_from_current_context<'s>( location: v8::Local<'s, v8::Object>, ) { let location = location_target(scope, location); + if location.get_creation_context(scope) != Some(scope.get_current_context()) { + // A replacement Window may still be adopting its proxy. Its old + // Location belongs to the retired realm and must keep that snapshot. + return; + } let Some(origin) = WindowSecurityOrigin::for_context(scope.get_current_context()) else { return; }; + if for_target(scope, location).is_none() { + install(scope, location); + return; + } let Some(value) = location.get_internal_field(scope, SECURITY_ORIGIN_FIELD) else { return; }; diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs index 540fc05b2b7..21a391a211a 100644 --- a/moli-renderer-v8/src/lib.rs +++ b/moli-renderer-v8/src/lib.rs @@ -29,6 +29,7 @@ pub use app_manifest::{ mod abort_signal_route; #[cfg(feature = "ace-protocol")] pub mod ace_page_task; +mod agent_cluster; mod app_manifest; mod blob; mod broadcast_channel_runtime; diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs index d8b7d891a94..2571c713d4a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs @@ -99,6 +99,12 @@ impl PageScriptHost { .is_some(); let security_origin_allows_reuse = creation_kind != DocumentCreationKind::Error && !current_document_domain_was_set + && self.window_agent_cluster(OwnerDispatchScope::Child(handle)) + == self.window_agent_cluster_for_policy( + OwnerDispatchScope::Child(handle), + &snapshot.policy_container, + origin.clone(), + ) && preflight .current_access_origin .as_ref() diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs index fe6ff3663ad..03ec854ecb9 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -85,7 +85,13 @@ impl PageScriptHost { }; crate::frame_owner_model::FrameDocumentLocalWindowTransition::for_document_commit( self.initial_empty_main_document, - same_origin, + same_origin + && self.window_agent_cluster(OwnerDispatchScope::Top) + == self.window_agent_cluster_for_policy( + OwnerDispatchScope::Top, + policy, + origin.to_owned(), + ), self.document_policy_container(), policy, ) diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index 0b7b955cfb2..d59127e53fe 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -1136,6 +1136,11 @@ impl PageScriptHost { None } .unwrap_or_default(); + let initial_agent_cluster = self.window_agent_cluster_for_policy( + OwnerDispatchScope::LightweightPopup(popup_id), + &initial_document_state.policy_container, + initial_origin.serialized_origin(), + ); let session_storage_store = match opener { Some(opener) => self.cloned_lightweight_popup_session_storage_store( scope, @@ -1169,6 +1174,7 @@ impl PageScriptHost { super::window_security_tokens::PopupWindowSecurityOrigin { origin: initial_origin, domain: initial_domain, + agent_cluster: initial_agent_cluster, }, )), secure_context, @@ -2427,6 +2433,11 @@ impl PageScriptHost { }; let retained_access_origin = current_document.access_origin.borrow().current_origin(); let retained_origin_state = current_document.access_origin.clone(); + let retained_agent_cluster = current_document + .access_origin + .borrow() + .agent_cluster + .clone(); let domain = if matches!( commit.origin, LightweightPopupDocumentCommitOrigin::RetainCurrent @@ -2469,11 +2480,17 @@ impl PageScriptHost { } } }; + let agent_cluster = self.window_agent_cluster_for_policy( + OwnerDispatchScope::LightweightPopup(popup_id), + &commit.state.policy_container, + access_origin.serialized_origin(), + ); // The first same-origin navigation can reuse the initial Window even // though it commits a new Document and its own resource authority. let reuse_initial_window = changed_document && was_initial_empty && !document_domain_was_set + && retained_agent_cluster == agent_cluster && retained_access_origin.can_access(&access_origin); if reuse_initial_window { current_local_window_id = previous_local_window_id; @@ -2490,6 +2507,7 @@ impl PageScriptHost { let access_origin = super::window_security_tokens::PopupWindowSecurityOrigin { origin: access_origin, domain, + agent_cluster, }; let access_origin = if changed_window { Rc::new(RefCell::new(access_origin)) diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs index fa2383a8902..778b6c92d70 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs @@ -927,11 +927,13 @@ impl PageScriptHost { if !policy .cross_origin_embedder_policy .enables_cross_origin_isolation() + && !policy.credentialless { return false; } - // COOP chooses the top-level group's mode. A COEP-only child joins it; - // a child's own COOP header cannot isolate an otherwise ordinary group. + // COOP chooses the top-level group's mode. A COEP child, or a + // credentialless Document exempt from COEP embedding checks, joins it. + // A child's own COOP cannot isolate an otherwise ordinary group. match self.child_browsing_context_root_scope(handle) { Some(OwnerDispatchScope::Top) => self.document_policy_container().coop_coep_isolation, Some(OwnerDispatchScope::LightweightPopup(id)) => self @@ -948,38 +950,52 @@ impl PageScriptHost { if !self.window_cross_origin_isolated(owner) { return None; } - let dip = match owner { - OwnerDispatchScope::Top => self.document_isolation_policy(), - OwnerDispatchScope::Child(handle) => { - let policy = self.child_browsing_context_policy_container_snapshot(handle)?; - policy.document_isolation_policy - } - OwnerDispatchScope::LightweightPopup(id) => { - let policy = self.lightweight_popup_policy_container(id)?; - policy.document_isolation_policy - } - }; + self.window_agent_cluster(owner) + } + + pub(super) fn window_agent_cluster( + &self, + owner: OwnerDispatchScope, + ) -> Option { + let policy = self.window_policy_container(owner)?; let origin = self.window_document_origin(owner)?; - // DIP supplies its own isolation origin; otherwise the top-level - // isolation origin is inherited, independently from the document origin. - let isolation_origin = if dip.enables_cross_origin_isolation() { - origin.clone() - } else { - let root = match owner { - OwnerDispatchScope::Child(handle) => { - self.child_browsing_context_root_scope(handle)? - } - root => root, - }; - self.window_document_origin(root)? - }; - if origin == "null" || isolation_origin == "null" { + self.window_agent_cluster_for_policy(owner, &policy, origin) + } + + pub(super) fn window_agent_cluster_for_policy( + &self, + owner: OwnerDispatchScope, + policy: &DocumentPolicyContainer, + origin: String, + ) -> Option { + use crate::agent_cluster::{AgentClusterIdentity, WindowAgentClusterIsolation}; + + if origin == "null" + || !self.window_agent_cluster_is_cross_origin_isolated_with_policy(owner, policy) + { return None; } - Some(crate::structured_clone::SharedMemoryAgentCluster::window( + let isolation = if policy + .document_isolation_policy + .enables_cross_origin_isolation() + { + WindowAgentClusterIsolation::DocumentIsolation + } else { + let isolation_origin = match owner { + OwnerDispatchScope::Child(handle) => { + self.window_document_origin(self.child_browsing_context_root_scope(handle)?)? + } + OwnerDispatchScope::Top | OwnerDispatchScope::LightweightPopup(_) => origin.clone(), + }; + if isolation_origin == "null" { + return None; + } + WindowAgentClusterIsolation::CoopCoep { isolation_origin } + }; + Some(AgentClusterIdentity::window( self.browser_context_runtime().storage_partition_identity(), origin, - isolation_origin, + isolation, )) } diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs index 5f29833f79a..cf65211c1be 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs @@ -21,6 +21,7 @@ pub(crate) struct WindowEnvironmentSettings { access_origin: WindowAccessOrigin, domain_owner_document: DomHandle, execution_identity: WindowExecutionContextIdentity, + agent_cluster: Option, } impl WindowEnvironmentSettings { @@ -52,6 +53,7 @@ impl WindowEnvironmentSettings { access_origin, domain_owner_document, execution_identity, + agent_cluster: host.window_agent_cluster(OwnerDispatchScope::Child(child_handle)), })); Some(()) } @@ -80,6 +82,7 @@ impl WindowEnvironmentSettings { access_origin, domain_owner_document: host.document_handle(), execution_identity, + agent_cluster: host.window_agent_cluster(OwnerDispatchScope::Top), })); Some(()) } @@ -98,6 +101,9 @@ impl WindowEnvironmentSettings { if self.execution_identity.grants_universal_access() { return true; } + if self.agent_cluster != target_host.window_agent_cluster(target.dispatch_scope()) { + return false; + } // Retiring a resource loader must not turn an inherited origin into // the origin of its about:blank URL. Keep that origin, while observing // domain changes on the exact Document that owns the shared origin. diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs index acf2f377fb5..b3deb2e12a7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs @@ -4,11 +4,15 @@ use super::{ WindowExecutionContextOwner, child_frames::{ChildAncestorOriginsReferrerPolicy, ChildBrowsingContextEntry}, }; +use crate::agent_cluster::AgentClusterIdentity; 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:"; +const WINDOW_CLUSTER_SECURITY_TOKEN_PREFIX: &str = "moli-window-agent-cluster-v1:"; +const WINDOW_ISOLATED_CLUSTER_SECURITY_TOKEN_PREFIX: &str = + "moli-window-isolated-agent-cluster-v1:"; pub(crate) fn window_contexts_allow_access( scope: &mut v8::PinScope<'_, '_>, @@ -137,6 +141,7 @@ struct WindowContextSecurityOrigin { origin: WindowAccessOrigin, domain: Option, access_policy: WindowExecutionContextAccessPolicy, + agent_cluster: Option, } /// The origin of a particular LocalWindow, including virtual popup realms. @@ -166,6 +171,7 @@ enum WindowSecurityOriginSource { pub(super) struct PopupWindowSecurityOrigin { pub(super) origin: WindowAccessOrigin, pub(super) domain: DocumentDomainState, + pub(super) agent_cluster: Option, } impl PopupWindowSecurityOrigin { @@ -206,7 +212,15 @@ impl WindowSecurityOrigin { pub(crate) fn can_access(&self, target: &Self) -> bool { matches!(&self.0, WindowSecurityOriginSource::Context(origin) if origin.access_policy == WindowExecutionContextAccessPolicy::Universal) - || self.current_origin().can_access(&target.current_origin()) + || (self.agent_cluster() == target.agent_cluster() + && self.current_origin().can_access(&target.current_origin())) + } + + fn agent_cluster(&self) -> Option { + match &self.0 { + WindowSecurityOriginSource::Context(origin) => origin.agent_cluster.clone(), + WindowSecurityOriginSource::Popup(origin) => origin.borrow().agent_cluster.clone(), + } } } @@ -420,8 +434,11 @@ impl PageScriptHost { origin, domain, access_policy, + agent_cluster: self.window_agent_cluster(dispatch_scope), })); self.retain_window_global_csp_context(context); + let scope = &mut v8::ContextScope::new(scope, context); + crate::context_bootstrap::refresh_global_location_security_origin(scope); } pub(in crate::native_bridge::context_host) fn window_context_origins_allow_access( @@ -436,9 +453,10 @@ impl PageScriptHost { return false; }; accessing.access_policy == WindowExecutionContextAccessPolicy::Universal - || accessing - .current_origin() - .can_access(&accessed.current_origin()) + || (accessing.agent_cluster == accessed.agent_cluster + && accessing + .current_origin() + .can_access(&accessed.current_origin())) } pub(in crate::native_bridge::context_host) fn child_ancestor_origins_referrer_policy_from_owner_attribute( @@ -522,7 +540,7 @@ impl PageScriptHost { if self.document_domain_override.get().is_some() { return None; } - window_security_token_key(origin) + self.window_default_world_token_for_agent_cluster(OwnerDispatchScope::Top, origin) } pub(crate) fn popup_default_world_security_token_key(&self, popup_id: u64) -> Option { @@ -534,7 +552,10 @@ impl PageScriptHost { { return None; } - window_security_token_key(origin.serialized_origin()) + self.window_default_world_token_for_agent_cluster( + OwnerDispatchScope::LightweightPopup(popup_id), + origin.serialized_origin(), + ) } pub(crate) fn child_default_world_security_token_key( @@ -551,7 +572,20 @@ impl PageScriptHost { { return None; } - window_security_token_key(origin) + self.window_default_world_token_for_agent_cluster(OwnerDispatchScope::Child(handle), origin) + } + + fn window_default_world_token_for_agent_cluster( + &self, + owner: OwnerDispatchScope, + origin: String, + ) -> Option { + match self.window_agent_cluster(owner) { + Some(cluster) => { + cluster.window_security_token_key(WINDOW_CLUSTER_SECURITY_TOKEN_PREFIX) + } + None => window_security_token_key(origin), + } } pub(crate) fn install_child_default_world_security_token( @@ -584,7 +618,8 @@ impl PageScriptHost { if self.document_sandbox_policy().forces_opaque_origin { return None; } - window_isolated_world_security_token_key( + self.window_isolated_world_token_for_agent_cluster( + OwnerDispatchScope::Top, self.main_document_origin(), self.document_domain_override.get().is_some(), ) @@ -598,13 +633,29 @@ impl PageScriptHost { return None; } let origin = self.child_browsing_context_window_origin(handle)?; - window_isolated_world_security_token_key( + self.window_isolated_world_token_for_agent_cluster( + OwnerDispatchScope::Child(handle), origin, self.child_browsing_context_document_domain_override(handle) .is_some(), ) } + fn window_isolated_world_token_for_agent_cluster( + &self, + owner: OwnerDispatchScope, + origin: String, + document_domain_was_set: bool, + ) -> Option { + let origin_key = window_isolated_world_security_token_key(origin, document_domain_was_set)?; + match self.window_agent_cluster(owner) { + Some(cluster) => { + cluster.window_security_token_key(WINDOW_ISOLATED_CLUSTER_SECURITY_TOKEN_PREFIX) + } + None => Some(origin_key), + } + } + pub(crate) fn refresh_security_tokens_after_document_domain_mutation( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -790,7 +841,11 @@ impl PageScriptHost { let Some(child) = self.child_window_access_origin(handle) else { return false; }; - top.can_access(&child) + self.window_agent_clusters_match( + OwnerDispatchScope::Top, + self, + OwnerDispatchScope::Child(handle), + ) && top.can_access(&child) } pub(crate) fn frame_owner_can_access_content_document(&self, handle: DomHandle) -> bool { @@ -808,12 +863,14 @@ impl PageScriptHost { } else { return false; }; - // HTML's content document algorithm compares the container's node - // Document with the active child Document, using same origin-domain. - // Neither the top-level Window nor the callback's realm is its owner. - self.window_access_origin_for_dispatch_scope(owner_scope) - .zip(self.child_window_access_origin(handle)) - .is_some_and(|(owner, child)| owner.can_access(&child)) + // The returned Document also passes the native Window agent-cluster + // check. The container's node Document owns this access, independently + // from the callback's realm or the top-level Window. + self.window_agent_clusters_match(owner_scope, self, OwnerDispatchScope::Child(handle)) + && self + .window_access_origin_for_dispatch_scope(owner_scope) + .zip(self.child_window_access_origin(handle)) + .is_some_and(|(owner, child)| owner.can_access(&child)) } pub(in crate::native_bridge::context_host) fn accessing_context_can_access_child_window( @@ -842,18 +899,19 @@ impl PageScriptHost { } // Opaque identities are host-local; only tuple origins can be compared // between hosts before the target has materialized a V8 Context. - accessing_host - .window_access_origin(identity) - .zip(self.child_window_access_origin(handle)) - .is_some_and(|(origin, target)| { - matches!( - (&origin, &target), - ( - WindowAccessOrigin::Tuple { .. }, - WindowAccessOrigin::Tuple { .. } - ) - ) && origin.can_access(&target) - }) + accessing_host.window_agent_clusters_match(identity.dispatch_scope(), self, target) + && accessing_host + .window_access_origin(identity) + .zip(self.child_window_access_origin(handle)) + .is_some_and(|(origin, target)| { + matches!( + (&origin, &target), + ( + WindowAccessOrigin::Tuple { .. }, + WindowAccessOrigin::Tuple { .. } + ) + ) && origin.can_access(&target) + }) } /// Compares the Window's origin with its top-level origin without applying @@ -911,6 +969,13 @@ impl PageScriptHost { if accessing.grants_universal_access() { return true; } + if !self.window_agent_clusters_match( + accessing.dispatch_scope(), + target_host, + accessed.dispatch_scope(), + ) { + return false; + } let Some(origin) = self.window_access_origin(accessing) else { return false; }; @@ -954,6 +1019,9 @@ impl PageScriptHost { if accessing.owner() == accessed_owner { return true; } + if !self.window_agent_clusters_match(accessing.dispatch_scope(), self, accessed_scope) { + return false; + } let Some(accessing_origin) = self.window_access_origin(accessing) else { return false; }; @@ -964,6 +1032,15 @@ impl PageScriptHost { accessing_origin.can_access(&accessed_origin) } + fn window_agent_clusters_match( + &self, + source: OwnerDispatchScope, + target_host: &Self, + target: OwnerDispatchScope, + ) -> bool { + self.window_agent_cluster(source) == target_host.window_agent_cluster(target) + } + fn window_access_origin( &self, identity: WindowExecutionContextIdentity, diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index f771f99a676..2b46acffc2d 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2635,6 +2635,7 @@ mod window_scheduling_receivers; mod window_immutable_prototype_chain; +mod window_agent_clusters; mod window_getter_consolidation; mod window_node_events; #[cfg(feature = "devtools")] diff --git a/moli-renderer-v8/src/script_vm/tests/window_agent_clusters.rs b/moli-renderer-v8/src/script_vm/tests/window_agent_clusters.rs new file mode 100644 index 00000000000..76ec9a6534b --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/window_agent_clusters.rs @@ -0,0 +1,150 @@ +use super::*; + +const DIP: &str = "Document-Isolation-Policy: isolate-and-require-corp\r\n"; +const DIP_CREDENTIALLESS: &str = "Document-Isolation-Policy: isolate-and-credentialless\r\n"; +const COEP: &str = "Cross-Origin-Embedder-Policy: require-corp\r\n"; +const COOP_COEP: &str = + "Cross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Embedder-Policy: require-corp\r\n"; +const DIP_COEP: &str = "Document-Isolation-Policy: isolate-and-require-corp\r\nCross-Origin-Embedder-Policy: require-corp\r\n"; +const DENIED_COOP_COEP: &str = "Cross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Embedder-Policy: require-corp\r\nPermissions-Policy: cross-origin-isolated=()\r\n"; + +#[tokio::test(flavor = "current_thread")] +async fn window_access_and_shared_memory_follow_native_agent_clusters() { + for (root_headers, child_headers, credentialless, allowed, shared, child_isolated) in [ + ("", DIP, false, false, false, true), + (DIP, "", false, false, false, false), + (DIP, DIP_CREDENTIALLESS, false, true, true, true), + (COOP_COEP, COEP, false, true, true, true), + (DENIED_COOP_COEP, COEP, false, true, false, false), + (COOP_COEP, DIP_COEP, false, false, true, true), + ("", COEP, false, true, false, false), + (COOP_COEP, "", true, true, true, true), + (DENIED_COOP_COEP, "", true, true, false, false), + ] { + let server = StaticHttpServer::spawn_with_raw_responder(1, move |_, _| { + let body = r#""#; + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n{child_headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + }) + .await; + let loader = static_http_loader([server.resolve_entry("localhost")]); + let root_url = server.url_for_host("localhost", "/root"); + let child_url = server.url_for_host("localhost", "/child"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(root_url.as_str(), &loader); + let headers = root_headers + .lines() + .map(|line| { + let (name, value) = line.split_once(':').unwrap(); + (name.to_owned(), value.trim().as_bytes().to_vec()) + }) + .collect::>(); + vm.set_main_navigation_policy_container( + crate::document_runtime::DocumentPolicyContainer::from_navigation_response_headers( + &headers, &root_url, + ), + ); + vm.eval(&format!( + r#" +globalThis.clusterReady = null; +globalThis.clusterShared = null; +onmessage = event => {{ + if (event.data.kind === 'ready') clusterReady = event.data; + if (event.data.kind === 'shared') clusterShared = event.data.value; +}}; +const root = document.documentElement || document.appendChild(document.createElement('html')); +const body = document.body || root.appendChild(document.createElement('body')); +body.appendChild(Object.assign(document.createElement('iframe'), {{id:'target', credentialless:{credentialless}, src:{:?}}})); +"#, + child_url.as_str() + )) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(clusterReady !== null)", + "true", + "the child agent must report through the cross-origin-allowed postMessage surface", + ) + .await; + let result = vm + .eval( + r#"JSON.stringify((() => { + const frame = document.getElementById('target'); + const attempt = callback => { try { return callback(); } catch (error) { return error.name; } }; + return {contentDocument:frame.contentDocument !== null, + read:attempt(() => frame.contentWindow.document.nodeType === 9), + write:attempt(() => {frame.contentWindow.nativeProbe = true; return true;}), + location:attempt(() => new URL(frame.contentWindow.location.href).hostname === location.hostname), + child:clusterReady.value, childLocation:clusterReady.location, childIsolated:clusterReady.isolated, + postMessage:clusterReady.postMessage, frames:clusterReady.frames}; +})())"#, + ) + .unwrap(); + let expected_access = if allowed { + serde_json::json!(true) + } else { + serde_json::json!("SecurityError") + }; + assert_eq!( + serde_json::from_str::(&result).unwrap(), + serde_json::json!({"contentDocument":allowed, "read":expected_access, + "write":expected_access,"location":expected_access,"child":expected_access, + "childLocation":expected_access,"childIsolated":child_isolated, + "postMessage":"function","frames":"object"}), + "root={root_headers:?}, child={child_headers:?}, credentialless={credentialless}" + ); + for universal in [false, true] { + let world = vm + .create_isolated_world( + if universal { + "agent-cluster-universal" + } else { + "agent-cluster-restricted" + }, + universal, + ) + .unwrap(); + assert_eq!( + vm.eval_in_isolated_context( + world, + r#"(() => { + try { return String(document.getElementById('target').contentWindow.document.nodeType === 9); } + catch (error) { return error.name; } +})()"# + ) + .unwrap(), + if universal || allowed { + "true" + } else { + "SecurityError" + }, + "universal={universal}, root={root_headers:?}, child={child_headers:?}" + ); + } + if shared { + vm.eval("document.getElementById('target').contentWindow.postMessage(new SharedArrayBuffer(4), '*')") + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(clusterShared)", + if allowed { "shared" } else { "messageerror" }, + "shared memory must use the same cluster boundary as DOM access", + ) + .await; + } + assert_eq!(server.finish_targets().await, ["/child"]); + } +} diff --git a/moli-renderer-v8/src/structured_clone.rs b/moli-renderer-v8/src/structured_clone.rs index 8a43b167931..22c23d65055 100644 --- a/moli-renderer-v8/src/structured_clone.rs +++ b/moli-renderer-v8/src/structured_clone.rs @@ -80,39 +80,7 @@ const GEOMETRY_KIND_DOM_MATRIX: u32 = 6; // Kind 4 remains readable for existing numeric Quad payloads. const GEOMETRY_KIND_DOM_QUAD_REFERENCES: u32 = 7; -/// Native shared-memory identity. Compatible isolated Window agents can share -/// a cluster even across unrelated browsing contexts. Dedicated Workers inherit -/// their creator's identity; top-level Worker agents receive a fresh identity. -#[derive(Clone, Debug, Eq, PartialEq)] -pub(crate) struct SharedMemoryAgentCluster(Arc); - -#[derive(Debug, Eq, PartialEq)] -enum SharedMemoryAgentClusterKey { - Window { - partition: crate::runtime::RendererStoragePartitionIdentity, - origin: String, - isolation_origin: String, - }, - Worker(crate::resource_owner::ResourceOwnerId), -} - -impl SharedMemoryAgentCluster { - pub(crate) fn window( - partition: crate::runtime::RendererStoragePartitionIdentity, - origin: String, - isolation_origin: String, - ) -> Self { - Self(Arc::new(SharedMemoryAgentClusterKey::Window { - partition, - origin, - isolation_origin, - })) - } - - pub(crate) fn worker(owner: crate::resource_owner::ResourceOwnerId) -> Self { - Self(Arc::new(SharedMemoryAgentClusterKey::Worker(owner))) - } -} +pub(crate) use crate::agent_cluster::AgentClusterIdentity as SharedMemoryAgentCluster; #[derive(Debug)] struct ClonedSharedMemory {