diff --git a/moli-core/tests/scripts/css_import_referrer.js b/moli-core/tests/scripts/css_import_referrer.js new file mode 100644 index 00000000000..8ac8bf0049f --- /dev/null +++ b/moli-core/tests/scripts/css_import_referrer.js @@ -0,0 +1,69 @@ +(async () => { + const controlled = navigator.serviceWorker.controller ? Promise.resolve() : + new Promise(resolve => navigator.serviceWorker.addEventListener('controllerchange', resolve, {once:true})); + await navigator.serviceWorker.register('/css-import-referrer-worker.js', {scope:'/'}); + await navigator.serviceWorker.ready; + await controlled; + const setPolicy = policy => { + const meta=document.createElement('meta'); + meta.name='referrer';meta.content=policy;document.head.append(meta);meta.remove(); + }; + const failures=[]; + globalThis.cssImportFailures=failures; + for (const name of ['default','no-referrer','origin','unsafe','multiple','invalid', + 'redirect','inline','inline-direct','reset','nested','diamond','data','inline-data', + 'external-data','insert-root','insert-child','synthetic-inherit','request-override']) { + setPolicy('no-referrer'); + const resource=file => new URL('/css-referrer/' + name + '/' + file, location.href).href; + const root=resource('root.css'), mid=resource('mid.css'); + const row=(file,referrer,policy) => ({file,referrer,policy}); + const expected=[]; + if (name === 'redirect') expected.push(row('start.css','','no-referrer')); + if (!['data','inline-data','inline-direct'].includes(name)) + expected.push(name === 'request-override' ? row('root.css',location.origin+'/','origin') : row('root.css','','no-referrer')); + if (name === 'reset') expected.push(row('mid.css','','no-referrer'),row('leaf.css','','no-referrer')); + else if (name === 'nested') expected.push(row('mid.css',root,'unsafe-url'),row('leaf.css','','no-referrer')); + else if (name === 'synthetic-inherit') expected.push(row('mid.css',root,'unsafe-url'),row('leaf.css','','no-referrer')); + else if (name === 'diamond') expected.push(row('left.css',root,'unsafe-url'),row('right.css',root,'unsafe-url'), + row('leaf.css','','no-referrer')); + else if (name === 'insert-child') expected.push(row('mid.css',root,'unsafe-url'),row('leaf.css',location.origin+'/','origin')); + else if (['no-referrer','insert-root','inline-direct'].includes(name)) expected.push(row('leaf.css','','no-referrer')); + else if (name === 'origin') expected.push(row('leaf.css',location.origin+'/','origin')); + else if (['unsafe','multiple','redirect'].includes(name)) expected.push(row('leaf.css',root,'unsafe-url')); + else if (['data','inline-data','external-data'].includes(name)) expected.push(row('leaf.css','','no-referrer')); + else expected.push(row('leaf.css','','no-referrer')); + + const inline=name.startsWith('inline'); + const element=document.createElement(inline ? 'style' : 'link'); + let url=name === 'redirect' ? resource('start.css') : root; + if (name === 'data' || name === 'inline-data') + url='data:text/css,'+encodeURIComponent('@import url("'+resource('leaf.css')+'");'); + if (name === 'inline-direct') url=resource('leaf.css'); + if (inline) element.textContent='@import url("'+url+'");'; + else {element.rel='stylesheet';element.href=url;} + if (name === 'request-override') element.referrerPolicy='origin'; + if (inline) document.head.append(element); + else await new Promise((resolve,reject) => { + element.onload=resolve; + element.onerror=() => reject(new Error(name+': stylesheet failed')); + document.head.append(element); + }); + if (name === 'insert-root' || name === 'insert-child') { + setPolicy('unsafe-url'); + const sheet=name === 'insert-root' ? element.sheet : element.sheet.cssRules[0].styleSheet; + sheet.insertRule('@import url("'+resource('leaf.css')+'");',0); + } + let actual=[]; + for (let attempt=0;attempt<200;attempt++) { + actual=await (await fetch('/css-import-observations?case='+name)).json(); + if (actual.length >= expected.length) break; + await new Promise(resolve => setTimeout(resolve,10)); + } + const normalize=rows => rows.map(value => JSON.stringify(value)).sort(); + if (JSON.stringify(normalize(actual)) !== JSON.stringify(normalize(expected))) + failures.push(name+': '+JSON.stringify(actual)+' != '+JSON.stringify(expected)); + element.remove(); + } + if (failures.length) throw new Error(failures.join('\n')); + return true; +})(); diff --git a/moli-core/tests/scripts/css_import_referrer.rs b/moli-core/tests/scripts/css_import_referrer.rs new file mode 100644 index 00000000000..fca9b5cf595 --- /dev/null +++ b/moli-core/tests/scripts/css_import_referrer.rs @@ -0,0 +1,28 @@ +use super::*; + +#[tokio::test(flavor = "multi_thread")] +async fn css_import_requests_use_the_parent_stylesheet_referrer() -> Result<()> { + let servers = IntegrityServers::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let mut page = browser + .fetch(&format!("{}/page.html", servers.origin)) + .await?; + let result = tokio::time::timeout( + Duration::from_secs(20), + page.evaluate_runtime_expression_with_await_async( + include_str!("css_import_referrer.js"), + true, + ), + ) + .await??; + assert_eq!(result["value"], true, "{result}"); + assert!( + !servers + .requests + .lock() + .iter() + .any(|request| request.path.starts_with("/css-referrer/")), + "import requests must pass through the controlling service worker" + ); + Ok(()) +} diff --git a/moli-core/tests/scripts/css_import_referrer_worker.js b/moli-core/tests/scripts/css_import_referrer_worker.js new file mode 100644 index 00000000000..0d75ec4814b --- /dev/null +++ b/moli-core/tests/scripts/css_import_referrer_worker.js @@ -0,0 +1,48 @@ +const observations = new Map(); +self.addEventListener('activate', event => event.waitUntil(clients.claim())); +self.addEventListener('fetch', event => { + const url = new URL(event.request.url); + if (url.pathname === '/css-import-observations') { + event.respondWith(new Response(JSON.stringify(observations.get(url.searchParams.get('case')) || []), { + headers: {'Content-Type':'application/json'} + })); + return; + } + if (!url.pathname.startsWith('/css-referrer/')) return; + const [, , name, file] = url.pathname.split('/'); + const rows = observations.get(name) || []; + rows.push({file,referrer:event.request.referrer,policy:event.request.referrerPolicy}); + observations.set(name, rows); + const resource = file => new URL('/css-referrer/' + name + '/' + file, url).href; + const imports = file => '@import url("' + resource(file) + '");'; + if (file === 'start.css') { + event.respondWith(Response.redirect(resource('root.css'))); + return; + } + let body = ''; + let policy; + if (file === 'root.css') { + policy = { + 'no-referrer':'no-referrer', origin:'origin', unsafe:'unsafe-url', + multiple:'origin, invalid, unsafe-url', invalid:'not-a-policy', + redirect:'unsafe-url', reset:'no-referrer', nested:'unsafe-url', 'synthetic-inherit':'unsafe-url', + diamond:'unsafe-url', 'external-data':'unsafe-url', + 'insert-root':'no-referrer', 'insert-child':'unsafe-url' + }[name]; + if (['reset','nested','insert-child','synthetic-inherit'].includes(name)) body=imports('mid.css'); + else if (name === 'diamond') body=imports('left.css')+imports('right.css'); + else if (name === 'external-data') + body='@import url("data:text/css,' + encodeURIComponent(imports('leaf.css')) + '");'; + else if (name !== 'insert-root') body=imports('leaf.css'); + } else if (file === 'mid.css') { + if (name === 'nested') policy='no-referrer'; + if (name === 'insert-child') policy='origin'; + else body=imports('leaf.css'); + } else if (file === 'left.css' || file === 'right.css') { + policy=file === 'left.css' ? 'no-referrer' : 'unsafe-url'; + body=imports('leaf.css'); + } + const headers={'Content-Type':'text/css','Cache-Control':'no-store'}; + if (policy !== undefined) headers['Referrer-Policy']=policy; + event.respondWith(new Response(body,{headers})); +}); diff --git a/moli-core/tests/scripts/integrity.rs b/moli-core/tests/scripts/integrity.rs index 6ddf52c7bfe..26026fcf8b2 100644 --- a/moli-core/tests/scripts/integrity.rs +++ b/moli-core/tests/scripts/integrity.rs @@ -52,6 +52,8 @@ mod referrer_policy_inheritance; #[path = "fetch_client_referrer.rs"] mod fetch_client_referrer; +#[path = "css_import_referrer.rs"] +mod css_import_referrer; #[path = "service_worker_referrer.rs"] mod service_worker_referrer; @@ -392,6 +394,11 @@ fn fixture_response( format!("{javascript}Cache-Control: no-store\r\n"), include_str!("native_referrer_worker.js").to_owned(), ), + "/css-import-referrer-worker.js" => ( + "200 OK", + format!("{javascript}Cache-Control: no-store\r\n"), + include_str!("css_import_referrer_worker.js").to_owned(), + ), "/cors.js" | "/cors-null.js" | "/cors-origin.js" => ( "200 OK", format!( diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs index fea2be78c6a..811808f1251 100644 --- a/moli-renderer-v8/src/document_runtime.rs +++ b/moli-renderer-v8/src/document_runtime.rs @@ -107,7 +107,7 @@ pub(crate) use stylesheet_runtime::{ ConnectedLoadCompletion, LinkedStylesheetImportGraphCompletion, LiveStylesheetImportLoadCompletion, StylesheetImportCompletionAuthority, fetch_complete_stylesheet_import_graph, fetch_complete_stylesheet_import_graph_from_root, - live_stylesheet_import_responses, + live_stylesheet_import_responses, stylesheet_import_options, }; use stylesheet_runtime::{ ConnectedLoadOperation, LinkedStylesheetImportGraphs, QueuedConnectedStyleLoad, @@ -449,6 +449,7 @@ impl ConnectedStyleImportRoot { pub(crate) struct ConnectedLoadNetworkResult { /// Request provenance survives clearing the stylesheet installation owner. pub(crate) resource_timing_initiator_type: &'static str, + pub(crate) import_options: Option, pub(crate) consumed_preload_error: bool, /// Exact request Document, independent of an element's current location. pub(crate) document_owner: Option, @@ -2734,6 +2735,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: None, @@ -2786,6 +2788,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: Some(active_load.fetch().clone()), @@ -2843,6 +2846,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: Some(detached_load.fetch().clone()), @@ -2900,6 +2904,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: Some(detached_load.fetch().clone()), @@ -3511,6 +3516,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: None, @@ -3610,6 +3616,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "css", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: None, @@ -3687,6 +3694,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "css", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: None, @@ -3752,6 +3760,7 @@ mod tests { network_results: vec![ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "css", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: None, @@ -3894,6 +3903,7 @@ mod tests { .push_back(ConnectedLoadNetworkResult { network_observed: false, resource_timing_initiator_type: "link", + import_options: None, consumed_preload_error: false, document_owner: None, stylesheet_fetch: None, diff --git a/moli-renderer-v8/src/live_stylesheet/import_graph.rs b/moli-renderer-v8/src/live_stylesheet/import_graph.rs index 4fed0a84567..7f7ef21cbb3 100644 --- a/moli-renderer-v8/src/live_stylesheet/import_graph.rs +++ b/moli-renderer-v8/src/live_stylesheet/import_graph.rs @@ -1,6 +1,19 @@ use super::*; impl LiveStylesheet { + pub(crate) fn import_options( + &self, + ) -> Option { + self.import_options.borrow().clone() + } + + pub(crate) fn set_import_options( + &self, + options: crate::stylesheet_blocking::StylesheetFetchOptions, + ) { + self.import_options.replace(Some(options)); + } + pub(crate) fn top_level_import_state(&self) -> (bool, Vec) { if self.import_edges.borrow().is_empty() { return (false, Vec::new()); @@ -19,6 +32,9 @@ impl LiveStylesheet { Some(LiveStylesheetImportRequest { edge_id: edge.id, url: edge.rule.read_with(&guard).url.url()?.as_ref().clone(), + import_options: self + .import_options() + .filter(|options| options.referrer_url().is_some()), }) }) .collect() diff --git a/moli-renderer-v8/src/live_stylesheet/mod.rs b/moli-renderer-v8/src/live_stylesheet/mod.rs index ae0733a2c5a..3faf384d190 100644 --- a/moli-renderer-v8/src/live_stylesheet/mod.rs +++ b/moli-renderer-v8/src/live_stylesheet/mod.rs @@ -873,6 +873,7 @@ enum LiveStylesheetCssomRuntimeState { pub(crate) struct LiveStylesheetImportRequest { pub(crate) edge_id: StylesheetImportEdgeId, pub(crate) url: url::Url, + pub(crate) import_options: Option, } #[derive(Clone, Debug)] @@ -883,6 +884,7 @@ pub(crate) struct LiveStylesheetImportResponse { pub(crate) parsed_stylesheet: Option, pub(crate) successful: bool, pub(crate) origin_clean: bool, + pub(crate) import_options: Option, } #[derive(Debug)] @@ -959,6 +961,7 @@ pub(crate) struct LiveStylesheet { quirks_mode: QuirksMode, allow_import_rules: AllowImportRules, origin_clean: Cell, + import_options: RefCell>, cssom_runtime_state: LiveStylesheetCssomRuntimeState, contents_revision: Cell, cascade_generation: Cell, @@ -1333,6 +1336,7 @@ impl LiveStylesheet { quirks_mode, allow_import_rules, origin_clean: Cell::new(true), + import_options: RefCell::new(None), cssom_runtime_state, contents_revision: Cell::new(1), cascade_generation: Cell::new(1), diff --git a/moli-renderer-v8/src/live_stylesheet/registry.rs b/moli-renderer-v8/src/live_stylesheet/registry.rs index af4def3ec08..d7afe58f13c 100644 --- a/moli-renderer-v8/src/live_stylesheet/registry.rs +++ b/moli-renderer-v8/src/live_stylesheet/registry.rs @@ -253,6 +253,7 @@ impl LiveStylesheetRegistry { parsed_stylesheet: None, successful, origin_clean, + import_options: None, }, ) } @@ -319,6 +320,12 @@ impl LiveStylesheetRegistry { }; let child = Rc::new(child); child.set_origin_clean(response.origin_clean); + child.set_import_options(response.import_options.clone().unwrap_or_else(|| { + crate::stylesheet_blocking::StylesheetFetchOptions::for_import( + child.base_url().clone(), + None, + ) + })); self.entries.borrow_mut().insert(id, Rc::downgrade(&child)); if !parent.install_import_child(edge_id, child.clone(), response.successful) { self.entries.borrow_mut().remove(&id); @@ -355,12 +362,17 @@ impl LiveStylesheetRegistry { .or_insert(response); } let mut data_expansions = 0; - Some(self.install_import_graph_for_stylesheet( - &root, - &responses_by_request_identity, - &ancestors, - &mut data_expansions, - )) + Some( + self.install_import_graph_for_stylesheet( + &root, + &responses_by_request_identity, + &ancestors, + &mut data_expansions, + root.import_options() + .and_then(|options| options.document_referrer_policy().map(str::to_owned)) + .as_deref(), + ), + ) } fn install_import_graph_for_stylesheet( @@ -369,6 +381,7 @@ impl LiveStylesheetRegistry { responses_by_request_identity: &HashMap, ancestors: &HashSet, data_expansions: &mut usize, + document_referrer_policy: Option<&str>, ) -> bool { enum ImportGraphTraversal { Visit { @@ -432,6 +445,7 @@ impl LiveStylesheetRegistry { parsed_stylesheet: None, successful: false, origin_clean: true, + import_options: None, }, ); continue; @@ -455,6 +469,16 @@ impl LiveStylesheetRegistry { parsed_stylesheet: None, successful: true, origin_clean: true, + + import_options: Some( + crate::stylesheet_blocking::StylesheetFetchOptions::for_import( + request.url.clone(), + document_referrer_policy.map(str::to_owned), + ) + .with_document_referrer_policy( + document_referrer_policy.map(str::to_owned), + ), + ), }, None => LiveStylesheetImportResponse { request_url: request.url.clone(), @@ -463,6 +487,8 @@ impl LiveStylesheetRegistry { parsed_stylesheet: None, successful: false, origin_clean: true, + + import_options: None, }, }) } else { @@ -473,6 +499,7 @@ impl LiveStylesheetRegistry { parsed_stylesheet: None, successful: false, origin_clean: false, + import_options: None, }) }; all_successful &= response.successful; diff --git a/moli-renderer-v8/src/live_stylesheet/tests.rs b/moli-renderer-v8/src/live_stylesheet/tests.rs index 43204104862..b8dfce941b7 100644 --- a/moli-renderer-v8/src/live_stylesheet/tests.rs +++ b/moli-renderer-v8/src/live_stylesheet/tests.rs @@ -254,6 +254,7 @@ fn descendant_import_replacement_invalidates_a_root_graph_snapshot() { root_revision, stale_import_generation, &[LiveStylesheetImportResponse { + import_options: None, request_url: stale_leaf_request.url.clone(), response_url: stale_leaf_request.url, css_text: ".stale { color: red; }".to_owned(), @@ -285,6 +286,7 @@ fn imported_leaf_releases_detached_parse_and_reuses_contents_for_later_owners() ), ); let response = LiveStylesheetImportResponse { + import_options: None, request_url: leaf_url.clone(), response_url: leaf_url, css_text: leaf_text.to_owned(), @@ -359,6 +361,7 @@ fn import_graph_uses_each_response_url_as_the_nested_parser_base() { ); let responses = vec![ LiveStylesheetImportResponse { + import_options: None, request_url: url::Url::parse("https://example.test/assets/redirected.css").unwrap(), response_url: child_url, css_text: String::new(), @@ -367,6 +370,7 @@ fn import_graph_uses_each_response_url_as_the_nested_parser_base() { origin_clean: true, }, LiveStylesheetImportResponse { + import_options: None, request_url: leaf_url.clone(), response_url: leaf_url, css_text: String::new(), @@ -454,6 +458,7 @@ fn deep_import_graph_walks_and_generation_propagation_are_iterative() { root.contents_revision(), generation_before_terminal, &[LiveStylesheetImportResponse { + import_options: None, request_url: pending[0].url.clone(), response_url: pending[0].url.clone(), css_text: ".terminal { color: green; }".to_owned(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs index d60a5d48a86..72a4ebb80e7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs @@ -154,6 +154,9 @@ impl PageScriptHost { // not retroactively constrain an already admitted link or inline import. let csp_context = fetcher.csp_context().cloned(); let fetch_document_url = document_url.clone(); + let import_options = fetcher.prepare_stylesheet_fetch_options( + crate::stylesheet_blocking::StylesheetFetchOptions::default(), + ); let graph = match &signature { DocumentBlockingStylesheetSignature::Link { url, options } => { let started = moli_time::unix_epoch_millis(); @@ -180,6 +183,7 @@ impl PageScriptHost { fetcher, fetch_document_url, urls.clone(), + import_options, ), ) } @@ -452,6 +456,7 @@ impl PageScriptHost { prepared, ), ); + self.retain_linked_stylesheet_import_options(owner, terminal); if has_import_rules && let Some(sheet) = self.linked_live_stylesheet(owner) { import_roots.push(crate::document_runtime::ConnectedStyleImportRoot::new( owner, diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs index 06d8601692c..ab3b532b777 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs @@ -316,11 +316,49 @@ impl PageScriptHost { .imported_stylesheet_for_rule_wrapper(id, expected_stylesheet_id) } + pub(crate) fn retain_linked_stylesheet_import_options( + &self, + owner: DomHandle, + terminal: &crate::stylesheet_blocking::StylesheetFetchTerminal, + ) { + let document_policy = self + .dom_host() + .owner_document_handle(owner) + .and_then(|document| { + crate::context_bootstrap::document_referrer_policy_for_native_document( + self, document, + ) + }); + let document_options = crate::stylesheet_blocking::StylesheetFetchOptions::default() + .with_document_referrer_policy(document_policy); + if let Some(options) = + crate::document_runtime::stylesheet_import_options(terminal, &document_options) + && let Some(stylesheet) = self.linked_live_stylesheet(owner) + { + stylesheet.set_import_options(options); + } + } + pub(crate) fn install_and_refresh_live_stylesheet_import_graph( &mut self, root: crate::document_runtime::ConnectedStyleImportRoot, responses: &[crate::live_stylesheet::LiveStylesheetImportResponse], ) -> Option { + let document_policy = + self.dom_host() + .owner_document_handle(root.owner) + .and_then(|document| { + crate::context_bootstrap::document_referrer_policy_for_native_document( + self, document, + ) + }); + let stylesheet = self.live_stylesheets.get(root.stylesheet_id)?; + stylesheet.set_import_options( + stylesheet + .import_options() + .unwrap_or_default() + .with_document_referrer_policy(document_policy), + ); let successful = self.live_stylesheets.install_import_graph( root.stylesheet_id, root.contents_revision, diff --git a/moli-renderer-v8/src/network/preloads.rs b/moli-renderer-v8/src/network/preloads.rs index 69ba3cd8e70..0fae5675e71 100644 --- a/moli-renderer-v8/src/network/preloads.rs +++ b/moli-renderer-v8/src/network/preloads.rs @@ -16,6 +16,7 @@ use crate::{ #[derive(Clone, Debug)] pub(crate) struct DocumentPreloadResponse { + pub(crate) service_worker_response_url: Option, pub(crate) response: NavigationResponse, pub(crate) from_service_worker: bool, pub(crate) response_filter: Option, @@ -266,6 +267,7 @@ mod tests { fn response() -> DocumentPreloadResponse { DocumentPreloadResponse { + service_worker_response_url: None, response: NavigationResponse::from_text_body( request().url, 200, diff --git a/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs b/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs index 11d1967d283..0f761f839a1 100644 --- a/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs +++ b/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs @@ -265,6 +265,11 @@ impl RendererBrowserContextRuntime { .await .map_err(crate::network::preloads::ConsumedPreloadError)?; return Ok(Some(ServiceWorkerDirectFetchResponse { + response_url: if preload.from_service_worker { + preload.service_worker_response_url + } else { + Some(preload.response.final_url.clone()) + }, response: Box::new(preload.response), response_filter: preload.response_filter, from_network_fallback: !preload.from_service_worker, diff --git a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs index 47f66c15a2e..df0cbc223fd 100644 --- a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs +++ b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs @@ -2543,6 +2543,7 @@ impl ScriptVm { let crate::document_runtime::ConnectedLoadNetworkResult { network_observed, resource_timing_initiator_type, + import_options, consumed_preload_error, document_owner, stylesheet_fetch, @@ -2608,6 +2609,7 @@ impl ScriptVm { }); if is_import_graph_result { let response = crate::live_stylesheet::LiveStylesheetImportResponse { + import_options: import_options.clone(), request_url: request_url.clone(), response_url: stylesheet_base_url.clone(), css_text: stylesheet_text.clone(), diff --git a/moli-renderer-v8/src/service_worker_runtime/events.rs b/moli-renderer-v8/src/service_worker_runtime/events.rs index 0e999934d44..126d874332c 100644 --- a/moli-renderer-v8/src/service_worker_runtime/events.rs +++ b/moli-renderer-v8/src/service_worker_runtime/events.rs @@ -673,6 +673,8 @@ pub(crate) enum ServiceWorkerDirectFetchResult { #[derive(Debug)] pub(crate) struct ServiceWorkerDirectFetchResponse { + /// The worker response's URL before applying the request-URL fallback. + pub(crate) response_url: Option, pub(crate) response: Box, pub(crate) response_filter: Option, pub(crate) from_network_fallback: bool, diff --git a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs index 0e6cf56c82c..7eb4057a426 100644 --- a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs +++ b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs @@ -360,6 +360,7 @@ impl ServiceWorkerRuntimeService { body, ); ServiceWorkerDirectFetchResult::Response(ServiceWorkerDirectFetchResponse { + response_url: Some(navigation_response.final_url.clone()), response: Box::new(navigation_response), response_filter, from_network_fallback: true, @@ -588,12 +589,8 @@ impl ServiceWorkerRuntimeService { ); return; } - let final_url = response - .head - .metadata - .final_url() - .cloned() - .unwrap_or_else(|| job.request.url.clone()); + let response_url = response.head.metadata.final_url().cloned(); + let final_url = response_url.clone().unwrap_or_else(|| job.request.url.clone()); if let Err(message) = validate_service_worker_fetch_response_head_security_policy( &job, &final_url, @@ -684,6 +681,7 @@ impl ServiceWorkerRuntimeService { if let Some(completion_tx) = job.direct_completion_tx.take() { let _ = completion_tx.send(ServiceWorkerDirectFetchResult::Response( ServiceWorkerDirectFetchResponse { + response_url, response: Box::new(navigation_response), response_filter, from_network_fallback: false, diff --git a/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs b/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs index 1c80ea9d3bd..7a0acd72176 100644 --- a/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs +++ b/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs @@ -513,6 +513,7 @@ fn retained_imported_font_resources_keep_each_import_parser_base_and_response_sl ); let responses = vec![ crate::live_stylesheet::LiveStylesheetImportResponse { + import_options: None, request_url: url::Url::parse("https://example.test/theme/first/imported.css").unwrap(), response_url: url::Url::parse("https://example.test/theme/first/imported.css").unwrap(), css_text: concat!( @@ -525,6 +526,7 @@ fn retained_imported_font_resources_keep_each_import_parser_base_and_response_sl origin_clean: true, }, crate::live_stylesheet::LiveStylesheetImportResponse { + import_options: None, request_url: url::Url::parse("https://example.test/theme/second/imported.css").unwrap(), response_url: url::Url::parse("https://example.test/theme/second/imported.css") .unwrap(), @@ -538,6 +540,7 @@ fn retained_imported_font_resources_keep_each_import_parser_base_and_response_sl origin_clean: true, }, crate::live_stylesheet::LiveStylesheetImportResponse { + import_options: None, request_url: url::Url::parse("https://example.test/redirect/entry.css").unwrap(), response_url: url::Url::parse("https://cdn.example.test/final/entry.css").unwrap(), css_text: "@import './nested.css';".to_owned(), @@ -546,6 +549,7 @@ fn retained_imported_font_resources_keep_each_import_parser_base_and_response_sl origin_clean: true, }, crate::live_stylesheet::LiveStylesheetImportResponse { + import_options: None, request_url: url::Url::parse("https://cdn.example.test/final/nested.css").unwrap(), response_url: url::Url::parse("https://assets.example.test/styles/nested.css").unwrap(), css_text: concat!( diff --git a/moli-renderer-v8/src/stylesheet_blocking.rs b/moli-renderer-v8/src/stylesheet_blocking.rs index 691f0374dff..69f1c6acef9 100644 --- a/moli-renderer-v8/src/stylesheet_blocking.rs +++ b/moli-renderer-v8/src/stylesheet_blocking.rs @@ -323,6 +323,7 @@ impl StylesheetFetcher for RendererStylesheetFetcher { self.clone(), document_url, urls, + self.prepare_stylesheet_fetch_options(StylesheetFetchOptions::default()), ), ) } @@ -429,7 +430,8 @@ pub(crate) async fn fetch_stylesheet_readiness_with_service_worker( filter: response.response_filter, } }; - return terminal_from_response(*response.response, response_provenance); + return terminal_from_response(*response.response, response_provenance) + .with_service_worker_response_url(response.response_url); } Ok(None) => {} Err(error) => { @@ -551,6 +553,7 @@ fn stylesheet_terminal_from_preload( preload.response, provenance, ) + .with_service_worker_response_url(preload.service_worker_response_url) } Err(error) => StylesheetFetchTerminal::consumed_preload_error(error), } @@ -563,9 +566,14 @@ pub(crate) fn stylesheet_request_mode_and_credentials( } pub(crate) fn apply_stylesheet_request_parameters( - request: moli_fetch::Request, + mut request: moli_fetch::Request, options: &StylesheetFetchOptions, ) -> moli_fetch::Request { + if let Some(referrer_url) = options.referrer_url() { + request = request + .with_fetch_referrer(referrer_url.as_str()) + .expect("a parsed stylesheet referrer URL remains valid"); + } let (request_mode, credentials_mode) = stylesheet_request_mode_and_credentials(options); request .with_request_mode(request_mode) @@ -751,6 +759,7 @@ fn stylesheet_preload_response( // Preserve the fetch response even when it cannot be installed as CSS. Ok(crate::network::preloads::DocumentPreloadResponse { response: response.clone(), + service_worker_response_url: terminal.service_worker_response_url().cloned(), from_service_worker: terminal.from_service_worker(), response_filter: terminal.response_filter().cloned().map(Into::into), }) @@ -868,6 +877,102 @@ mod tests { } } + #[test] + fn imported_stylesheets_keep_document_origin_and_cookie_initiator() { + let document = Url::parse("https://page.test/document").unwrap(); + let origin = moli_url::WebOrigin::from_url(&document); + let parent = Url::parse("https://user:password@cdn.test/parent.css#fragment").unwrap(); + let target = Url::parse("https://cdn.test/child.css").unwrap(); + for (policy, expected) in [ + (None, Some("https://cdn.test/parent.css")), + (Some("no-referrer"), None), + (Some("origin"), Some("https://cdn.test/")), + ] { + let options = + StylesheetFetchOptions::for_import(parent.clone(), policy.map(str::to_owned)) + .with_document_referrer_policy(Some("no-referrer".to_owned())); + let request = stylesheet_readiness_request( + &document, + &origin, + &target, + &options, + moli_fetch::RequestResourceType::CssStyleSheet, + false, + None, + ); + assert_eq!(request.referrer_header_value(&target).as_deref(), expected); + assert_eq!(request.browser_origin().unwrap(), &origin); + assert_eq!( + request.cookie_context.initiator_url.as_ref(), + Some(&document) + ); + } + } + + #[test] + fn stylesheet_import_policy_distinguishes_network_and_synthetic_responses() { + let url = Url::parse("https://example.test/parent.css").unwrap(); + let origin = moli_url::WebOrigin::from_url(&url); + let document_options = StylesheetFetchOptions::default() + .with_document_referrer_policy(Some("no-referrer".to_owned())); + for (provenance, response_url, expected) in [ + ( + StylesheetResponseProvenance::Network, + None, + moli_fetch::DEFAULT_REFERRER_POLICY, + ), + ( + StylesheetResponseProvenance::ServiceWorker { filter: None }, + None, + "no-referrer", + ), + ( + StylesheetResponseProvenance::ServiceWorker { + filter: Some(AsyncSubresourceFetchResponseFilter::Network( + moli_fetch::FetchResponseType::Basic, + )), + }, + None, + "no-referrer", + ), + ( + StylesheetResponseProvenance::ServiceWorker { + filter: Some(AsyncSubresourceFetchResponseFilter::Network( + moli_fetch::FetchResponseType::Basic, + )), + }, + Some(url.clone()), + moli_fetch::DEFAULT_REFERRER_POLICY, + ), + ] { + let response = stylesheet_response(&url, Some("text/css"), ""); + let terminal = stylesheet_terminal_from_response( + &origin, + &url, + &document_options, + response, + provenance, + ); + let terminal = terminal.with_service_worker_response_url(response_url); + let options = + crate::document_runtime::stylesheet_import_options(&terminal, &document_options) + .unwrap(); + assert_eq!(options.referrer_policy(), Some(expected)); + assert_eq!(options.referrer_url(), Some(&url)); + let preload = stylesheet_preload_response(&terminal, &document_options).unwrap(); + let consumed = + stylesheet_terminal_from_preload(&origin, &url, &document_options, Ok(preload)); + let consumed_options = + crate::document_runtime::stylesheet_import_options(&consumed, &document_options) + .unwrap(); + assert_eq!(consumed_options.referrer_policy(), Some(expected)); + assert_eq!( + consumed.service_worker_response_url(), + terminal.service_worker_response_url() + ); + } + } + #[test] fn stylesheet_integrity_checks_raw_bytes_and_strongest_hash() { let document_url = Url::parse("https://example.test/page").unwrap(); diff --git a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs index 2d6d540232c..473ac3fc91d 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs @@ -453,6 +453,7 @@ impl DocumentRuntime { } else { "link" }, + import_options: None, consumed_preload_error: result.terminal.is_consumed_preload_error(), document_owner, stylesheet_fetch: result.fetch, diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs index 18675442191..240d38f2688 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs @@ -9,7 +9,7 @@ use crate::module_runtime::{ use crate::planning::{ScriptFetchMetadata, module_script_credentials_mode}; use crate::service_worker_runtime::ServiceWorkerRequestDestination; use crate::stylesheet_blocking::{ - StylesheetFetchOptions, connected_preload_like_link_url, + StylesheetFetchOptions, StylesheetFetcher, connected_preload_like_link_url, document_owned_blocking_stylesheet_candidate_for_node, link_rel_includes_token, preload_like_link_loads_stylesheet, stylesheet_link_disposition, stylesheet_preload_link_request, @@ -46,6 +46,7 @@ struct ConnectedLinkReadinessFetchResponse { response_filter: Option, integrity_matches: bool, from_service_worker: bool, + service_worker_response_url: Option, } impl ConnectedLinkReadinessFetchResponse { @@ -55,6 +56,7 @@ impl ConnectedLinkReadinessFetchResponse { load_event_successful: bool, integrity: Option<&str>, from_service_worker: bool, + service_worker_response_url: Option, ) -> Self { // Hash the original body, including binary responses. A matching digest // must not make an opaque response eligible, including SW responses to @@ -77,6 +79,7 @@ impl ConnectedLinkReadinessFetchResponse { response_filter, integrity_matches, from_service_worker, + service_worker_response_url, } } @@ -87,6 +90,7 @@ impl ConnectedLinkReadinessFetchResponse { return Err("preload response failed its integrity check".to_owned()); } Ok(crate::network::preloads::DocumentPreloadResponse { + service_worker_response_url: self.service_worker_response_url.clone(), response: self.response.clone(), from_service_worker: self.from_service_worker, response_filter: self.response_filter.clone(), @@ -1355,6 +1359,7 @@ impl DocumentRuntime { resource_timing_initiator_type: preload_like_resource_initiator_type( resource_type, ), + import_options: None, consumed_preload_error: false, document_owner, stylesheet_fetch: None, @@ -1542,11 +1547,14 @@ impl DocumentRuntime { .document_url() .clone(); let resource_loader = stylesheet_fetcher.resource_loader().clone(); + let options = + stylesheet_fetcher.prepare_stylesheet_fetch_options(StylesheetFetchOptions::default()); resource_loader.spawn_resource_task(async move { let (graph, network_results) = fetch_observed_stylesheet_import_graph( stylesheet_fetcher, document_url, urls, + options, vec![handle], ) .await; @@ -1582,10 +1590,10 @@ impl DocumentRuntime { root_is_external_resource: bool, host_ptr: *mut PageScriptHost, ) { - let urls = stylesheet - .pending_import_requests_in_graph() - .into_iter() - .map(|request| request.url) + let pending_imports = stylesheet.pending_import_requests_in_graph(); + let urls = pending_imports + .iter() + .map(|request| request.url.clone()) .collect::>(); if urls.is_empty() { return; @@ -1599,14 +1607,14 @@ impl DocumentRuntime { ) }); let root = ConnectedStyleImportRoot::new(owner, &stylesheet, root_resource_url); - let urls = match connected_style_import_readiness(urls) { + match connected_style_import_readiness(urls) { ConnectedStyleImportReadiness::Ready(_) => { let _ = unsafe { &mut *host_ptr } .install_and_refresh_live_stylesheet_import_graph(root, &[]); return; } - ConnectedStyleImportReadiness::Pending(urls) => urls, - }; + ConnectedStyleImportReadiness::Pending(_) => {} + } let task_producer = self .stylesheet_lifecycle .task_producer @@ -1619,16 +1627,38 @@ impl DocumentRuntime { .document_url() .clone(); let resource_loader = stylesheet_fetcher.resource_loader().clone(); + let document_options = + stylesheet_fetcher.prepare_stylesheet_fetch_options(StylesheetFetchOptions::default()); + let mut groups = Vec::<(StylesheetFetchOptions, Vec)>::new(); + let mut group_indices = HashMap::new(); + for request in pending_imports { + let options = request + .import_options + .unwrap_or_else(|| document_options.clone()); + let index = *group_indices.entry(options.clone()).or_insert_with(|| { + groups.push((options, Vec::new())); + groups.len() - 1 + }); + groups[index].1.push(request.url); + } resource_loader.spawn_resource_task(async move { - let (_, mut network_results) = fetch_observed_stylesheet_import_graph( - stylesheet_fetcher, - document_url, - urls, - vec![owner], - ) - .await; - for result in &mut network_results { - result.import_roots.push(root.clone()); + let results = + futures_util::future::join_all(groups.into_iter().map(|(options, urls)| { + fetch_observed_stylesheet_import_graph( + stylesheet_fetcher.clone(), + document_url.clone(), + urls, + options, + vec![owner], + ) + })) + .await; + let mut network_results = Vec::new(); + for (_, results) in results { + for mut result in results { + result.import_roots.push(root.clone()); + network_results.push(result); + } } let _ = task_producer.send_live_import_completion(LiveStylesheetImportLoadCompletion { network_results, @@ -2550,6 +2580,7 @@ async fn fetch_connected_link_readiness_with_service_worker( load_event_successful, integrity, !response.from_network_fallback, + response.response_url, )); } Ok(None) => {} @@ -2581,6 +2612,7 @@ async fn fetch_connected_link_readiness_with_service_worker( load_event_successful, integrity, false, + None, ) }) } diff --git a/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs index 458995ca4de..dc929500849 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/import_graph.rs @@ -26,9 +26,15 @@ pub(in crate::document_runtime) enum ConnectedStyleImportReadiness { const MAX_DATA_STYLESHEET_IMPORT_EXPANSIONS: usize = 16; const MAX_DATA_STYLESHEET_IMPORT_URL_BYTES: usize = 16 * 1024; +struct PendingStylesheetImport { + url: Url, + options: StylesheetFetchOptions, +} + #[derive(Default)] struct ConnectedNetworkStyleImportGraph { pending_urls: VecDeque, + pending_options: HashMap, requested_identities: HashSet, root_response_identity: Option, } @@ -56,6 +62,33 @@ impl ConnectedNetworkStyleImportGraph { } } + fn extend_with_options( + &mut self, + urls: impl IntoIterator, + options: &StylesheetFetchOptions, + ) { + let urls = urls.into_iter().collect::>(); + for url in &urls { + self.pending_options + .entry(import_url_identity(url)) + .or_insert_with(|| options.clone()); + } + self.extend(urls); + } + + fn take_pending_requests(&mut self) -> Vec { + self.take_pending() + .into_iter() + .map(|url| { + let options = self + .pending_options + .remove(&import_url_identity(&url)) + .unwrap_or_default(); + PendingStylesheetImport { url, options } + }) + .collect() + } + fn response_imports( &mut self, result: &mut crate::stylesheet_blocking::StylesheetImportNetworkResult, @@ -91,12 +124,40 @@ impl ConnectedNetworkStyleImportGraph { } } +pub(crate) fn stylesheet_import_options( + terminal: &crate::stylesheet_blocking::StylesheetFetchTerminal, + document_options: &StylesheetFetchOptions, +) -> Option { + let response = terminal.ready_response()?; + let inherits_document_policy = matches!(response.final_url.scheme(), "data" | "blob") + || (terminal.from_service_worker() && terminal.service_worker_response_url().is_none()); + let policy = + moli_fetch::response_referrer_policy_from_headers(&response.headers).or_else(|| { + inherits_document_policy.then(|| { + moli_fetch::effective_referrer_policy( + None, + document_options.document_referrer_policy(), + ) + .to_owned() + }) + }); + Some( + StylesheetFetchOptions::for_import(response.final_url.clone(), policy) + .with_document_referrer_policy( + document_options + .document_referrer_policy() + .map(str::to_owned), + ), + ) +} + pub(crate) fn fetch_complete_stylesheet_import_graph( stylesheet_fetcher: crate::stylesheet_blocking::RendererStylesheetFetcher, document_url: Url, urls: Vec, + options: StylesheetFetchOptions, ) -> impl Future + Send { - fetch_stylesheet_import_graph(stylesheet_fetcher, document_url, urls, None) + fetch_stylesheet_import_graph(stylesheet_fetcher, document_url, urls, None, options) } /// Continue from a root fetched with its link-specific request options. Keep @@ -106,7 +167,15 @@ pub(crate) fn fetch_complete_stylesheet_import_graph_from_root( document_url: Url, root: crate::stylesheet_blocking::StylesheetImportNetworkResult, ) -> impl Future + Send { - fetch_stylesheet_import_graph(stylesheet_fetcher, document_url, Vec::new(), Some(root)) + let options = + stylesheet_fetcher.prepare_stylesheet_fetch_options(StylesheetFetchOptions::default()); + fetch_stylesheet_import_graph( + stylesheet_fetcher, + document_url, + Vec::new(), + Some(root), + options, + ) } fn fetch_stylesheet_import_graph( @@ -114,11 +183,12 @@ fn fetch_stylesheet_import_graph( document_url: Url, urls: Vec, root: Option, + options: StylesheetFetchOptions, ) -> impl Future + Send { // A policy-bearing graph must admit data: imports before decoding them, // just like network imports. Keep them in the result so CSSOM cannot later // reconstruct the body of a refused local import. - let check_data_imports = stylesheet_fetcher.csp_context().is_some(); + let check_data_imports = true; let readiness = move |urls: Vec| { if check_data_imports && !urls.is_empty() { ConnectedStyleImportReadiness::Pending(urls) @@ -130,38 +200,47 @@ fn fetch_stylesheet_import_graph( ConnectedStyleImportReadiness::Ready(successful) => (successful, Vec::new()), ConnectedStyleImportReadiness::Pending(urls) => (true, urls), }; + let document_options = + stylesheet_fetcher.prepare_stylesheet_fetch_options(StylesheetFetchOptions::default()); let mut network_results = Vec::new(); let mut import_graph = ConnectedNetworkStyleImportGraph::new(root.as_ref()); let mut pending_results: Vec<_> = root.into_iter().collect(); - import_graph.extend(urls); + import_graph.extend_with_options(urls, &options); let mut data_expansions = 0; // Prepare the initial requests before yielding to the parser. Descendants // are prepared after their parent response, under the policy then in force. let initial_requests = prepare_import_requests( &stylesheet_fetcher, &document_url, - import_graph.take_pending(), + import_graph.take_pending_requests(), &mut data_expansions, ); async move { pending_results.extend(join_all(initial_requests).await); while !pending_results.is_empty() { - for mut result in std::mem::take(&mut pending_results) { + for result in std::mem::take(&mut pending_results) { successful &= result.terminal().is_ready(); + let import_options = + stylesheet_import_options(result.terminal(), &document_options); + let mut result = result.with_import_options(import_options.clone()); let imports = import_graph.response_imports(&mut result, stylesheet_fetcher.quirks_mode()); match readiness(imports) { ConnectedStyleImportReadiness::Ready(nested_successful) => { successful &= nested_successful; } - ConnectedStyleImportReadiness::Pending(urls) => import_graph.extend(urls), + ConnectedStyleImportReadiness::Pending(urls) => import_graph + .extend_with_options( + urls, + import_options.as_ref().unwrap_or(&document_options), + ), } network_results.push(result); } pending_results = join_all(prepare_import_requests( &stylesheet_fetcher, &document_url, - import_graph.take_pending(), + import_graph.take_pending_requests(), &mut data_expansions, )) .await; @@ -176,11 +255,12 @@ fn fetch_stylesheet_import_graph( fn prepare_import_requests( fetcher: &crate::stylesheet_blocking::RendererStylesheetFetcher, document_url: &Url, - urls: Vec, + urls: Vec, data_expansions: &mut usize, ) -> Vec> { urls.into_iter() - .map(|url| -> BoxFuture<'static, _> { + .map(|request| -> BoxFuture<'static, _> { + let PendingStylesheetImport { url, options } = request; let started = moli_time::unix_epoch_millis(); let terminal: BoxFuture<'static, _> = if url.scheme() == "data" { *data_expansions += 1; @@ -196,7 +276,7 @@ fn prepare_import_requests( .fetch_stylesheet_resource( document_url.clone(), url.clone(), - StylesheetFetchOptions::default(), + options, ) }; Box::pin(async move { diff --git a/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs b/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs index 68791297224..327adf56562 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/import_graph_projection.rs @@ -10,6 +10,7 @@ pub(in crate::document_runtime) async fn fetch_observed_stylesheet_import_graph( stylesheet_fetcher: crate::stylesheet_blocking::RendererStylesheetFetcher, document_url: Url, urls: Vec, + options: crate::stylesheet_blocking::StylesheetFetchOptions, source_owners: Vec, ) -> ( Arc, @@ -20,6 +21,7 @@ pub(in crate::document_runtime) async fn fetch_observed_stylesheet_import_graph( stylesheet_fetcher, document_url.clone(), urls, + options, ) .await, ); @@ -32,10 +34,12 @@ pub(in crate::document_runtime) async fn fetch_observed_stylesheet_import_graph( let terminal = result.terminal(); let origin_clean = terminal.origin_clean().unwrap_or(false); let parsed_stylesheet = result.parsed_stylesheet().cloned(); + let import_options = result.import_options().cloned(); let result = terminal.physical().as_result(); ConnectedLoadNetworkResult { network_observed: terminal.network_was_observed(), resource_timing_initiator_type: "css", + import_options, consumed_preload_error: terminal.is_consumed_preload_error(), document_owner: None, stylesheet_fetch: None, @@ -66,6 +70,7 @@ pub(crate) fn live_stylesheet_import_responses( let terminal = result.terminal(); let ready_response = terminal.ready_response(); crate::live_stylesheet::LiveStylesheetImportResponse { + import_options: result.import_options().cloned(), request_url: result.request_url().clone(), response_url: match terminal.physical() { crate::stylesheet_blocking::StylesheetPhysicalOutcome::Response(response) => { diff --git a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs index b45a0ca861c..9f36a60a27a 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs @@ -1,4 +1,5 @@ use super::*; +use crate::stylesheet_blocking::StylesheetFetcher; #[derive(Debug)] pub(crate) struct LinkedStylesheetImportGraphCompletion { @@ -345,7 +346,7 @@ impl DocumentRuntime { ) { let fetch = load.fetch().clone(); let roots = self.linked_stylesheet_import_roots(&fetch); - let urls = match super::import_graph::connected_style_import_readiness(urls.clone()) { + let urls = match super::import_graph::connected_style_import_readiness(urls) { super::import_graph::ConnectedStyleImportReadiness::Ready(graph_successful) => { if !host_ptr.is_null() { for root in &roots { @@ -393,12 +394,22 @@ impl DocumentRuntime { .expect("linked stylesheet import requires a bound Page task producer"); let resource_loader = stylesheet_fetcher.resource_loader().clone(); let document_url = resource_loader.fetch_context().document_url().clone(); + let document_options = stylesheet_fetcher.prepare_stylesheet_fetch_options( + crate::stylesheet_blocking::StylesheetFetchOptions::default(), + ); + let options = fetch + .terminal() + .and_then(|terminal| { + super::import_graph::stylesheet_import_options(&terminal, &document_options) + }) + .expect("a linked import graph requires a usable root response"); resource_loader.spawn_resource_task(async move { let (graph, network_results) = super::import_graph_projection::fetch_observed_stylesheet_import_graph( stylesheet_fetcher, document_url, urls, + options, Vec::new(), ) .await; diff --git a/moli-renderer-v8/src/stylesheet_runtime/mod.rs b/moli-renderer-v8/src/stylesheet_runtime/mod.rs index 49cb86b92cd..85e2eeb94b0 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/mod.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/mod.rs @@ -36,6 +36,7 @@ pub(crate) use connected::{ConnectedStyleLoadPrimeResult, PreparedConnectedStyle pub(super) use import_graph::{ConnectedStyleImportReadiness, connected_style_import_readiness}; pub(crate) use import_graph::{ fetch_complete_stylesheet_import_graph, fetch_complete_stylesheet_import_graph_from_root, + stylesheet_import_options, }; pub(super) use import_graph_projection::fetch_observed_stylesheet_import_graph; pub(crate) use import_graph_projection::live_stylesheet_import_responses; diff --git a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs index 19f8352c5bd..67d628c6c80 100644 --- a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs +++ b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs @@ -208,6 +208,7 @@ impl DocumentRuntime { request_url.clone(), prepared.clone(), )); + host.retain_linked_stylesheet_import_options(load.owner(), terminal); } let import_root = prepared.as_ref().and_then(|_| { host.linked_live_stylesheet(load.owner()).map(|stylesheet| { diff --git a/moli-stylesheet-blocking/src/fetcher.rs b/moli-stylesheet-blocking/src/fetcher.rs index 7a85bafec9b..935627c5bd7 100644 --- a/moli-stylesheet-blocking/src/fetcher.rs +++ b/moli-stylesheet-blocking/src/fetcher.rs @@ -24,6 +24,7 @@ struct StylesheetFetchOptionsData { cross_origin: Option, referrer_policy: Option, document_referrer_policy: Option, + referrer_url: Option, integrity: Option, nonce: Option, charset: Option, @@ -50,6 +51,7 @@ impl StylesheetFetchOptions { cross_origin: normalize_cross_origin(cross_origin), referrer_policy: normalize_token(referrer_policy), document_referrer_policy: None, + referrer_url: None, integrity: normalize_preserved_value(integrity), nonce: normalize_preserved_value(nonce), charset: normalize_token(charset), @@ -80,6 +82,25 @@ impl StylesheetFetchOptions { self.0.document_referrer_policy.as_deref() } + /// Requests initiated by an external sheet use that sheet's response URL + /// and policy, independently of the owning Document's fetch authority. + pub fn for_import(mut referrer_url: Url, referrer_policy: Option) -> Self { + referrer_url.set_fragment(None); + Self(Arc::new(StylesheetFetchOptionsData { + referrer_url: Some(referrer_url), + referrer_policy: Some( + referrer_policy + .filter(|policy| !policy.is_empty()) + .unwrap_or_else(|| moli_fetch::DEFAULT_REFERRER_POLICY.to_owned()), + ), + ..Default::default() + })) + } + + pub fn referrer_url(&self) -> Option<&Url> { + self.0.referrer_url.as_ref() + } + pub fn integrity(&self) -> Option<&str> { self.0.integrity.as_deref() } @@ -143,6 +164,7 @@ pub struct StylesheetResourceKey { credentials_mode: RequestCredentialsMode, referrer_policy: Option, document_referrer_policy: Option, + referrer_url: Option, integrity: Option, charset: Option, quirks_mode_mime_compatibility: bool, @@ -158,6 +180,7 @@ impl StylesheetResourceKey { credentials_mode, referrer_policy: options.referrer_policy().map(str::to_owned), document_referrer_policy: options.document_referrer_policy().map(str::to_owned), + referrer_url: options.referrer_url().cloned(), integrity: options.integrity().map(str::to_owned), charset: options.charset().map(str::to_owned), quirks_mode_mime_compatibility: options.quirks_mode_mime_compatibility(), @@ -207,6 +230,7 @@ impl StylesheetUsability { #[derive(Debug, Clone)] pub struct StylesheetFetchTerminal { + service_worker_response_url: Option, physical: StylesheetPhysicalOutcome, usability: StylesheetUsability, origin_clean: Option, @@ -236,6 +260,7 @@ impl StylesheetFetchTerminal { origin_clean: Some(origin_clean), network_observed: false, from_service_worker: false, + service_worker_response_url: None, response_filter: None, consumed_preload_error: false, } @@ -267,6 +292,7 @@ impl StylesheetFetchTerminal { origin_clean: None, network_observed: false, from_service_worker: false, + service_worker_response_url: None, response_filter: None, consumed_preload_error: false, } @@ -296,6 +322,15 @@ impl StylesheetFetchTerminal { self.from_service_worker } + pub fn with_service_worker_response_url(mut self, url: Option) -> Self { + self.service_worker_response_url = url; + self + } + + pub fn service_worker_response_url(&self) -> Option<&Url> { + self.service_worker_response_url.as_ref() + } + pub fn response_filter(&self) -> Option<&moli_fetch::PreloadResponseFilter> { self.response_filter.as_ref() } diff --git a/moli-stylesheet-blocking/src/types.rs b/moli-stylesheet-blocking/src/types.rs index 14b5c0c652d..2b7cfeedefc 100644 --- a/moli-stylesheet-blocking/src/types.rs +++ b/moli-stylesheet-blocking/src/types.rs @@ -189,6 +189,7 @@ pub struct StylesheetImportNetworkResult { pub(crate) start_unix_millis: f64, pub(crate) terminal: StylesheetFetchTerminal, parsed_stylesheet: Option, + import_options: Option, } impl StylesheetImportNetworkResult { @@ -202,6 +203,7 @@ impl StylesheetImportNetworkResult { start_unix_millis, terminal, parsed_stylesheet: None, + import_options: None, } } @@ -225,6 +227,15 @@ impl StylesheetImportNetworkResult { &self.terminal } + pub fn with_import_options(mut self, options: Option) -> Self { + self.import_options = options; + self + } + + pub fn import_options(&self) -> Option<&crate::StylesheetFetchOptions> { + self.import_options.as_ref() + } + pub fn into_parts(self) -> (Url, f64, StylesheetFetchTerminal) { (self.request_url, self.start_unix_millis, self.terminal) }