diff --git a/moli-csp/src/checks.rs b/moli-csp/src/checks.rs index 2c56effcaee..2baf1148c5a 100644 --- a/moli-csp/src/checks.rs +++ b/moli-csp/src/checks.rs @@ -909,9 +909,17 @@ fn source_list_activates_strict_dynamic(sources: &[&str]) -> bool { } fn csp_nonce_source_value(source: &str) -> Option<&str> { - source - .strip_prefix("'nonce-") - .and_then(|value| value.strip_suffix('\'')) + if !source.get(..7)?.eq_ignore_ascii_case("'nonce-") { + return None; + } + let value = source.get(7..)?.strip_suffix('\'')?; + let digits = value.trim_end_matches('='); + (!digits.is_empty() + && value.len() - digits.len() <= 2 + && digits + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'-' | b'_'))) + .then_some(value) } #[derive(Clone, Copy, Debug, Eq, PartialEq, strum::EnumString)] @@ -1507,3 +1515,7 @@ pub fn content_security_policy_trusted_types_policy_violation_with_disposition_a column_number: 0, }) } + +#[path = "embedded_enforcement.rs"] +mod embedded_enforcement; +pub use embedded_enforcement::RequiredCspResponse; diff --git a/moli-csp/src/embedded_enforcement.rs b/moli-csp/src/embedded_enforcement.rs new file mode 100644 index 00000000000..b65e7396823 --- /dev/null +++ b/moli-csp/src/embedded_enforcement.rs @@ -0,0 +1,282 @@ +mod sources; +mod subsumption; + +use crate::{ContentSecurityPolicy, IframeCspAttribute}; +use url::Url; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RequiredCspResponse { + Satisfied, + Enforce(Url), + Blocked, +} + +impl IframeCspAttribute { + pub fn subsumes(&self, policies: &[ContentSecurityPolicy], origin: &Url) -> bool { + subsumption::subsumes(self.policy(), policies, origin) + } + + pub fn response_disposition( + &self, + request_origin: &str, + response_url: &Url, + headers: &[(String, Vec)], + response_policies: &[ContentSecurityPolicy], + ) -> RequiredCspResponse { + if matches!( + response_url.scheme(), + "about" | "data" | "blob" | "file" | "filesystem" + ) { + // Local Documents inherit the embedder's interpretation of 'self', + // including data URLs whose own origin is opaque. + return RequiredCspResponse::Enforce( + Url::parse(request_origin).unwrap_or_else(|_| response_url.clone()), + ); + } + // Explicit acceptance installs the requirement even if the response + // also happens to subsume it. Only implicit acceptance uses the + // response policy alone (and keeps nonce values private). + if allows_blanket_enforcement(request_origin, headers) { + RequiredCspResponse::Enforce(response_url.clone()) + } else if self.subsumes(response_policies, response_url) { + RequiredCspResponse::Satisfied + } else { + RequiredCspResponse::Blocked + } + } +} + +fn allows_blanket_enforcement(request_origin: &str, headers: &[(String, Vec)]) -> bool { + let mut values = headers + .iter() + .filter(|(name, _)| name.eq_ignore_ascii_case("Allow-CSP-From")); + let Some((_, value)) = values.next() else { + return false; + }; + if values.next().is_some() { + return false; + } + let Ok(value) = std::str::from_utf8(value) else { + return false; + }; + let value = value.trim_ascii(); + value == "*" || (request_origin != "null" && value == request_origin) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn required_policies_compare_effective_source_intersections_without_disclosing_nonces() { + let origin = Url::parse("https://embedee.test/frame").unwrap(); + for (required, returned, expected) in [ + ( + "img-src 'none'", + vec!["img-src http://example.test", "img-src wss://example.test"], + false, + ), + ( + "img-src https://example.test", + vec!["img-src http://example.test", "img-src wss://example.test"], + true, + ), + ( + "img-src http://example.test", + vec!["img-src http://example.test:80"], + true, + ), + ( + "img-src http://example.test:36", + vec!["img-src https://example.test:36"], + true, + ), + ( + "img-src http://example.test", + vec!["img-src https://example.test:80"], + false, + ), + ( + "img-src http://example.test:80", + vec!["img-src https://example.test:80"], + true, + ), + ( + "script-src 'NoNcE-parent'", + vec!["script-src 'nonce-child'"], + true, + ), + ( + "script-src 'none'", + vec![ + "script-src 'nonce-a'", + "script-src 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='", + ], + false, + ), + ( + "script-src 'nonce-parent'", + vec![ + "script-src 'nonce-child' 'unsafe-inline'", + "script-src 'unsafe-inline'", + ], + true, + ), + ( + "script-src 'strict-dynamic' 'nonce-parent'", + vec!["script-src 'nonce-child'", "script-src https://cdn.test"], + true, + ), + ( + "script-src 'nonce-parent'", + vec![ + "script-src 'strict-dynamic' 'nonce-child'", + "script-src https://cdn.test", + ], + false, + ), + ( + "script-src 'nonce-parent'", + vec!["script-src 'nonce-child'"], + true, + ), + ( + "script-src 'nonce-parent'", + vec!["script-src 'unsafe-inline'"], + false, + ), + ( + "script-src 'none'", + vec!["script-src 'nonce-a'", "script-src 'nonce-b'"], + true, + ), + ( + "img-src https://*.example.test/asset/", + vec![ + "img-src https://*.test:*", + "default-src https://cdn.example.test/asset/icon", + ], + true, + ), + ( + "img-src https://*.example.test/asset/", + vec![ + "img-src https://*.test:*", + "default-src https://cdn.example.test/other/", + ], + false, + ), + ( + "img-src https://example.test/a%2Fb", + vec!["img-src https://example.test/a/b"], + false, + ), + ( + "frame-src http://example.test:80", + vec!["child-src https://example.test:443"], + true, + ), + ( + "frame-src https://example.test:443", + vec!["child-src http://example.test:80"], + false, + ), + ( + "script-src-attr 'none'", + vec!["default-src 'none'; script-src 'unsafe-inline'"], + false, + ), + ("plugin-types application/pdf", vec![], true), + ("default-src 'none'", vec![], false), + ] { + let policy = IframeCspAttribute::parse(required).unwrap(); + let returned = returned.into_iter().map(ContentSecurityPolicy::from).collect::>(); + assert_eq!( + policy.subsumes(&returned, &origin), + expected, + "{required:?}, {returned:?}" + ); + } + } + + #[test] + fn required_policy_needs_explicit_response_acceptance_or_enforced_subsumption() { + let required = IframeCspAttribute::parse("script-src 'nonce-parent'").unwrap(); + let origin = Url::parse("https://embedee.test/frame").unwrap(); + for (headers, expected) in [ + (vec![], RequiredCspResponse::Blocked), + ( + vec![("Allow-CSP-From", b"*".as_slice())], + RequiredCspResponse::Enforce(origin.clone()), + ), + ( + vec![("Allow-CSP-From", b"https://embedder.test".as_slice())], + RequiredCspResponse::Enforce(origin.clone()), + ), + ( + vec![("Allow-CSP-From", b"https://other.test".as_slice())], + RequiredCspResponse::Blocked, + ), + ( + vec![("Allow-CSP-From", b"*, https://embedder.test".as_slice())], + RequiredCspResponse::Blocked, + ), + ( + vec![ + ("Allow-CSP-From", b"*".as_slice()), + ("allow-csp-from", b"*".as_slice()), + ], + RequiredCspResponse::Blocked, + ), + ( + vec![("Allow-CSP-From", b"*\xff".as_slice())], + RequiredCspResponse::Blocked, + ), + ] { + let headers = headers + .into_iter() + .map(|(name, value)| (name.to_owned(), value.to_vec())) + .collect::>(); + assert_eq!( + required.response_disposition("https://embedder.test", &origin, &headers, &[]), + expected + ); + } + assert_eq!( + required.response_disposition( + "null", + &origin, + &[("Allow-CSP-From".to_owned(), b"null".to_vec())], + &[] + ), + RequiredCspResponse::Blocked + ); + assert_eq!( + required.response_disposition( + "https://embedder.test", + &origin, + &[], + &["script-src 'nonce-response'".into()] + ), + RequiredCspResponse::Satisfied + ); + assert_eq!( + required.response_disposition( + "https://embedder.test", + &origin, + &[("Allow-CSP-From".to_owned(), b"*".to_vec())], + &["script-src 'nonce-response'".into()] + ), + RequiredCspResponse::Enforce(origin.clone()) + ); + assert_eq!( + required.response_disposition( + "https://embedder.test", + &Url::parse("data:text/html,hello").unwrap(), + &[], + &[] + ), + RequiredCspResponse::Enforce(Url::parse("https://embedder.test").unwrap()) + ); + } +} diff --git a/moli-csp/src/embedded_enforcement/sources.rs b/moli-csp/src/embedded_enforcement/sources.rs new file mode 100644 index 00000000000..2af72ce8179 --- /dev/null +++ b/moli-csp/src/embedded_enforcement/sources.rs @@ -0,0 +1,192 @@ +use super::super::{ + CspSchemeMatch, csp_host_part_matches, csp_path_part_matches, csp_scheme_match, + default_port_for_scheme, parse_host_source, +}; +use url::Url; + +/// Preserve source-expression syntax for CSP subsumption. In particular, +/// omitted and explicit default ports have distinct scheme-upgrade rules. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(super) struct UrlSource { + scheme: String, + host: Option, + port: Port, + path: String, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Port { + Any, + Number(u16), + Unspecified, +} + +impl UrlSource { + fn scheme(scheme: &str) -> Self { + Self { + scheme: scheme.to_ascii_lowercase(), + host: None, + port: Port::Any, + path: String::new(), + } + } + + pub(super) fn parse(value: &str, origin: &Url) -> Vec { + if value == "*" { + return ["ftp", "http", "ws", origin.scheme()] + .into_iter() + .map(Self::scheme) + .collect(); + } + if super::super::csp_keyword_eq(value, "self") { + if matches!(origin.origin(), url::Origin::Tuple(..)) + && let Some(host) = origin.host_str() + { + return vec![Self { + scheme: origin.scheme().to_owned(), + host: Some(host.to_ascii_lowercase()), + port: origin + .port_or_known_default() + .map_or(Port::Unspecified, Port::Number), + path: String::new(), + }]; + } + return Vec::new(); + } + if let Some(scheme) = value.strip_suffix(':') { + let mut bytes = scheme.bytes(); + if bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) + && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')) + { + return vec![Self::scheme(scheme)]; + } + return Vec::new(); + } + let Some(source) = parse_host_source(value) else { + return Vec::new(); + }; + let scheme = source + .scheme + .unwrap_or(origin.scheme()) + .to_ascii_lowercase(); + let port = match source.port { + Some("*") => Port::Any, + Some(value) => match value.parse() { + Ok(port) => Port::Number(port), + Err(_) => return Vec::new(), + }, + None => Port::Unspecified, + }; + vec![Self { + scheme, + host: Some(source.host.to_ascii_lowercase()), + port, + path: source.path.unwrap_or_default().to_owned(), + }] + } + + pub(super) fn subsumes(&self, other: &Self) -> bool { + csp_scheme_match(&self.scheme, &other.scheme) != CspSchemeMatch::NotMatching + && host_subsumes(self.host.as_deref(), other.host.as_deref()) + && self.port_subsumes(other) + && csp_path_part_matches(&self.path, &other.path) + } + + pub(super) fn intersect(&self, other: &Self) -> Option { + let scheme = if csp_scheme_match(&self.scheme, &other.scheme) != CspSchemeMatch::NotMatching + { + other.scheme.clone() + } else if csp_scheme_match(&other.scheme, &self.scheme) != CspSchemeMatch::NotMatching { + self.scheme.clone() + } else if csp_scheme_match(&self.scheme, "https") != CspSchemeMatch::NotMatching + && csp_scheme_match(&other.scheme, "https") != CspSchemeMatch::NotMatching + { + // HTTP and WSS both permit HTTPS under CSP's scheme-part rules. + // Neither source subsumes the other, but their intersection is + // not empty. + "https".to_owned() + } else { + return None; + }; + // A scheme-only source adds no host, port or path restriction. + if self.host.is_none() || other.host.is_none() { + let mut result = if self.host.is_none() { + other.clone() + } else { + self.clone() + }; + result.scheme = scheme.clone(); + return Some(result); + } + let host = if host_subsumes(self.host.as_deref(), other.host.as_deref()) { + other.host.clone() + } else if host_subsumes(other.host.as_deref(), self.host.as_deref()) { + self.host.clone() + } else { + return None; + }; + let port = if self.port == Port::Any { + other.port + } else if other.port == Port::Any { + self.port + } else if self.port_subsumes(other) + && (self.port == Port::Unspecified || other.port != Port::Unspecified) + { + other.port + } else if other.port_subsumes(self) { + self.port + } else { + return None; + }; + let path = if csp_path_part_matches(&self.path, &other.path) { + other.path.clone() + } else if csp_path_part_matches(&other.path, &self.path) { + self.path.clone() + } else { + return None; + }; + Some(Self { + scheme: scheme.clone(), + host, + port, + path, + }) + } + + fn port_subsumes(&self, other: &Self) -> bool { + if self.port == Port::Any { + return true; + } + if other.port == Port::Any { + return false; + } + if self.port == other.port { + return true; + } + let default = default_port_for_scheme(&other.scheme); + if (self.port == Port::Unspecified + && other.port == default.map_or(Port::Unspecified, Port::Number)) + || (other.port == Port::Unspecified + && self.port == default.map_or(Port::Unspecified, Port::Number)) + { + return true; + } + let source_port = match self.port { + Port::Number(port) => Some(port), + _ => default_port_for_scheme(&self.scheme), + }; + let other_port = match other.port { + Port::Number(port) => Some(port), + _ => default, + }; + source_port == Some(80) && other_port == Some(443) + } +} + +fn host_subsumes(a: Option<&str>, b: Option<&str>) -> bool { + match (a, b) { + (None, _) => true, + (Some(a), Some(b)) => csp_host_part_matches(a, b), + (Some(_), None) => false, + } +} diff --git a/moli-csp/src/embedded_enforcement/subsumption.rs b/moli-csp/src/embedded_enforcement/subsumption.rs new file mode 100644 index 00000000000..9ef0d8e5dcf --- /dev/null +++ b/moli-csp/src/embedded_enforcement/subsumption.rs @@ -0,0 +1,303 @@ +use super::super::{ + BASE_URI, CHILD_SRC, CONNECT_SRC, CspHashAlgorithm, DEFAULT_SRC, FONT_SRC, FRAME_ANCESTORS, + FRAME_SRC, IMG_SRC, MANIFEST_SRC, MEDIA_SRC, SCRIPT_SRC, SCRIPT_SRC_ATTR, SCRIPT_SRC_ELEM, + STYLE_SRC, STYLE_SRC_ATTR, STYLE_SRC_ELEM, WORKER_SRC, csp_hash_source_value, csp_keyword_eq, + csp_nonce_source_value, directive_source_list, ContentSecurityPolicy, +}; +use super::sources::UrlSource; +use base64::{ + Engine as _, alphabet, + engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}, +}; +use url::Url; + +const BASE64: GeneralPurpose = GeneralPurpose::new( + &alphabet::STANDARD, + GeneralPurposeConfig::new() + .with_decode_padding_mode(DecodePaddingMode::Indifferent) + .with_decode_allow_trailing_bits(true), +); + +// A missing directive is unrestricted, not an empty source list. Evaluate +// every effective directive, including independent element/attribute fallbacks. +const DIRECTIVES: &[&[&str]] = &[ + &[CHILD_SRC, DEFAULT_SRC], + &[CONNECT_SRC, DEFAULT_SRC], + &[FONT_SRC, DEFAULT_SRC], + &[FRAME_SRC, CHILD_SRC, DEFAULT_SRC], + &[IMG_SRC, DEFAULT_SRC], + &[MANIFEST_SRC, DEFAULT_SRC], + &[MEDIA_SRC, DEFAULT_SRC], + &["object-src", DEFAULT_SRC], + &[SCRIPT_SRC, DEFAULT_SRC], + &[SCRIPT_SRC_ATTR, SCRIPT_SRC, DEFAULT_SRC], + &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC], + &[STYLE_SRC, DEFAULT_SRC], + &[STYLE_SRC_ATTR, STYLE_SRC, DEFAULT_SRC], + &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC], + &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC], + &[BASE_URI], + &[FRAME_ANCESTORS], + &["form-action"], + &["fenced-frame-src", DEFAULT_SRC], +]; + +/// Whether all behavior permitted by the returned policy list is permitted by +/// the required policy. Nonces compare by presence after intersecting the +/// returned list; their actual values must not become an embedder oracle. +pub(super) fn subsumes(required: &ContentSecurityPolicy, returned: &[ContentSecurityPolicy], origin: &Url) -> bool { + DIRECTIVES.iter().all(|fallbacks| { + let Some((name, tokens)) = fallbacks + .iter() + .find_map(|name| directive_source_list(required, name).map(|tokens| (*name, tokens))) + else { + return true; + }; + let required = SourceList::parse(&tokens, origin); + let lists = returned + .iter() + .filter_map(|policy| { + fallbacks + .iter() + .find_map(|name| directive_source_list(policy, name)) + .map(|tokens| SourceList::parse(&tokens, origin)) + }) + .collect::>(); + if lists.is_empty() { + return false; + } + required.subsumes(&lists, name) + }) +} + +#[derive(Default)] +struct SourceList { + urls: Vec, + nonces: Vec, + hashes: Vec<(CspHashAlgorithm, Vec)>, + inline: bool, + eval: bool, + wasm_eval: bool, + trusted_eval: bool, + dynamic: bool, + unsafe_hashes: bool, +} + +impl SourceList { + fn parse(tokens: &[&str], origin: &Url) -> Self { + let mut result = Self::default(); + for token in tokens { + if let Some(nonce) = csp_nonce_source_value(token) { + result.nonces.push(nonce.to_owned()); + } else if let Some(hash) = csp_hash_source_value(token) { + let normalized = hash.digest.replace('-', "+").replace('_', "/"); + if let Ok(digest) = BASE64.decode(normalized) { + result.hashes.push((hash.algorithm, digest)); + } + } else { + result.inline |= csp_keyword_eq(token, "unsafe-inline"); + result.eval |= csp_keyword_eq(token, "unsafe-eval"); + result.wasm_eval |= csp_keyword_eq(token, "wasm-unsafe-eval"); + result.trusted_eval |= csp_keyword_eq(token, "trusted-types-eval"); + result.dynamic |= csp_keyword_eq(token, "strict-dynamic"); + result.unsafe_hashes |= csp_keyword_eq(token, "unsafe-hashes"); + result.urls.extend(UrlSource::parse(token, origin)); + } + } + result.wasm_eval |= result.eval; + result.trusted_eval |= result.eval; + result + } + + fn subsumes(&self, others: &[Self], directive: &str) -> bool { + let script = directive == DEFAULT_SRC || directive.starts_with("script-src"); + let style = directive == DEFAULT_SRC || directive.starts_with("style-src"); + if (script || style) + && ((!self.eval && others.iter().all(|policy| policy.eval)) + || (!self.unsafe_hashes && others.iter().all(|policy| policy.unsafe_hashes)) + || (script + && ((!self.wasm_eval && others.iter().all(|policy| policy.wasm_eval)) + || (!self.trusted_eval + && others.iter().all(|policy| policy.trusted_eval))))) + { + return false; + } + if script || style { + let inline = ExecutionKind::Inline { + script, + attribute: directive.ends_with("-attr"), + }; + if has_uncovered_execution(self, others, &ExecutionConstraint::default(), inline) { + return false; + } + if directive.ends_with("-attr") { + return true; + } + !has_uncovered_execution( + self, + others, + &ExecutionConstraint::default(), + ExecutionKind::External { script }, + ) + } else { + !has_uncovered_execution( + self, + others, + &ExecutionConstraint::default(), + ExecutionKind::Url, + ) + } + } + + fn allows_all_inline(&self, script: bool) -> bool { + self.inline + && self.nonces.is_empty() + && self.hashes.is_empty() + && (!script || !self.dynamic) + } + + fn alternatives(&self, kind: ExecutionKind) -> Vec> { + let mut result = Vec::new(); + match kind { + ExecutionKind::Inline { script, attribute } => { + if self.allows_all_inline(script) { + return vec![Permit::Any]; + } + if !attribute { + result.extend(self.nonces.iter().map(|value| Permit::Nonce(value))); + } + if !attribute || self.unsafe_hashes { + result.extend(self.hashes.iter().map(Permit::Hash)); + } + } + ExecutionKind::External { script } => { + if script && self.dynamic { + result.push(Permit::Dynamic); + } else { + result.extend(self.urls.iter().map(Permit::Url)); + } + result.extend(self.nonces.iter().map(|value| Permit::Nonce(value))); + result.extend(self.hashes.iter().map(Permit::Hash)); + } + ExecutionKind::Url => result.extend(self.urls.iter().map(Permit::Url)), + } + result + } + + fn covers(&self, execution: &ExecutionConstraint, kind: ExecutionKind) -> bool { + for permit in self.alternatives(kind) { + // Compare required nonce values by presence, without allowing the + // embedder to probe which nonce the response actually chose. + if matches!(permit, Permit::Nonce(_)) && execution.nonce.is_some() { + return true; + } + if execution.satisfies(&permit) { + return true; + } + } + false + } +} + +#[derive(Clone, Copy)] +enum ExecutionKind { + Url, + Inline { script: bool, attribute: bool }, + External { script: bool }, +} + +#[derive(Clone, Copy)] +enum Permit<'a> { + Any, + Url(&'a UrlSource), + Nonce(&'a str), + Hash(&'a (CspHashAlgorithm, Vec)), + Dynamic, +} + +/// A conjunction of response-policy conditions, including combinations that +/// cannot be serialized as a single CSP source list (such as nonce AND hash). +#[derive(Clone, Default)] +struct ExecutionConstraint { + url: Option, + nonce: Option, + hashes: Vec<(CspHashAlgorithm, Vec)>, + dynamic: bool, +} + +impl ExecutionConstraint { + fn satisfies(&self, permit: &Permit<'_>) -> bool { + match permit { + Permit::Any => true, + Permit::Url(source) => self.url.as_ref().is_some_and(|url| source.subsumes(url)), + Permit::Nonce(nonce) => self.nonce.as_deref() == Some(*nonce), + Permit::Hash(hash) => self.hashes.contains(hash), + Permit::Dynamic => self.dynamic, + } + } + + fn intersect(&self, permit: Permit<'_>) -> Option { + let mut result = self.clone(); + match permit { + Permit::Any => {} + Permit::Url(source) => { + result.url = Some(match &self.url { + Some(url) => url.intersect(source)?, + None => source.clone(), + }); + } + Permit::Nonce(nonce) => { + if self.nonce.as_ref().is_some_and(|value| value != nonce) { + return None; + } + result.nonce = Some(nonce.to_owned()); + } + Permit::Hash(hash) => { + if self + .hashes + .iter() + .any(|value| value.0 == hash.0 && value.1 != hash.1) + { + return None; + } + if !self.hashes.contains(hash) { + result.hashes.push(hash.clone()); + } + } + Permit::Dynamic => result.dynamic = true, + } + Some(result) + } +} + +fn has_uncovered_execution( + required: &SourceList, + mut returned: &[SourceList], + execution: &ExecutionConstraint, + kind: ExecutionKind, +) -> bool { + if required.covers(execution, kind) { + return false; + } + loop { + let Some((policy, remaining)) = returned.split_first() else { + return true; + }; + let alternatives = policy.alternatives(kind); + if alternatives + .iter() + .any(|permit| execution.satisfies(permit)) + { + returned = remaining; + continue; + } + for permit in alternatives { + if let Some(next) = execution.intersect(permit) + && has_uncovered_execution(required, remaining, &next, kind) + { + return true; + } + } + return false; + } +} diff --git a/moli-csp/src/iframe_attribute.rs b/moli-csp/src/iframe_attribute.rs index 1830ceeff68..7b6aea62e4e 100644 --- a/moli-csp/src/iframe_attribute.rs +++ b/moli-csp/src/iframe_attribute.rs @@ -3,7 +3,7 @@ //! policy value. Source-list interpretation remains the CSP parser's job. #[derive(Clone, Debug, Eq, PartialEq)] -pub struct IframeCspAttribute(String); +pub struct IframeCspAttribute(crate::ContentSecurityPolicy); impl IframeCspAttribute { pub fn parse(value: &str) -> Option { @@ -36,11 +36,15 @@ impl IframeCspAttribute { return None; } } - Some(Self(value.to_owned())) + Some(Self(value.into())) + } + + pub(crate) fn policy(&self) -> &crate::ContentSecurityPolicy { + &self.0 } pub fn as_str(&self) -> &str { - &self.0 + self.0.as_str() } } diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs index e75e498dc46..c208dc3029e 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/fetch_timing.rs @@ -363,20 +363,22 @@ impl FetchResourceTiming { &self, entry: &mut ResourcePerformanceEntry, network: &crate::protocol_types::ChildFrameDocumentNetworkSnapshot, + expose_document_response: bool, ) { + let timing_allowed = expose_document_response && network.resource_timing_allowed; // Cross-origin timing failures use the enclosing frame's actual load // boundary, rather than leaking when its response body finished. - entry.end_unix_millis = Some(if network.resource_timing_allowed { + entry.end_unix_millis = Some(if timing_allowed { self.end() } else { self.now() }); - if !network.resource_timing_body_visible { + if !expose_document_response || !network.resource_timing_body_visible { entry.content_encoding.clear(); entry.response_status = 0.0; entry.content_type.clear(); } - if !network.resource_timing_allowed { + if !timing_allowed { entry.encoded_body_size = 0.0; entry.decoded_body_size = 0.0; entry.transfer_size = 0.0; diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs index cf233719d05..5c03ec25e4f 100644 --- a/moli-renderer-v8/src/document_runtime.rs +++ b/moli-renderer-v8/src/document_runtime.rs @@ -655,6 +655,8 @@ pub(crate) struct DocumentPolicyContainer { pub(crate) inherited_meta_content_security_policies: Vec, // Preserve the policy's source when local-scheme Documents inherit it. pub(crate) content_security_policy_self_url: Option, + pub(crate) required_content_security_policy: + Option, pub(crate) content_security_reporting_endpoints: crate::content_security_policy::ContentSecurityPolicyReportingEndpoints, pub(crate) credentialless: bool, diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs index 81d12d8dad1..dc9189662e6 100644 --- a/moli-renderer-v8/src/document_runtime/security_policy.rs +++ b/moli-renderer-v8/src/document_runtime/security_policy.rs @@ -447,6 +447,45 @@ impl DocumentPolicyContainer { } } + pub(crate) fn apply_required_content_security_policy( + &mut self, + required: &crate::content_security_policy::IframeCspAttribute, + request_origin: &str, + final_url: &Url, + headers: &[(String, Vec)], + ) -> bool { + use crate::content_security_policy::RequiredCspResponse; + let disposition = required.response_disposition( + request_origin, + final_url, + headers, + &self.response_content_security_policies, + ); + self.required_content_security_policy = Some(required.clone()); + if disposition == RequiredCspResponse::Blocked { + return false; + } + if let RequiredCspResponse::Enforce(self_url) = disposition { + self.document_content_security_policies + .push(required.as_str().to_owned()); + self.response_content_security_policies + .push(required.as_str().to_owned()); + self.content_security_policy_self_url + .get_or_insert(self_url); + self.sandbox = self.sandbox.with_response_content_security_policy( + DocumentSandboxPolicy::from_response_content_security_policies( + &self.response_content_security_policies, + ), + ); + if self.sandbox.forces_opaque_origin { + self.permissions_policy = self + .permissions_policy + .for_document_origin(&url::Origin::new_opaque()); + } + } + true + } + pub(crate) fn navigation_response_frame_ancestors_check( &self, protected_url: &Url, @@ -479,6 +518,7 @@ impl DocumentPolicyContainer { } pub(crate) fn clear_content_security_policy_for_bypass(&mut self) { + self.required_content_security_policy = None; self.document_content_security_policies.clear(); self.response_content_security_policies.clear(); self.response_content_security_report_only_policies.clear(); @@ -1289,7 +1329,18 @@ pub(crate) fn set_response_content_security_report_only_policies( Default::default(), ); } - DocumentConnectPolicySnapshot { + self.installed_document_request_policy_snapshot(document_handle, policy) + } + + // Snapshot the installed policies and account for meta delivery even when + // bypass is enabled. Callers decide whether their request bypasses CSP; + // the runtime switch does not erase an existing Document's policy. + fn installed_document_request_policy_snapshot( + &self, + document_handle: Option, + policy: &DocumentPolicyContainer, + ) -> DocumentRequestPolicySnapshot { + DocumentRequestPolicySnapshot { resource_kind: ContentSecurityPolicyResourceKind::DocumentConnect, preload_metadata: None, policy_self_url: policy @@ -1374,32 +1425,13 @@ pub(crate) fn set_response_content_security_report_only_policies( request_url: &Url, kind: DocumentSubresourceCspKind, ) -> DocumentContentSecurityPolicyCheck { - let policies = self.document_content_security_policies_for_optional_document( - document_handle, - &policy_container.response_content_security_policies, - &policy_container.content_security_reporting_endpoints, - ); - let enforced_violations = document_url_policy_violations_from_document_policies( - policies, - document_url, - request_url, - kind.resource_kind(), - ContentSecurityPolicyRedirectStatus::NoRedirect, - ContentSecurityPolicyDisposition::Enforce, - ); - let report_only_violations = document_url_policy_violations( - &policy_container.response_content_security_report_only_policies, - &policy_container.content_security_reporting_endpoints, - document_url, - request_url, - kind.resource_kind(), - ContentSecurityPolicyRedirectStatus::NoRedirect, - ContentSecurityPolicyDisposition::Report, - ); - DocumentContentSecurityPolicyCheck { - report_only_violations, - enforced_violations, - } + self.installed_document_request_policy_snapshot(document_handle, policy_container) + .for_resource_kind(kind.resource_kind()) + .check_url( + document_url, + request_url, + ContentSecurityPolicyRedirectStatus::NoRedirect, + ) } #[cfg(test)] @@ -3075,6 +3107,64 @@ mod tests { } } + #[test] + fn local_subresource_checks_keep_policy_origin_separate_from_report_document() { + let runtime = runtime_for_html(""); + let document_url = Url::parse("data:text/html,local-document").unwrap(); + let mut policy = DocumentPolicyContainer::from_navigation_response_headers( + &[ + ( + "Content-Security-Policy".to_owned(), + b"default-src 'self'".to_vec(), + ), + ( + "Content-Security-Policy-Report-Only".to_owned(), + b"default-src 'none'".to_vec(), + ), + ], + &document_url, + ); + policy.content_security_policy_self_url = + Some(Url::parse("https://embedder.test/").unwrap()); + for kind in [ + DocumentSubresourceCspKind::Image, + DocumentSubresourceCspKind::Manifest, + DocumentSubresourceCspKind::Media, + ] { + for (url, blocked) in [ + ("https://embedder.test/resource", false), + ("https://other.test/resource", true), + ] { + let (reported, enforced) = runtime + .document_subresource_csp_check_for_document( + None, + &document_url, + &policy, + &Url::parse(url).unwrap(), + kind, + ) + .into_violations(); + assert_eq!( + reported.len(), + 1, + "report-only policy must remain independent of enforcement" + ); + assert_eq!( + enforced.len(), + usize::from(blocked), + "'self' must use the retained policy origin" + ); + for violation in reported.iter().chain(&enforced) { + assert_eq!( + violation.document_uri, "data", + "reports identify the protected Document, not the policy origin" + ); + assert_eq!(violation.source_file, "data"); + } + } + } + } + #[test] fn document_csp_checks_report_each_violated_header_and_meta_policy() { let mut runtime = runtime_for_html( diff --git a/moli-renderer-v8/src/frame_owner_model/records.rs b/moli-renderer-v8/src/frame_owner_model/records.rs index 40327d03a43..70f83d99fe2 100644 --- a/moli-renderer-v8/src/frame_owner_model/records.rs +++ b/moli-renderer-v8/src/frame_owner_model/records.rs @@ -283,9 +283,13 @@ impl FrameDocumentLocalWindowTransition { pub(crate) enum DocumentCreationKind { InitialEmpty, Navigation, + /// An inert, opaque-origin Document committed after a response was blocked. + Error, Srcdoc, JavascriptUrl, - DocumentOpen { is_initial_empty: bool }, + DocumentOpen { + is_initial_empty: bool, + }, } impl DocumentCreationKind { diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs index 95ad89f7938..27e9e356b89 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs @@ -28,6 +28,9 @@ pub(crate) enum LocalChildDocumentPreparation { /// A local response is available, but must not replace the active Document. IgnoredNavigation, Ready(Box), + /// Restore the historical local resource and its policy container intact; + /// current iframe attributes apply to new navigations, not this resource. + Historical(Box), } impl LocalChildDocumentPreparation { @@ -35,7 +38,7 @@ impl LocalChildDocumentPreparation { /// inspect the disposition so an ignored response cannot clear a Document. pub(crate) fn into_snapshot(self) -> Option { match self { - Self::Ready(snapshot) => Some(*snapshot), + Self::Ready(snapshot) | Self::Historical(snapshot) => Some(*snapshot), Self::Unavailable | Self::IgnoredNavigation => None, } } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs index 46d835cc81d..7bde8a9b722 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs @@ -46,7 +46,7 @@ impl JsContextHost { self.finish_child_frame_navigation_without_load_dispatch(handle, navigation_load); return Some(ChildDocumentCommitResult::ready(None)); } - let creation_kind = child_document_creation_kind_for_bootstrap(&bootstrap); + let mut creation_kind = child_document_creation_kind_for_bootstrap(&bootstrap); if let Some(request_url) = child_document_frame_csp_request_url(&bootstrap) { if let Some(violation) = self.frame_navigation_csp_report_only_violation(handle, request_url) @@ -86,7 +86,29 @@ impl JsContextHost { self.cancel_child_meta_refresh_navigation(handle); let cached_snapshot = match self.materialize_local_child_snapshot_for_bootstrap(handle, &bootstrap) { - LocalChildDocumentPreparation::Ready(snapshot) => Some(*snapshot), + LocalChildDocumentPreparation::Ready(snapshot) => { + let mut snapshot = *snapshot; + if !target_snapshot.apply_response_policy( + &mut snapshot.policy_container, + &snapshot.url, + &[], + ) { + let policy = crate::document_runtime::DocumentPolicyContainer { + required_content_security_policy: snapshot + .policy_container + .required_content_security_policy, + ..Default::default() + }; + snapshot = ChildBrowsingContextSnapshot::html( + snapshot.url, + "".to_owned(), + ) + .with_policy_container(policy); + creation_kind = DocumentCreationKind::Error; + } + Some(snapshot) + } + LocalChildDocumentPreparation::Historical(snapshot) => Some(*snapshot), LocalChildDocumentPreparation::Unavailable => None, LocalChildDocumentPreparation::IgnoredNavigation => { crate::context_bootstrap::finish_joint_history_without_document_commit( diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs index 270af2f7435..b9a6a4aa0e9 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs @@ -74,14 +74,18 @@ impl JsContextHost { !creation_kind.is_initial_empty(), "initial-empty frame initialization must not enter snapshot commit planning" ); - let origin = self - .child_browsing_context_document_origin_for_url(handle, &snapshot.url) - .unwrap_or_else(|| moli_url::origin_ascii_serialization(&snapshot.url)); + let origin = if creation_kind == DocumentCreationKind::Error { + "null".to_owned() + } else { + self.child_browsing_context_document_origin_for_url(handle, &snapshot.url) + .unwrap_or_else(|| moli_url::origin_ascii_serialization(&snapshot.url)) + }; let current_document_domain_was_set = preflight.current_document_domain_was_set || self .child_browsing_context_document_domain_override(handle) .is_some(); - let security_origin_allows_reuse = !current_document_domain_was_set + let security_origin_allows_reuse = creation_kind != DocumentCreationKind::Error + && !current_document_domain_was_set && preflight .current_access_origin .as_ref() @@ -229,7 +233,7 @@ impl JsContextHost { if let Some(origin) = self.child_window_access_origin(handle) && let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { - entry.remember_srcdoc_history_resource(snapshot, origin); + entry.remember_local_history_resource(snapshot, origin); } self.remember_child_history(handle); let owner_local_window_id = current_owner.local_window_id; diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/frame_owner_resource_timing.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/frame_owner_resource_timing.rs index 0bec8cca083..8eecec7bf21 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/frame_owner_resource_timing.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/frame_owner_resource_timing.rs @@ -70,6 +70,7 @@ impl PendingFrameOwnerResourceTiming { fn performance_entry( &self, network: &crate::protocol_types::ChildFrameDocumentNetworkSnapshot, + expose_document_response: bool, ) -> ResourcePerformanceEntry { let mut entry = ResourcePerformanceEntry::from_child_frame_document_network( self.request_url.clone(), @@ -85,7 +86,7 @@ impl PendingFrameOwnerResourceTiming { if let Some(native) = network.resource_timing_response.as_deref() { timing.observe_native_timing(*native); } - timing.apply_child_document_timing(&mut entry, network); + timing.apply_child_document_timing(&mut entry, network, expose_document_response); entry } } @@ -133,7 +134,16 @@ impl JsContextHost { else { return; }; - if !self.record_frame_owner_resource_timing(scope, &timing.timing, &timing.network) { + let expose_response = self + .frame_owner_store + .current_child_document_creation_kind(action.child_handle()) + != Some(crate::frame_owner_model::DocumentCreationKind::Error); + if !self.record_frame_owner_resource_timing( + scope, + &timing.timing, + &timing.network, + expose_response, + ) { return; } if let Some(entry) = self.child_browsing_contexts.get_mut(&action.child_handle()) { @@ -151,7 +161,7 @@ impl JsContextHost { // Document or load event. Downloads and unsupported MIME types do not. // A TAO failure has no normal entry and, without load, no fallback entry. if matches!(network.status, 204 | 205) && network.resource_timing_allowed { - self.record_frame_owner_resource_timing(scope, timing, network); + self.record_frame_owner_resource_timing(scope, timing, network, true); } } @@ -160,6 +170,7 @@ impl JsContextHost { scope: &mut v8::PinScope<'_, '_>, timing: &PendingFrameOwnerResourceTiming, network: &crate::protocol_types::ChildFrameDocumentNetworkSnapshot, + expose_document_response: bool, ) -> bool { if !timing.parent_owner_is_current(self) { return false; @@ -174,7 +185,10 @@ impl JsContextHost { }; { let scope = &mut v8::ContextScope::new(scope, context); - record_resource_performance_entry(scope, timing.performance_entry(network)); + record_resource_performance_entry( + scope, + timing.performance_entry(network, expose_document_response), + ); } true } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs index 638fa444db7..fe775f055fc 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs @@ -1,6 +1,6 @@ use super::super::{ ChildBrowsingContextBootstrap, JsContextHost, OwnerDispatchScope, - child_frames::PendingChildFrameNavigation, + child_frames::{ChildNavigationTargetSnapshot, PendingChildFrameNavigation}, }; use super::{ ChildDocumentNavigationInitiator, PendingChildDocumentNavigation, @@ -229,9 +229,12 @@ impl JsContextHost { )) .with_page_network_policy() .with_network_partition_key(network_partition_key); - let request_url = request.url.as_str().to_owned(); - let request_method = request.method.clone(); - let request_headers = request.request_headers.to_byte_strings(); + let request_snapshot = ChildDocumentRequestSnapshot { + request_url: request.url.as_str().to_owned(), + request_method: request.method.clone(), + request_headers: request.request_headers.to_byte_strings(), + target: target_snapshot, + }; if let Some(client_id) = service_worker_client_id && let Some(response) = browser_context_runtime .fetch_service_worker_child_main_resource_for_reserved_client( @@ -249,9 +252,7 @@ impl JsContextHost { .map_err(|error| error.to_string())?; let (head, body) = response.into_body(); return child_document_load_outcome_from_response( - request_url, - request_method, - request_headers, + request_snapshot, head, body, ChildDocumentTiming { @@ -267,9 +268,7 @@ impl JsContextHost { .map_err(|error| error.to_string())?; let (head, body) = response.into_body(); child_document_load_outcome_from_response( - request_url, - request_method, - request_headers, + request_snapshot, head, body, ChildDocumentTiming { @@ -512,9 +511,12 @@ impl JsContextHost { ); } if let Some(violation) = enforced_violations.into_iter().next() { - Err(format!( - "child document response blocked by Content Security Policy `{}` for `{}`", - violation.effective_directive, violation.blocked_uri + tracing::debug!(directive = %violation.effective_directive, + url = %violation.blocked_uri, "child response blocked by frame-ancestors"); + Ok(ChildDocumentLoadOutcome::blocked_response( + loaded.final_url, + loaded.document_network, + loaded.policy_container.required_content_security_policy, )) } else { Ok(ChildDocumentLoadOutcome::Loaded(loaded)) @@ -546,11 +548,25 @@ impl JsContextHost { true, ) } + Ok(ChildDocumentLoadOutcome::BlockedResponse(mut document)) => { + if let Some(network) = document.document_network.take() { + self.record_child_document_network_activity(&network_attribution, network); + } + ( + Err("object response blocked by Content Security Policy".to_owned()), + true, + ) + } Err(error) => (Err(error), true), } } else { (result, false) }; + let creation_kind = if matches!(&result, Ok(ChildDocumentLoadOutcome::BlockedResponse(_))) { + DocumentCreationKind::Error + } else { + DocumentCreationKind::Navigation + }; let document_credentialless = pending.document_credentialless; let credentialless_storage_nonce = pending.credentialless_storage_nonce; let replaces_existing_document = self @@ -595,7 +611,10 @@ impl JsContextHost { body_activity, }; } - Ok(ChildDocumentLoadOutcome::Loaded(loaded)) => { + Ok( + ChildDocumentLoadOutcome::Loaded(loaded) + | ChildDocumentLoadOutcome::BlockedResponse(loaded), + ) => { let loaded = *loaded; if self.dispatch_child_browsing_context_unload_lifecycle_if_needed(scope, handle) { body_activity = ChildDocumentLoadBodyActivity::PageCodeOrEventDispatch; @@ -617,7 +636,10 @@ impl JsContextHost { completion: ChildDocumentLoadCompletion::new( target, network_attribution, - Ok(ChildDocumentLoadOutcome::Loaded(Box::new(loaded))), + Ok(ChildDocumentLoadOutcome::from_prepared_document( + loaded, + creation_kind, + )), ), body_activity, }; @@ -657,7 +679,10 @@ impl JsContextHost { completion: ChildDocumentLoadCompletion::new( target, network_attribution, - Ok(ChildDocumentLoadOutcome::Loaded(Box::new(loaded))), + Ok(ChildDocumentLoadOutcome::from_prepared_document( + loaded, + creation_kind, + )), ), body_activity, }; @@ -782,7 +807,7 @@ impl JsContextHost { handle, snapshot, window_commit_preflight, - DocumentCreationKind::Navigation, + creation_kind, Some(loader_id), ); let Some(install) = self.install_child_browsing_context_current_document_from_snapshot( @@ -899,10 +924,15 @@ struct ChildDocumentTiming<'a> { response: moli_fetch::FetchResponseTiming, } -fn child_document_load_outcome_from_response( +struct ChildDocumentRequestSnapshot { request_url: String, request_method: String, request_headers: Vec<(String, String)>, + target: ChildNavigationTargetSnapshot, +} + +fn child_document_load_outcome_from_response( + request: ChildDocumentRequestSnapshot, head: moli_fetch::ResponseHead, body: moli_fetch::ResponseBody, timing: ChildDocumentTiming<'_>, @@ -914,9 +944,9 @@ fn child_document_load_outcome_from_response( ); let encoded_data_length = response_body.len(); let network = crate::protocol_types::ChildFrameDocumentNetworkSnapshot { - request_url, - request_method, - request_headers, + request_url: request.request_url, + request_method: request.request_method, + request_headers: request.request_headers, final_url: head.final_url.as_str().to_owned(), status: head.status, response_headers: head.headers.clone(), @@ -943,13 +973,23 @@ fn child_document_load_outcome_from_response( .negotiated_http_version .filter(|_| head.cache_state != moli_fetch::ResponseCacheState::Local), }; + let mut policy_container = + DocumentPolicyContainer::from_navigation_response_headers(&head.headers, &head.final_url); + if !request + .target + .apply_response_policy(&mut policy_container, &head.final_url, &head.headers) + { + return Ok(ChildDocumentLoadOutcome::blocked_response( + head.final_url, + Some(network), + policy_container.required_content_security_policy, + )); + } if child_document_response_should_ignore_navigation(head.status, &head.headers) { return Ok(ChildDocumentLoadOutcome::IgnoredNavigation(Box::new( network, ))); } - let policy_container = - DocumentPolicyContainer::from_navigation_response_headers(&head.headers, &head.final_url); let (content_type, content, character_set) = { let body_bytes = response_body .try_bytes() @@ -1083,9 +1123,12 @@ mod tests { }; for timing_origin in [Some(&origin), None] { let outcome = child_document_load_outcome_from_response( - home.as_str().to_owned(), - "GET".to_owned(), - Vec::new(), + ChildDocumentRequestSnapshot { + request_url: home.as_str().to_owned(), + request_method: "GET".to_owned(), + request_headers: Vec::new(), + target: Default::default(), + }, head.clone(), moli_fetch::ResponseBody::materialized_bytes(b"body".to_vec()), ChildDocumentTiming { @@ -1118,9 +1161,12 @@ mod tests { fn loaded_child_document_retains_exact_network_response_body() { let body_bytes = b"

