Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(fetch): unify script headers and CORS response validation

ldm04a1e6fd19688
diff --git a/moli-core/tests/scripts/integrity.rs b/moli-core/tests/scripts/integrity.rs
index e65d08ab8..43fd222ba 100644
--- a/moli-core/tests/scripts/integrity.rs
+++ b/moli-core/tests/scripts/integrity.rs
@@ -23,6 +23,9 @@ struct IntegrityRequest {
path: String,
origin: Option<String>,
cookie: Option<String>,
+ sec_fetch_dest: Option<String>,
+ sec_fetch_mode: Option<String>,
+ sec_fetch_site: Option<String>,
}
impl Drop for IntegrityServers {
@@ -69,6 +72,9 @@ impl IntegrityServers {
let incoming = IntegrityRequest {
method: request.split_whitespace().next().unwrap_or("GET").to_owned(),
path: path.to_owned(), origin: header("Origin"), cookie: header("Cookie"),
+ sec_fetch_dest: header("Sec-Fetch-Dest"),
+ sec_fetch_mode: header("Sec-Fetch-Mode"),
+ sec_fetch_site: header("Sec-Fetch-Site"),
};
let (status, headers, body) = fixture_response(&incoming, &origin, &cross_origin);
requests.lock().push(incoming);
@@ -100,6 +106,9 @@ fn network_cases(origin: &str, cross: &str) -> serde_json::Value {
{"name": "cross-no-cors", "src": format!("{cross}/script.js"), "integrity": INTEGRITY, "expected": "error"},
{"name": "cross-anonymous", "src": format!("{cross}/cors.js"), "integrity": INTEGRITY, "crossOrigin": "anonymous", "expected": "load"},
{"name": "cross-no-acao", "src": format!("{cross}/script.js"), "integrity": INTEGRITY, "crossOrigin": "anonymous", "expected": "error"},
+ {"name": "cors-without-integrity", "src": format!("{cross}/script.js"), "crossOrigin": "anonymous", "expected": "error"},
+ {"name": "cors-empty-integrity", "src": format!("{cross}/script.js"), "integrity": "", "crossOrigin": "anonymous", "expected": "error"},
+ {"name": "cors-unsupported-integrity", "src": format!("{cross}/script.js"), "integrity": "sha1-ignored", "crossOrigin": "anonymous", "expected": "error"},
{"name": "redirect-cross", "src": format!("{origin}/redirect.js"), "integrity": INTEGRITY, "expected": "error"},
{"name": "redirect-home", "src": format!("{origin}/roundtrip.js"), "integrity": INTEGRITY, "expected": "error"},
{"name": "cors-redirect", "src": format!("{origin}/cors-redirect.js"), "integrity": INTEGRITY, "crossOrigin": "anonymous", "expected": "load"},
@@ -121,7 +130,11 @@ fn fixture_response(
let (path, query) = request.path.split_once('?').unwrap_or((&request.path, ""));
let javascript = "Content-Type: text/javascript\r\n";
match path {
- "/echo-origin.js" | "/echo-origin-redirect.js" => {
+ "/echo-origin.js"
+ | "/echo-origin-redirect.js"
+ | "/echo-origin-home.js"
+ | "/echo-origin-roundtrip.js"
+ | "/module-graph.js" => {
// Echo the actual request Origin: a missing header must not silently
// receive ACAO: null and hide a broken redirect handoff.
let mut headers = format!(
@@ -134,13 +147,87 @@ fn fixture_response(
headers.push_str("Access-Control-Allow-Methods: GET, PUT\r\nAccess-Control-Allow-Headers: x-sri-test\r\n");
return ("204 No Content", headers, String::new());
}
- if path == "/echo-origin-redirect.js" {
- headers.push_str(&format!("Location: {cross}/echo-origin.js?{query}\r\n"));
+ let target = match path {
+ "/echo-origin-redirect.js" => Some(format!("{cross}/echo-origin.js?{query}")),
+ "/echo-origin-home.js" => Some(format!("{origin}/echo-origin.js?{query}")),
+ "/echo-origin-roundtrip.js" => Some(format!("{cross}/echo-origin-home.js?{query}")),
+ _ => None,
+ };
+ if let Some(target) = target {
+ headers.push_str(&format!("Location: {target}\r\n"));
("302 Found", headers, String::new())
+ } else if path == "/module-graph.js" {
+ (
+ "200 OK",
+ headers,
+ format!(
+ "import '{cross}/{}';",
+ if query == "graph-blocked" {
+ "script.js?blocked-static"
+ } else {
+ "echo-origin.js?static-dependency"
+ }
+ ),
+ )
} else {
("200 OK", headers, SCRIPT.to_owned())
}
}
+ "/style.css"
+ | "/style-roundtrip.css"
+ | "/style-home.css"
+ | "/app.webmanifest"
+ | "/manifest-roundtrip.webmanifest"
+ | "/manifest-home.webmanifest" => {
+ let mut headers = "Cache-Control: no-store\r\nVary: Origin\r\n".to_owned();
+ if let Some(incoming_origin) = &request.origin
+ && !(query == "bad-hop" && path.contains("-home."))
+ {
+ let allowed_origin = if query == "bad-final" && !path.contains('-') {
+ origin
+ } else {
+ incoming_origin
+ };
+ headers.push_str(&format!(
+ "Access-Control-Allow-Origin: {allowed_origin}\r\n"
+ ));
+ }
+ let target = match path {
+ "/style-roundtrip.css" => Some(format!("{cross}/style-home.css?{query}")),
+ "/style-home.css" => Some(format!("{origin}/style.css?{query}")),
+ "/manifest-roundtrip.webmanifest" => {
+ Some(format!("{cross}/manifest-home.webmanifest?{query}"))
+ }
+ "/manifest-home.webmanifest" => Some(format!("{origin}/app.webmanifest?{query}")),
+ _ => None,
+ };
+ if let Some(target) = target {
+ headers.push_str(&format!("Location: {target}\r\n"));
+ ("302 Found", headers, String::new())
+ } else if path.ends_with(".css") {
+ headers.push_str("Content-Type: text/css\r\n");
+ ("200 OK", headers, "body { color: green; }".to_owned())
+ } else {
+ headers.push_str("Content-Type: application/manifest+json\r\n");
+ (
+ "200 OK",
+ headers,
+ r#"{"name":"Redirected manifest"}"#.to_owned(),
+ )
+ }
+ }
+ "/manifest-page.html" => (
+ "200 OK",
+ "Content-Type: text/html\r\n".to_owned(),
+ format!(
+ "<!doctype html><link rel=manifest href='/{}?{query}'>",
+ if query == "same-origin" {
+ "app.webmanifest"
+ } else {
+ "manifest-roundtrip.webmanifest"
+ }
+ ),
+ ),
"/script.js" => ("200 OK", javascript.to_owned(), SCRIPT.to_owned()),
"/cacheable.js" => (
"200 OK",
@@ -240,8 +327,11 @@ fn fixture_response(
);
("200 OK", javascript.to_owned(), body)
}
- "/page.html" | "/parser.html" | "/cookie-page.html" => {
+ "/page.html" | "/parser.html" | "/cookie-page.html" | "/csp-page.html" => {
let mut html = "<!doctype html><body><script>globalThis.sriEvents = {}; globalThis.sriExecutions = 0;</script>".to_owned();
+ if path == "/csp-page.html" {
+ html.insert_str(15, "<meta http-equiv='Content-Security-Policy' content=\"script-src 'self' 'unsafe-inline'\">");
+ }
if path == "/parser.html" {
for case in network_cases(origin, cross).as_array().unwrap() {
let name = case["name"].as_str().unwrap();
@@ -354,12 +444,343 @@ async fn module_script_integrity_requires_readable_response() -> Result<()> {
let cases = serde_json::json!([
{"name": "same-origin", "src": "/script.js", "type": "module", "integrity": INTEGRITY, "expected": "load"},
{"name": "cors", "src": format!("{}/cors.js", servers.cross_origin), "type": "module", "integrity": INTEGRITY, "expected": "load"},
- {"name": "no-acao", "src": format!("{}/script.js", servers.cross_origin), "type": "module", "integrity": INTEGRITY, "expected": "error"}
+ {"name": "no-acao", "src": format!("{}/script.js", servers.cross_origin), "type": "module", "integrity": INTEGRITY, "expected": "error"},
+ {"name": "without-integrity", "src": format!("{}/script.js?absent", servers.cross_origin), "type": "module", "expected": "error"},
+ {"name": "empty-integrity", "src": format!("{}/script.js?empty", servers.cross_origin), "type": "module", "integrity": "", "expected": "error"},
+ {"name": "unsupported-integrity", "src": format!("{}/script.js?unsupported", servers.cross_origin), "type": "module", "integrity": "sha1-ignored", "expected": "error"}
+ ]);
+ let result = page
+ .evaluate_runtime_expression_with_await_async(&dynamic_probe(&cases, false), true)
+ .await?;
+ assert_integrity_results(result, &cases);
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn direct_scripts_send_origin_and_fetch_metadata() -> Result<()> {
+ let servers = IntegrityServers::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let mut page = browser
+ .fetch(&format!("{}/cookie-page.html", servers.origin))
+ .await?;
+ let origin = &servers.origin;
+ let cross = &servers.cross_origin;
+ let cases = serde_json::json!([
+ {"name": "control", "src": "/echo-origin.js?control", "type": "module", "integrity": INTEGRITY, "expected": "load"},
+ {"name": "classic", "src": format!("{cross}/echo-origin.js?classic"), "crossOrigin": "anonymous", "integrity": INTEGRITY, "expected": "load"},
+ {"name": "module", "src": format!("{cross}/echo-origin.js?module"), "type": "module", "integrity": INTEGRITY, "expected": "load"},
+ {"name": "include", "src": format!("{cross}/echo-origin.js?include"), "type": "module", "crossOrigin": "use-credentials", "integrity": INTEGRITY, "expected": "load"},
+ {"name": "home", "src": format!("{cross}/echo-origin-home.js?home"), "type": "module", "integrity": INTEGRITY, "expected": "load"},
+ {"name": "roundtrip", "src": "/echo-origin-roundtrip.js?roundtrip", "type": "module", "integrity": INTEGRITY, "expected": "load"},
+ {"name": "no-cors", "src": format!("{cross}/echo-origin.js?no-cors"), "expected": "load"},
+ {"name": "graph", "src": "/module-graph.js?graph", "type": "module", "expected": "load"},
+ {"name": "graph-blocked", "src": "/module-graph.js?graph-blocked", "type": "module", "expected": "error"}
]);
let result = page
.evaluate_runtime_expression_with_await_async(&dynamic_probe(&cases, false), true)
.await?;
assert_integrity_results(result, &cases);
+ let imported = page
+ .evaluate_runtime_expression_with_await_async(
+ &format!("import('{cross}/echo-origin.js?dynamic-import').then(() => 'loaded')"),
+ true,
+ )
+ .await?;
+ assert_eq!(imported["value"], "loaded");
+ let rejected = page
+ .evaluate_runtime_expression_with_await_async(
+ &format!(
+ "import('{cross}/script.js?blocked-dynamic').then(() => 'loaded', () => 'rejected')"
+ ),
+ true,
+ )
+ .await?;
+ assert_eq!(rejected["value"], "rejected");
+ let executions = page
+ .evaluate_runtime_expression_async("sriExecutions")
+ .await?;
+ assert_eq!(
+ executions["value"], 9,
+ "CORS-rejected dependencies must not execute"
+ );
+
+ let requests = servers.requests.lock();
+ for name in [
+ "control",
+ "classic",
+ "module",
+ "include",
+ "home",
+ "roundtrip",
+ "no-cors",
+ "graph",
+ "graph-blocked",
+ "static-dependency",
+ "dynamic-import",
+ "blocked-static",
+ "blocked-dynamic",
+ ] {
+ let actual: Vec<_> = requests
+ .iter()
+ .filter(|request| request.path.ends_with(&format!("?{name}")))
+ .collect();
+ let expected_origins = match name {
+ "home" => vec![Some(origin.as_str()), Some("null")],
+ "roundtrip" => vec![None, Some(origin.as_str()), Some("null")],
+ "control" | "graph" | "graph-blocked" | "no-cors" => vec![None],
+ _ => vec![Some(origin.as_str())],
+ };
+ assert_eq!(actual.len(), expected_origins.len(), "{name}: {actual:?}");
+ for (index, (request, expected_origin)) in actual.iter().zip(expected_origins).enumerate() {
+ assert_eq!(
+ request.origin.as_deref(),
+ expected_origin,
+ "{name}: {request:?}"
+ );
+ assert_eq!(
+ request.sec_fetch_dest.as_deref(),
+ Some("script"),
+ "{name}: {request:?}"
+ );
+ assert_eq!(
+ request.sec_fetch_mode.as_deref(),
+ Some(if name == "no-cors" { "no-cors" } else { "cors" }),
+ "{name}: {request:?}"
+ );
+ let same_origin = matches!(name, "control" | "graph" | "graph-blocked")
+ || (name == "roundtrip" && index == 0);
+ assert_eq!(
+ request.sec_fetch_site.as_deref(),
+ Some(if same_origin {
+ "same-origin"
+ } else {
+ "same-site"
+ }),
+ "{name}: {request:?}"
+ );
+ assert_eq!(
+ request.cookie.as_deref(),
+ if same_origin || matches!(name, "include" | "no-cors") {
+ Some("sriSession=present")
+ } else {
+ None
+ },
+ "{name}: {request:?}"
+ );
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn srcdoc_module_requests_use_window_origin_instead_of_base_url() -> Result<()> {
+ let servers = IntegrityServers::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let mut page = browser
+ .fetch(&format!("{}/cookie-page.html", servers.origin))
+ .await?;
+ let result = page.evaluate_runtime_expression_with_await_async(&format!(r#"(async () => {{
+ const results = [];
+ for (const kind of ['module', 'classic', 'preload', 'dynamic']) {{
+ for (const originKind of ['same-origin', 'inherited', 'sandboxed']) {{
+ const name = originKind + '-' + kind;
+ const frame = document.createElement('iframe');
+ if (originKind === 'sandboxed') frame.setAttribute('sandbox', 'allow-scripts');
+ const terminal = new Promise(resolve => {{
+ const handler = event => {{
+ if (event.source !== frame.contentWindow || !String(event.data).startsWith(name + ':')) return;
+ removeEventListener('message', handler);
+ resolve(event.data);
+ }};
+ addEventListener('message', handler);
+ }});
+ const terminalAttributes = `onload="parent.postMessage('${{name}}:load', '*')" onerror="parent.postMessage('${{name}}:error', '*')"`;
+ const source = './echo-origin.js?' + name;
+ const resource = kind === 'preload'
+ ? `<link rel='modulepreload' href='${{source}}' integrity='{INTEGRITY}' ${{terminalAttributes}}>`
+ : kind === 'dynamic'
+ ? `<script>import('${{source}}').then(() => parent.postMessage('${{name}}:load', '*'), () => parent.postMessage('${{name}}:error', '*'));<\/script>`
+ : `<script type='${{kind === 'module' ? 'module' : 'text/javascript'}}' crossorigin='anonymous' src='${{source}}' integrity='{INTEGRITY}' ${{terminalAttributes}}><\/script>`;
+ frame.srcdoc = `<base href='${{originKind === 'same-origin' ? location.origin : '{cross}'}}/'>` + resource;
+ document.body.append(frame);
+ results.push(await terminal);
+ frame.remove();
+ }}
+ }}
+ return JSON.stringify(results);
+ }})()"#, cross = servers.cross_origin), true).await?;
+ let result: serde_json::Value = serde_json::from_str(result["value"].as_str().unwrap())?;
+ let mut expected = Vec::new();
+ let requests = servers.requests.lock();
+ for kind in ["module", "classic", "preload", "dynamic"] {
+ for (origin_kind, origin) in [
+ ("same-origin", None),
+ ("inherited", Some(servers.origin.as_str())),
+ ("sandboxed", Some("null")),
+ ] {
+ let name = format!("{origin_kind}-{kind}");
+ expected.push(format!("{name}:load"));
+ let request = requests
+ .iter()
+ .find(|request| request.path == format!("/echo-origin.js?{name}"))
+ .expect("child script request");
+ assert_eq!(request.origin.as_deref(), origin, "{request:?}");
+ assert_eq!(request.sec_fetch_dest.as_deref(), Some("script"));
+ assert_eq!(request.sec_fetch_mode.as_deref(), Some("cors"));
+ assert_eq!(
+ request.cookie.as_deref(),
+ if origin_kind == "same-origin" {
+ Some("sriSession=present")
+ } else {
+ None
+ },
+ "{request:?}"
+ );
+ }
+ }
+ assert_eq!(result, serde_json::json!(expected));
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn csp_blocks_dynamic_scripts_before_cors_fetch_and_reports_violation() -> Result<()> {
+ let servers = IntegrityServers::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let mut page = browser
+ .fetch(&format!("{}/csp-page.html", servers.origin))
+ .await?;
+ let result = page.evaluate_runtime_expression_with_await_async(&format!(r#"(async () => {{
+ const results = [];
+ for (const type of ['', 'module']) {{
+ const script = document.createElement('script');
+ script.type = type;
+ script.crossOrigin = 'anonymous';
+ script.src = '{cross}/script.js?csp-blocked-' + type;
+ const violation = new Promise(resolve => {{
+ document.addEventListener('securitypolicyviolation', event => resolve(event.effectiveDirective), {{once: true}});
+ }});
+ const terminal = new Promise(resolve => {{
+ script.onload = () => resolve('load');
+ script.onerror = () => resolve('error');
+ }});
+ document.body.append(script);
+ results.push(await Promise.all([terminal, violation]));
+ }}
+ return JSON.stringify(results);
+ }})()"#, cross = servers.cross_origin), true).await?;
+ let result: serde_json::Value = serde_json::from_str(result["value"].as_str().unwrap())?;
+ assert_eq!(
+ result,
+ serde_json::json!([["error", "script-src-elem"], ["error", "script-src-elem"]])
+ );
+ assert!(
+ !servers
+ .requests
+ .lock()
+ .iter()
+ .any(|request| request.path.contains("csp-blocked")),
+ "CSP must reject before sending a request"
+ );
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn stylesheet_roundtrip_preserves_cors_validation_and_cssom_origin_clean() -> 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 = page
+ .evaluate_runtime_expression_with_await_async(
+ r#"(async () => {
+ const results = {};
+ for (const name of ['same-origin', 'no-cors', 'allow', 'bad-hop', 'bad-final']) {
+ const link = document.createElement('link');
+ link.rel = 'stylesheet';
+ link.href = (name === 'same-origin' ? '/style.css?' : '/style-roundtrip.css?') + name;
+ if (!['same-origin', 'no-cors'].includes(name)) link.crossOrigin = 'anonymous';
+ const event = await new Promise(resolve => {
+ link.onload = () => resolve('load');
+ link.onerror = () => resolve('error');
+ document.head.append(link);
+ });
+ let rules;
+ try { rules = link.sheet ? link.sheet.cssRules.length : null; }
+ catch (error) { rules = error.name; }
+ results[name] = {event, rules};
+ link.remove();
+ }
+ return JSON.stringify(results);
+ })()"#,
+ true,
+ )
+ .await?;
+ let result: serde_json::Value = serde_json::from_str(result["value"].as_str().unwrap())?;
+ assert_eq!(
+ result,
+ serde_json::json!({
+ "same-origin": {"event": "load", "rules": 1},
+ "no-cors": {"event": "load", "rules": "SecurityError"},
+ "allow": {"event": "load", "rules": 1},
+ // Chromium keeps an unreadable empty sheet after a failed load.
+ "bad-hop": {"event": "error", "rules": "SecurityError"},
+ "bad-final": {"event": "error", "rules": "SecurityError"}
+ })
+ );
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn manifest_roundtrip_checks_intermediate_and_final_cors_responses() -> Result<()> {
+ let servers = IntegrityServers::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ for name in ["same-origin", "allow", "bad-hop", "bad-final"] {
+ let mut page = browser
+ .fetch(&format!("{}/manifest-page.html?{name}", servers.origin))
+ .await?;
+ let completion = page.start_prepare_app_manifest_load()?.wait().await?;
+ let moli_renderer_v8::RendererAppManifestLoadPreparation::Ready(load) =
+ page.finish_prepare_app_manifest_load(completion)?
+ else {
+ anyhow::bail!("{name}: expected a network manifest load");
+ };
+ let (result, publication) = load.execute().await.into_parts();
+ let completion = page
+ .start_publish_app_manifest_load(publication)?
+ .wait()
+ .await?;
+ page.finish_publish_app_manifest_load(completion)?;
+ let allowed = matches!(name, "same-origin" | "allow");
+ assert_eq!(
+ result.data.as_deref(),
+ Some(if allowed {
+ r#"{"name":"Redirected manifest"}"#
+ } else {
+ ""
+ }),
+ "{name}: {result:?}",
+ );
+ assert_eq!(
+ result.manifest.name.as_deref(),
+ allowed.then_some("Redirected manifest"),
+ "{name}: {result:?}"
+ );
+ }
+ let requests = servers.requests.lock();
+ let roundtrip: Vec<_> = requests
+ .iter()
+ .filter(|request| request.path.ends_with(".webmanifest?allow"))
+ .collect();
+ assert_eq!(roundtrip.len(), 3, "{roundtrip:?}");
+ for (request, expected_origin) in
+ roundtrip
+ .iter()
+ .zip([None, Some(servers.origin.as_str()), Some("null")])
+ {
+ assert_eq!(request.origin.as_deref(), expected_origin, "{request:?}");
+ assert_eq!(request.sec_fetch_dest.as_deref(), Some("manifest"));
+ }
Ok(())
}
@@ -447,6 +868,16 @@ async fn service_worker_script_redirect_preserves_origin_and_credentials() -> Re
"{name}: {requests:?}"
);
for request in requests {
+ assert_eq!(
+ request.sec_fetch_dest.as_deref(),
+ Some("script"),
+ "{name}: {request:?}"
+ );
+ assert_eq!(
+ request.sec_fetch_mode.as_deref(),
+ Some("cors"),
+ "{name}: {request:?}"
+ );
assert_eq!(
request.origin.as_deref(),
if name == "control" {
diff --git a/moli-fetch/src/blocking/mod.rs b/moli-fetch/src/blocking/mod.rs
index 3eab82420..76de311f3 100644
--- a/moli-fetch/src/blocking/mod.rs
+++ b/moli-fetch/src/blocking/mod.rs
@@ -14,7 +14,7 @@ use moli_cookie_jar::{
NetworkCookieRequestContext, SharedBrowserCookieStore, StoredCookieQueryReport,
StoredCookieSetReport, same_site_urls,
};
-use moli_url::{is_potentially_trustworthy_url, same_origin, tuple_origin_url};
+use moli_url::{is_potentially_trustworthy_url, tuple_origin_url};
use moli_url_policy::ensure_http_network_transport_url;
use tracing::debug;
use url::Url;
@@ -192,6 +192,10 @@ pub(crate) fn outgoing_request_headers_for_url(
append_browser_subresource_headers(&mut outgoing, config, request, request_url);
append_browser_storage_access_header(&mut outgoing, request, request_url);
+ if let Some(origin) = request_origin_header_value(request, request_url) {
+ append_header_if_missing(&mut outgoing, "Origin", origin);
+ }
+
if !header_present(&outgoing, "referer")
&& let Some(referer) = referrer_header_value_for_request(request, request_url)
{
@@ -312,10 +316,6 @@ fn append_browser_navigation_headers(
append_header_if_missing(outgoing, "Cache-Control", "max-age=0".to_owned());
}
- if let Some(origin) = request_origin_header_value(request, request_url) {
- append_header_if_missing(outgoing, "Origin", origin);
- }
-
append_browser_client_hints(outgoing, config);
}
@@ -343,6 +343,7 @@ fn append_browser_subresource_headers(
| BrowserRequestMetadata::JsonModule
| BrowserRequestMetadata::Manifest
| BrowserRequestMetadata::Ping
+ | BrowserRequestMetadata::Script
| BrowserRequestMetadata::Style
| BrowserRequestMetadata::StyleModule
| BrowserRequestMetadata::TextTrack
@@ -380,6 +381,7 @@ fn append_browser_subresource_headers(
BrowserRequestMetadata::Image => "image",
BrowserRequestMetadata::JsonModule => "json",
BrowserRequestMetadata::Manifest => "manifest",
+ BrowserRequestMetadata::Script => "script",
BrowserRequestMetadata::Style | BrowserRequestMetadata::StyleModule => "style",
BrowserRequestMetadata::TextTrack => "track",
BrowserRequestMetadata::Video => "video",
@@ -390,16 +392,6 @@ fn append_browser_subresource_headers(
| BrowserRequestMetadata::Xhr => "empty",
};
append_header_if_missing(outgoing, "Sec-Fetch-Dest", destination.to_owned());
- let origin = if matches!(metadata, BrowserRequestMetadata::Style)
- && !matches!(request.request_mode, crate::RequestMode::Cors)
- {
- None
- } else {
- request_origin_header_value(request, request_url)
- };
- if let Some(origin) = origin {
- append_header_if_missing(outgoing, "Origin", origin);
- }
append_browser_client_hints(outgoing, config);
}
}
@@ -473,12 +465,13 @@ fn request_sec_fetch_site(request: &Request, request_url: &Url) -> String {
};
let initiator_url =
tuple_origin_url(initiator_url).unwrap_or(std::borrow::Cow::Borrowed(initiator_url));
- if same_origin(initiator_url.as_ref(), request_url) {
+ let urls = request.url_list(request_url);
+ if !urls.has_cross_origin_url(initiator_url.as_ref()) {
"same-origin".to_owned()
- } else if same_site_urls(initiator_url.as_ref(), request_url, true) {
- "same-site".to_owned()
- } else {
+ } else if urls.has_cross_site_url(initiator_url.as_ref()) {
"cross-site".to_owned()
+ } else {
+ "same-site".to_owned()
}
}
@@ -1370,7 +1363,7 @@ mod tests {
assert_eq!(header_value(&headers, "origin"), Some("null".to_owned()));
assert_eq!(
header_value(&headers, "sec-fetch-site"),
- Some("same-origin".to_owned())
+ Some("cross-site".to_owned())
);
}
@@ -1396,7 +1389,7 @@ mod tests {
assert_eq!(header_value(&headers, "origin"), Some("null".to_owned()));
assert_eq!(
header_value(&headers, "sec-fetch-site"),
- Some("same-origin".to_owned())
+ Some("same-site".to_owned())
);
}
@@ -1423,7 +1416,7 @@ mod tests {
assert_eq!(header_value(&headers, "origin"), Some("null".to_owned()));
assert_eq!(
header_value(&headers, "sec-fetch-site"),
- Some("same-origin".to_owned())
+ Some("cross-site".to_owned())
);
}
@@ -1454,6 +1447,51 @@ mod tests {
);
}
+ #[test]
+ fn origin_header_does_not_require_browser_metadata() {
+ let config = FetchConfig::default();
+ let initiator = url("https://app.test/page");
+ for (method, target, mode, expected) in [
+ (
+ "GET",
+ "https://cdn.test/script.js",
+ RequestMode::Cors,
+ Some("https://app.test"),
+ ),
+ (
+ "HEAD",
+ "https://cdn.test/script.js",
+ RequestMode::Cors,
+ Some("https://app.test"),
+ ),
+ ("GET", "https://app.test/script.js", RequestMode::Cors, None),
+ (
+ "GET",
+ "https://cdn.test/script.js",
+ RequestMode::NoCors,
+ None,
+ ),
+ (
+ "POST",
+ "https://app.test/data",
+ RequestMode::NoCors,
+ Some("https://app.test"),
+ ),
+ ] {
+ let request = Request::new(method, target, None, Vec::new())
+ .unwrap()
+ .with_initiator_url(&initiator)
+ .with_request_mode(mode);
+ assert_eq!(request.browser_request_metadata(), None);
+ let headers = outgoing_request_headers_for_url(&config, &request, &request.url, None);
+ assert_eq!(
+ header_value(&headers, "origin").as_deref(),
+ expected,
+ "{method} {target} {mode:?}"
+ );
+ }
+ }
+
#[test]
fn browser_subresource_sec_fetch_mode_uses_request_mode() {
let config = FetchConfig::default();
diff --git a/moli-fetch/src/fetch_url_list.rs b/moli-fetch/src/fetch_url_list.rs
new file mode 100644
index 000000000..c5181f7df
--- /dev/null
+++ b/moli-fetch/src/fetch_url_list.rs
@@ -0,0 +1,58 @@
+use moli_cookie_jar::same_site_urls;
+use moli_url::{origin_ascii_serialization, same_origin};
+use url::Url;
+
+use crate::{RedirectInfo, RedirectSource};
+
+/// A borrowed view of the URLs visited by a fetch. Requests and responses use
+/// the same rules for redirect taint, including synthetic redirects.
+#[derive(Clone, Copy, Debug)]
+pub struct FetchUrlList<'a> {
+ current_url: &'a Url,
+ redirects: &'a [RedirectInfo],
+}
+
+impl<'a> FetchUrlList<'a> {
+ pub fn new(current_url: &'a Url, redirects: &'a [RedirectInfo]) -> Self {
+ Self {
+ current_url,
+ redirects,
+ }
+ }
+
+ fn urls(self) -> impl Iterator<Item = &'a Url> {
+ self.redirects
+ .iter()
+ .flat_map(|redirect| [&redirect.from_url, &redirect.to_url])
+ .chain(std::iter::once(self.current_url))
+ }
+
+ /// Returning to the initiating origin cannot restore basic response tainting.
+ pub fn has_cross_origin_url(self, origin: &Url) -> bool {
+ self.urls().any(|url| !same_origin(origin, url))
+ }
+
+ pub fn has_cross_site_url(self, origin: &Url) -> bool {
+ self.urls().any(|url| !same_site_urls(origin, url, true))
+ }
+
+ /// A first hop out of the initiating origin retains that origin. Crossing
+ /// origins from an already cross-origin URL serializes the origin as null.
+ pub fn serialized_origin(self, origin: &Url) -> String {
+ if self.redirects.iter().any(|redirect| {
+ !same_origin(&redirect.from_url, &redirect.to_url)
+ && !same_origin(origin, &redirect.from_url)
+ }) {
+ "null".to_owned()
+ } else {
+ origin_ascii_serialization(origin)
+ }
+ }
+
+ pub fn redirect_count(self) -> usize {
+ self.redirects
+ .iter()
+ .filter(|redirect| redirect.source != RedirectSource::Internal)
+ .count()
+ }
+}
diff --git a/moli-fetch/src/lib.rs b/moli-fetch/src/lib.rs
index 6b5ccf33e..6f0639f13 100644
--- a/moli-fetch/src/lib.rs
+++ b/moli-fetch/src/lib.rs
@@ -11,6 +11,7 @@ mod client_hints;
mod config;
mod dns;
mod error;
+mod fetch_url_list;
mod headers;
mod network_fetch_result;
mod proxy_connect;
@@ -37,6 +38,7 @@ pub use cancellation::FetchCancelHandle;
pub use client::{FetchClient, FetchClientHandle};
pub use config::FetchConfig;
pub use error::{NET_ERR_ABORTED_ERROR_TEXT, ensure_http_status_success};
+pub use fetch_url_list::FetchUrlList;
pub use headers::{
cors_unsafe_request_header_names, is_cors_safelisted_method,
is_cors_safelisted_request_content_type, is_cors_safelisted_request_header,
diff --git a/moli-fetch/src/request.rs b/moli-fetch/src/request.rs
index 547861194..ed6b64f50 100644
--- a/moli-fetch/src/request.rs
+++ b/moli-fetch/src/request.rs
@@ -9,11 +9,11 @@ use moli_cookie_jar::{
NetworkSiteContextMetadata, NetworkSiteContextTrackMetadata, redirect_types_for_request,
site_context_downgrade_type,
};
-use moli_url::{origin_ascii_serialization, same_origin};
+use moli_url::same_origin;
use url::Url;
use crate::{
- FetchConfig, RedirectInfo, RedirectSource, network_fetch_result::NetworkObservationRecorder,
+ FetchConfig, FetchUrlList, RedirectInfo, network_fetch_result::NetworkObservationRecorder,
};
#[derive(Debug, Clone)]
@@ -55,6 +55,7 @@ pub enum BrowserRequestMetadata {
JsonModule,
Manifest,
Ping,
+ Script,
Style,
StyleModule,
TextTrack,
@@ -659,10 +660,11 @@ impl Request {
}
pub fn redirect_count(&self) -> usize {
- self.redirect_chain
- .iter()
- .filter(|redirect| redirect.source != RedirectSource::Internal)
- .count()
+ self.url_list(&self.url).redirect_count()
+ }
+
+ pub fn url_list<'a>(&'a self, request_url: &'a Url) -> FetchUrlList<'a> {
+ FetchUrlList::new(request_url, &self.redirect_chain)
}
/// Whether the URL list has left the initiating origin. For subresource
@@ -672,12 +674,8 @@ impl Request {
.initiator_url
.as_ref()
.is_some_and(|initiator| {
- !same_origin(initiator, request_url)
- || !same_origin(initiator, &self.url)
- || self.redirect_chain.iter().any(|redirect| {
- !same_origin(initiator, &redirect.from_url)
- || !same_origin(initiator, &redirect.to_url)
- })
+ !same_origin(initiator, &self.url)
+ || self.url_list(request_url).has_cross_origin_url(initiator)
})
}
@@ -688,14 +686,7 @@ impl Request {
let Some(initiator) = self.cookie_context.initiator_url.as_ref() else {
return "null".to_owned();
};
- if self.redirect_chain.iter().any(|redirect| {
- !same_origin(&redirect.from_url, &redirect.to_url)
- && !same_origin(initiator, &redirect.from_url)
- }) {
- "null".to_owned()
- } else {
- origin_ascii_serialization(initiator)
- }
+ self.url_list(&self.url).serialized_origin(initiator)
}
pub fn with_network_partition_key(mut self, key: Option<String>) -> Self {
diff --git a/moli-fetch/src/response.rs b/moli-fetch/src/response.rs
index 3613e5782..4b8b4c9f9 100644
--- a/moli-fetch/src/response.rs
+++ b/moli-fetch/src/response.rs
@@ -50,6 +50,12 @@ pub struct ResponseHead {
pub negotiated_http_version: Option<NegotiatedHttpVersion>,
}
+impl ResponseHead {
+ pub fn url_list(&self) -> crate::FetchUrlList<'_> {
+ crate::FetchUrlList::new(&self.final_url, &self.redirect_chain)
+ }
+}
+
#[derive(Debug)]
pub enum ResponseBody {
MaterializedText {
diff --git a/moli-fetch/src/runtime.rs b/moli-fetch/src/runtime.rs
index 5bddcb0d1..37ee418a9 100644
--- a/moli-fetch/src/runtime.rs
+++ b/moli-fetch/src/runtime.rs
@@ -3062,6 +3062,7 @@ fn request_fetch_load_priority(request: &Request) -> crate::ResourceLoadPriority
| crate::BrowserRequestMetadata::Font
| crate::BrowserRequestMetadata::Image
| crate::BrowserRequestMetadata::Ping
+ | crate::BrowserRequestMetadata::Script
| crate::BrowserRequestMetadata::Style
| crate::BrowserRequestMetadata::TextTrack
| crate::BrowserRequestMetadata::Video,
diff --git a/moli-fetch/src/tests/cookie_store.rs b/moli-fetch/src/tests/cookie_store.rs
index 3aa2ee760..639c75c5a 100644
--- a/moli-fetch/src/tests/cookie_store.rs
+++ b/moli-fetch/src/tests/cookie_store.rs
@@ -276,6 +276,7 @@ fn outgoing_request_headers_skip_manual_cookie_when_store_cookie_exists() {
vec![
("Cookie".to_owned(), "sid=server".to_owned()),
("X-Test".to_owned(), "ok".to_owned()),
+ ("Origin".to_owned(), "null".to_owned()),
]
);
}
@@ -301,6 +302,7 @@ fn outgoing_request_headers_include_default_config_headers() {
("X-Test".to_owned(), "one".to_owned()),
("X-Trace".to_owned(), "two".to_owned()),
("X-Request".to_owned(), "three".to_owned()),
+ ("Origin".to_owned(), "null".to_owned()),
]
);
}
@@ -319,6 +321,7 @@ fn outgoing_request_headers_skip_default_cookie_when_store_cookie_exists() {
vec![
("Cookie".to_owned(), "sid=server".to_owned()),
("X-Test".to_owned(), "ok".to_owned()),
+ ("Origin".to_owned(), "null".to_owned()),
]
);
}
@@ -337,6 +340,7 @@ fn outgoing_request_headers_keep_default_cookie_without_store_cookie() {
vec![
("Cookie".to_owned(), "manual=1".to_owned()),
("X-Test".to_owned(), "ok".to_owned()),
+ ("Origin".to_owned(), "null".to_owned()),
]
);
}
@@ -384,6 +388,7 @@ fn outgoing_request_headers_preserve_duplicate_default_headers_in_order() {
("X-Test".to_owned(), "one".to_owned()),
("X-Test".to_owned(), "two".to_owned()),
("X-Test".to_owned(), "three".to_owned()),
+ ("Origin".to_owned(), "null".to_owned()),
]
);
}
diff --git a/moli-renderer-v8/src/app_manifest.rs b/moli-renderer-v8/src/app_manifest.rs
index cc4215378..5c7c9fc80 100644
--- a/moli-renderer-v8/src/app_manifest.rs
+++ b/moli-renderer-v8/src/app_manifest.rs
@@ -266,10 +266,9 @@ impl RendererPreparedAppManifestLoad {
RendererNetworkResourceLoadOutcome::Response(response) => {
let response = *response;
let security_error = response.completion_error.clone().or_else(|| {
- crate::network_host::validate_cors_response(
+ crate::network_host::validate_cors_response_chain(
&document_url,
- &response.final_url,
- &response.headers,
+ &response.head(),
credentials_mode,
)
.err()
diff --git a/moli-renderer-v8/src/frame_owner_model/records.rs b/moli-renderer-v8/src/frame_owner_model/records.rs
index d9713e413..409a4bcfb 100644
--- a/moli-renderer-v8/src/frame_owner_model/records.rs
+++ b/moli-renderer-v8/src/frame_owner_model/records.rs
@@ -1356,6 +1356,19 @@ pub(crate) struct FrameSettingsObject {
pub(crate) module_map_owner: ModuleMapOwner,
}
+impl FrameSettingsObject {
+ pub(crate) fn request_initiator_url(&self, base_url: &Url) -> Url {
+ // URL resolution uses the document base, but fetch security uses the
+ // Window's origin, including inherited and sandboxed opaque origins.
+ if moli_url::origin_ascii_serialization(base_url) == self.origin {
+ base_url.clone()
+ } else {
+ Url::parse(&self.origin)
+ .unwrap_or_else(|_| Url::parse("about:blank").expect("valid opaque initiator URL"))
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ModuleMapOwner {
Document(DocumentId),
diff --git a/moli-renderer-v8/src/module_runtime/graph.rs b/moli-renderer-v8/src/module_runtime/graph.rs
index b45c2edce..160833d26 100644
--- a/moli-renderer-v8/src/module_runtime/graph.rs
+++ b/moli-renderer-v8/src/module_runtime/graph.rs
@@ -363,7 +363,7 @@ impl NativeModuleGraphFetchRequest {
request.with_browser_request_metadata(BrowserRequestMetadata::JsonModule)
}
ModuleKind::JavaScript | ModuleKind::ModulePreloadText | ModuleKind::WebAssembly => {
- request
+ request.with_browser_request_metadata(BrowserRequestMetadata::Script)
}
})
}
@@ -468,15 +468,16 @@ impl NativeModuleGraphFetchRequest {
&response.headers,
);
let (head, _, body_bytes) = response.into_parts();
- let response_is_eligible = crate::network_host::network_response_filter(
+ crate::network_host::validate_cors_response_chain(
&initiator_url,
&head,
- request_mode,
- ).is_none() && crate::network_host::validate_cors_response_chain(
+ credentials_mode,
+ ).map_err(|error| ModuleLoadError::new(ModuleLoadStage::Fetch, error).message().to_owned())?;
+ let response_is_eligible = crate::network_host::network_response_filter(
&initiator_url,
&head,
- credentials_mode,
- ).is_ok();
+ request_mode,
+ ).is_none();
if !crate::subresource_integrity::response_matches_subresource_integrity_metadata(
&body_bytes,
integrity.as_deref(),
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
index 04ec6fa99..6fc592f8c 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
@@ -590,7 +590,7 @@ impl JsContextHost {
&mut self,
child_handle: DomHandle,
document_handle: DomHandle,
- handoff: ParserScriptHandoff,
+ mut handoff: ParserScriptHandoff,
) -> ScriptDisposition {
let (script_handle, start_line, start_column) = handoff.start_position();
self.note_parser_script_start_position(script_handle, start_line, start_column);
@@ -603,6 +603,18 @@ impl JsContextHost {
return ScriptDisposition::Continue;
}
+ if let Some(initiator_url) = self.child_browsing_context_request_initiator_url(child_handle)
+ {
+ match &mut handoff {
+ ParserScriptHandoff::BlockingClassic { script, .. }
+ | ParserScriptHandoff::AsyncPostParse { script, .. }
+ | ParserScriptHandoff::NonAsyncPostParse { script, .. } => {
+ script.initiator_url = initiator_url;
+ }
+ _ => {}
+ }
+ }
+
match handoff {
ParserScriptHandoff::BlockingClassic {
node_id,
@@ -971,7 +983,11 @@ impl JsContextHost {
let Some(raw_href) = modulepreload_href(element) else {
continue;
};
- let document_url = self.document_url_for_handle(document_handle);
+ let Some(initiator_url) =
+ self.child_browsing_context_request_initiator_url(child_handle)
+ else {
+ continue;
+ };
let document_base_url = self.document_base_url_for_handle(document_handle);
let Some(request_url) =
resolve_parser_network_resource_url(&document_base_url, raw_href)
@@ -979,7 +995,7 @@ impl JsContextHost {
continue;
};
let Some(candidate) =
- modulepreload_fetch_candidate(element, request_url, &document_url, None)
+ modulepreload_fetch_candidate(element, request_url, &initiator_url, None)
else {
continue;
};
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs
index 1a4a12cfa..a8629a413 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs
@@ -262,6 +262,19 @@ impl JsContextHost {
self.child_browsing_context_window_origin(handle)
}
+ pub(crate) fn child_browsing_context_request_initiator_url(
+ &self,
+ handle: DomHandle,
+ ) -> Option<Url> {
+ let owner = self
+ .frame_owner_store
+ .current_child_owner_snapshot(handle)?;
+ let base_url = self
+ .child_browsing_context_base_url(handle)
+ .unwrap_or(owner.document_base_url);
+ Some(owner.settings.request_initiator_url(&base_url))
+ }
+
pub(crate) fn child_browsing_context_web_storage_scope(
&mut self,
handle: DomHandle,
diff --git a/moli-renderer-v8/src/network/devtools_resource_load.rs b/moli-renderer-v8/src/network/devtools_resource_load.rs
index bcfdd2819..9e7d2202d 100644
--- a/moli-renderer-v8/src/network/devtools_resource_load.rs
+++ b/moli-renderer-v8/src/network/devtools_resource_load.rs
@@ -93,3 +93,24 @@ pub struct RendererNetworkResourceLoadResponse {
pub negotiated_http_version: Option<moli_fetch::NegotiatedHttpVersion>,
pub network_request_headers: Option<Vec<(String, String)>>,
}
+
+impl RendererNetworkResourceLoadResponse {
+ pub fn head(&self) -> moli_fetch::ResponseHead {
+ moli_fetch::ResponseHead {
+ final_url: self.final_url.clone(),
+ status: self.status,
+ headers: self.headers.clone(),
+ request_cookie_report: self.request_cookie_report.clone(),
+ cookie_set_reports: self.cookie_set_reports.clone(),
+ redirected: !self.redirect_chain.is_empty(),
+ redirect_chain: self
+ .redirect_chain
+ .iter()
+ .cloned()
+ .map(Into::into)
+ .collect(),
+ from_cache: self.from_cache,
+ negotiated_http_version: self.negotiated_http_version,
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs
index fe4463ee5..4681ef3b8 100644
--- a/moli-renderer-v8/src/network_host.rs
+++ b/moli-renderer-v8/src/network_host.rs
@@ -154,7 +154,7 @@ pub(crate) use self::response::{
materialize_response_object_body_with_chunk_callback, materialize_response_object_head,
materialize_response_object_head_for_service_worker_respond_with,
materialized_body_bytes_from_value, network_response_filter, response_constructor_callback,
- validate_cors_preflight_response, validate_cors_response, validate_cors_response_chain,
+ validate_cors_preflight_response, validate_cors_response_chain,
validate_cross_origin_embedder_and_document_isolation_policy,
validate_cross_origin_resource_policy, validate_fetch_response_security_policy,
validate_fetch_response_security_policy_with_body,
diff --git a/moli-renderer-v8/src/network_host/response.rs b/moli-renderer-v8/src/network_host/response.rs
index a770b0a18..8f5463ec1 100644
--- a/moli-renderer-v8/src/network_host/response.rs
+++ b/moli-renderer-v8/src/network_host/response.rs
@@ -15,7 +15,7 @@ pub(super) use self::body_methods::install_response_body_methods;
pub(crate) use self::cors::{
FetchResponseSecurityViolation, cors_preflight_request_headers,
filter_cors_exposed_response_headers, is_cors_policy_failure_message,
- validate_cors_preflight_response, validate_cors_response, validate_cors_response_chain,
+ validate_cors_preflight_response, validate_cors_response_chain,
validate_cors_response_for_origin,
validate_cross_origin_embedder_and_document_isolation_policy,
validate_cross_origin_resource_policy, validate_fetch_response_security_policy,
diff --git a/moli-renderer-v8/src/network_host/response/cors.rs b/moli-renderer-v8/src/network_host/response/cors.rs
index 882663472..e697ff742 100644
--- a/moli-renderer-v8/src/network_host/response/cors.rs
+++ b/moli-renderer-v8/src/network_host/response/cors.rs
@@ -36,23 +36,6 @@ pub(crate) fn is_cors_policy_failure_message(message: &str) -> bool {
message.contains("CORS check failed:") || message.contains("CORS preflight failed:")
}
-pub(crate) fn validate_cors_response(
- document_url: &url::Url,
- response_url: &url::Url,
- response_headers: &[(String, String)],
- credentials_mode: RequestCredentialsMode,
-) -> Result<(), String> {
- if same_origin(document_url, response_url) {
- return Ok(());
- }
- if !matches!(response_url.scheme(), "http" | "https") {
- return Ok(());
- }
-
- let origin = origin_ascii_serialization(document_url);
- validate_cors_response_for_origin(&origin, response_headers, credentials_mode)
-}
-
/// Validates an already fetched network response and its network redirects.
/// Service worker and browser-generated redirects still contribute to taint,
/// but their synthetic response headers are not subject to the CORS check.
@@ -63,23 +46,27 @@ pub(crate) fn validate_cors_response_chain(
head: &moli_fetch::ResponseHead,
credentials_mode: RequestCredentialsMode,
) -> Result<(), String> {
- let mut origin = origin_ascii_serialization(document_url);
- let mut cors_tainted = false;
- for redirect in &head.redirect_chain {
- cors_tainted |= !same_origin(document_url, &redirect.from_url);
- if cors_tainted {
- if redirect.source == RedirectSource::Network {
- validate_cors_response_for_origin(&origin, &redirect.headers, credentials_mode)?;
- }
- if !same_origin(&redirect.from_url, &redirect.to_url) {
- origin = "null".to_owned();
- }
+ for (index, redirect) in head.redirect_chain.iter().enumerate() {
+ // This response precedes the redirect: only earlier hops contribute to
+ // the Origin that was sent for it.
+ let urls = moli_fetch::FetchUrlList::new(&redirect.from_url, &head.redirect_chain[..index]);
+ if redirect.source == RedirectSource::Network && urls.has_cross_origin_url(document_url) {
+ validate_cors_response_for_origin(
+ &urls.serialized_origin(document_url),
+ &redirect.headers,
+ credentials_mode,
+ )?;
}
}
+ let urls = head.url_list();
if matches!(head.final_url.scheme(), "http" | "https")
- && (cors_tainted || !same_origin(document_url, &head.final_url))
+ && urls.has_cross_origin_url(document_url)
{
- validate_cors_response_for_origin(&origin, &head.headers, credentials_mode)?;
+ validate_cors_response_for_origin(
+ &urls.serialized_origin(document_url),
+ &head.headers,
+ credentials_mode,
+ )?;
}
Ok(())
}
@@ -484,7 +471,7 @@ pub(crate) fn filter_cors_exposed_response_headers(
credentials_mode: RequestCredentialsMode,
) -> Vec<(String, String)> {
let response_headers = &head.headers;
- if !super::materialize::response_has_cross_origin_url(document_url, head) {
+ if !head.url_list().has_cross_origin_url(document_url) {
return response_headers.to_vec();
}
if !matches!(head.final_url.scheme(), "http" | "https") {
diff --git a/moli-renderer-v8/src/network_host/response/materialize.rs b/moli-renderer-v8/src/network_host/response/materialize.rs
index 6d41c7209..db83b61e9 100644
--- a/moli-renderer-v8/src/network_host/response/materialize.rs
+++ b/moli-renderer-v8/src/network_host/response/materialize.rs
@@ -97,7 +97,7 @@ pub(crate) fn network_response_filter(
if is_redirect_status(head.status) {
Some(AsyncSubresourceFetchResponseFilter::OpaqueRedirect)
} else if request_mode == RequestMode::NoCors
- && response_has_cross_origin_url(document_url, head)
+ && head.url_list().has_cross_origin_url(document_url)
{
Some(AsyncSubresourceFetchResponseFilter::Opaque)
} else {
@@ -105,17 +105,6 @@ pub(crate) fn network_response_filter(
}
}
-pub(super) fn response_has_cross_origin_url(
- document_url: &url::Url,
- head: &moli_fetch::ResponseHead,
-) -> bool {
- !moli_url::same_origin(document_url, &head.final_url)
- || head.redirect_chain.iter().any(|redirect| {
- !moli_url::same_origin(document_url, &redirect.from_url)
- || !moli_url::same_origin(document_url, &redirect.to_url)
- })
-}
-
fn compute_fetch_response_type(
document_url: &url::Url,
head: &moli_fetch::ResponseHead,
@@ -127,7 +116,7 @@ fn compute_fetch_response_type(
FetchResponseFilter::Cors => "cors",
FetchResponseFilter::Opaque => "opaque",
FetchResponseFilter::OpaqueRedirect => "opaqueredirect",
- FetchResponseFilter::None if response_has_cross_origin_url(document_url, head) => "cors",
+ FetchResponseFilter::None if head.url_list().has_cross_origin_url(document_url) => "cors",
FetchResponseFilter::None => "basic",
}
}
@@ -168,14 +157,6 @@ fn filtered_response_status_text(
}
}
-fn legacy_fetch_response_type(document_url: &url::Url, response_url: &url::Url) -> &'static str {
- if moli_url::same_origin(document_url, response_url) {
- "basic"
- } else {
- "cors"
- }
-}
-
pub(crate) fn build_fetch_response_object_for_request_mode<'s>(
scope: &mut v8::PinScope<'s, '_>,
document_url: &url::Url,
@@ -385,7 +366,7 @@ fn finish_fetch_response_object_with_body_stream<'s>(
body_stream: Option<v8::Local<'s, v8::Object>>,
) -> v8::Local<'s, v8::Object> {
let response_type = response_slot_string(scope, obj, RESPONSE_TYPE_SLOT)
- .unwrap_or_else(|| legacy_fetch_response_type(&head.final_url, &head.final_url).to_owned());
+ .expect("fetch response head has a response type");
let filter = match response_type.as_str() {
"opaque" => FetchResponseFilter::Opaque,
"opaqueredirect" => FetchResponseFilter::OpaqueRedirect,
diff --git a/moli-renderer-v8/src/planning.rs b/moli-renderer-v8/src/planning.rs
index 25966339e..5007eec97 100644
--- a/moli-renderer-v8/src/planning.rs
+++ b/moli-renderer-v8/src/planning.rs
@@ -345,6 +345,7 @@ pub(crate) fn external_script_request(
.expect("prepared script url should already be parsed")
.with_page_network_policy()
.with_initiator_url(&script.initiator_url)
+ .with_browser_request_metadata(moli_fetch::BrowserRequestMetadata::Script)
.with_credentials_mode(external_script_credentials_mode(
script.kind,
&script.fetch_metadata,
@@ -393,9 +394,7 @@ pub(crate) async fn load_service_worker_aware_external_script_source_outcome(
*response.response,
document_character_set,
response.response_filter,
- response
- .response_filter
- .is_none_or(|filter| filter.is_readable()),
+ None,
),
Ok(None) => {
load_prepared_script_source_outcome_with_document_character_set(
@@ -508,20 +507,22 @@ pub(crate) fn external_script_source_load_outcome_from_response(
let head = response.head();
let response_filter =
crate::network_host::network_response_filter(&script.initiator_url, &head, request_mode);
- let response_is_eligible = response_filter.is_none_or(|filter| filter.is_readable())
- && (request_mode == RequestMode::NoCors
- || crate::network_host::validate_cors_response_chain(
- &script.initiator_url,
- &head,
- external_script_credentials_mode(script.kind, &script.fetch_metadata),
- )
- .is_ok());
+ let cors_error = if request_mode == RequestMode::Cors {
+ crate::network_host::validate_cors_response_chain(
+ &script.initiator_url,
+ &head,
+ external_script_credentials_mode(script.kind, &script.fetch_metadata),
+ )
+ .err()
+ } else {
+ None
+ };
external_script_source_load_outcome_from_response_inner(
script,
response,
document_character_set,
response_filter,
- response_is_eligible,
+ cors_error,
)
}
@@ -545,13 +546,15 @@ fn external_script_source_load_outcome_from_response_inner(
response: crate::protocol_types::NavigationResponse,
document_character_set: Option<&str>,
response_filter: Option<crate::types::AsyncSubresourceFetchResponseFilter>,
- response_is_eligible: bool,
+ cors_error: Option<String>,
) -> PreparedScriptSourceLoadOutcome {
let response_bytes = response.body_bytes().to_vec();
let opaque_status_zero = response_filter
== Some(crate::types::AsyncSubresourceFetchResponseFilter::Opaque)
&& response.status == 0;
- let source_result = if !(opaque_status_zero || (200..=299).contains(&response.status)) {
+ let source_result = if let Some(error) = cors_error {
+ Err(format!("script request `{}` failed: {error}", script.url))
+ } else if !(opaque_status_zero || (200..=299).contains(&response.status)) {
Err(format!(
"script request `{}` returned HTTP {}",
script.url, response.status
@@ -564,7 +567,7 @@ fn external_script_source_load_outcome_from_response_inner(
} else if !crate::subresource_integrity::response_matches_subresource_integrity_metadata(
&response_bytes,
script.fetch_metadata.integrity.as_deref(),
- response_is_eligible && response_filter.is_none_or(|filter| filter.is_readable()),
+ response_filter.is_none_or(|filter| filter.is_readable()),
) {
Err(format!(
"script request `{}` failed its integrity check",
@@ -1312,7 +1315,7 @@ mod tests {
response,
None,
Some(crate::types::AsyncSubresourceFetchResponseFilter::Opaque),
- false,
+ None,
);
assert_eq!(outcome.source_result.expect("opaque script source"), source);
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 525eb0b41..46fa0be0d 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -3468,9 +3468,9 @@ impl ScriptVm {
&self,
child_handle: crate::document_runtime::DomHandle,
) -> Option<Url> {
- let host = self._context_host.borrow();
- host.child_browsing_context_base_url(child_handle)
- .or_else(|| host.child_browsing_context_current_url(child_handle))
+ self._context_host
+ .borrow()
+ .child_browsing_context_request_initiator_url(child_handle)
}
fn isolated_world_runtime_realm_info(
diff --git a/moli-renderer-v8/src/script_vm/child_document_modulator.rs b/moli-renderer-v8/src/script_vm/child_document_modulator.rs
index 45d60bae7..fadf98e08 100644
--- a/moli-renderer-v8/src/script_vm/child_document_modulator.rs
+++ b/moli-renderer-v8/src/script_vm/child_document_modulator.rs
@@ -490,7 +490,11 @@ impl ScriptVm {
snapshot.local_window_id == document_owner.local_window_id
&& snapshot.document_id == document_owner.document_id
})
- .map(|snapshot| snapshot.document_base_url)
+ .map(|snapshot| {
+ snapshot
+ .settings
+ .request_initiator_url(&snapshot.document_base_url)
+ })
.unwrap_or_else(|| fallback_url.clone())
}
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 3e3ae6a14..8274c97d0 100644
--- a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs
+++ b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs
@@ -115,6 +115,53 @@ impl ScriptVm {
task_runner: crate::network::RendererResourceTaskRunner,
admission: RuntimeScriptAdmission,
) {
+ // Check CSP before starting the source fetch. A CORS or network failure
+ // must not bypass CSP reporting by skipping the execution boundary.
+ let (payload, binding) = admission.into_parts();
+ let payload = match payload {
+ crate::host::RuntimeScriptAdmissionPayload::Script(script)
+ if script.source_kind == crate::types::ScriptSourceKind::External =>
+ {
+ let request = self.content_security_policy_script_element_request(&script);
+ if let Some(violation) = self
+ .document_runtime
+ .script_element_request_csp_violation_with_request(&script.url, request)
+ {
+ if let Some(report_only) = self
+ .document_runtime
+ .script_element_request_csp_report_only_violation_with_request(
+ &script.url,
+ request,
+ )
+ {
+ self.queue_content_security_policy_violation_event_best_effort(
+ &report_only,
+ );
+ }
+ self.queue_content_security_policy_violation_event_best_effort(&violation);
+ let message = format!(
+ "Refused to load script `{}` because it violates the document Content Security Policy directive `{}`",
+ script.url, violation.effective_directive,
+ );
+ let failure_kind = if script.kind == crate::types::ScriptKind::Module {
+ crate::host::QueuedScriptFailureKind::ModuleTopLevelLoad
+ } else {
+ crate::host::QueuedScriptFailureKind::Immediate
+ };
+ crate::host::RuntimeScriptAdmissionPayload::Failed(
+ crate::host::FailedDynamicScript {
+ script,
+ message,
+ failure_kind,
+ },
+ )
+ } else {
+ crate::host::RuntimeScriptAdmissionPayload::Script(script)
+ }
+ }
+ payload => payload,
+ };
+ let admission = RuntimeScriptAdmission::from_boxed_payload(Box::new(payload), binding);
let document_character_set = self.document_runtime.document_character_set().to_owned();
let service_worker_context = {
let host = self._context_host.borrow();
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch.rs
index 2c4475d47..c99536657 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch.rs
@@ -2122,6 +2122,19 @@ impl ScriptVm {
continuation,
deferred_request_started,
} = pending;
+ // Request-stage fulfillment has no followed redirects yet. Reuse this
+ // complete head for validation and response materialization.
+ let head = moli_fetch::ResponseHead {
+ final_url: info.url.clone(),
+ status: response_code,
+ headers: response_headers.clone(),
+ request_cookie_report: info.request_cookie_report.clone(),
+ cookie_set_reports: Vec::new(),
+ redirected: false,
+ redirect_chain: Vec::new(),
+ from_cache: false,
+ negotiated_http_version: None,
+ };
let pending = match continuation {
PendingSubresourceContinuation::WebSocket(connection) => {
if response_code != 101 {
@@ -2162,10 +2175,9 @@ impl ScriptVm {
let validation = if request_mode == moli_fetch::RequestMode::NoCors {
Ok(())
} else {
- crate::network_host::validate_cors_response(
+ crate::network_host::validate_cors_response_chain(
&info.document_url,
- &info.url,
- &response_headers,
+ &head,
credentials_mode,
)
};
@@ -2269,10 +2281,9 @@ impl ScriptVm {
let request_method = info.method.clone();
let request_headers = info.request_headers.clone();
let request_body = info.request_body.clone();
- let validation = crate::network_host::validate_cors_response(
+ let validation = crate::network_host::validate_cors_response_chain(
&info.document_url,
- &info.url,
- &response_headers,
+ &head,
credentials_mode,
);
match validation {
@@ -2446,19 +2457,7 @@ impl ScriptVm {
false,
None,
None,
- Ok(
- response_body.into_navigation_response(moli_fetch::ResponseHead {
- final_url: info.url,
- status: response_code,
- headers: response_headers,
- request_cookie_report: info.request_cookie_report,
- cookie_set_reports: Vec::new(),
- redirected: false,
- redirect_chain: Vec::new(),
- from_cache: false,
- negotiated_http_version: None,
- }),
- ),
+ Ok(response_body.into_navigation_response(head)),
)?;
Ok(AsyncSubresourceCommandExecution::after_body((), activity))
}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index c34483685..09059bc4b 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -9027,7 +9027,8 @@ async fn child_dynamic_import_root_fetch_uses_child_import_map_and_initiator_url
.expect("child dynamic import must bind its current execution context");
assert_eq!(
child_initiator_url.as_str(),
- "https://child-dynamic-owner.test/nested/frame.html"
+ "https://parent-dynamic-owner.test/",
+ "srcdoc inherits its parent's origin even when <base> changes module URL resolution"
);
let (_child_handle, task_owner, realm_id) = dynamic_import_owner
@@ -9913,7 +9914,7 @@ async fn spawn_child_external_parser_module_ready_lane_server() -> (
let body = r#"parent.__childExternalParserModuleEvents.push("module:" + (globalThis === self));
globalThis.__childExternalParserModuleValue = 188;"#;
let response = format!(
- "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
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 57dd79fd6..23a305917 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
@@ -787,6 +787,7 @@ fn service_worker_fetch_browser_metadata(
moli_fetch::BrowserRequestMetadata::Manifest
}
crate::types::SubresourceResourceType::Xhr => moli_fetch::BrowserRequestMetadata::Xhr,
+ crate::types::SubresourceResourceType::Script => moli_fetch::BrowserRequestMetadata::Script,
_ => moli_fetch::BrowserRequestMetadata::Fetch,
}
}
diff --git a/moli-renderer-v8/src/stylesheet_blocking.rs b/moli-renderer-v8/src/stylesheet_blocking.rs
index 6e7cbe412..cf30dcf21 100644
--- a/moli-renderer-v8/src/stylesheet_blocking.rs
+++ b/moli-renderer-v8/src/stylesheet_blocking.rs
@@ -263,9 +263,9 @@ enum StylesheetResponseProvenance {
}
impl StylesheetResponseProvenance {
- fn is_cors_same_origin(self, document_url: &Url, response_url: &Url) -> bool {
+ fn is_cors_same_origin(self, document_url: &Url, head: &moli_fetch::ResponseHead) -> bool {
match self {
- Self::Network => moli_url::same_origin(document_url, response_url),
+ Self::Network => !head.url_list().has_cross_origin_url(document_url),
Self::ServiceWorker { filter } => !matches!(
filter,
Some(
@@ -285,6 +285,7 @@ fn stylesheet_terminal_from_response(
response_provenance: StylesheetResponseProvenance,
) -> StylesheetFetchTerminal {
let (request_mode, credentials_mode) = options.request_mode_and_credentials();
+ let head = response.head();
let cors_usability =
(request_mode == moli_fetch::RequestMode::Cors).then(|| match response_provenance {
StylesheetResponseProvenance::ServiceWorker {
@@ -297,16 +298,17 @@ fn stylesheet_terminal_from_response(
"failed to fetch stylesheet `{request_url}`: CORS response is opaque"
)),
StylesheetResponseProvenance::ServiceWorker { .. } => Ok(()),
- StylesheetResponseProvenance::Network => crate::network_host::validate_cors_response(
- document_url,
- &response.final_url,
- &response.headers,
- credentials_mode,
- )
- .map_err(|error| format!("failed to fetch stylesheet `{request_url}`: {error}")),
+ StylesheetResponseProvenance::Network => {
+ crate::network_host::validate_cors_response_chain(
+ document_url,
+ &head,
+ credentials_mode,
+ )
+ .map_err(|error| format!("failed to fetch stylesheet `{request_url}`: {error}"))
+ }
});
let origin_clean = cors_usability.as_ref().map_or_else(
- || response_provenance.is_cors_same_origin(document_url, &response.final_url),
+ || response_provenance.is_cors_same_origin(document_url, &head),
Result::is_ok,
);
let usability = if !(200..=299).contains(&response.status) {
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index 431ac9313..66d4a6a6f 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -2169,6 +2169,7 @@ fn connected_link_readiness_request(
request = request.with_resource_type(resource_type);
}
if let Some(metadata) = options.script_fetch_metadata.as_ref() {
+ request = request.with_browser_request_metadata(moli_fetch::BrowserRequestMetadata::Script);
request = request.with_script_fetch_metadata(moli_fetch::ScriptFetchRequestMetadata {
cross_origin: metadata.cross_origin.clone(),
referrer_policy: metadata.referrer_policy.clone(),