Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(window): honor top-level CSP sandbox origins and tokens

ldm0291a33ba9dd8
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 30b662de6..7d7130d0e 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
@@ -8,6 +8,9 @@ const WINDOW_ISOLATED_WORLD_SECURITY_TOKEN_PREFIX: &str = "moli-window-isolated-
impl JsContextHost {
pub(crate) fn main_default_world_security_token_key(&self) -> Option<String> {
+ if self.document_sandbox_policy().forces_opaque_origin {
+ return None;
+ }
let origin = moli_url::origin_ascii_serialization(self.document_url());
if self.document_domain_override.is_some() {
return None;
@@ -33,6 +36,9 @@ impl JsContextHost {
}
pub(crate) fn main_isolated_world_security_token_key(&self) -> Option<String> {
+ if self.document_sandbox_policy().forces_opaque_origin {
+ return None;
+ }
window_isolated_world_security_token_key(
moli_url::origin_ascii_serialization(self.document_url()),
self.document_domain_override.is_some(),
@@ -241,7 +247,7 @@ impl JsContextHost {
fn main_window_access_origin(&self) -> Option<WindowAccessOrigin> {
let serialized_origin = moli_url::origin_ascii_serialization(self.document_url());
- if serialized_origin == "null" {
+ if self.document_sandbox_policy().forces_opaque_origin || serialized_origin == "null" {
return Some(WindowAccessOrigin::opaque(
self.current_window_execution_context_owner(OwnerDispatchScope::Top)?,
));
diff --git a/moli-renderer-v8/src/script_vm/document_environment.rs b/moli-renderer-v8/src/script_vm/document_environment.rs
index dc29f888b..f34a45150 100644
--- a/moli-renderer-v8/src/script_vm/document_environment.rs
+++ b/moli-renderer-v8/src/script_vm/document_environment.rs
@@ -13,6 +13,18 @@ impl ScriptVm {
) {
self.document_runtime
.set_main_navigation_policy_container(policy);
+ // The main context exists before its navigation response policy is applied.
+ // Refresh its token so a CSP sandbox cannot retain the URL's tuple token.
+ let _ = self.with_default_context_scope(|scope, host_ptr| {
+ let key = unsafe { &*host_ptr }.main_default_world_security_token_key();
+ let context = scope.get_current_context();
+ if !crate::native_bridge::set_window_security_token(scope, context, key.as_deref()) {
+ tracing::warn!(
+ "failed to refresh main Window security token; using unique context token"
+ );
+ }
+ Ok(())
+ });
}
pub(crate) fn document_content_security_policies(&self) -> Vec<String> {
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs
index e68296f94..ee3c181aa 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs
@@ -2092,3 +2092,83 @@ fn iframe_sandbox_allow_same_origin_disallows_document_domain_after_document_ope
assert_eq!(result, "SecurityError:false:true:18");
}
+
+#[tokio::test(flavor = "current_thread")]
+async fn csp_sandbox_top_origin_blocks_tuple_documents_and_preserves_allow_same_origin() {
+ for opaque in [false, true] {
+ let server = StaticHttpServer::spawn(1).await;
+ let base = server.base_url();
+ let source = base.join("source.html").unwrap();
+ let destination = base.join("common/blank.html").unwrap();
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(source.as_str(), &loader);
+ vm.set_main_navigation_policy_container(crate::document_runtime::DocumentPolicyContainer {
+ response_content_security_policies: vec![if opaque {
+ "sandbox allow-scripts".into()
+ } else {
+ "sandbox allow-scripts allow-same-origin".into()
+ }],
+ ..Default::default()
+ });
+ vm.eval(r#"
+ if (!document.documentElement) document.appendChild(document.createElement('html'));
+ if (!document.body) document.documentElement.appendChild(document.createElement('body'));
+ globalThis.sandboxFrame=document.createElement('iframe');
+ globalThis.initialSandboxFrameReady=false;
+ sandboxFrame.onload=()=>initialSandboxFrameReady=true;
+ document.body.appendChild(sandboxFrame);
+ "#).unwrap();
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "initialSandboxFrameReady",
+ "true",
+ "initial sandbox document load",
+ )
+ .await;
+ assert_eq!(
+ vm.eval("sandboxFrame.contentDocument !== null").unwrap(),
+ if opaque { "false" } else { "true" },
+ "creation sandbox flags determine the initial document origin"
+ );
+ vm.eval(&format!(
+ r#"
+ globalThis.sandboxTupleResult='pending';
+ sandboxFrame.onload=()=>{{
+ let access;
+ try {{ access=typeof sandboxFrame.contentWindow.fetch; }}
+ catch(error) {{ access=error.name; }}
+ sandboxTupleResult=String(sandboxFrame.contentDocument===null)+'|'+access;
+ }};
+ sandboxFrame.src={url:?};
+ "#,
+ url = destination.as_str()
+ ))
+ .unwrap();
+ let expected = if opaque {
+ "true|SecurityError"
+ } else {
+ "false|function"
+ };
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "sandboxTupleResult",
+ expected,
+ "sandboxed top document access after child commit",
+ )
+ .await;
+ {
+ let host = vm._context_host.borrow();
+ assert_eq!(
+ host.main_default_world_security_token_key().is_none(),
+ opaque
+ );
+ assert_eq!(
+ host.main_isolated_world_security_token_key().is_none(),
+ opaque
+ );
+ }
+ assert_eq!(server.finish_targets().await, vec!["/common/blank.html"]);
+ }
+}