fix(service-worker): preserve child frame storage partitions

Reserve navigation clients after the actual request partition and credentialless nonce are known, then preserve that key when the Window client commits. Popup descendants inherit the popup storage partition instead of the opener top-level site.

Keep same-partition ServiceWorker control and localStorage sharing while isolating identical frame origins embedded under a different top-level site. Validate both outcomes over trusted TLS and retain reserved-client visibility checks.
This commit is contained in:
ldm0
2026-11-20 22:48:01 +08:00
parent 7e908e9501
commit 4e1a60fcb4
8 changed files with 186 additions and 32 deletions
@@ -196,6 +196,18 @@ impl PageScriptHost {
&bootstrap,
credentialless_storage_nonce,
);
// Reserve the navigation client only after its actual storage partition
// (including a credentialless nonce) is known. The eventual committed
// client must use the same partition as this main-resource request.
if let Some(storage_key) = network_partition_key.as_ref() {
self.register_reserved_service_worker_child_client_for_navigation(
handle,
&target_url,
storage_key.clone(),
);
} else {
self.clear_pending_service_worker_child_client(handle);
}
let browser_context_runtime = self.browser_context_runtime();
let service_worker_client_id = self
.child_browsing_contexts
@@ -90,7 +90,6 @@ impl PageScriptHost {
return false;
}
let download_policy = self.capture_child_navigation_download_policy(scope, handle);
self.register_reserved_service_worker_child_client_for_navigation(handle, &url);
let queued = self.queue_child_browsing_context_navigation_commit(handle);
self.remember_child_navigation_download_policy(handle, download_policy, queued)
}
@@ -289,7 +288,6 @@ impl PageScriptHost {
{
return false;
}
self.register_reserved_service_worker_child_client_for_navigation(handle, &url);
let queued = self.queue_child_browsing_context_navigation_commit(handle);
self.remember_child_navigation_download_policy(handle, download_policy, queued)
}
@@ -287,7 +287,6 @@ impl PageScriptHost {
{
return false;
}
self.register_reserved_service_worker_child_client_for_navigation(handle, url);
self.queue_child_browsing_context_navigation_commit(handle)
}
@@ -753,20 +753,6 @@ impl PageScriptHost {
"The navigation was canceled.".to_owned(),
);
}
let pending_attribute_url =
self.child_browsing_contexts.get(&handle).and_then(|entry| {
entry
.pending_attribute_bootstrap_commit()
.then(|| {
Self::child_browsing_context_navigation_entry_url(
entry.attribute_bootstrap(),
)
})
.flatten()
});
if let Some(url) = pending_attribute_url.as_ref() {
self.register_reserved_service_worker_child_client_for_navigation(handle, url);
}
if is_new {
self.cancel_child_meta_refresh_navigation(handle);
self.disconnect_shared_worker_clients_for_child_context(handle);
@@ -315,7 +315,13 @@ impl PageScriptHost {
current = self.child_browsing_context_parent_handle(handle);
}
let mut inherited_scope = self.web_storage_scope_for_top_document_origin(top_origin);
let mut inherited_scope = match self.child_browsing_context_root_scope(handle)? {
OwnerDispatchScope::Top => self.web_storage_scope_for_top_document_origin(top_origin),
OwnerDispatchScope::LightweightPopup(popup_id) => {
self.lightweight_popup_bound_web_storage_scope(popup_id)?
}
OwnerDispatchScope::Child(_) => return None,
};
for handle in ancestry.into_iter().rev() {
inherited_scope =
self.child_browsing_context_web_storage_scope_with_parent(handle, inherited_scope)?;
@@ -323,6 +329,19 @@ impl PageScriptHost {
Some(inherited_scope)
}
fn child_browsing_context_top_level_storage_site(&self, handle: DomHandle) -> Option<String> {
match self.child_browsing_context_root_scope(handle)? {
OwnerDispatchScope::Top => Some(self.top_level_storage_site()),
OwnerDispatchScope::LightweightPopup(popup_id) => Some(
self.lightweight_popup_bound_web_storage_scope(popup_id)?
.storage_key()
.top_level_site()
.to_owned(),
),
OwnerDispatchScope::Child(_) => None,
}
}
pub(crate) fn child_browsing_context_network_partition_key(
&self,
handle: DomHandle,
@@ -334,7 +353,7 @@ impl PageScriptHost {
.get(&handle)
.copied()
});
let top_level_site = self.top_level_storage_site();
let top_level_site = self.child_browsing_context_top_level_storage_site(handle)?;
let origin = self.child_browsing_context_network_partition_origin(handle)?;
let relation =
StoragePartitionRelation::from_sites(&site_for_url(&current_url), &top_level_site);
@@ -351,7 +370,7 @@ impl PageScriptHost {
bootstrap: &ChildBrowsingContextBootstrap,
credentialless_storage_nonce: Option<OpaqueOriginNonce>,
) -> Option<String> {
let top_level_site = self.top_level_storage_site();
let top_level_site = self.child_browsing_context_top_level_storage_site(handle)?;
let origin =
self.child_browsing_context_navigation_network_partition_origin(handle, bootstrap)?;
let target_url = Self::child_browsing_context_bootstrap_url(bootstrap)?;
@@ -370,7 +389,10 @@ impl PageScriptHost {
}
fn child_browsing_context_ancestor_chain_is_cross_site(&self, handle: DomHandle) -> bool {
let top_level_site = self.top_level_storage_site();
let Some(top_level_site) = self.child_browsing_context_top_level_storage_site(handle)
else {
return true;
};
let mut current = self.child_browsing_context_parent_handle(handle);
let mut depth = 0;
while let Some(parent) = current {
@@ -572,7 +594,7 @@ impl PageScriptHost {
let parent_has_cross_site_ancestor = parent_scope.storage_key().has_cross_site_ancestor();
if self.child_browsing_context_has_opaque_origin(handle) {
let url = self.child_browsing_context_current_url(handle)?;
let top_level_site = self.top_level_storage_site();
let top_level_site = parent_scope.storage_key().top_level_site().to_owned();
let relation = if moli_url::is_about_blank(&url) {
StoragePartitionRelation::Unknown
} else {
@@ -604,7 +626,7 @@ impl PageScriptHost {
parent_scope.origin(),
)
};
let top_level_site = self.top_level_storage_site();
let top_level_site = parent_scope.storage_key().top_level_site().to_owned();
let mut storage_key = web_storage_key_for_origin_and_top_level_site_with_nonce(
&origin,
top_level_site,
@@ -623,7 +645,7 @@ impl PageScriptHost {
&url,
parent_scope.origin(),
);
let top_level_site = self.top_level_storage_site();
let top_level_site = parent_scope.storage_key().top_level_site().to_owned();
let mut storage_key =
web_storage_key_for_origin_and_top_level_site_with_nonce(&origin, top_level_site, None);
if parent_has_cross_site_ancestor {
@@ -645,7 +667,7 @@ impl PageScriptHost {
.is_some_and(|sandbox| sandbox_attribute_forces_opaque_origin(&sandbox))
|| url.scheme() == "data"
{
let top_level_site = self.top_level_storage_site();
let top_level_site = parent_scope.storage_key().top_level_site().to_owned();
let relation = if moli_url::is_about_blank(url) {
StoragePartitionRelation::Unknown
} else {
@@ -669,7 +691,7 @@ impl PageScriptHost {
url,
parent_scope.origin(),
);
let top_level_site = self.top_level_storage_site();
let top_level_site = parent_scope.storage_key().top_level_site().to_owned();
WebStorageScope::new(
origin.clone(),
web_storage_key_for_origin_and_top_level_site_with_nonce(&origin, top_level_site, None),
@@ -1246,7 +1246,10 @@ impl PageScriptHost {
return None;
}
let popup_id = document_owner.popup_id();
let storage_key = service_worker_first_party_storage_key(&document_url);
let storage_key = self
.storage_context_for_lightweight_popup(popup_id)?
.storage_key()
.serialized_storage_key();
if let Some(client_id) = self.service_worker_popup_clients.get(&popup_id).copied() {
self.browser_context_runtime
.update_service_worker_client_document(
@@ -1281,7 +1284,10 @@ impl PageScriptHost {
let Some(document_owner) = self.current_lightweight_popup_document_owner(popup_id) else {
return false;
};
let storage_key = service_worker_first_party_storage_key(&document_url);
let Some(context) = self.storage_context_for_lightweight_popup(popup_id) else {
return false;
};
let storage_key = context.storage_key().serialized_storage_key();
self.browser_context_runtime
.update_service_worker_client_document(
client_id,
@@ -1305,7 +1311,10 @@ impl PageScriptHost {
return None;
}
let document_url = self.child_browsing_context_current_url(handle)?;
let storage_key = service_worker_first_party_storage_key(&document_url);
let storage_key = self
.storage_context_for_child_browsing_context(handle)?
.storage_key()
.serialized_storage_key();
let document_owner = self
.frame_owner_store
.current_child_document_task_owner(handle)
@@ -1348,6 +1357,7 @@ impl PageScriptHost {
&mut self,
handle: crate::document_runtime::DomHandle,
document_url: &Url,
storage_key: String,
) {
if !matches!(document_url.scheme(), "http" | "https") {
self.clear_pending_service_worker_child_client(handle);
@@ -1364,7 +1374,6 @@ impl PageScriptHost {
return;
}
self.clear_pending_service_worker_child_client(handle);
let storage_key = service_worker_first_party_storage_key(document_url);
let client_id = self
.browser_context_runtime
.register_reserved_service_worker_client(
@@ -2059,6 +2059,19 @@ async fn navigator_service_worker_clients_query_nested_frame_type() {
"frame-appended",
)
.await;
// Navigation clients are reserved with the request's final partition
// inputs, rather than during the DOM insertion which queued that request.
// Stop immediately after its fetch starts, before applying its completion.
for _ in 0..32 {
if vm._context_host.borrow().has_pending_child_document_loads() {
break;
}
assert!(
drain_service_worker_test_turn(&mut vm, &browser_context_runtime, &loader).await,
"the child navigation must reach request preparation"
);
}
assert!(vm._context_host.borrow().has_pending_child_document_loads());
let pending_diagnostics = browser_context_runtime
.service_worker_runtime()
.diagnostics_snapshot();
@@ -32,6 +32,31 @@ const POPUP: &str = r#"<!doctype html><body><script>
addEventListener('message', e => opener.postMessage(e.data, '*'));
</script><iframe src='/child'></iframe>"#;
const PARTITION_WORKER: &str = r#"
addEventListener('install', e => e.waitUntil(skipWaiting()));
addEventListener('activate', e => e.waitUntil(clients.claim()));
addEventListener('fetch', e => {
if (new URL(e.request.url).pathname === '/sw-probe') {
e.respondWith(new Response(`<!doctype html><script>
parent.postMessage({marker:location.search.slice(1),kind:'interception',
controlled:!!navigator.serviceWorker.controller,
stored:localStorage.getItem('partition-probe')},'*');
<\/script>`, {headers:{'Content-Type':'text/html'}}));
}
});
"#;
const PARTITION_NETWORK: &str = r#"<!doctype html><script>
parent.postMessage({marker:location.search.slice(1),kind:'network',
controlled:!!navigator.serviceWorker.controller,
stored:localStorage.getItem('partition-probe')},'*');
</script>"#;
const PARTITION_POPUP: &str = r#"<!doctype html><body><script>
addEventListener('message', e => opener.postMessage(e.data,'*'));
const frame=document.createElement('iframe');
frame.src=new URLSearchParams(location.search).get('child');
document.body.appendChild(frame);
</script>"#;
struct SecureChildFixture {
_directory: tempfile::TempDir,
ca_file: std::path::PathBuf,
@@ -57,7 +82,7 @@ async fn secure_child_fixture() -> SecureChildFixture {
ca_params.key_usages = vec![KeyUsagePurpose::KeyCertSign];
let ca = ca_params.self_signed(&ca_key).unwrap();
let key = KeyPair::generate().unwrap();
let certificate = CertificateParams::new(vec!["127.0.0.1".to_owned()])
let certificate = CertificateParams::new(vec!["127.0.0.1".to_owned(), "localhost".to_owned()])
.unwrap()
.signed_by(&key, &ca, &ca_key)
.unwrap();
@@ -106,12 +131,15 @@ async fn secure_child_fixture() -> SecureChildFixture {
let request = String::from_utf8_lossy(&request);
let path = request.split_whitespace().nth(1).unwrap_or("/");
request_log.lock().push(path.to_owned());
let (content_type, body) = match path {
let (content_type, body) = match path.split('?').next().unwrap() {
"/child" => ("text/html", CHILD),
"/popup" => ("text/html", POPUP),
"/worker.js" => ("application/javascript", WORKER),
"/shared.js" => ("application/javascript", SHARED),
"/probe" => ("text/plain", "fixture ready"),
"/sw.js" => ("application/javascript", PARTITION_WORKER),
"/sw-probe" => ("text/html", PARTITION_NETWORK),
"/sw-popup" => ("text/html", PARTITION_POPUP),
_ => ("text/plain", "unexpected resource"),
};
let header = format!(
@@ -226,3 +254,90 @@ addEventListener('message', e => secureAncestorResults.push(e.data));
page.close_async().await.unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn service_worker_frames_keep_top_level_storage_partition_in_popups() {
let fixture = secure_child_fixture().await;
let base = fixture.url.strip_suffix("/child").unwrap();
let root_url = url::Url::parse(&format!("{base}/sw-root")).unwrap();
let mut config = moli_fetch::FetchConfig::default();
config.set_tls_credentials(Some(fixture.ca_file.clone()), None, None, None);
config.set_http_host_resolve(vec![format!(
"localhost:{}:127.0.0.1",
root_url.port().unwrap()
)]);
let loader = ResourceRequestClient::new(&config).unwrap();
let runtime = JsRuntime::initialize();
let html = r#"<!doctype html><body><script>
globalThis.swPartitionMessages=[];
globalThis.swPartitionError=null;
addEventListener('message', e=>swPartitionMessages.push(e.data));
(async()=>{
localStorage.setItem('partition-probe','first-party');
const registration=await navigator.serviceWorker.register('/sw.js');
const worker=registration.installing||registration.waiting||registration.active;
if(worker.state!=='activated') await new Promise(resolve=>{
worker.addEventListener('statechange',()=>{
if(worker.state==='activated') resolve();
});
});
const direct=document.createElement('iframe');
direct.src='/sw-probe?direct';document.body.appendChild(direct);
for(const [marker,host] of [['same','127.0.0.1'],['other','localhost']]){
const child=new URL('/sw-probe?'+marker,location.href);
const popup=new URL('/sw-popup',location.href);
popup.hostname=host;popup.searchParams.set('child',child.href);
open(popup.href);
}
})().catch(e=>{swPartitionError=String(e)});
</script>"#;
let (mut page, _, _, _artifacts, download) = runtime
.create_html_page_from_response(
root_url.clone(),
root_url,
None,
false,
0,
200,
vec![("content-type".to_owned(), b"text/html".to_vec())],
&loader,
crate::RendererWebStorageHandles::ephemeral(),
html.to_owned(),
crate::RendererDocumentOptions::default(),
)
.await
.unwrap();
assert!(download.is_none());
let delivered = page
.run_async_command(RendererPageCommand::WaitForScriptTruthy {
expression: "swPartitionMessages.length===3 || swPartitionError!==null".to_owned(),
timeout_ms: 2_000,
loader: loader.clone(),
})
.await;
let (reply, _)=page.run_async_command(RendererPageCommand::EvaluateExpression {
expression:"JSON.stringify({error:swPartitionError,messages:swPartitionMessages.sort((a,b)=>a.marker<b.marker?-1:1)})".to_owned(),
await_promise:false,
}).await.unwrap();
let RendererPageReply::RuntimeEvaluationResult(reply) = reply else {
panic!("expected partition results")
};
let payload = reply.into_protocol_payload();
let result: serde_json::Value =
serde_json::from_str(payload["value"].as_str().unwrap()).unwrap();
assert!(
delivered.is_ok(),
"wait={:?}; results={result}; requests={:?}",
delivered.as_ref().err(),
fixture.requests.lock()
);
assert_eq!(
result,
serde_json::json!({"error":null,"messages":[
{"marker":"direct","kind":"interception","controlled":true,"stored":"first-party"},
{"marker":"other","kind":"network","controlled":false,"stored":null},
{"marker":"same","kind":"interception","controlled":true,"stored":"first-party"},
]})
);
page.close_async().await.unwrap();
}