child network body \xff

".to_vec(); let outcome = child_document_load_outcome_from_response( - "https://example.test/child".to_owned(), - "GET".to_owned(), - Vec::new(), + ChildDocumentRequestSnapshot { + request_url: "https://example.test/child".to_owned(), + request_method: "GET".to_owned(), + request_headers: Vec::new(), + target: Default::default(), + }, moli_fetch::ResponseHead { status_text: None, final_url: url::Url::parse("https://example.test/child").unwrap(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/snapshots.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/snapshots.rs index d4d29e4f5e8..a6ee47706c2 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/snapshots.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/snapshots.rs @@ -118,20 +118,20 @@ impl JsContextHost { handle: DomHandle, bootstrap: &ChildBrowsingContextBootstrap, ) -> LocalChildDocumentPreparation { + if let Some(snapshot) = self + .child_browsing_contexts + .get(&handle) + .and_then(|entry| entry.pending_local_history_snapshot(bootstrap)) + { + return LocalChildDocumentPreparation::Historical(Box::new( + self.apply_page_csp_bypass_to_child_snapshot(snapshot), + )); + } let mut snapshot = match bootstrap { ChildBrowsingContextBootstrap::AboutBlank => ChildBrowsingContextSnapshot::about_blank( self.document_base_url_for_child_context(handle), ), ChildBrowsingContextBootstrap::Srcdoc { base_url, markup } => { - if let Some(snapshot) = self - .child_browsing_contexts - .get(&handle) - .and_then(|entry| entry.pending_srcdoc_history_snapshot()) - { - return LocalChildDocumentPreparation::Ready(Box::new( - self.apply_page_csp_bypass_to_child_snapshot(snapshot), - )); - } ChildBrowsingContextSnapshot::srcdoc(base_url.clone(), markup.clone()) } ChildBrowsingContextBootstrap::Url(url) => { diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs index e2c01e899e1..4d0af0fcea6 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs @@ -67,7 +67,7 @@ impl JsContextHost { ChildBrowsingContextBootstrap::Request(request), None, ChildDocumentNavigationInitiator::BrowsingContext, - self.snapshot_child_navigation_target(handle), + self.snapshot_child_navigation_target(handle, &url), ), false, None, @@ -206,7 +206,7 @@ impl JsContextHost { let bootstrap = self .child_browsing_contexts .get(&handle) - .and_then(|entry| entry.srcdoc_history_bootstrap(&entry_seed)) + .and_then(|entry| entry.local_history_bootstrap(&entry_seed)) .unwrap_or_else(|| ChildBrowsingContextBootstrap::Url(url.clone())); self.reject_replaced_service_worker_child_client_navigation( handle, @@ -222,7 +222,7 @@ impl JsContextHost { bootstrap, initiator_url, ChildDocumentNavigationInitiator::BrowsingContext, - self.snapshot_child_navigation_target(handle), + self.snapshot_child_navigation_target(handle, &url), ), false, None, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs index 298d0dee98e..8f5fef39cba 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commit.rs @@ -273,7 +273,7 @@ impl JsContextHost { ChildBrowsingContextBootstrap::Url(url.clone()), initiator_url, navigation_initiator, - self.snapshot_child_navigation_target(handle), + self.snapshot_child_navigation_target(handle, url), ), true, initiator, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs index a6d476c014d..23aedde49ba 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs @@ -28,12 +28,12 @@ use url::Url; mod classic_scripts; mod discovery; +mod local_history; mod lookup; mod module_scripts; mod nested_history; mod registry; mod request_scope; -mod srcdoc_history; mod stylesheets; mod target_snapshot; pub(in crate::native_bridge::context_host) use target_snapshot::ChildNavigationTargetSnapshot; @@ -75,8 +75,7 @@ pub(super) struct ChildBrowsingContextEntry { navigation_entry_seed: NavigationHistoryEntrySeed, committed_navigation_entry_seed: NavigationHistoryEntrySeed, cached_snapshot: Option, - srcdoc_history: - HashMap>, + local_history: HashMap>, document_policy_container: ChildDocumentPolicyContainer, // Captured at Document commit; changing sandbox or document.domain must // not grant a descendant permission to navigate the top without activation. @@ -431,6 +430,9 @@ impl ChildBrowsingContextEntry { credentialless: bool, credentialless_storage_nonce: Option, ) { + self.document_policy_container + .required_content_security_policy = + policy_container.required_content_security_policy.clone(); self.document_policy_container .content_security_policy_self_url = policy_container.content_security_policy_self_url.clone(); @@ -471,6 +473,11 @@ impl ChildBrowsingContextEntry { &mut self, snapshot: &ChildBrowsingContextSnapshot, ) { + self.document_policy_container + .required_content_security_policy = snapshot + .policy_container + .required_content_security_policy + .clone(); self.document_policy_container .content_security_policy_self_url = snapshot .policy_container @@ -732,7 +739,7 @@ impl ChildBrowsingContextEntry { pub(super) fn commit_current_navigation_entry_seed(&mut self) { self.committed_navigation_entry_seed = self.navigation_entry_seed.clone(); - self.prune_srcdoc_history(); + self.prune_local_history(); } pub(super) fn restore_navigation_entry_seed_from_committed(&mut self) { @@ -858,7 +865,7 @@ impl ChildBrowsingContextEntry { } if same_document_update { self.committed_navigation_entry_seed = entry_seed; - self.prune_srcdoc_history(); + self.prune_local_history(); if !self.pending_attribute_bootstrap_commit() { self.pending_live_navigation_reflects_window_state = false; } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/srcdoc_history.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/local_history.rs similarity index 53% rename from moli-renderer-v8/src/native_bridge/context_host/child_frames/srcdoc_history.rs rename to moli-renderer-v8/src/native_bridge/context_host/child_frames/local_history.rs index 3e6a194692b..4262763daa6 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/srcdoc_history.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/local_history.rs @@ -6,11 +6,12 @@ use crate::document_runtime::DocumentSandboxPolicy; use std::sync::Arc; use url::Url; -/// The resource belongs to a historical Document, not to its owner element's -/// current srcdoc attribute. Same-document entries share the original source, +/// A local-scheme resource belongs to its historical Document. It cannot be +/// reconstructed from a mutable owner attribute or a possibly revoked blob URL. +/// Same-document entries share the original source, /// fallback base URL and policy, while each entry retains its own URL/state. #[derive(Debug)] -pub(super) struct SrcdocHistoryResource { +pub(super) struct LocalHistoryResource { snapshot: ChildBrowsingContextSnapshot, origin: WindowAccessOrigin, } @@ -22,26 +23,35 @@ fn current_entry(seed: &NavigationHistoryEntrySeed) -> Option<&NavigationHistory } impl ChildBrowsingContextEntry { - pub(in crate::native_bridge::context_host) fn srcdoc_history_bootstrap( + pub(in crate::native_bridge::context_host) fn local_history_bootstrap( &self, seed: &NavigationHistoryEntrySeed, ) -> Option { - let resource = self.srcdoc_history.get(¤t_entry(seed)?.document_id)?; - Some(ChildBrowsingContextBootstrap::Srcdoc { - base_url: resource.snapshot.fallback_base_url.clone()?, - markup: resource.snapshot.markup().into_owned(), - }) + let entry = current_entry(seed)?; + let resource = self.local_history.get(&entry.document_id)?; + if resource.snapshot.url.scheme() == "about" && resource.snapshot.url.path() == "srcdoc" { + Some(ChildBrowsingContextBootstrap::Srcdoc { + base_url: resource.snapshot.fallback_base_url.clone()?, + markup: resource.snapshot.markup().into_owned(), + }) + } else { + Some(ChildBrowsingContextBootstrap::Url( + Url::parse(&entry.url).ok()?, + )) + } } - pub(in crate::native_bridge::context_host) fn pending_srcdoc_history_snapshot( + pub(in crate::native_bridge::context_host) fn pending_local_history_snapshot( &self, + bootstrap: &ChildBrowsingContextBootstrap, ) -> Option { + let target = + super::super::JsContextHost::child_browsing_context_navigation_entry_url(bootstrap)?; + if !is_local_history_url(&target) { + return None; + } let entry = current_entry(&self.navigation_entry_seed)?; - let mut snapshot = self - .srcdoc_history - .get(&entry.document_id)? - .snapshot - .clone(); + let mut snapshot = self.local_history.get(&entry.document_id)?.snapshot.clone(); snapshot.url = Url::parse(&entry.url).ok()?; // The iframe's current sandbox attribute is applied at commit. Only // CSP restrictions belong to the historical policy container; keeping @@ -54,45 +64,39 @@ impl ChildBrowsingContextEntry { Some(snapshot) } - pub(in crate::native_bridge::context_host) fn current_srcdoc_history_origin( + pub(in crate::native_bridge::context_host) fn current_local_history_origin( &self, ) -> Option<&WindowAccessOrigin> { - if !matches!( - self.live_bootstrap, - ChildBrowsingContextBootstrap::Srcdoc { .. } - ) { + if !self.live_bootstrap.security_origin_inherited() { return None; } let entry = current_entry(&self.committed_navigation_entry_seed)?; - Some(&self.srcdoc_history.get(&entry.document_id)?.origin) + Some(&self.local_history.get(&entry.document_id)?.origin) } - pub(in crate::native_bridge::context_host) fn remember_srcdoc_history_resource( + pub(in crate::native_bridge::context_host) fn remember_local_history_resource( &mut self, snapshot: &ChildBrowsingContextSnapshot, origin: WindowAccessOrigin, ) { - if !matches!( - self.live_bootstrap, - ChildBrowsingContextBootstrap::Srcdoc { .. } - ) { + if !is_local_history_url(&snapshot.url) { return; } let Some(entry) = current_entry(&self.committed_navigation_entry_seed) else { return; }; - self.srcdoc_history + self.local_history .entry(entry.document_id.clone()) .or_insert_with(|| { - Arc::new(SrcdocHistoryResource { + Arc::new(LocalHistoryResource { snapshot: snapshot.clone(), origin, }) }); } - pub(super) fn prune_srcdoc_history(&mut self) { - self.srcdoc_history.retain(|document_id, _| { + pub(super) fn prune_local_history(&mut self) { + self.local_history.retain(|document_id, _| { self.committed_navigation_entry_seed .entries .iter() @@ -100,3 +104,8 @@ impl ChildBrowsingContextEntry { }); } } + +fn is_local_history_url(url: &Url) -> bool { + matches!(url.scheme(), "blob" | "data") + || (url.scheme() == "about" && matches!(url.path(), "blank" | "srcdoc")) +} diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/nested_history.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/nested_history.rs index e056b3edad6..a529400e2ba 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/nested_history.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/nested_history.rs @@ -49,7 +49,7 @@ enum ChildHistoryKey { #[derive(Clone, Debug)] pub(super) struct ChildHistoryRecord { seed: NavigationHistoryEntrySeed, - resources: HashMap>, + resources: HashMap>, positions: NavigableHistory, } @@ -246,7 +246,7 @@ impl JsContextHost { &record.positions.entries, ); if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { - entry.srcdoc_history = record.resources; + entry.local_history = record.resources; entry.restored_history_positions = Some(record.positions); entry.restoring_history = true; } @@ -311,7 +311,7 @@ impl JsContextHost { } let record = ChildHistoryRecord { seed, - resources: entry.srcdoc_history.clone(), + resources: entry.local_history.clone(), positions, }; store.records.lock().insert(identity, record); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs index bd84fcc0b7a..13a10beb34e 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs @@ -466,7 +466,10 @@ impl JsContextHost { .as_ref() .and_then(|entry| entry.pending_attribute_navigation.clone()) } else { - Some(self.snapshot_child_navigation_target(handle)) + let target_url = + Self::child_browsing_context_bootstrap_url(&attribute_bootstrap) + .unwrap_or_else(|| self.document_url_for_child_context(handle)); + Some(self.snapshot_child_navigation_target(handle, &target_url)) }; let pending_attribute_permissions_policy = pending_attribute_bootstrap_commit.then(|| { @@ -560,6 +563,8 @@ impl JsContextHost { .unwrap_or_default(), content_security_policy_self_url: refresh_policy_source .and_then(|policy| policy.content_security_policy_self_url.clone()), + required_content_security_policy: refresh_policy_source + .and_then(|policy| policy.required_content_security_policy.clone()), permissions_policy: if is_new { // The synchronous initial about:blank Document is // already subject to the iframe's container policy. @@ -638,9 +643,9 @@ impl JsContextHost { navigation_entry_seed, committed_navigation_entry_seed, cached_snapshot, - srcdoc_history: existing + local_history: existing .as_ref() - .map(|entry| entry.srcdoc_history.clone()) + .map(|entry| entry.local_history.clone()) .unwrap_or_default(), document_policy_container, can_navigate_top_without_user_gesture: existing 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 167449d53d1..7077096ff1a 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 @@ -380,6 +380,13 @@ impl JsContextHost { &self, handle: DomHandle, ) -> Option { + if self + .frame_owner_store + .current_child_document_creation_kind(handle) + == Some(crate::frame_owner_model::DocumentCreationKind::Error) + { + return Some("null".to_owned()); + } let url = self.child_browsing_context_current_url(handle)?; self.child_browsing_context_document_origin_for_url(handle, &url) } @@ -393,7 +400,7 @@ impl JsContextHost { if entry.document_sandbox_forces_opaque_origin() { return Some("null".to_owned()); } - if let Some(origin) = entry.current_srcdoc_history_origin() { + if let Some(origin) = entry.current_local_history_origin() { return Some(origin.serialized_origin()); } if entry.security_origin_inherited() { @@ -780,6 +787,13 @@ impl JsContextHost { } pub(crate) fn child_browsing_context_has_opaque_origin(&self, handle: DomHandle) -> bool { + if self + .frame_owner_store + .current_child_document_creation_kind(handle) + == Some(crate::frame_owner_model::DocumentCreationKind::Error) + { + return true; + } if self .child_browsing_contexts .get(&handle) diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/target_snapshot.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/target_snapshot.rs index d72b5d43639..374cb657efc 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/target_snapshot.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/target_snapshot.rs @@ -1,14 +1,35 @@ use super::super::JsContextHost; -use crate::{content_security_policy::IframeCspAttribute, document_runtime::DomHandle}; +use crate::{ + content_security_policy::IframeCspAttribute, + document_runtime::{DocumentPolicyContainer, DomHandle}, +}; +use url::Url; /// Policy inputs belong to the navigation admission, not to the later fetch /// task or a subsequent refresh of the owner element's live attributes. #[derive(Clone, Debug, Default)] pub(in crate::native_bridge::context_host) struct ChildNavigationTargetSnapshot { required_csp: Option, + embedding_origin: Option, } impl ChildNavigationTargetSnapshot { + pub(in crate::native_bridge::context_host) fn apply_response_policy( + &self, + policy: &mut DocumentPolicyContainer, + final_url: &Url, + headers: &[(String, Vec)], + ) -> bool { + self.required_csp.as_ref().is_none_or(|required| { + policy.apply_required_content_security_policy( + required, + self.embedding_origin.as_deref().unwrap_or("null"), + final_url, + headers, + ) + }) + } + pub(in crate::native_bridge::context_host) fn configure_request( &self, mut request: moli_fetch::Request, @@ -30,7 +51,21 @@ impl JsContextHost { pub(in crate::native_bridge::context_host) fn snapshot_child_navigation_target( &self, handle: DomHandle, + target_url: &Url, ) -> ChildNavigationTargetSnapshot { + let owner = self.owner_dispatch_scope_for_node(handle); + let embedding_origin = owner + .and_then(|owner| self.window_access_origin_for_dispatch_scope(owner)) + .map(|origin| origin.serialized_origin()); + if self.bypass_content_security_policy() { + return ChildNavigationTargetSnapshot { + embedding_origin, + ..Default::default() + }; + } + let inherited = owner + .and_then(|owner| self.document_policy_container_for_inheritance(owner)) + .and_then(|policy| policy.required_content_security_policy); let required_csp = if self.dom_host().is_html_element_named(handle, "iframe") { self.dom_host() .get_attribute(handle, "csp") @@ -39,7 +74,17 @@ impl JsContextHost { } else { None }; - ChildNavigationTargetSnapshot { required_csp } + let required_csp = required_csp + .filter(|policy| { + inherited + .as_ref() + .is_none_or(|parent| parent.subsumes(&[policy.as_str().into()], target_url)) + }) + .or(inherited); + ChildNavigationTargetSnapshot { + required_csp, + embedding_origin, + } } } @@ -64,6 +109,7 @@ mod tests { ]); let snapshot = ChildNavigationTargetSnapshot { required_csp: policy, + ..Default::default() }; let request = snapshot.configure_request(request); let mut expected = vec![ diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index ff234a66f92..96a7ed79df1 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -2995,7 +2995,8 @@ impl JsContextHost { }, ); let local_outcome = match local_preparation { - LocalChildDocumentPreparation::Ready(snapshot) => { + LocalChildDocumentPreparation::Ready(snapshot) + | LocalChildDocumentPreparation::Historical(snapshot) => { let snapshot = *snapshot; let mut policy_container = snapshot.policy_container.clone(); if policy_container diff --git a/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs b/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs index 749be85148f..b2e7e2a94fd 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs @@ -1288,6 +1288,14 @@ impl JsContextHost { &mut self, handle: crate::document_runtime::DomHandle, ) -> Option { + if self + .frame_owner_store + .current_child_document_creation_kind(handle) + == Some(crate::frame_owner_model::DocumentCreationKind::Error) + { + self.unregister_service_worker_child_client(handle); + return None; + } let document_url = self.child_browsing_context_current_url(handle)?; let storage_key = service_worker_first_party_storage_key(&document_url); let document_owner = self @@ -1369,6 +1377,14 @@ impl JsContextHost { &mut self, handle: crate::document_runtime::DomHandle, ) { + if self + .frame_owner_store + .current_child_document_creation_kind(handle) + == Some(crate::frame_owner_model::DocumentCreationKind::Error) + { + self.unregister_service_worker_child_client(handle); + return; + } let old_client_id = { let Some(entry) = self.child_browsing_contexts.get_mut(&handle) else { return; diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs index 6ea36af1fae..c86a9c0862d 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs @@ -1056,7 +1056,7 @@ impl JsContextHost { return WindowAccessOrigin::from_serialized_origin(serialized_origin, document_domain); } if entry.security_origin_inherited() && !entry.document_sandbox_forces_opaque_origin() { - if let Some(origin) = entry.current_srcdoc_history_origin() { + if let Some(origin) = entry.current_local_history_origin() { return Some(origin.clone()); } if let Some(popup_id) = self.child_browsing_context_popup_owner_id(handle) { diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/child_document_completion.rs b/moli-renderer-v8/src/runtime/page_vm/tests/child_document_completion.rs index f8386130cd3..606386c4245 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/child_document_completion.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/child_document_completion.rs @@ -399,6 +399,93 @@ async fn child_document_response_frame_ancestors_gates_commit() { .expect("frame-ancestors response gate test should run"); } +#[tokio::test(flavor = "current_thread")] +async fn required_csp_rejection_commits_an_opaque_document_without_rewriting_network_facts() { + run_page_vm_async_test(async move { + for (status, status_line) in [ + (200, "HTTP/1.1 200 OK\r\nTiming-Allow-Origin: *"), + (204, "HTTP/1.1 204 No Content\r\nTiming-Allow-Origin: *"), + (205, "HTTP/1.1 205 Reset Content\r\nTiming-Allow-Origin: *"), + ] { + let body = ""; + let (base_url, server) = spawn_path_response_http_server(vec![ + ("/reject", status_line, body.to_owned(), Duration::ZERO), + ("/accepted", "HTTP/1.1 200 OK", "

