fix(navigation): retain auxiliary sandbox across document commits

Apply the sandbox flags stored on an auxiliary browsing context to each new document environment before parsing and realm bootstrap. Network responses must retain inherited origin, storage and script restrictions while keeping their own CSP constraints.

Cover direct window.open, hyperlink activation and an initial blank popup followed by network navigation. Check successive documents, opaque origins, cookie, localStorage and sessionStorage access, request Origin headers, script blocking, noscript parsing and explicit sandbox escape.
This commit is contained in:
ldm0
2026-11-20 22:48:01 +08:00
parent 1454127b45
commit d6325b3c3e
9 changed files with 389 additions and 18 deletions
@@ -9,6 +9,7 @@ mod document_open;
mod history_traversal;
mod lifecycle;
mod policy_inheritance;
mod sandbox;
async fn gated_page() -> (SameDocumentPage, Arc<ResponseGate>) {
let gate = Arc::new(ResponseGate {
@@ -0,0 +1,304 @@
use super::*;
const SANDBOX_DOCUMENT: &str = r#"<!doctype html><body><script>
if (opener) {
addEventListener('load', async () => {
const access = operation => {
try { operation(); return 'allowed'; } catch (error) { return error.name; }
};
const fetchOrigin = await fetch('/sandbox-origin-check', {method:'POST'})
.then(response => response.text());
opener.postMessage({
phase: location.pathname,
origin,
cookie: access(() => document.cookie),
storage: access(() => localStorage.getItem('sandbox-test')),
sessionStorage: access(() => sessionStorage.getItem('sandbox-test')),
fetchOrigin,
}, '*');
if (location.pathname === '/sandbox-creator') {
location.href = '/sandbox-successor';
}
}, {once:true});
} else {
const kind = new URL(location).searchParams.get('kind');
onmessage = event => {
if (event.data === 'start') {
if (kind === 'link') {
const link = document.createElement('a');
link.href = location.href;
link.target = '_blank';
link.rel = 'opener';
document.body.append(link);
link.click();
} else if (kind === 'blank') {
const popup = open();
popup.location.href = location.href;
}
} else {
parent.postMessage({frameOrigin:origin, messageOrigin:event.origin, facts:event.data}, '*');
}
};
if (kind === 'direct') open(location.href);
else parent.postMessage('sandbox-frame-ready', '*');
}
</script>"#;
#[tokio::test(flavor = "multi_thread")]
async fn auxiliary_windows_keep_inherited_sandbox_across_network_documents() {
run_history_test(async {
for kind in ["direct", "link", "blank"] {
for (sandbox, opaque) in [
("allow-scripts allow-popups", true),
(
"allow-scripts allow-popups allow-popups-to-escape-sandbox",
false,
),
("allow-scripts allow-popups allow-same-origin", false),
] {
let routes = axum::Router::new()
.route(
"/sandbox-creator",
axum::routing::get(|| async { axum::response::Html(SANDBOX_DOCUMENT) }),
)
.route(
"/sandbox-successor",
axum::routing::get(|| async { axum::response::Html(SANDBOX_DOCUMENT) }),
)
.route(
"/sandbox-origin-check",
axum::routing::post(|headers: axum::http::HeaderMap| async move {
(
[(axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")],
headers
.get(axum::http::header::ORIGIN)
.and_then(|value| value.to_str().ok())
.unwrap_or("<missing>")
.to_owned(),
)
}),
);
let mut page = SameDocumentPage::with_routes(routes).await;
let origin = url::Url::parse(&page.base_url)
.unwrap()
.origin()
.ascii_serialization();
let result = page
.evaluate(&format!(
r#"(async () => {{
const messages = [];
let finish;
const complete = new Promise(resolve => finish = resolve);
const frame = document.createElement('iframe');
let ready;
const frameReady = new Promise(resolve => ready = resolve);
addEventListener('message', event => {{
if (event.data === 'sandbox-frame-ready' && event.source === frame.contentWindow) {{
ready();
return;
}}
if (!event.data?.facts) return;
messages.push({{outerOrigin:event.origin, ...event.data}});
if (messages.length === 2) finish(messages);
}});
frame.sandbox = {sandbox:?};
frame.src = '/sandbox-creator?kind={kind}';
document.body.append(frame);
if ({kind:?} !== 'direct') {{
await frameReady;
frame.contentWindow.postMessage('start', '*');
}}
return complete;
}})()"#
))
.await;
let frame_origin = if sandbox.contains("allow-same-origin") {
origin.as_str()
} else {
"null"
};
let popup_origin = if opaque { "null" } else { origin.as_str() };
let access = if opaque { "SecurityError" } else { "allowed" };
let expected = ["/sandbox-creator", "/sandbox-successor"].map(|phase| {
json!({
"outerOrigin":frame_origin,
"frameOrigin":frame_origin,
"messageOrigin":popup_origin,
"facts": {"phase":phase, "origin":popup_origin,
"cookie":access, "storage":access, "sessionStorage":access,
"fetchOrigin":popup_origin},
})
});
assert_eq!(result, json!(expected), "{kind}/{sandbox}");
page.ctx
.process_and_wait_for_response_async(json!({
"id":1003, "method":"Target.getTargets", "params":{},
}))
.await;
let targets = take_response_by_id(&mut page.ctx, 1003);
assert!(targets["error"].is_null(), "{targets}");
let target = targets["result"]["targetInfos"]
.as_array()
.unwrap()
.iter()
.find(|target| {
target["url"]
.as_str()
.is_some_and(|url| url.ends_with("/sandbox-successor"))
})
.expect("successor popup should remain open for its protocol identity check")
["targetId"]
.as_str()
.unwrap()
.to_owned();
page.ctx
.process_and_wait_for_response_async(json!({
"id":1004, "method":"Target.attachToTarget",
"params":{"targetId":target,"flatten":true},
}))
.await;
let attached = take_response_by_id(&mut page.ctx, 1004);
assert!(attached["error"].is_null(), "{attached}");
let session = attached["result"]["sessionId"].as_str().unwrap();
let tree = page
.command_in_session(session, "Page.getFrameTree", json!({}))
.await;
// Blink projects Page.Frame.securityOrigin from the loader URL.
// The sandboxed origin is checked above through script and fetch.
assert_eq!(
tree["frameTree"]["frame"]["securityOrigin"],
origin.as_str(),
"{kind}/{sandbox}: {tree}"
);
page.ctx
.process_and_wait_for_response_async(json!({
"id":1005, "method":"Target.closeTarget",
"params":{"targetId":target},
}))
.await;
let closed = take_response_by_id(&mut page.ctx, 1005);
assert!(closed["error"].is_null(), "{closed}");
}
}
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn auxiliary_sandbox_script_restrictions_apply_before_parsing_network_documents() {
run_history_test(async {
for (sandbox, csp, scripts_allowed) in [
("allow-same-origin allow-popups", false, false),
("allow-same-origin allow-popups allow-scripts", false, true),
(
"allow-same-origin allow-popups allow-popups-to-escape-sandbox",
false,
true,
),
("allow-same-origin allow-popups allow-scripts", true, false),
] {
let routes = axum::Router::new().route(
"/sandbox-script-check",
axum::routing::get(move || async move {
let mut headers = axum::http::HeaderMap::new();
headers.insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("text/html"),
);
if csp {
headers.insert(
axum::http::header::CONTENT_SECURITY_POLICY,
axum::http::HeaderValue::from_static("sandbox allow-same-origin"),
);
}
(headers, "<!doctype html><body><noscript><p id=fallback>Fallback</p></noscript><script>globalThis.sandboxScriptDidRun = true;</script>")
}),
);
let mut page = SameDocumentPage::with_routes(routes).await;
page.evaluate(&format!(r#"(async () => {{
const frame = document.createElement('iframe');
frame.sandbox = {sandbox:?};
frame.srcdoc = '<p>Creator</p>';
const loaded = new Promise(resolve => frame.onload = () => {{
if (frame.contentDocument.URL === 'about:srcdoc') resolve();
}});
document.body.append(frame);
await loaded;
const link = frame.contentDocument.createElement('a');
link.href = '/sandbox-script-check';
link.target = '_blank';
link.rel = 'opener';
frame.contentDocument.body.append(link);
link.click();
return true;
}})()"#)).await;
let target = page.ctx.sent.iter().rev().find(|message| {
message["method"] == "Target.targetCreated"
&& message["params"]["targetInfo"]["url"].as_str()
.is_some_and(|url| url.ends_with("/sandbox-script-check"))
}).expect("sandboxed hyperlink should create an auxiliary target")
["params"]["targetInfo"]["targetId"].as_str().unwrap().to_owned();
page.ctx.process_and_wait_for_response_async(json!({
"id":1003, "method":"Target.attachToTarget",
"params":{"targetId":target,"flatten":true},
})).await;
let attached = take_response_by_id(&mut page.ctx, 1003);
assert!(attached["error"].is_null(), "{attached}");
let session = attached["result"]["sessionId"].as_str().unwrap().to_owned();
let first_url = url::Url::parse(&page.base_url).unwrap()
.join("/sandbox-script-check").unwrap().to_string();
let first = sandbox_popup_snapshot(&mut page, &session, &first_url).await;
let second_url = format!("{first_url}?successor");
page.command_in_session(&session, "Page.navigate", json!({"url":second_url})).await;
let second = sandbox_popup_snapshot(&mut page, &session, &second_url).await;
let result = json!([first, second]);
let expected = json!({"ran":scripts_allowed, "fallback":!scripts_allowed});
assert_eq!(result, json!([expected, expected]), "{sandbox}/csp={csp}");
}
}).await;
}
async fn sandbox_popup_snapshot(
page: &mut SameDocumentPage,
session: &str,
expected_url: &str,
) -> serde_json::Value {
page.command_in_session(session, "Page.enable", json!({}))
.await;
let mut tree = page
.command_in_session(session, "Page.getFrameTree", json!({}))
.await;
if tree["frameTree"]["frame"]["url"] != expected_url {
crate::testing::wait_until_scheduler_message(
&mut page.ctx,
"sandbox popup document commit",
|message| {
message["sessionId"] == session
&& message["method"] == "Page.frameNavigated"
&& message["params"]["frame"]["url"] == expected_url
},
)
.await;
tree = page
.command_in_session(session, "Page.getFrameTree", json!({}))
.await;
}
let frame = &tree["frameTree"]["frame"];
assert_eq!(frame["url"], expected_url, "{tree}");
crate::testing::wait_until_renderer_document_load(
&mut page.ctx,
Some(session),
frame["id"].as_str().unwrap(),
frame["loaderId"].as_str().unwrap(),
)
.await;
let result = page.command_in_session(session, "Runtime.evaluate", json!({
"expression":"({url:document.URL, ready:document.readyState, ran:globalThis.sandboxScriptDidRun === true, fallback:!!document.getElementById('fallback')})",
"returnByValue":true,
})).await;
assert!(result["exceptionDetails"].is_null(), "{result}");
let value = &result["result"]["value"];
assert_eq!(value["url"], expected_url);
assert_eq!(value["ready"], "complete");
json!({"ran":value["ran"],"fallback":value["fallback"]})
}
@@ -1095,8 +1095,10 @@ impl DocumentRuntime {
&mut self,
mut policy: DocumentPolicyContainer,
) {
policy.sandbox = DocumentSandboxPolicy::from_response_content_security_policies(
&policy.response_content_security_policies,
policy.sandbox = policy.sandbox.with_response_content_security_policy(
DocumentSandboxPolicy::from_response_content_security_policies(
&policy.response_content_security_policies,
),
);
self.policy_container = policy;
self.sync_document_resource_client_policy();
@@ -1083,7 +1083,9 @@ impl PageScriptHost {
};
browsing_context_name
.set(trackable_lightweight_popup_window_name(target_name).unwrap_or_default());
let auxiliary_window = self.browser_context_runtime.new_auxiliary_window();
let auxiliary_window = self
.browser_context_runtime
.new_auxiliary_window_with_sandbox(initial_policy_container.sandbox);
let popup_id = auxiliary_window.id();
let (window, facade_context) = self.bridge.bindings.instantiate_window_proxy_shell(scope);
let initial_document_owner = self.allocate_lightweight_popup_document_owner(popup_id);
+19 -1
View File
@@ -1279,6 +1279,22 @@ struct PageVmRendererDocumentIsolateBootstrap {
}
impl PageVmRuntimeHooks {
pub(in crate::runtime) fn apply_auxiliary_sandbox(&self, env: &mut PageVmEnvConfig) {
let window = self
.renderer_page_script_environment
.as_ref()
.and_then(|environment| environment.window_identity().auxiliary_window());
if let Some(window) = window {
// Auxiliary sandbox flags belong to the browsing context, so a
// network response cannot replace them with its own CSP policy.
// Apply them before parsing and before origin/storage bootstrap.
env.document_policy_container.sandbox = env
.document_policy_container
.sandbox
.with_response_content_security_policy(window.frame_sandbox());
}
}
pub(in crate::runtime) fn with_web_mcp_navigation(
mut self,
id: Option<moli_page_types::RendererWebMcpNavigation>,
@@ -4492,7 +4508,9 @@ impl PageVm {
env.document_policy_container = environment.policy_container.clone();
env
});
let env = inherited_env.as_ref().unwrap_or(env);
let mut document_env = inherited_env.as_ref().unwrap_or(env).clone();
runtime_hooks.apply_auxiliary_sandbox(&mut document_env);
let env = &document_env;
let backend_node_registry = new_shared_renderer_backend_node_registry();
let initial_document_loader_bootstrap =
crate::network::context::DocumentResourceLoaderBootstrap::new(
@@ -69,14 +69,16 @@ impl ConcurrentParseTimeRuntime {
html: String,
started: Instant,
) -> Result<ParseTimePageVmCreationOutcome> {
let mut env = env.clone();
runtime_hooks.apply_auxiliary_sandbox(&mut env);
let mut state = ParseTimeDriverState::new_with_scripting_enabled(
final_url.clone(),
main_document_parser_scripting_enabled(env),
main_document_parser_scripting_enabled(&env),
);
state
.buffered_document_preloads
.set_script_fetch_requires_owner_admission(script_preloads_require_owner_admission(
env,
&env,
));
state
.buffered_document_preloads
@@ -117,7 +119,7 @@ impl ConcurrentParseTimeRuntime {
page_id,
local_executor.clone(),
loader.clone(),
env.clone(),
env,
runtime_hooks,
state,
started,
@@ -116,6 +116,7 @@ fn script_preloads_require_owner_admission(env: &PageVmEnvConfig) -> bool {
pub(in crate::runtime) fn main_document_parser_scripting_enabled(env: &PageVmEnvConfig) -> bool {
!env.document_settings.script_execution_disabled
&& env.document_policy_container.sandbox.allows_scripts
&& crate::content_security_policy::content_security_policy_sandbox_allows_scripts(
&env.document_policy_container
.response_content_security_policies,
@@ -281,6 +281,7 @@ impl ConcurrentParseTimeRuntime {
debug_assert!(!response_headers_indicate_download(&response_headers));
let mut env = env.clone();
env.apply_navigation_response_metadata(&final_url, response_status, &response_headers);
runtime_hooks.apply_auxiliary_sandbox(&mut env);
let content_type = content_type.or_else(|| {
moli_web_mime::navigation_response_mime_type_from_headers(&response_headers)
+51 -11
View File
@@ -2058,10 +2058,6 @@ impl ScriptVmPageRealmBootstrap {
{
dom_host.set_document_fallback_base_url_for_handle(document_handle, Some(base));
}
let top_level_storage_key = initial_environment
.as_ref()
.and_then(|environment| environment.storage_key.clone())
.or(top_level_storage_key);
let document_url = dom_host
.dom()
.final_url()
@@ -2070,14 +2066,55 @@ impl ScriptVmPageRealmBootstrap {
let document_base_url = dom_host
.document_base_url_for_handle(document_handle)
.unwrap_or_else(|| document_url.clone());
let initial_origin = initial_environment
.as_ref()
.map(|environment| environment.origin.clone())
.unwrap_or_else(|| moli_url::origin_ascii_serialization(&document_url));
let initial_policy = initial_environment
let creation_sandbox = initial_policy.sandbox;
let mut initial_policy = initial_environment
.as_ref()
.map(|environment| environment.policy_container.clone())
.unwrap_or(initial_policy);
initial_policy.sandbox = initial_policy
.sandbox
.with_response_content_security_policy(creation_sandbox);
let sandbox_forces_opaque_origin = initial_policy.sandbox.forces_opaque_origin;
let initial_origin = if sandbox_forces_opaque_origin {
"null".to_owned()
} else {
initial_environment
.as_ref()
.map(|environment| environment.origin.clone())
.unwrap_or_else(|| moli_url::origin_ascii_serialization(&document_url))
};
let top_level_storage_key = initial_environment
.as_ref()
.and_then(|environment| environment.storage_key.clone())
.or(top_level_storage_key);
let top_level_storage_key = if sandbox_forces_opaque_origin {
// Sandboxing creates a fresh opaque Document origin even for an
// HTTP URL. Use it before creating storage and service worker
// clients, preserving only the supplied partition metadata.
let top_level_site = top_level_storage_key
.as_ref()
.map(|key| key.top_level_site().to_owned())
.unwrap_or_else(|| moli_storage_key::site_for_url(&document_url));
let relation = moli_storage_key::StoragePartitionRelation::from_sites(
&moli_storage_key::site_for_url(&document_url),
&top_level_site,
);
let mut key = moli_storage_key::MoliStorageKey::new(
initial_origin.clone(),
top_level_site,
Some(browser_context_runtime.next_web_storage_opaque_context_nonce()),
relation,
);
if top_level_storage_key
.as_ref()
.is_some_and(|key| key.has_cross_site_ancestor())
{
key = key.with_cross_site_ancestor();
}
Some(key)
} else {
top_level_storage_key
};
let mut frame_owner_store = FrameOwnerStore::default();
frame_owner_store.ensure_main_frame(
document_handle,
@@ -2097,6 +2134,7 @@ impl ScriptVmPageRealmBootstrap {
.expect("main Document must own a LocalWindow")
.inherited_opaque_origin = initial_environment
.as_ref()
.filter(|_| !sandbox_forces_opaque_origin)
.and_then(|environment| environment.opaque_origin.clone());
let post_domcontentloaded_page_task_tx = page_task_tx.page_task_sender();
let page_runtime_wake_tx = page_task_tx.page_runtime_wake_sender();
@@ -2125,9 +2163,11 @@ impl ScriptVmPageRealmBootstrap {
let inherited_document_domain = initial_environment
.as_ref()
.filter(|_| !sandbox_forces_opaque_origin)
.map(|environment| environment.document_domain_override.clone());
let inherited_security_token =
initial_environment.and_then(|environment| environment.security_token);
let inherited_security_token = initial_environment
.filter(|_| !sandbox_forces_opaque_origin)
.and_then(|environment| environment.security_token);
let RendererDocumentIsolateBootstrap {
initial_document_environment: _,
renderer_document_isolate,