mirror of
https://github.com/lexmount/moli.git
synced 2026-11-21 00:03:15 +00:00
fix(worker): inherit local script referrer policies
Resolve local worker policy from the Blob URL creator environment, including meta updates delivered before startup. Keep existing worker snapshots and SharedWorker reuse stable, and carry the policy through worker-created URLs. Preserve parent request and child response policy for nested HTTP workers. Validate with the complete fmt, clippy, and nextest gates (20,458 passed), 73 original WPT files (665 -> 667 passed, zero regressions), and 226 network comparisons covering worker types, ownership, policy timing, and overrides.
This commit is contained in:
Generated
+1
@@ -2894,6 +2894,7 @@ dependencies = [
|
||||
"moli-html-input-temporal",
|
||||
"moli-html-input-type",
|
||||
"moli-html2md",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"selectors",
|
||||
"serde",
|
||||
|
||||
@@ -54,6 +54,8 @@ mod fetch_client_referrer;
|
||||
|
||||
#[path = "css_import_referrer.rs"]
|
||||
mod css_import_referrer;
|
||||
#[path = "local_worker_referrer.rs"]
|
||||
mod local_worker_referrer;
|
||||
#[path = "service_worker_referrer.rs"]
|
||||
mod service_worker_referrer;
|
||||
|
||||
@@ -230,6 +232,9 @@ fn fixture_response(
|
||||
| "/child-sri-accepted.css"
|
||||
| "/child-sri-forbidden.css" => child_stylesheet_integrity::fixture_response(path, query),
|
||||
"/import-referrer.js" => dynamic_import_referrer::fixture_response(query),
|
||||
"/local-referrer-worker.js" | "/local-referrer-page.html" => {
|
||||
local_worker_referrer::fixture_response(path, query, request.referer.as_deref())
|
||||
}
|
||||
"/import-credentials.js" => (
|
||||
"200 OK",
|
||||
format!("{javascript}Cache-Control: no-store\r\n"),
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
(async () => {
|
||||
const script = await (await fetch('/local-referrer-worker.js')).text();
|
||||
const source = location.origin + '/private-worker-referrer?probe=1';
|
||||
const cross = globalThis.localWorkerCrossOrigin;
|
||||
const checks = globalThis.localWorkerReferrerChecks = [];
|
||||
const failures = globalThis.localWorkerReferrerFailures = [];
|
||||
let sequence = 0;
|
||||
function policy(owner, value) {
|
||||
const meta = owner.document.createElement('meta');
|
||||
meta.name = 'referrer';
|
||||
meta.content = value;
|
||||
owner.document.head.append(meta);
|
||||
meta.remove();
|
||||
}
|
||||
function blob(owner) {
|
||||
return owner.URL.createObjectURL(new owner.Blob([script], {type: 'text/javascript'}));
|
||||
}
|
||||
function start(owner, url, type, shared, name = 'referrer-' + ++sequence) {
|
||||
const worker = shared ? new owner.SharedWorker(url, {type, name}) : new owner.Worker(url, {type});
|
||||
const channel = shared ? worker.port : worker;
|
||||
const pending = new Map();
|
||||
channel.onmessage = ({data}) => {
|
||||
const operation = pending.get(data.id);
|
||||
if (!operation) return;
|
||||
pending.delete(data.id);
|
||||
clearTimeout(operation.timer);
|
||||
if (data.error) operation.reject(new Error(data.error));
|
||||
else operation.resolve(data.value);
|
||||
};
|
||||
if (shared) channel.start();
|
||||
return {
|
||||
name,
|
||||
send(data) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++sequence;
|
||||
const timer = setTimeout(() => reject(new Error('Worker reply timeout: ' + globalThis.localWorkerReferrerProgress)), 8000);
|
||||
pending.set(id, {resolve, reject, timer});
|
||||
channel.postMessage({...data, id});
|
||||
});
|
||||
},
|
||||
close() {
|
||||
if (shared) {channel.postMessage({kind: 'close'}); channel.close();}
|
||||
else worker.terminate();
|
||||
}
|
||||
};
|
||||
}
|
||||
async function check(worker, expectedPolicy, label) {
|
||||
for (const target of [location.origin, cross]) {
|
||||
for (const explicit of [false, true]) {
|
||||
const command = {kind: 'fetch', url: target + '/meta-policy-fetch?worker=' + ++sequence, referrer: source};
|
||||
if (explicit) command.policy = 'unsafe-url';
|
||||
const expected = explicit || expectedPolicy === 'unsafe-url' ? source :
|
||||
expectedPolicy === 'no-referrer' ? null :
|
||||
expectedPolicy === 'default' && target === location.origin ? source : location.origin + '/';
|
||||
globalThis.localWorkerReferrerProgress = label;
|
||||
const actual = await worker.send(command);
|
||||
checks.push({label, target, explicit, actual, expected});
|
||||
if (actual !== expected) failures.push(label + ': ' + JSON.stringify(actual) + ' != ' + JSON.stringify(expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const shared of [false, true]) {
|
||||
for (const type of ['classic', 'module']) {
|
||||
const label = (shared ? 'shared ' : 'dedicated ') + type;
|
||||
const active = [];
|
||||
const urls = [];
|
||||
const frame = document.createElement('iframe');
|
||||
frame.src = '/local-referrer-page.html?policy=no-referrer';
|
||||
await new Promise(resolve => {frame.onload = resolve; document.body.append(frame);});
|
||||
const child = frame.contentWindow;
|
||||
const launch = (owner, url) => {
|
||||
const worker = start(owner, url, type, shared);
|
||||
active.push(worker);
|
||||
return worker;
|
||||
};
|
||||
try {
|
||||
policy(window, 'unsafe-url');
|
||||
const responseUrl = blob(child); urls.push(responseUrl);
|
||||
const responseWorker = launch(window, responseUrl);
|
||||
await check(responseWorker, 'no-referrer', label + ' Blob creator response policy');
|
||||
policy(window, 'origin');
|
||||
const url = blob(window); urls.push(url);
|
||||
policy(window, 'no-referrer');
|
||||
const first = launch(window, url);
|
||||
await check(first, 'no-referrer', label + ' Blob creator policy at launch');
|
||||
policy(window, 'origin');
|
||||
await check(launch(window, url), 'origin', label + ' later worker');
|
||||
await check(first, 'no-referrer', label + ' existing worker snapshot');
|
||||
if (shared) {
|
||||
const reused = start(window, url, type, true, first.name); active.push(reused);
|
||||
await check(reused, 'no-referrer', label + ' reused worker snapshot');
|
||||
}
|
||||
|
||||
policy(child, 'origin');
|
||||
await check(responseWorker, 'no-referrer', label + ' response policy snapshot after meta delivery');
|
||||
policy(window, 'no-referrer');
|
||||
const foreignUrl = blob(child); urls.push(foreignUrl);
|
||||
const foreign = launch(window, foreignUrl);
|
||||
await check(foreign, 'origin', label + ' Blob URL creator differs from constructor');
|
||||
policy(child, 'no-referrer');
|
||||
await check(launch(window, foreignUrl), 'no-referrer', label + ' creator meta update');
|
||||
await check(foreign, 'origin', label + ' prior foreign worker snapshot');
|
||||
|
||||
policy(window, 'unsafe-url');
|
||||
const parentUrl = blob(window); urls.push(parentUrl);
|
||||
await check(launch(child, parentUrl), 'unsafe-url', label + ' child constructor uses Blob creator');
|
||||
const workerUrl = await first.send({kind: 'blob', source: script}); urls.push(workerUrl);
|
||||
await check(launch(window, workerUrl), 'no-referrer', label + ' worker-created Blob');
|
||||
|
||||
for (const nestedType of shared ? [] : ['classic', 'module']) {
|
||||
const nested = {send: command => first.send({kind: 'nested', source: script, type: nestedType, command})};
|
||||
await check(nested, 'no-referrer', label + ' nested Blob ' + nestedType);
|
||||
}
|
||||
policy(window, 'no-referrer');
|
||||
await check(launch(window, '/local-referrer-worker.js?policy=origin&id=' + ++sequence), 'origin', label + ' network response policy');
|
||||
await check(launch(window, '/local-referrer-worker.js?id=' + ++sequence), 'default', label + ' network default policy');
|
||||
if (!shared) {
|
||||
const networkParent = launch(window, '/local-referrer-worker.js?policy=origin&id=' + ++sequence);
|
||||
const nestedUrl = location.origin + '/local-referrer-worker.js?policy=no-referrer&id=' + ++sequence;
|
||||
const nested = {send: command => networkParent.send({kind: 'nested', url: nestedUrl, type, command})};
|
||||
const entryReferrer = await nested.send({kind: 'entry-referrer'});
|
||||
checks.push({label: label + ' nested script request', actual: entryReferrer, expected: location.origin + '/'});
|
||||
if (entryReferrer !== location.origin + '/') failures.push(label + ': nested entry referrer ' + entryReferrer);
|
||||
await check(nested, 'no-referrer', label + ' nested network response policy');
|
||||
}
|
||||
} finally {
|
||||
for (const worker of active) worker.close();
|
||||
for (const url of urls) URL.revokeObjectURL(url);
|
||||
frame.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failures.length) throw new Error(failures.join('\n'));
|
||||
return true;
|
||||
})();
|
||||
@@ -0,0 +1,57 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn fixture_response(
|
||||
path: &str,
|
||||
query: &str,
|
||||
referer: Option<&str>,
|
||||
) -> (&'static str, String, String) {
|
||||
let policy = url::form_urlencoded::parse(query.as_bytes())
|
||||
.find(|(name, _)| name == "policy")
|
||||
.map(|(_, value)| value.into_owned());
|
||||
let content_type = if path == "/local-referrer-page.html" {
|
||||
"text/html"
|
||||
} else {
|
||||
"text/javascript"
|
||||
};
|
||||
let mut headers = format!("Content-Type: {content_type}\r\nCache-Control: no-store\r\n");
|
||||
if let Some(policy) = policy {
|
||||
headers.push_str(&format!("Referrer-Policy: {policy}\r\n"));
|
||||
}
|
||||
if path == "/local-referrer-page.html" {
|
||||
return (
|
||||
"200 OK",
|
||||
headers,
|
||||
"<!doctype html><body>Worker creator".to_owned(),
|
||||
);
|
||||
}
|
||||
(
|
||||
"200 OK",
|
||||
headers,
|
||||
format!(
|
||||
"globalThis.workerEntryReferrer = {};\n{}",
|
||||
serde_json::to_string(&referer).unwrap(),
|
||||
include_str!("local_worker_referrer_worker.js"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn local_workers_inherit_the_correct_environment_referrer_policy() -> Result<()> {
|
||||
let servers = IntegrityServers::spawn().await?;
|
||||
let browser = Browser::new(AppConfig::default())?;
|
||||
let mut page = browser
|
||||
.fetch(&format!("{}/page.html", servers.origin))
|
||||
.await?;
|
||||
let expression = format!(
|
||||
"globalThis.localWorkerCrossOrigin = {}; {}",
|
||||
serde_json::to_string(&servers.cross_origin)?,
|
||||
include_str!("local_worker_referrer.js"),
|
||||
);
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(40),
|
||||
page.evaluate_runtime_expression_with_await_async(&expression, true),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(result["value"], true, "{result}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
function connect(channel) {
|
||||
channel.onmessage = async ({data}) => {
|
||||
if (data.kind === 'close') {
|
||||
self.close();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let value;
|
||||
if (data.kind === 'fetch') {
|
||||
const options = {referrer: data.referrer};
|
||||
if (data.policy !== undefined) options.referrerPolicy = data.policy;
|
||||
value = await (await fetch(data.url, options)).json();
|
||||
} else if (data.kind === 'blob') {
|
||||
value = URL.createObjectURL(new Blob([data.source], {type: 'text/javascript'}));
|
||||
} else if (data.kind === 'entry-referrer') {
|
||||
value = globalThis.workerEntryReferrer ?? null;
|
||||
} else if (data.kind === 'nested') {
|
||||
const url = data.url || URL.createObjectURL(new Blob([data.source], {type: 'text/javascript'}));
|
||||
const worker = new Worker(url, {type: data.type});
|
||||
try {
|
||||
value = await new Promise((resolve, reject) => {
|
||||
worker.onmessage = event => event.data.error ? reject(new Error(event.data.error)) : resolve(event.data.value);
|
||||
worker.onerror = event => reject(new Error(event.message));
|
||||
worker.postMessage({...data.command, id: 1});
|
||||
});
|
||||
} finally {
|
||||
worker.terminate();
|
||||
if (!data.url) URL.revokeObjectURL(url);
|
||||
}
|
||||
} else {
|
||||
throw new Error('Unknown command: ' + data.kind);
|
||||
}
|
||||
channel.postMessage({id: data.id, value});
|
||||
} catch (error) {
|
||||
channel.postMessage({id: data.id, error: error.name + ': ' + error.message});
|
||||
}
|
||||
};
|
||||
if (channel !== self) channel.start();
|
||||
}
|
||||
|
||||
if ('onconnect' in self) {
|
||||
self.onconnect = event => connect(event.ports[0]);
|
||||
} else {
|
||||
connect(self);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ moli-css-parse = { path = "../moli-css-parse" }
|
||||
moli-html-input-type = { path = "../moli-html-input-type" }
|
||||
moli-html2md = { path = "../moli-html2md" }
|
||||
moli-html-input-temporal = { path = "../moli-html-input-temporal" }
|
||||
parking_lot = "0.12"
|
||||
percent-encoding = "2.3"
|
||||
selectors = "0.41"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
|
||||
@@ -12,6 +12,8 @@ mod tests;
|
||||
|
||||
pub use base_url::DocumentBaseUrlPolicyCheck;
|
||||
use base_url::DocumentBaseUrlState;
|
||||
pub use referrer_policy::DocumentMetaReferrerPolicySource;
|
||||
use referrer_policy::MetaReferrerPolicy;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DocumentTitleSetterTarget {
|
||||
@@ -81,8 +83,6 @@ struct DocumentMetadata {
|
||||
default_language: Option<Box<str>>,
|
||||
source_last_modified_ms: Option<f64>,
|
||||
base_url_state: DocumentBaseUrlState,
|
||||
// Delivered meta policy survives element removal but belongs to this Document.
|
||||
meta_referrer_policy: Option<&'static str>,
|
||||
}
|
||||
|
||||
// Node relationships and the associated template-owner role belong to one
|
||||
@@ -92,7 +92,7 @@ struct DocumentArenaState {
|
||||
source_response_status: Option<u16>,
|
||||
// Meta delivery updates policy in time order; removing the element does
|
||||
// not undo the policy it delivered to this Document.
|
||||
meta_referrer_policy: Option<&'static str>,
|
||||
meta_referrer_policy: MetaReferrerPolicy,
|
||||
// Sticky for this Document; aborting a parser disables document.open/write.
|
||||
active_parser_was_aborted: bool,
|
||||
is_inert_template_document: bool,
|
||||
@@ -140,7 +140,6 @@ impl Document {
|
||||
scripting_enabled,
|
||||
default_language: None,
|
||||
source_last_modified_ms: None,
|
||||
meta_referrer_policy: None,
|
||||
},
|
||||
arena_state: DocumentArenaState::default(),
|
||||
}
|
||||
@@ -165,7 +164,6 @@ impl Document {
|
||||
.metadata
|
||||
.base_url_state
|
||||
.clone_without_tree_caches(self.url()),
|
||||
meta_referrer_policy: None,
|
||||
..self.metadata.clone()
|
||||
},
|
||||
arena_state: DocumentArenaState::default(),
|
||||
@@ -228,10 +226,6 @@ impl Document {
|
||||
self.metadata.ready_state
|
||||
}
|
||||
|
||||
pub fn meta_referrer_policy(&self) -> Option<&str> {
|
||||
self.metadata.meta_referrer_policy
|
||||
}
|
||||
|
||||
pub fn active_parser_was_aborted(&self) -> bool {
|
||||
self.arena_state.active_parser_was_aborted
|
||||
}
|
||||
@@ -241,7 +235,11 @@ impl Document {
|
||||
}
|
||||
|
||||
pub fn meta_referrer_policy(&self) -> Option<&str> {
|
||||
self.arena_state.meta_referrer_policy
|
||||
self.arena_state.meta_referrer_policy.get()
|
||||
}
|
||||
|
||||
pub fn meta_referrer_policy_source(&self) -> DocumentMetaReferrerPolicySource {
|
||||
self.arena_state.meta_referrer_policy.source()
|
||||
}
|
||||
|
||||
pub fn visibility_hidden(&self) -> bool {
|
||||
|
||||
@@ -1,4 +1,52 @@
|
||||
use crate::native::{NativeDom, NativeNodeId, Node};
|
||||
use parking_lot::RwLock;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// A read-only view of a Document's delivered meta policy, retained by local
|
||||
/// resources that refer to its environment after the Document is removed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DocumentMetaReferrerPolicySource(Arc<RwLock<Option<&'static str>>>);
|
||||
|
||||
impl DocumentMetaReferrerPolicySource {
|
||||
pub fn get(&self) -> Option<&'static str> {
|
||||
*self.0.read()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct MetaReferrerPolicy {
|
||||
value: Option<&'static str>,
|
||||
source: OnceLock<DocumentMetaReferrerPolicySource>,
|
||||
}
|
||||
|
||||
impl Clone for MetaReferrerPolicy {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
value: self.value,
|
||||
source: OnceLock::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MetaReferrerPolicy {
|
||||
pub(super) fn get(&self) -> Option<&'static str> {
|
||||
self.value
|
||||
}
|
||||
|
||||
fn set(&mut self, policy: &'static str) {
|
||||
self.value = Some(policy);
|
||||
if let Some(source) = self.source.get() {
|
||||
*source.0.write() = self.value;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn source(&self) -> DocumentMetaReferrerPolicySource {
|
||||
// Ordinary Documents need no allocation or lock for policy reads.
|
||||
self.source
|
||||
.get_or_init(|| DocumentMetaReferrerPolicySource(Arc::new(RwLock::new(self.value))))
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeDom {
|
||||
pub(crate) fn process_meta_referrer(&mut self, handle: NativeNodeId) {
|
||||
@@ -25,7 +73,7 @@ impl NativeDom {
|
||||
.node_mut(document)
|
||||
.and_then(|node| node.data_mut().as_document_mut())
|
||||
{
|
||||
document.metadata.meta_referrer_policy = Some(policy);
|
||||
document.arena_state.meta_referrer_policy.set(policy);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +171,36 @@ mod tests {
|
||||
assert_eq!(policy(&host, document), Some("origin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_meta_referrer_policy_tracks_its_document_and_not_clones() {
|
||||
let mut host = host();
|
||||
let document = host.document_handle();
|
||||
let head = host.document_head_handle().unwrap();
|
||||
let source = host
|
||||
.node(document)
|
||||
.unwrap()
|
||||
.as_document()
|
||||
.unwrap()
|
||||
.meta_referrer_policy_source();
|
||||
let element = meta(&mut host, "origin");
|
||||
assert_eq!(source.get(), None);
|
||||
host.append_child(head, element);
|
||||
let cloned = host.node(document).unwrap().as_document().unwrap().clone();
|
||||
let cloned_source = cloned.meta_referrer_policy_source();
|
||||
assert_eq!(source.get(), Some("origin"));
|
||||
assert_eq!(cloned_source.get(), Some("origin"));
|
||||
host.set_attribute(element, "content", "no-referrer");
|
||||
host.remove_child(head, element);
|
||||
assert_eq!(source.get(), Some("no-referrer"));
|
||||
assert_eq!(cloned_source.get(), Some("origin"));
|
||||
assert_eq!(
|
||||
cloned.clone_for_node().meta_referrer_policy_source().get(),
|
||||
None
|
||||
);
|
||||
drop(host);
|
||||
assert_eq!(source.get(), Some("no-referrer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meta_referrer_accepts_html_aliases_but_not_header_lists_or_whitespace() {
|
||||
let mut host = host();
|
||||
|
||||
@@ -18,8 +18,8 @@ use std::sync::Arc;
|
||||
|
||||
use document::DocumentKind;
|
||||
pub use document::{
|
||||
Document, DocumentBaseUrlPolicyCheck, DocumentFragment, DocumentReadyState,
|
||||
DocumentTitleSetterTarget, DocumentType,
|
||||
Document, DocumentBaseUrlPolicyCheck, DocumentFragment, DocumentMetaReferrerPolicySource,
|
||||
DocumentReadyState, DocumentTitleSetterTarget, DocumentType,
|
||||
};
|
||||
pub use element::{
|
||||
Attribute, CustomElementState, Element, SelectedFile, html_element_interface_name,
|
||||
|
||||
@@ -32,10 +32,25 @@ type RendererBlobStore = BlobStore<
|
||||
ResourceOwnerId,
|
||||
RendererStoragePartitionIdentity,
|
||||
ObjectUrlAccessKey,
|
||||
crate::content_security_policy::ContentSecurityPolicySource,
|
||||
ObjectUrlPolicySource,
|
||||
Arc<MediaSourceObject>,
|
||||
>;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ObjectUrlPolicySource {
|
||||
pub(crate) content_security_policy: crate::content_security_policy::ContentSecurityPolicySource,
|
||||
pub(crate) referrer_policy: Option<String>,
|
||||
pub(crate) document_meta_referrer_policy:
|
||||
Option<moli_dom::native::DocumentMetaReferrerPolicySource>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ObjectUrlPolicySnapshot {
|
||||
pub(crate) content_security_policy:
|
||||
crate::content_security_policy::InheritedContentSecurityPolicy,
|
||||
pub(crate) referrer_policy: Option<String>,
|
||||
}
|
||||
|
||||
static BLOB_STORE: OnceLock<RendererBlobStore> = OnceLock::new();
|
||||
|
||||
fn blob_store() -> &'static RendererBlobStore {
|
||||
@@ -109,16 +124,20 @@ pub(super) fn create_object_url_for_object<'s>(
|
||||
let origin = storage_key.origin().to_owned();
|
||||
let lifetime_id = native_bridge::current_runtime_observable_context_token(scope)
|
||||
.map(native_bridge::RuntimeObservableContextToken::as_u64);
|
||||
let policy_source = if let Some(host_ptr) =
|
||||
crate::util::context_host_ptr_from_global_bridge(scope)
|
||||
{
|
||||
let global = scope.get_current_context().global(scope);
|
||||
// SAFETY: the Window callback keeps its host alive for this call.
|
||||
unsafe { &*host_ptr }.local_worker_content_security_policy_source_for_global(scope, global)
|
||||
} else {
|
||||
crate::worker::worker_content_security_policy_snapshot(scope)
|
||||
.map(|policy| Arc::new(parking_lot::RwLock::new(policy)))
|
||||
};
|
||||
let policy_source =
|
||||
if let Some(host_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) {
|
||||
let global = scope.get_current_context().global(scope);
|
||||
// SAFETY: the Window callback keeps its host alive for this call.
|
||||
unsafe { &*host_ptr }.object_url_policy_source_for_global(scope, global)
|
||||
} else {
|
||||
crate::worker::worker_content_security_policy_snapshot(scope).map(|policy| {
|
||||
ObjectUrlPolicySource {
|
||||
content_security_policy: Arc::new(parking_lot::RwLock::new(policy)),
|
||||
referrer_policy: crate::worker::worker_referrer_policy(scope),
|
||||
document_meta_referrer_policy: None,
|
||||
}
|
||||
})
|
||||
};
|
||||
blob_store().create_object_url_with_target(
|
||||
owner_id,
|
||||
lifetime_id,
|
||||
@@ -138,10 +157,17 @@ pub(crate) fn object_url_data(url: &str) -> Option<RendererObjectUrlData> {
|
||||
blob_store().object_url_data(url)
|
||||
}
|
||||
|
||||
pub(crate) fn object_url_content_security_policy(
|
||||
url: &str,
|
||||
) -> Option<crate::content_security_policy::InheritedContentSecurityPolicy> {
|
||||
Some(blob_store().object_url_metadata(url)?.read().clone())
|
||||
pub(crate) fn object_url_policy(url: &str) -> Option<ObjectUrlPolicySnapshot> {
|
||||
let source = blob_store().object_url_metadata(url)?;
|
||||
Some(ObjectUrlPolicySnapshot {
|
||||
content_security_policy: source.content_security_policy.read().clone(),
|
||||
referrer_policy: source
|
||||
.document_meta_referrer_policy
|
||||
.as_ref()
|
||||
.and_then(moli_dom::native::DocumentMetaReferrerPolicySource::get)
|
||||
.map(str::to_owned)
|
||||
.or(source.referrer_policy),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn revoke_object_url(
|
||||
|
||||
@@ -256,7 +256,7 @@ fn shared_worker_constructor_callback_inner<'s>(
|
||||
.local_worker_content_security_policy_source_for_global(scope, global)
|
||||
.map(|source| source.read().clone())
|
||||
.unwrap_or_default();
|
||||
script_load.with_ready_content_security_policy(policy)
|
||||
script_load.with_ready_inherited_policies(policy, context.document_referrer_policy.clone())
|
||||
} else {
|
||||
script_load
|
||||
};
|
||||
|
||||
@@ -256,7 +256,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
|
||||
// Capture the creator policy before loading the body so concurrent URL
|
||||
// revocation cannot leave a loaded script without its policy.
|
||||
let blob_policy = (resolved_url.scheme() == "blob")
|
||||
.then(|| crate::blob::object_url_content_security_policy(resolved_url.as_str()));
|
||||
.then(|| crate::blob::object_url_policy(resolved_url.as_str()));
|
||||
let materialized = match materialize_worker_script_source(&resolved_url) {
|
||||
Ok(source) => source,
|
||||
Err(message) => {
|
||||
@@ -266,12 +266,16 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
|
||||
};
|
||||
let creator_secure_context = worker_creator_secure_context(scope, host, child_handle);
|
||||
let worker_id = if let Some(script_source) = materialized {
|
||||
let inherited_policy = if let Some(policy) = blob_policy {
|
||||
policy.unwrap_or_default()
|
||||
let (inherited_policy, inherited_referrer_policy) = if let Some(policy) = blob_policy {
|
||||
let policy = policy.unwrap_or_default();
|
||||
(policy.content_security_policy, policy.referrer_policy)
|
||||
} else {
|
||||
host.local_worker_content_security_policy_source_for_owner(dispatch_scope)
|
||||
.map(|source| source.read().clone())
|
||||
.unwrap_or_default()
|
||||
(
|
||||
host.local_worker_content_security_policy_source_for_owner(dispatch_scope)
|
||||
.map(|source| source.read().clone())
|
||||
.unwrap_or_default(),
|
||||
document_referrer_policy,
|
||||
)
|
||||
};
|
||||
let request_url = worker_script_resource_url(&resolved_url);
|
||||
let network_response =
|
||||
@@ -307,6 +311,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
|
||||
)
|
||||
.with_script_kind(worker_options.worker_type)
|
||||
.with_content_security_policy_snapshot(inherited_policy)
|
||||
.with_referrer_policy(inherited_referrer_policy)
|
||||
.with_module_credentials_mode(worker_options.credentials_mode.0)
|
||||
.with_module_static_import_initiator_url(base_url.clone())
|
||||
.with_module_static_import_content_security_policies(document_content_security_policies)
|
||||
@@ -471,7 +476,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
|
||||
);
|
||||
return;
|
||||
}
|
||||
let (script_url, script_source, content_security_policy) = match materialize_nested_worker_script_source(
|
||||
let loaded = match materialize_nested_worker_script_source(
|
||||
&resolved_url,
|
||||
&nested_context,
|
||||
worker_options.worker_type,
|
||||
@@ -498,12 +503,14 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
|
||||
}
|
||||
};
|
||||
let mut network_policy = nested_context.network_policy.clone();
|
||||
let secure_context = Url::parse(&script_url).ok().is_some_and(|script_url| {
|
||||
nested_context
|
||||
.network_policy
|
||||
.secure_context
|
||||
.resolve(&script_url)
|
||||
});
|
||||
let secure_context = Url::parse(&loaded.script_url)
|
||||
.ok()
|
||||
.is_some_and(|script_url| {
|
||||
nested_context
|
||||
.network_policy
|
||||
.secure_context
|
||||
.resolve(&script_url)
|
||||
});
|
||||
network_policy.secure_context = WorkerSecureContextPolicy::Inherited(secure_context);
|
||||
let reserved_service_worker_client_id =
|
||||
reserve_nested_inherited_service_worker_worker_client_for_local_script(
|
||||
@@ -516,12 +523,13 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
|
||||
worker_policy_context.cross_origin_isolated = false;
|
||||
}
|
||||
let options = WorkerSpawnOptions::new_with_request_client(
|
||||
script_source,
|
||||
script_url,
|
||||
loaded.source,
|
||||
loaded.script_url,
|
||||
nested_context.loader.request_client().clone(),
|
||||
)
|
||||
.with_interception_context(nested_context.interception_context.clone())
|
||||
.with_content_security_policy_snapshot(content_security_policy)
|
||||
.with_content_security_policy_snapshot(loaded.content_security_policy)
|
||||
.with_referrer_policy(loaded.referrer_policy)
|
||||
.with_script_kind(worker_options.worker_type)
|
||||
.with_module_credentials_mode(worker_options.credentials_mode.0)
|
||||
.with_module_static_import_initiator_url(nested_context.base_url.clone())
|
||||
@@ -854,28 +862,37 @@ fn child_context_handle_from_global<'s>(
|
||||
.map(|value| DomHandle::new(value as usize))
|
||||
}
|
||||
|
||||
struct LoadedNestedWorkerScript {
|
||||
script_url: String,
|
||||
source: String,
|
||||
content_security_policy: crate::content_security_policy::InheritedContentSecurityPolicy,
|
||||
referrer_policy: Option<String>,
|
||||
}
|
||||
|
||||
fn materialize_nested_worker_script_source(
|
||||
script_url: &Url,
|
||||
context: &NestedWorkerContext,
|
||||
script_kind: WorkerScriptKind,
|
||||
module_credentials_mode: moli_fetch::RequestCredentialsMode,
|
||||
) -> Result<
|
||||
(
|
||||
String,
|
||||
String,
|
||||
crate::content_security_policy::InheritedContentSecurityPolicy,
|
||||
),
|
||||
String,
|
||||
> {
|
||||
) -> Result<LoadedNestedWorkerScript, String> {
|
||||
let blob_policy = (script_url.scheme() == "blob")
|
||||
.then(|| crate::blob::object_url_content_security_policy(script_url.as_str()));
|
||||
.then(|| crate::blob::object_url_policy(script_url.as_str()));
|
||||
if let Some(source) = materialize_worker_script_source(script_url)? {
|
||||
let policy = if let Some(policy) = blob_policy {
|
||||
policy.unwrap_or_default()
|
||||
let (content_security_policy, referrer_policy) = if let Some(policy) = blob_policy {
|
||||
let policy = policy.unwrap_or_default();
|
||||
(policy.content_security_policy, policy.referrer_policy)
|
||||
} else {
|
||||
context.content_security_policy_snapshot.clone()
|
||||
(
|
||||
context.content_security_policy_snapshot.clone(),
|
||||
context.referrer_policy.clone(),
|
||||
)
|
||||
};
|
||||
return Ok((script_url.to_string(), source, policy));
|
||||
return Ok(LoadedNestedWorkerScript {
|
||||
script_url: script_url.to_string(),
|
||||
source,
|
||||
content_security_policy,
|
||||
referrer_policy,
|
||||
});
|
||||
}
|
||||
let loader = context.loader.clone();
|
||||
let resource_url = worker_script_resource_url(script_url);
|
||||
@@ -895,7 +912,11 @@ fn materialize_nested_worker_script_source(
|
||||
.creator_message_security
|
||||
.serialized_origin()
|
||||
.unwrap_or("null"),
|
||||
));
|
||||
))
|
||||
.with_script_fetch_metadata(moli_fetch::ScriptFetchRequestMetadata {
|
||||
document_referrer_policy: context.referrer_policy.clone(),
|
||||
..Default::default()
|
||||
});
|
||||
let response = loader
|
||||
.request_client()
|
||||
.fetch_text_for_worker_blocking_boundary(request)
|
||||
@@ -916,6 +937,8 @@ fn materialize_nested_worker_script_source(
|
||||
response.body_bytes(),
|
||||
)?;
|
||||
let (head, body) = response.into_text_parts();
|
||||
let referrer_policy =
|
||||
crate::referrer_policy::response_referrer_policy_from_headers(&head.headers);
|
||||
let policy = crate::content_security_policy::InheritedContentSecurityPolicy {
|
||||
self_url: Some(head.final_url.clone()),
|
||||
header_policies: crate::content_security_policy::content_security_policy_headers(
|
||||
@@ -934,7 +957,12 @@ fn materialize_nested_worker_script_source(
|
||||
};
|
||||
let mut final_url = head.final_url;
|
||||
final_url.set_fragment(script_url.fragment());
|
||||
Ok((final_url.to_string(), body, policy))
|
||||
Ok(LoadedNestedWorkerScript {
|
||||
script_url: final_url.to_string(),
|
||||
source: body,
|
||||
content_security_policy: policy,
|
||||
referrer_policy,
|
||||
})
|
||||
}
|
||||
|
||||
fn worker_script_inherits_parent_service_worker_controller(script_url: &Url) -> bool {
|
||||
|
||||
@@ -428,6 +428,25 @@ impl PageScriptHost {
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn object_url_policy_source_for_global<'s>(
|
||||
&self,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
global: v8::Local<'s, v8::Object>,
|
||||
) -> Option<crate::blob::ObjectUrlPolicySource> {
|
||||
let owner = policy_owner_dispatch_scope_for_global(scope, global);
|
||||
let snapshot = self.owner_document_policy_snapshot(owner)?;
|
||||
Some(crate::blob::ObjectUrlPolicySource {
|
||||
content_security_policy: self
|
||||
.local_worker_content_security_policy_source_for_owner(owner)?,
|
||||
referrer_policy: snapshot.policy_container.referrer_policy,
|
||||
document_meta_referrer_policy: snapshot
|
||||
.document_handle
|
||||
.and_then(|document| self.dom_host().node(document))
|
||||
.and_then(moli_dom::native::Node::as_document)
|
||||
.map(moli_dom::native::Document::meta_referrer_policy_source),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn document_permissions_policy_for_owner(
|
||||
&self,
|
||||
owner: OwnerDispatchScope,
|
||||
|
||||
@@ -362,12 +362,14 @@ impl SharedWorkerLoadedScript {
|
||||
}
|
||||
|
||||
impl SharedWorkerScriptLoad {
|
||||
pub(crate) fn with_ready_content_security_policy(
|
||||
pub(crate) fn with_ready_inherited_policies(
|
||||
mut self,
|
||||
policy: crate::content_security_policy::InheritedContentSecurityPolicy,
|
||||
referrer_policy: Option<String>,
|
||||
) -> Self {
|
||||
if let SharedWorkerScriptLoadKind::Ready(script) = &mut self.kind {
|
||||
script.content_security_policy_snapshot = Some(Box::new(policy));
|
||||
script.response_referrer_policy = referrer_policy;
|
||||
}
|
||||
self
|
||||
}
|
||||
@@ -611,12 +613,13 @@ pub(super) fn load_shared_worker_blob_script_source(
|
||||
) -> Result<SharedWorkerLoadedScript, String> {
|
||||
let mut resource_url = script_url.clone();
|
||||
resource_url.set_fragment(None);
|
||||
let policy =
|
||||
crate::blob::object_url_content_security_policy(resource_url.as_str()).unwrap_or_default();
|
||||
let policy = crate::blob::object_url_policy(resource_url.as_str()).unwrap_or_default();
|
||||
crate::blob::object_url_body_and_type(resource_url.as_str())
|
||||
.map(|(body, _)| {
|
||||
let mut script = SharedWorkerLoadedScript::new(script_url.to_string(), body);
|
||||
script.content_security_policy_snapshot = Some(Box::new(policy));
|
||||
script.content_security_policy_snapshot =
|
||||
Some(Box::new(policy.content_security_policy));
|
||||
script.response_referrer_policy = policy.referrer_policy;
|
||||
script
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
|
||||
@@ -222,7 +222,8 @@ use state::worker_close_callback;
|
||||
pub(crate) use state::{
|
||||
WorkerGlobalState, get_worker_state, worker_content_security_policy_snapshot,
|
||||
worker_current_script_url, worker_exception_report_target, worker_global_is_closed,
|
||||
worker_realm_secure_context_available, worker_service_worker_control_state, worker_storage_key,
|
||||
worker_storage_partition_identity, worker_termination_requested,
|
||||
worker_realm_secure_context_available, worker_referrer_policy,
|
||||
worker_service_worker_control_state, worker_storage_key, worker_storage_partition_identity,
|
||||
worker_termination_requested,
|
||||
};
|
||||
pub(super) use timers::{TimerInfo, WorkerIsolateTimerQueues, worker_isolate_timer_queues};
|
||||
|
||||
@@ -27,6 +27,7 @@ pub(crate) struct NestedWorkerContext {
|
||||
pub(crate) module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
|
||||
pub(crate) content_security_policy_snapshot:
|
||||
crate::content_security_policy::InheritedContentSecurityPolicy,
|
||||
pub(crate) referrer_policy: Option<String>,
|
||||
pub(crate) require_trusted_types_for_script: bool,
|
||||
pub(crate) network_policy: crate::worker::handle::WorkerNetworkPolicy,
|
||||
pub(crate) policy_context: crate::types::SubresourcePolicyContext,
|
||||
@@ -64,6 +65,7 @@ pub(crate) fn reserve_nested_worker_context(
|
||||
storage_bucket_store: state.storage_bucket_store.clone(),
|
||||
module_static_import_content_security_policies: state.content_security_policies.clone(),
|
||||
content_security_policy_snapshot: content_security_policy::worker_policy_snapshot(&state),
|
||||
referrer_policy: state.referrer_policy.clone(),
|
||||
require_trusted_types_for_script:
|
||||
crate::content_security_policy::content_security_policy_requires_trusted_types_for_script(
|
||||
&state.content_security_policies,
|
||||
|
||||
@@ -344,6 +344,10 @@ pub(crate) fn worker_storage_partition_identity(
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn worker_referrer_policy(scope: &mut v8::PinScope<'_, '_>) -> Option<String> {
|
||||
get_worker_state(scope)?.borrow().referrer_policy.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn worker_current_script_url(scope: &mut v8::PinScope<'_, '_>) -> Option<Url> {
|
||||
get_worker_state(scope)?.borrow().current_script_url.clone()
|
||||
}
|
||||
|
||||
@@ -56,11 +56,11 @@ pub(crate) use global_scope::{
|
||||
worker_allows_wasm_code_generation_by_csp,
|
||||
worker_broadcast_channel_registry, worker_broadcast_channel_storage_key,
|
||||
worker_broadcast_channel_wake_sender, worker_broadcast_channel_wrapper,
|
||||
worker_content_security_policy_snapshot,
|
||||
worker_current_script_url, worker_global_is_closed, worker_global_origin,
|
||||
worker_message_port_registry, worker_message_port_wake_sender, worker_message_port_wrapper,
|
||||
worker_notification_permission_state, worker_opfs_directory_iterator_registry,
|
||||
worker_opfs_handle_registry, worker_realm_secure_context_available,
|
||||
worker_content_security_policy_snapshot, worker_current_script_url, worker_global_is_closed,
|
||||
worker_global_origin, worker_message_port_registry, worker_message_port_wake_sender,
|
||||
worker_message_port_wrapper, worker_notification_permission_state,
|
||||
worker_opfs_directory_iterator_registry, worker_opfs_handle_registry,
|
||||
worker_realm_secure_context_available, worker_referrer_policy,
|
||||
worker_service_worker_control_state, worker_storage_key, worker_storage_partition_identity,
|
||||
worker_termination_requested, worker_trusted_types_for_script_requirements,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user