accepted

".to_owned(), Duration::ZERO), + ]).await; + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let (mut page_vm, mut queue, mut wake_rx) = owner_attached_page_vm( + &loader, Url::parse(&format!("{base_url}/page.html"))?, + ); + let rejected_url = format!("{base_url}/reject"); + page_vm.vm_mut().eval(&format!(r#" + globalThis.__rejectedBodyRan = false; + globalThis.__blockedLoads = 0; + globalThis.__policyFrame = document.createElement('iframe'); + __policyFrame.id = 'required-policy-frame'; + __policyFrame.csp = "default-src 'none'"; + __policyFrame.onload = () => {{ __blockedLoads++; }}; + __policyFrame.src = {rejected_url:?}; + document.body.appendChild(__policyFrame); + globalThis.__policyProxy = __policyFrame.contentWindow; + "#))?; + run_expected_child_frame_task_source_after_realm_prerequisite_for_wait( + &mut page_vm, ChildFrameSemanticTurnKind::NavigationCommit, "required policy rejection start", + ).await; + wait_for_page_resource_completion(&mut queue, &mut wake_rx, "required policy response").await; + page_vm.apply_one_page_resource_terminal_owner_admission_for_test(&mut queue)? + .expect("the blocked response must still apply to its current owner"); + run_child_interactive_domcontentloaded_then_host_load_for_wait(&mut page_vm, "blocked error Document load").await; + assert_eq!(page_vm.vm_mut().eval(r#"(() => { + if (__policyFrame.contentDocument !== null || __policyFrame.contentWindow !== __policyProxy || __rejectedBodyRan || __blockedLoads !== 1) return false; + try { void __policyProxy.location.href; } catch (e) { return e.name === 'SecurityError'; } + return false; + })()"#)?, "true", "an inert opaque error Document must replace the child while retaining WindowProxy identity and dispatching load"); + assert!(page_vm.take_completed_child_document_networks().is_empty(), + "the committed error Document carries its response in the navigation projection, not the historical-only network queue"); + let navigations = page_vm.take_completed_child_frame_navigation_loads(); + assert_eq!(navigations.len(), 1); + assert!(navigations[0].security_origin_opaque); + let network = navigations[0].document_network.as_ref().expect("blocked navigation must retain its real response"); + assert_eq!(network.status, status); + assert_eq!(network.request_url, rejected_url); + assert!(network.resource_timing_allowed && network.resource_timing_body_visible); + assert!(network.resource_timing_response.is_some()); + let expected_body = if status == 200 { body.as_bytes() } else { b"" }; + assert_eq!(network.response_body.as_ref().unwrap().try_bytes()?.as_ref(), expected_body); + let entries: serde_json::Value = serde_json::from_str(&page_vm.vm_mut().eval( + &format!("JSON.stringify(performance.getEntriesByName({rejected_url:?}, 'resource').map(e => e.toJSON()))"), + )?)?; + let entries = entries.as_array().unwrap(); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + for name in ["responseStatus", "requestStart", "responseStart", "transferSize", "encodedBodySize", "decodedBodySize"] { + assert_eq!(entry[name], 0, "blocked Document {name} must be hidden even with same-origin/TAO permission"); + } + assert_eq!(entry["nextHopProtocol"], ""); + assert!(entry["responseEnd"].as_f64().unwrap() >= entry["fetchStart"].as_f64().unwrap()); + let accepted_url = format!("{base_url}/accepted"); + page_vm.vm_mut().eval(&format!("__policyFrame.removeAttribute('csp'); __policyFrame.src = {accepted_url:?};"))?; + let retired_navigation = page_vm.run_child_navigation_commit_body_for_test()? + .expect("the superseded navigation retains its exact stale-discard turn"); + assert!(matches!(retired_navigation.action.target_effect, + crate::page_task_queue::PageChildNavigationCommitTargetEffect::DiscardedStaleOwner { current_owner: Some(_) })); + let replacement_navigation = page_vm.run_child_navigation_commit_body_for_test()? + .expect("the replacement navigation retains its own current-owner turn"); + assert!(matches!(replacement_navigation.action.target_effect, + crate::page_task_queue::PageChildNavigationCommitTargetEffect::AppliedToCurrentOwner)); + let handle = page_vm.vm().element_handle_by_id_for_test("required-policy-frame").unwrap(); + assert!(page_vm.vm().current_child_document_navigation_fetch_target(handle).is_some(), + "navigation from HTTP {status} error Document must start a real request"); + wait_for_page_resource_completion(&mut queue, &mut wake_rx, &format!("response after HTTP {status} error Document")).await; + page_vm.apply_one_page_resource_terminal_owner_admission_for_test(&mut queue)?.expect("replacement response"); + run_child_interactive_domcontentloaded_then_host_load_for_wait(&mut page_vm, "accepted replacement Document load").await; + assert_eq!(page_vm.vm_mut().eval("String(__policyFrame.contentWindow === __policyProxy && __policyProxy.document.getElementById('accepted').textContent === 'accepted' && __blockedLoads === 2)")?, "true", "a later accepted navigation must restore its own tuple origin, not inherit the error Document's opaque origin"); + server.await.expect("policy response server should finish"); + } + Ok::<_, anyhow::Error>(()) + }).await.expect("required CSP blocked Document lifecycle test should run"); +} + #[tokio::test(flavor = "current_thread")] async fn failed_child_document_fetch_is_applied_only_to_its_exact_current_request() { run_page_vm_async_test(async move { diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs index fa8e504d856..8e22784f8b5 100644 --- a/moli-renderer-v8/src/types.rs +++ b/moli-renderer-v8/src/types.rs @@ -1717,11 +1717,49 @@ pub(super) struct LoadedChildDocument { #[derive(Debug)] pub(super) enum ChildDocumentLoadOutcome { Loaded(Box), + /// Preserve the physical response, but commit only an inert error Document. + BlockedResponse(Box), /// The response completed without replacing the active Document. Its /// network facts still belong to the original navigation request. IgnoredNavigation(Box), } +impl ChildDocumentLoadOutcome { + pub(super) fn blocked_response( + final_url: Url, + document_network: Option, + required_content_security_policy: Option< + crate::content_security_policy::IframeCspAttribute, + >, + ) -> Self { + Self::BlockedResponse(Box::new(LoadedChildDocument { + final_url, + policy_container: DocumentPolicyContainer { + required_content_security_policy, + ..Default::default() + }, + content_type: Some("text/html".to_owned()), + character_set: "UTF-8".to_owned(), + content: "" + .to_owned() + .into(), + response_links: Default::default(), + document_network, + })) + } + + pub(super) fn from_prepared_document( + document: LoadedChildDocument, + creation_kind: crate::frame_owner_model::DocumentCreationKind, + ) -> Self { + if creation_kind == crate::frame_owner_model::DocumentCreationKind::Error { + Self::BlockedResponse(Box::new(document)) + } else { + Self::Loaded(Box::new(document)) + } + } +} + /// Immutable frame/protocol attribution captured before a child-document /// navigation fetch starts. /// @@ -1798,7 +1836,10 @@ impl ChildDocumentLoadCompletion { &self, ) -> Option<&crate::protocol_types::ChildFrameDocumentNetworkSnapshot> { match &self.result { - Ok(ChildDocumentLoadOutcome::Loaded(loaded)) => loaded.document_network.as_ref(), + Ok( + ChildDocumentLoadOutcome::Loaded(loaded) + | ChildDocumentLoadOutcome::BlockedResponse(loaded), + ) => loaded.document_network.as_ref(), Ok(ChildDocumentLoadOutcome::IgnoredNavigation(network)) => Some(network), Err(_) => None, }