Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(csp): extract shared policy engine into moli-csp

ldm0f660ee584f15
diff --git a/Cargo.lock b/Cargo.lock
index 66543cebf..d461cd6dd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -743,6 +743,21 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+[[package]]
+name = "content-security-policy"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd26eb56761db2c5288e97cfb8593fb411d3a7907ced6b6679512207ea8759c"
+dependencies = [
+ "base64 0.22.1",
+ "bitflags",
+ "once_cell",
+ "percent-encoding 2.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "regex",
+ "sha2 0.10.9",
+ "url",
+]
+
[[package]]
name = "content_disposition"
version = "0.4.0"
@@ -2462,7 +2477,7 @@ dependencies = [
"nom 8.0.0",
"rand 0.10.3",
"rangemap",
- "sha2",
+ "sha2 0.11.0",
"stringprep",
"thiserror",
"weezl 0.2.1",
@@ -2780,6 +2795,20 @@ dependencies = [
"openssl",
]
+[[package]]
+name = "moli-csp"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "content-security-policy",
+ "moli-crypto",
+ "moli-header-field",
+ "percent-encoding 2.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde_json",
+ "strum",
+ "url",
+]
+
[[package]]
name = "moli-css-parse"
version = "0.1.0"
@@ -3323,6 +3352,7 @@ dependencies = [
"moli-canvas",
"moli-cookie-jar",
"moli-crypto",
+ "moli-csp",
"moli-css-parse",
"moli-disk-pool",
"moli-dom",
@@ -5145,6 +5175,17 @@ dependencies = [
"digest 0.10.7",
]
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
[[package]]
name = "sha2"
version = "0.11.0"
diff --git a/Cargo.toml b/Cargo.toml
index 868b5fd55..645717335 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,6 +15,7 @@ members = [
"moli-cookie-store",
"moli-content-type",
"moli-css-parse",
+ "moli-csp",
"moli-crypto",
"moli-curl",
"moli-dns-resolver",
diff --git a/moli-csp/Cargo.toml b/moli-csp/Cargo.toml
new file mode 100644
index 000000000..3e1c00cc5
--- /dev/null
+++ b/moli-csp/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+license.workspace = true
+name = "moli-csp"
+version = "0.1.0"
+edition = "2024"
+description = "Content Security Policy parsing, enforcement, and reporting for Moli"
+
+[dependencies]
+base64 = "0.22"
+content-security-policy = "0.9.0"
+moli-crypto = { path = "../moli-crypto" }
+moli-header-field = { path = "../moli-header-field" }
+percent-encoding = "2.3"
+serde_json = "1.0.145"
+strum = { version = "0.28.0", features = ["derive"] }
+url = "2.5.7"
+
+[lints]
+workspace = true
diff --git a/moli-csp/src/checks.rs b/moli-csp/src/checks.rs
new file mode 100644
index 000000000..72539dbb0
--- /dev/null
+++ b/moli-csp/src/checks.rs
@@ -0,0 +1,1464 @@
+use crate::integrity::integrity_metadata_hashes;
+use crate::policy::{ContentSecurityPolicy, directive_source_list};
+use crate::reporting::{
+ content_security_policy_report_to_endpoints, content_security_policy_report_uri_endpoints,
+ csp_url_for_report,
+};
+use crate::types::*;
+use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
+use moli_crypto::DigestAlgorithm;
+use percent_encoding::percent_decode_str;
+use url::Url;
+
+const CONNECT_SRC: &str = "connect-src";
+const CHILD_SRC: &str = "child-src";
+const DEFAULT_SRC: &str = "default-src";
+const FRAME_ANCESTORS: &str = "frame-ancestors";
+const FRAME_SRC: &str = "frame-src";
+const IMG_SRC: &str = "img-src";
+const MANIFEST_SRC: &str = "manifest-src";
+const MEDIA_SRC: &str = "media-src";
+const SCRIPT_SRC_ATTR: &str = "script-src-attr";
+const SCRIPT_SRC_ELEM: &str = "script-src-elem";
+const SCRIPT_SRC: &str = "script-src";
+const STYLE_SRC_ATTR: &str = "style-src-attr";
+const STYLE_SRC_ELEM: &str = "style-src-elem";
+const STYLE_SRC: &str = "style-src";
+const WORKER_SRC: &str = "worker-src";
+const REQUIRE_TRUSTED_TYPES_FOR: &str = "require-trusted-types-for";
+const TRUSTED_TYPES: &str = "trusted-types";
+const SANDBOX: &str = "sandbox";
+
+pub fn content_security_policy_requires_trusted_types_for_script(
+ policies: &[ContentSecurityPolicy],
+) -> bool {
+ policies
+ .iter()
+ .any(policy_requires_trusted_types_for_script)
+}
+
+pub fn content_security_policy_allows_trusted_types_eval(
+ policies: &[ContentSecurityPolicy],
+) -> bool {
+ // Like Blink's ContentSecurityPolicy::AllowTrustedTypesEval, this only
+ // activates the document-global Trusted Types relaxation. It is not the
+ // final CSP decision: CSP3 EnsureCSPDoesNotBlockStringCompilation still
+ // evaluates every policy through the TrustedTypesEval non-URL gate.
+ policies
+ .iter()
+ .any(policy_requires_trusted_types_for_script)
+ && policies.iter().any(policy_allows_trusted_types_eval)
+}
+
+pub fn content_security_policy_allows_trusted_type_policy_name(
+ policies: &[ContentSecurityPolicy],
+ policy_name: &str,
+) -> bool {
+ policies
+ .iter()
+ .all(|policy| policy_allows_trusted_type_policy_name(policy, policy_name))
+}
+
+pub fn content_security_policy_sandboxes_document_domain(
+ policies: &[ContentSecurityPolicy],
+) -> bool {
+ policies.iter().any(policy_sandboxes_document_domain)
+}
+
+pub fn content_security_policy_forces_opaque_origin(policies: &[ContentSecurityPolicy]) -> bool {
+ policies.iter().any(policy_forces_opaque_origin)
+}
+
+pub fn content_security_policy_sandbox_allows_scripts(policies: &[ContentSecurityPolicy]) -> bool {
+ policies
+ .iter()
+ .all(|policy| policy_sandbox_allows_scripts(policy).unwrap_or(true))
+}
+
+pub fn content_security_policy_sandbox_allows_modals(policies: &[ContentSecurityPolicy]) -> bool {
+ policies
+ .iter()
+ .all(|policy| policy_sandbox_allows_modals(policy).unwrap_or(true))
+}
+
+pub fn content_security_policy_sandbox_allows_top_navigation(
+ policies: &[ContentSecurityPolicy],
+) -> bool {
+ policies.iter().all(|policy| {
+ directive_source_list(policy, SANDBOX).is_none_or(|sources| {
+ sources
+ .iter()
+ .any(|token| token.eq_ignore_ascii_case("allow-top-navigation"))
+ })
+ })
+}
+
+pub fn content_security_policy_sandbox_allows_popups_to_escape(
+ policies: &[ContentSecurityPolicy],
+) -> bool {
+ let mut has_sandbox = false;
+ for policy in policies {
+ let Some(allows) = policy_sandbox_allows_popups_to_escape(policy) else {
+ continue;
+ };
+ has_sandbox = true;
+ if !allows {
+ return false;
+ }
+ }
+ has_sandbox
+}
+
+pub fn ensure_content_security_policy_allows_url(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ error: impl FnOnce() -> String,
+) -> Result<(), String> {
+ ensure_content_security_policy_allows_url_with_redirect_status(
+ policies,
+ protected_url,
+ request_url,
+ kind,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ error,
+ )
+}
+
+pub fn ensure_content_security_policy_allows_url_with_redirect_status(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ error: impl FnOnce() -> String,
+) -> Result<(), String> {
+ if content_security_policy_allows_url_with_redirect_status(
+ policies,
+ protected_url,
+ request_url,
+ kind,
+ redirect_status,
+ ) {
+ Ok(())
+ } else {
+ Err(error())
+ }
+}
+
+#[cfg(test)]
+fn content_security_policy_allows_url(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+) -> bool {
+ content_security_policy_allows_url_with_redirect_status(
+ policies,
+ protected_url,
+ request_url,
+ kind,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+}
+
+pub fn content_security_policy_allows_url_with_redirect_status(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+) -> bool {
+ policies.iter().all(|policy| {
+ let Some((_, source_list)) = effective_source_list_with_directive(policy, kind) else {
+ return true;
+ };
+ source_list_allows(source_list, protected_url, request_url, redirect_status)
+ })
+}
+
+#[cfg(test)]
+fn content_security_policy_url_violation_with_redirect_status(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_url_violation_with_redirect_status_and_disposition(
+ policies,
+ protected_url,
+ request_url,
+ kind,
+ redirect_status,
+ ContentSecurityPolicyDisposition::Enforce,
+ )
+}
+
+#[cfg(test)]
+fn content_security_policy_url_violation_with_redirect_status_and_disposition(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ disposition: ContentSecurityPolicyDisposition,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ policies,
+ protected_url,
+ request_url,
+ kind,
+ redirect_status,
+ disposition,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+}
+
+pub fn content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints(
+ policies,
+ protected_url,
+ request_url,
+ request_url,
+ kind,
+ redirect_status,
+ disposition,
+ reporting_endpoints,
+ )
+}
+
+pub fn content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ ancestor_origins: &[Option<Url>],
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ policies.iter().find_map(|policy| {
+ let source_list = normalized_source_list(directive_source_list(policy, FRAME_ANCESTORS)?);
+ if ancestor_origins.iter().all(|ancestor_origin| {
+ ancestor_origin.as_ref().is_some_and(|ancestor_origin| {
+ frame_ancestor_source_list_allows(&source_list, protected_url, ancestor_origin)
+ })
+ }) {
+ return None;
+ }
+ let document_uri = csp_url_for_report(protected_url);
+ Some(ContentSecurityPolicyUrlViolation {
+ effective_directive: FRAME_ANCESTORS,
+ blocked_uri: document_uri.clone(),
+ source_file: document_uri.clone(),
+ document_uri,
+ original_policy: policy.as_str().to_owned(),
+ disposition,
+ report_uri_endpoints: content_security_policy_report_uri_endpoints(
+ policy,
+ protected_url,
+ ),
+ report_to_endpoints: content_security_policy_report_to_endpoints(
+ policy,
+ reporting_endpoints,
+ ),
+ sample: String::new(),
+ line_number: 0,
+ column_number: 0,
+ })
+ })
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+ request: ContentSecurityPolicyScriptElementRequest<'_>,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
+ policies,
+ protected_url,
+ request_url,
+ request_url,
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ redirect_status,
+ disposition,
+ reporting_endpoints,
+ ContentSecurityPolicyUrlRequest::Script(request),
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn content_security_policy_style_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+ request: ContentSecurityPolicyStyleElementRequest<'_>,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
+ policies,
+ protected_url,
+ request_url,
+ request_url,
+ ContentSecurityPolicyResourceKind::DocumentStyleElement,
+ redirect_status,
+ disposition,
+ reporting_endpoints,
+ ContentSecurityPolicyUrlRequest::Style(request),
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ checked_url: &Url,
+ blocked_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
+ policies,
+ protected_url,
+ checked_url,
+ blocked_url,
+ kind,
+ redirect_status,
+ disposition,
+ reporting_endpoints,
+ ContentSecurityPolicyUrlRequest::Standard,
+ )
+}
+
+#[derive(Clone, Copy)]
+enum ContentSecurityPolicyUrlRequest<'a> {
+ Standard,
+ Script(ContentSecurityPolicyScriptElementRequest<'a>),
+ Style(ContentSecurityPolicyStyleElementRequest<'a>),
+}
+
+#[allow(clippy::too_many_arguments)]
+fn content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ checked_url: &Url,
+ blocked_url: &Url,
+ kind: ContentSecurityPolicyResourceKind,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+ request: ContentSecurityPolicyUrlRequest<'_>,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ policies.iter().find_map(|policy| {
+ let (effective_directive, source_list) =
+ effective_source_list_with_directive(policy, kind)?;
+ if source_list_allows_resource_request(
+ source_list,
+ protected_url,
+ checked_url,
+ redirect_status,
+ request,
+ ) {
+ return None;
+ }
+ let document_uri = csp_url_for_report(protected_url);
+ Some(ContentSecurityPolicyUrlViolation {
+ effective_directive,
+ blocked_uri: csp_url_for_report(blocked_url),
+ source_file: document_uri.clone(),
+ document_uri,
+ original_policy: policy.as_str().to_owned(),
+ disposition,
+ report_uri_endpoints: content_security_policy_report_uri_endpoints(
+ policy,
+ protected_url,
+ ),
+ report_to_endpoints: content_security_policy_report_to_endpoints(
+ policy,
+ reporting_endpoints,
+ ),
+ sample: String::new(),
+ line_number: 0,
+ column_number: 0,
+ })
+ })
+}
+
+pub fn content_security_policy_trusted_types_sink_violation_with_disposition_and_reporting_endpoints(
+ policies: &[ContentSecurityPolicy],
+ protected_url: &Url,
+ sink: &str,
+ sample: &str,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ policies.iter().find_map(|policy| {
+ if !policy_requires_trusted_types_for_script(policy) {
+ return None;
+ }
+ let document_uri = protected_url.to_string();
+ Some(ContentSecurityPolicyUrlViolation {
+ effective_directive: REQUIRE_TRUSTED_TYPES_FOR,
+ blocked_uri: "trusted-types-sink".to_owned(),
+ source_file: document_uri.clone(),
+ document_uri,
+ original_policy: policy.as_str().to_owned(),
+ disposition,
+ report_uri_endpoints: content_security_policy_report_uri_endpoints(
+ policy,
+ protected_url,
+ ),
+ report_to_endpoints: content_security_policy_report_to_endpoints(
+ policy,
+ reporting_endpoints,
+ ),
+ sample: trusted_types_sink_violation_sample(sink, sample),
+ line_number: 0,
+ column_number: 0,
+ })
+ })
+}
+
+pub fn content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ policy: &ContentSecurityPolicy,
+ protected_url: &Url,
+ kind: ContentSecurityPolicyNonUrlKind,
+ source: &str,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ debug_assert!(matches!(
+ kind,
+ ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler
+ | ContentSecurityPolicyNonUrlKind::DocumentInlineNavigation
+ | ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute
+ ));
+ content_security_policy_non_url_violation_with_source(
+ policy,
+ protected_url,
+ kind,
+ Some(source),
+ disposition,
+ reporting_endpoints,
+ )
+}
+
+pub fn content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
+ policy: &ContentSecurityPolicy,
+ protected_url: &Url,
+ source: &str,
+ request: ContentSecurityPolicyScriptElementRequest<'_>,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ let kind = ContentSecurityPolicyNonUrlKind::DocumentInlineScript;
+ let (effective_directive, source_list) =
+ kind.directive_fallbacks().iter().find_map(|directive| {
+ directive_source_list(policy, directive)
+ .map(|sources| (kind.effective_directive(), sources))
+ })?;
+ if inline_script_element_source_list_allows(source_list.clone(), source, request) {
+ return None;
+ }
+ let document_uri = protected_url.to_string();
+ Some(ContentSecurityPolicyUrlViolation {
+ effective_directive,
+ blocked_uri: kind.blocked_uri().to_owned(),
+ source_file: document_uri.clone(),
+ document_uri,
+ original_policy: policy.as_str().to_owned(),
+ disposition,
+ report_uri_endpoints: content_security_policy_report_uri_endpoints(policy, protected_url),
+ report_to_endpoints: content_security_policy_report_to_endpoints(
+ policy,
+ reporting_endpoints,
+ ),
+ sample: inline_source_violation_sample(&source_list, source),
+ line_number: 0,
+ column_number: 0,
+ })
+}
+
+pub fn content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
+ policy: &ContentSecurityPolicy,
+ protected_url: &Url,
+ source: &str,
+ request: ContentSecurityPolicyStyleElementRequest<'_>,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ let kind = ContentSecurityPolicyNonUrlKind::DocumentInlineStyleElement;
+ let (effective_directive, source_list) =
+ kind.directive_fallbacks().iter().find_map(|directive| {
+ directive_source_list(policy, directive)
+ .map(|sources| (kind.effective_directive(), sources))
+ })?;
+ if inline_style_element_source_list_allows(source_list.clone(), source, request) {
+ return None;
+ }
+ let document_uri = protected_url.to_string();
+ Some(ContentSecurityPolicyUrlViolation {
+ effective_directive,
+ blocked_uri: kind.blocked_uri().to_owned(),
+ source_file: document_uri.clone(),
+ document_uri,
+ original_policy: policy.as_str().to_owned(),
+ disposition,
+ report_uri_endpoints: content_security_policy_report_uri_endpoints(policy, protected_url),
+ report_to_endpoints: content_security_policy_report_to_endpoints(
+ policy,
+ reporting_endpoints,
+ ),
+ sample: inline_source_violation_sample(&source_list, source),
+ line_number: 0,
+ column_number: 0,
+ })
+}
+
+pub fn content_security_policy_non_url_violation_with_source(
+ policy: &ContentSecurityPolicy,
+ protected_url: &Url,
+ kind: ContentSecurityPolicyNonUrlKind,
+ source: Option<&str>,
+ disposition: ContentSecurityPolicyDisposition,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ let (effective_directive, source_list) =
+ kind.directive_fallbacks().iter().find_map(|directive| {
+ directive_source_list(policy, directive)
+ .map(|sources| (kind.effective_directive(), sources))
+ })?;
+ if kind.source_list_allows(&source_list, source) {
+ return None;
+ }
+ let document_uri = protected_url.to_string();
+ Some(ContentSecurityPolicyUrlViolation {
+ effective_directive,
+ blocked_uri: kind.blocked_uri().to_owned(),
+ source_file: document_uri.clone(),
+ document_uri,
+ original_policy: policy.as_str().to_owned(),
+ disposition,
+ report_uri_endpoints: content_security_policy_report_uri_endpoints(policy, protected_url),
+ report_to_endpoints: content_security_policy_report_to_endpoints(
+ policy,
+ reporting_endpoints,
+ ),
+ sample: source
+ .map(|source| inline_source_violation_sample(&source_list, source))
+ .unwrap_or_default(),
+ line_number: 0,
+ column_number: 0,
+ })
+}
+
+fn policy_requires_trusted_types_for_script(policy: &ContentSecurityPolicy) -> bool {
+ directive_source_list(policy, REQUIRE_TRUSTED_TYPES_FOR).is_some_and(|sources| {
+ sources
+ .iter()
+ .any(|source| csp_keyword_eq(source, "script"))
+ })
+}
+
+fn policy_allows_trusted_types_eval(policy: &ContentSecurityPolicy) -> bool {
+ [SCRIPT_SRC, DEFAULT_SRC]
+ .into_iter()
+ .find_map(|directive| directive_source_list(policy, directive))
+ .is_some_and(|sources| {
+ sources
+ .iter()
+ .any(|source| csp_keyword_eq(source, "trusted-types-eval"))
+ })
+}
+
+fn policy_allows_trusted_type_policy_name(
+ policy: &ContentSecurityPolicy,
+ policy_name: &str,
+) -> bool {
+ let Some(sources) = directive_source_list(policy, TRUSTED_TYPES) else {
+ return true;
+ };
+ sources.iter().any(|source| {
+ let source = *source;
+ source == "*"
+ || (!source.is_empty()
+ && source == policy_name
+ && source.bytes().all(|byte| {
+ byte.is_ascii_alphanumeric()
+ || matches!(byte, b'-' | b'#' | b'=' | b'_' | b'/' | b'@' | b'.' | b'%')
+ }))
+ })
+}
+
+fn policy_sandboxes_document_domain(policy: &ContentSecurityPolicy) -> bool {
+ directive_source_list(policy, SANDBOX).is_some()
+}
+
+fn policy_forces_opaque_origin(policy: &ContentSecurityPolicy) -> bool {
+ directive_source_list(policy, SANDBOX)
+ .is_some_and(|sources| !sandbox_sources_allow_same_origin(&sources))
+}
+
+fn policy_sandbox_allows_scripts(policy: &ContentSecurityPolicy) -> Option<bool> {
+ directive_source_list(policy, SANDBOX).map(|sources| sandbox_sources_allow_scripts(&sources))
+}
+
+fn policy_sandbox_allows_modals(policy: &ContentSecurityPolicy) -> Option<bool> {
+ directive_source_list(policy, SANDBOX).map(|sources| sandbox_sources_allow_modals(&sources))
+}
+
+fn policy_sandbox_allows_popups_to_escape(policy: &ContentSecurityPolicy) -> Option<bool> {
+ directive_source_list(policy, SANDBOX)
+ .map(|sources| sandbox_sources_allow_popups_to_escape(&sources))
+}
+
+fn sandbox_sources_allow_same_origin(sources: &[&str]) -> bool {
+ sources
+ .iter()
+ .any(|token| token.eq_ignore_ascii_case("allow-same-origin"))
+}
+
+fn sandbox_sources_allow_scripts(sources: &[&str]) -> bool {
+ sources
+ .iter()
+ .any(|token| token.eq_ignore_ascii_case("allow-scripts"))
+}
+
+fn sandbox_sources_allow_modals(sources: &[&str]) -> bool {
+ sources
+ .iter()
+ .any(|token| token.eq_ignore_ascii_case("allow-modals"))
+}
+
+fn sandbox_sources_allow_popups_to_escape(sources: &[&str]) -> bool {
+ sources
+ .iter()
+ .any(|token| token.eq_ignore_ascii_case("allow-popups-to-escape-sandbox"))
+}
+
+fn trusted_types_sink_violation_sample(sink: &str, sample: &str) -> String {
+ let clipped = sample.chars().take(40).collect::<String>();
+ format!("{sink}|{clipped}")
+}
+
+fn effective_source_list_with_directive(
+ policy: &ContentSecurityPolicy,
+ kind: ContentSecurityPolicyResourceKind,
+) -> Option<(&'static str, Vec<&str>)> {
+ kind.directive_fallbacks().iter().find_map(|directive| {
+ directive_source_list(policy, directive)
+ .map(|sources| (kind.effective_directive(), sources))
+ })
+}
+
+fn source_list_allows(
+ sources: Vec<&str>,
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+) -> bool {
+ let sources = normalized_source_list(sources);
+ normalized_source_list_allows_url(&sources, protected_url, request_url, redirect_status)
+}
+
+fn frame_ancestor_source_list_allows(
+ sources: &[&str],
+ protected_url: &Url,
+ ancestor_origin: &Url,
+) -> bool {
+ if sources.is_empty() || (sources.len() == 1 && csp_keyword_eq(sources[0], "none")) {
+ return false;
+ }
+ sources.iter().any(|source| {
+ !csp_keyword_eq(source, "none")
+ && !source_has_path(source)
+ && source_expression_matches(
+ source,
+ protected_url,
+ ancestor_origin,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+ })
+}
+
+fn source_list_allows_script_element_request(
+ sources: Vec<&str>,
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ request: ContentSecurityPolicyScriptElementRequest<'_>,
+) -> bool {
+ let sources = normalized_source_list(sources);
+ if let Some(nonce) = request
+ .nonce
+ .map(str::trim)
+ .filter(|nonce| !nonce.is_empty())
+ && sources
+ .iter()
+ .any(|source| csp_nonce_source_matches(source, nonce))
+ {
+ return true;
+ }
+ if script_integrity_matches_hash_source(request.integrity, &sources) {
+ return true;
+ }
+ if source_list_activates_strict_dynamic(&sources) {
+ return !request.parser_inserted;
+ }
+ normalized_source_list_allows_url(&sources, protected_url, request_url, redirect_status)
+}
+
+fn source_list_allows_style_element_request(
+ sources: Vec<&str>,
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ request: ContentSecurityPolicyStyleElementRequest<'_>,
+) -> bool {
+ let sources = normalized_source_list(sources);
+ if let Some(nonce) = request
+ .nonce
+ .map(str::trim)
+ .filter(|nonce| !nonce.is_empty())
+ && sources
+ .iter()
+ .any(|source| csp_nonce_source_matches(source, nonce))
+ {
+ return true;
+ }
+ normalized_source_list_allows_url(&sources, protected_url, request_url, redirect_status)
+}
+
+fn source_list_allows_resource_request(
+ sources: Vec<&str>,
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ request: ContentSecurityPolicyUrlRequest<'_>,
+) -> bool {
+ match request {
+ ContentSecurityPolicyUrlRequest::Standard => source_list_allows_script_element_request(
+ sources,
+ protected_url,
+ request_url,
+ redirect_status,
+ ContentSecurityPolicyScriptElementRequest::default(),
+ ),
+ ContentSecurityPolicyUrlRequest::Script(request) => {
+ source_list_allows_script_element_request(
+ sources,
+ protected_url,
+ request_url,
+ redirect_status,
+ request,
+ )
+ }
+ ContentSecurityPolicyUrlRequest::Style(request) => {
+ source_list_allows_style_element_request(
+ sources,
+ protected_url,
+ request_url,
+ redirect_status,
+ request,
+ )
+ }
+ }
+}
+
+fn inline_script_element_source_list_allows(
+ sources: Vec<&str>,
+ source: &str,
+ request: ContentSecurityPolicyScriptElementRequest<'_>,
+) -> bool {
+ let sources = normalized_source_list(sources);
+ if let Some(nonce) = request
+ .nonce
+ .map(str::trim)
+ .filter(|nonce| !nonce.is_empty())
+ && sources
+ .iter()
+ .any(|source| csp_nonce_source_matches(source, nonce))
+ {
+ return true;
+ }
+ if sources
+ .iter()
+ .filter_map(|source| csp_hash_source_value(source))
+ .any(|hash_source| inline_source_matches_hash(source, hash_source))
+ {
+ return true;
+ }
+ let has_strict_dynamic = sources
+ .iter()
+ .any(|source| csp_keyword_eq(source, "strict-dynamic"));
+ if has_strict_dynamic && !request.parser_inserted {
+ return true;
+ }
+ let has_nonce_or_hash = sources.iter().any(|source| {
+ csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
+ });
+ !has_nonce_or_hash
+ && !has_strict_dynamic
+ && sources
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-inline"))
+}
+
+fn inline_style_element_source_list_allows(
+ sources: Vec<&str>,
+ source: &str,
+ request: ContentSecurityPolicyStyleElementRequest<'_>,
+) -> bool {
+ let sources = normalized_source_list(sources);
+ if let Some(nonce) = request
+ .nonce
+ .map(str::trim)
+ .filter(|nonce| !nonce.is_empty())
+ && sources
+ .iter()
+ .any(|source| csp_nonce_source_matches(source, nonce))
+ {
+ return true;
+ }
+ if sources
+ .iter()
+ .filter_map(|source| csp_hash_source_value(source))
+ .any(|hash_source| inline_source_matches_hash(source, hash_source))
+ {
+ return true;
+ }
+ let has_nonce_or_hash = sources.iter().any(|source| {
+ csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
+ });
+ !has_nonce_or_hash
+ && sources
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-inline"))
+}
+
+fn inline_source_violation_sample(source_list: &[&str], source: &str) -> String {
+ if !source_list
+ .iter()
+ .any(|source| csp_keyword_eq(source, "report-sample"))
+ {
+ return String::new();
+ }
+ source.chars().take(40).collect()
+}
+
+fn normalized_source_list(sources: Vec<&str>) -> Vec<&str> {
+ // The directive parser already splits on CSP's ASCII whitespace. Trimming
+ // again would turn invalid tokens containing vertical tabs into sources.
+ sources
+ .into_iter()
+ .filter(|source| !source.is_empty())
+ .collect()
+}
+
+fn normalized_source_list_allows_url(
+ sources: &[&str],
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+) -> bool {
+ if sources.is_empty() {
+ return false;
+ }
+ if sources.len() == 1 && csp_keyword_eq(sources[0], "none") {
+ return false;
+ }
+ sources.iter().any(|source| {
+ !csp_keyword_eq(source, "none")
+ && source_expression_matches(source, protected_url, request_url, redirect_status)
+ })
+}
+
+fn csp_nonce_source_matches(source: &str, nonce: &str) -> bool {
+ csp_nonce_source_value(source).is_some_and(|value| value == nonce)
+}
+
+fn source_list_activates_strict_dynamic(sources: &[&str]) -> bool {
+ sources
+ .iter()
+ .any(|source| csp_keyword_eq(source, "strict-dynamic"))
+ && sources.iter().any(|source| {
+ csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
+ })
+}
+
+fn csp_nonce_source_value(source: &str) -> Option<&str> {
+ source
+ .strip_prefix("'nonce-")
+ .and_then(|value| value.strip_suffix('\''))
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::EnumString)]
+#[strum(serialize_all = "lowercase", ascii_case_insensitive)]
+enum CspHashAlgorithm {
+ Sha256,
+ Sha384,
+ Sha512,
+}
+
+impl CspHashAlgorithm {
+ fn digest_algorithm(self) -> DigestAlgorithm {
+ match self {
+ Self::Sha256 => DigestAlgorithm::Sha256,
+ Self::Sha384 => DigestAlgorithm::Sha384,
+ Self::Sha512 => DigestAlgorithm::Sha512,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+struct CspHashSourceValue<'a> {
+ algorithm: CspHashAlgorithm,
+ digest: &'a str,
+}
+
+fn hash_source_value(value: &str) -> Option<CspHashSourceValue<'_>> {
+ let (algorithm, digest) = value.split_once('-')?;
+ if digest.is_empty() {
+ return None;
+ }
+ Some(CspHashSourceValue {
+ algorithm: algorithm.parse().ok()?,
+ digest,
+ })
+}
+
+fn csp_hash_source_value(source: &str) -> Option<CspHashSourceValue<'_>> {
+ let source = source.strip_prefix('\'')?.strip_suffix('\'')?;
+ hash_source_value(source)
+}
+
+fn script_integrity_matches_hash_source(integrity: Option<&str>, sources: &[&str]) -> bool {
+ let Some(integrity) = integrity else {
+ return false;
+ };
+ // CSP requires a nonempty subset of its hash sources, including weaker
+ // algorithms. SRI checks the strongest hashes against the response later.
+ let mut hashes = integrity_metadata_hashes(integrity).peekable();
+ hashes.peek().is_some()
+ && hashes.all(|hash| {
+ sources
+ .iter()
+ .filter_map(|source| csp_hash_source_value(source))
+ .any(|source| {
+ source.algorithm.digest_algorithm() == hash.algorithm
+ && source.digest == hash.digest
+ })
+ })
+}
+
+fn source_expression_matches(
+ source: &str,
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+) -> bool {
+ if csp_keyword_eq(source, "self") {
+ return self_source_matches(protected_url, request_url);
+ }
+ if source == "*" {
+ return matches!(request_url.scheme(), "http" | "https" | "ws" | "wss");
+ }
+ if let Some(scheme) = source.strip_suffix(':')
+ && !scheme.contains('/')
+ && !scheme.is_empty()
+ {
+ return csp_scheme_match(scheme, request_url.scheme()) != CspSchemeMatch::NotMatching;
+ }
+ source_url_matches(source, protected_url, request_url, redirect_status)
+}
+
+fn source_url_matches(
+ source: &str,
+ protected_url: &Url,
+ request_url: &Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+) -> bool {
+ let Some(source) = parse_host_source(source) else {
+ return false;
+ };
+ let source_scheme = source.scheme.unwrap_or_else(|| protected_url.scheme());
+ let scheme_match = csp_scheme_match(source_scheme, request_url.scheme());
+ if scheme_match == CspSchemeMatch::NotMatching {
+ return false;
+ }
+ let port_match = host_source_port_match(source_scheme, source.port, request_url);
+ if !csp_scheme_and_port_match(scheme_match, port_match) {
+ return false;
+ }
+ let Some(request_host) = request_url.host_str() else {
+ return false;
+ };
+ if !csp_host_part_matches(source.host, request_host) {
+ return false;
+ }
+ // Keep the existing wildcard-port IPv4 restriction separate from grammar
+ // validation; sources with ordinary ports already accept literal IPv4.
+ if source.port == Some("*")
+ && source.host != "127.0.0.1"
+ && source.host.parse::<std::net::Ipv4Addr>().is_ok()
+ {
+ return false;
+ }
+ redirect_status == ContentSecurityPolicyRedirectStatus::FollowedRedirect
+ || source
+ .path
+ .is_none_or(|path| csp_path_part_matches(path, request_url.path()))
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum CspSchemeMatch {
+ NotMatching,
+ Exact,
+ WebSocketToHttp,
+ Upgrade,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum CspPortMatch {
+ NotMatching,
+ Exact,
+ Wildcard,
+ Upgrade,
+}
+
+fn self_source_matches(protected_url: &Url, request_url: &Url) -> bool {
+ if protected_url.host_str() != request_url.host_str() {
+ return false;
+ }
+ let scheme_match = csp_scheme_match(protected_url.scheme(), request_url.scheme());
+ let port_match = csp_port_match(
+ protected_url.scheme(),
+ protected_url.port_or_known_default(),
+ false,
+ request_url,
+ );
+ if scheme_match == CspSchemeMatch::Exact && port_match == CspPortMatch::Exact {
+ return true;
+ }
+ let source_port_is_default = protected_url
+ .port_or_known_default()
+ .is_some_and(|port| is_default_port_for_scheme(port, protected_url.scheme()));
+ let request_port_is_default = request_url
+ .port_or_known_default()
+ .is_some_and(|port| is_default_port_for_scheme(port, request_url.scheme()));
+ let ports_match_or_defaults =
+ port_match == CspPortMatch::Exact || (source_port_is_default && request_port_is_default);
+ ports_match_or_defaults
+ && (request_url.scheme().eq_ignore_ascii_case("https")
+ || request_url.scheme().eq_ignore_ascii_case("wss")
+ || protected_url.scheme().eq_ignore_ascii_case("http"))
+}
+
+fn csp_scheme_match(source_scheme: &str, request_scheme: &str) -> CspSchemeMatch {
+ if source_scheme.eq_ignore_ascii_case(request_scheme) {
+ return CspSchemeMatch::Exact;
+ }
+ // CSP permits WebSocket sources to match HTTP URLs at the same security
+ // level. Keep this distinct from exact matching used by 'self' and from
+ // secure upgrades, which also participate in port-upgrade checks.
+ // https://w3c.github.io/webappsec-csp/#match-schemes
+ if (source_scheme.eq_ignore_ascii_case("ws") && request_scheme.eq_ignore_ascii_case("http"))
+ || (source_scheme.eq_ignore_ascii_case("wss")
+ && request_scheme.eq_ignore_ascii_case("https"))
+ {
+ return CspSchemeMatch::WebSocketToHttp;
+ }
+ if (source_scheme.eq_ignore_ascii_case("http") && request_scheme.eq_ignore_ascii_case("https"))
+ || (source_scheme.eq_ignore_ascii_case("ws")
+ && (request_scheme.eq_ignore_ascii_case("wss")
+ || request_scheme.eq_ignore_ascii_case("https")))
+ {
+ return CspSchemeMatch::Upgrade;
+ }
+ CspSchemeMatch::NotMatching
+}
+
+fn csp_port_match(
+ source_scheme: &str,
+ source_port: Option<u16>,
+ source_port_wildcard: bool,
+ request_url: &Url,
+) -> CspPortMatch {
+ if source_port_wildcard {
+ return CspPortMatch::Wildcard;
+ }
+ let request_port = request_url.port_or_known_default();
+ if csp_scheme_match(source_scheme, request_url.scheme()) == CspSchemeMatch::Upgrade
+ && matches!(source_port, Some(80 | 443))
+ && request_port == Some(443)
+ {
+ return CspPortMatch::Upgrade;
+ }
+ if source_port.is_some() && source_port == request_port {
+ return CspPortMatch::Exact;
+ }
+ CspPortMatch::NotMatching
+}
+
+fn is_default_port_for_scheme(port: u16, scheme: &str) -> bool {
+ matches!(
+ (scheme.to_ascii_lowercase().as_str(), port),
+ ("http", 80) | ("ws", 80) | ("https", 443) | ("wss", 443)
+ )
+}
+
+fn csp_scheme_and_port_match(scheme_match: CspSchemeMatch, port_match: CspPortMatch) -> bool {
+ if port_match == CspPortMatch::NotMatching {
+ return false;
+ }
+ let requires_upgrade =
+ scheme_match == CspSchemeMatch::Upgrade || port_match == CspPortMatch::Upgrade;
+ if !requires_upgrade {
+ return true;
+ }
+ let scheme_can_upgrade = scheme_match == CspSchemeMatch::Upgrade;
+ let port_can_upgrade =
+ port_match == CspPortMatch::Upgrade || port_match == CspPortMatch::Wildcard;
+ scheme_can_upgrade && port_can_upgrade
+}
+
+struct CspHostSource<'a> {
+ scheme: Option<&'a str>,
+ host: &'a str,
+ port: Option<&'a str>,
+ path: Option<&'a str>,
+}
+
+fn parse_host_source(source: &str) -> Option<CspHostSource<'_>> {
+ // CSP host-source is not a URL: credentials and scheme-relative URLs are
+ // invalid, and URL parsing must not normalize hosts or dot segments.
+ // https://w3c.github.io/webappsec-csp/#source-lists
+ let (scheme, rest) = if let Some((scheme, rest)) = source.split_once("://")
+ && !scheme.contains('/')
+ {
+ let mut bytes = scheme.bytes();
+ if !bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic())
+ || !bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
+ {
+ return None;
+ }
+ (Some(scheme), rest)
+ } else {
+ (None, source)
+ };
+ let (authority, path) = split_authority_and_path(rest);
+ let (host, port) = if let Some((host, port)) = authority.split_once(':') {
+ if port != "*" && (port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit())) {
+ return None;
+ }
+ (host, Some(port))
+ } else {
+ (authority, None)
+ };
+ if host != "*" {
+ let labels = host.strip_prefix("*.").unwrap_or(host);
+ let labels = labels.strip_suffix('.').unwrap_or(labels);
+ if !labels.split('.').all(|label| {
+ !label.is_empty()
+ && label
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
+ }) {
+ return None;
+ }
+ }
+ if path.is_some_and(|path| !csp_path_part_is_valid(path)) {
+ return None;
+ }
+ Some(CspHostSource {
+ scheme,
+ host,
+ port,
+ path,
+ })
+}
+
+fn split_authority_and_path(source_rest: &str) -> (&str, Option<&str>) {
+ source_rest
+ .find('/')
+ .map(|path_start| (&source_rest[..path_start], Some(&source_rest[path_start..])))
+ .unwrap_or((source_rest, None))
+}
+
+fn csp_host_part_matches(source_host: &str, request_host: &str) -> bool {
+ if source_host == "*" {
+ return !request_host.is_empty();
+ }
+ if let Some(suffix) = source_host.strip_prefix('*') {
+ return request_host.len() >= suffix.len()
+ && request_host.as_bytes()[request_host.len() - suffix.len()..]
+ .eq_ignore_ascii_case(suffix.as_bytes());
+ }
+ source_host.eq_ignore_ascii_case(request_host)
+}
+
+fn csp_path_part_is_valid(path: &str) -> bool {
+ // RFC 3986 path-absolute, excluding raw ';' and ',' as required by CSP.
+ if !path.starts_with('/') || path.starts_with("//") {
+ return false;
+ }
+ let mut bytes = path.bytes();
+ while let Some(byte) = bytes.next() {
+ if byte == b'%' {
+ if !bytes.next().is_some_and(|byte| byte.is_ascii_hexdigit())
+ || !bytes.next().is_some_and(|byte| byte.is_ascii_hexdigit())
+ {
+ return false;
+ }
+ } else if !byte.is_ascii_alphanumeric()
+ && !matches!(
+ byte,
+ b'/' | b'-'
+ | b'.'
+ | b'_'
+ | b'~'
+ | b'!'
+ | b'$'
+ | b'&'
+ | b'\''
+ | b'('
+ | b')'
+ | b'*'
+ | b'+'
+ | b'='
+ | b':'
+ | b'@'
+ )
+ {
+ return false;
+ }
+ }
+ true
+}
+
+fn csp_path_part_matches(source_path: &str, request_path: &str) -> bool {
+ if source_path.is_empty() || (source_path == "/" && request_path.is_empty()) {
+ return true;
+ }
+ // Split before decoding so an encoded slash cannot create a path boundary.
+ // Compare bytes: distinct invalid UTF-8 sequences must not become equal.
+ // https://w3c.github.io/webappsec-csp/#match-paths
+ let mut source_segments = source_path.split('/').peekable();
+ let mut request_segments = request_path.split('/');
+ while let Some(source_segment) = source_segments.next() {
+ let Some(request_segment) = request_segments.next() else {
+ return false;
+ };
+ if source_segment.is_empty() && source_segments.peek().is_none() {
+ return true;
+ }
+ if !percent_decode_str(source_segment).eq(percent_decode_str(request_segment)) {
+ return false;
+ }
+ }
+ request_segments.next().is_none()
+}
+
+fn host_source_port_match(
+ source_scheme: &str,
+ source_port: Option<&str>,
+ request_url: &Url,
+) -> CspPortMatch {
+ match source_port {
+ Some("*") => CspPortMatch::Wildcard,
+ Some(port) => port
+ .parse::<u16>()
+ .ok()
+ .map(|source_port| csp_port_match(source_scheme, Some(source_port), false, request_url))
+ .unwrap_or(CspPortMatch::NotMatching),
+ None => csp_port_match(
+ source_scheme,
+ default_port_for_scheme(source_scheme),
+ false,
+ request_url,
+ ),
+ }
+}
+
+fn default_port_for_scheme(scheme: &str) -> Option<u16> {
+ match scheme.to_ascii_lowercase().as_str() {
+ "http" | "ws" => Some(80),
+ "https" | "wss" => Some(443),
+ "ftp" => Some(21),
+ _ => None,
+ }
+}
+
+fn source_has_path(source: &str) -> bool {
+ let after_scheme = source
+ .split_once("://")
+ .map(|(_, rest)| rest)
+ .or_else(|| source.strip_prefix("//"))
+ .unwrap_or(source);
+ after_scheme.contains('/')
+}
+
+fn csp_keyword_eq(source: &str, keyword: &str) -> bool {
+ source.len() == keyword.len() + 2
+ && source.starts_with('\'')
+ && source.ends_with('\'')
+ && source[1..source.len() - 1].eq_ignore_ascii_case(keyword)
+}
+
+impl ContentSecurityPolicyResourceKind {
+ fn effective_directive(self) -> &'static str {
+ match self {
+ Self::DocumentConnect => CONNECT_SRC,
+ Self::DocumentFrame => FRAME_SRC,
+ Self::DocumentImage => IMG_SRC,
+ Self::DocumentManifest => MANIFEST_SRC,
+ Self::DocumentMedia => MEDIA_SRC,
+ Self::DocumentScriptElement | Self::WorkerDynamicModuleImport => SCRIPT_SRC_ELEM,
+ Self::DocumentStyleElement => STYLE_SRC_ELEM,
+ Self::SharedWorkerScript | Self::WorkerStaticModuleImport => WORKER_SRC,
+ Self::WorkerConnect => CONNECT_SRC,
+ Self::WorkerScript => SCRIPT_SRC,
+ }
+ }
+
+ fn directive_fallbacks(self) -> &'static [&'static str] {
+ match self {
+ Self::DocumentConnect => &[CONNECT_SRC, DEFAULT_SRC],
+ Self::DocumentFrame => &[FRAME_SRC, CHILD_SRC, DEFAULT_SRC],
+ Self::DocumentImage => &[IMG_SRC, DEFAULT_SRC],
+ Self::DocumentManifest => &[MANIFEST_SRC, DEFAULT_SRC],
+ Self::DocumentMedia => &[MEDIA_SRC, DEFAULT_SRC],
+ Self::DocumentScriptElement => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
+ Self::DocumentStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC],
+ Self::SharedWorkerScript => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
+ Self::WorkerConnect => &[CONNECT_SRC, DEFAULT_SRC],
+ Self::WorkerDynamicModuleImport => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
+ Self::WorkerScript => &[SCRIPT_SRC, DEFAULT_SRC],
+ Self::WorkerStaticModuleImport => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
+ }
+ }
+}
+
+impl ContentSecurityPolicyNonUrlKind {
+ fn effective_directive(self) -> &'static str {
+ match self {
+ Self::DocumentInlineEventHandler => SCRIPT_SRC_ATTR,
+ Self::DocumentInlineNavigation | Self::DocumentInlineScript => SCRIPT_SRC_ELEM,
+ Self::DocumentInlineStyleAttribute => STYLE_SRC_ATTR,
+ Self::DocumentInlineStyleElement => STYLE_SRC_ELEM,
+ Self::Eval | Self::TrustedTypesEval => SCRIPT_SRC,
+ Self::WasmEval => SCRIPT_SRC,
+ }
+ }
+
+ fn directive_fallbacks(self) -> &'static [&'static str] {
+ match self {
+ Self::DocumentInlineEventHandler => &[SCRIPT_SRC_ATTR, SCRIPT_SRC, DEFAULT_SRC],
+ Self::DocumentInlineNavigation | Self::DocumentInlineScript => {
+ &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC]
+ }
+ Self::DocumentInlineStyleAttribute => &[STYLE_SRC_ATTR, STYLE_SRC, DEFAULT_SRC],
+ Self::DocumentInlineStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC],
+ Self::Eval | Self::TrustedTypesEval => &[SCRIPT_SRC, DEFAULT_SRC],
+ Self::WasmEval => &[SCRIPT_SRC, DEFAULT_SRC],
+ }
+ }
+
+ fn blocked_uri(self) -> &'static str {
+ match self {
+ Self::DocumentInlineEventHandler
+ | Self::DocumentInlineNavigation
+ | Self::DocumentInlineScript
+ | Self::DocumentInlineStyleAttribute
+ | Self::DocumentInlineStyleElement => "inline",
+ Self::Eval | Self::TrustedTypesEval => "eval",
+ Self::WasmEval => "wasm-eval",
+ }
+ }
+
+ fn source_list_allows(self, source_list: &[&str], source: Option<&str>) -> bool {
+ match self {
+ Self::DocumentInlineEventHandler
+ | Self::DocumentInlineNavigation
+ | Self::DocumentInlineStyleAttribute => {
+ inline_event_handler_source_list_allows(source_list, source.unwrap_or_default())
+ }
+ Self::DocumentInlineScript => source_list
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-inline")),
+ Self::DocumentInlineStyleElement => source_list
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-inline")),
+ Self::Eval => source_list
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-eval")),
+ Self::TrustedTypesEval => source_list.iter().any(|source| {
+ csp_keyword_eq(source, "unsafe-eval")
+ || csp_keyword_eq(source, "trusted-types-eval")
+ }),
+ Self::WasmEval => source_list.iter().any(|source| {
+ csp_keyword_eq(source, "unsafe-eval") || csp_keyword_eq(source, "wasm-unsafe-eval")
+ }),
+ }
+ }
+}
+
+fn inline_event_handler_source_list_allows(source_list: &[&str], source: &str) -> bool {
+ let has_nonce_or_hash = source_list.iter().any(|source| {
+ csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
+ });
+ if !has_nonce_or_hash
+ && source_list
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-inline"))
+ {
+ return true;
+ }
+ if !source_list
+ .iter()
+ .any(|source| csp_keyword_eq(source, "unsafe-hashes"))
+ {
+ return false;
+ }
+ source_list
+ .iter()
+ .filter_map(|source| csp_hash_source_value(source))
+ .any(|hash_source| inline_source_matches_hash(source, hash_source))
+}
+
+fn inline_source_matches_hash(source: &str, hash_source: CspHashSourceValue<'_>) -> bool {
+ let digest = hash_source
+ .algorithm
+ .digest_algorithm()
+ .digest_bytes(source.as_bytes());
+ let actual = BASE64_STANDARD.encode(digest);
+ // Inline checks normalize base64url symbols, preserving padding and all
+ // other bytes. External script integrity matches remain literal.
+ actual
+ .bytes()
+ .eq(hash_source.digest.bytes().map(|byte| match byte {
+ b'-' => b'+',
+ b'_' => b'/',
+ _ => byte,
+ }))
+}
+
+#[cfg(test)]
+#[path = "tests.rs"]
+mod tests;
diff --git a/moli-csp/src/integrity.rs b/moli-csp/src/integrity.rs
new file mode 100644
index 000000000..5d96d840d
--- /dev/null
+++ b/moli-csp/src/integrity.rs
@@ -0,0 +1,56 @@
+use moli_crypto::DigestAlgorithm;
+
+pub struct IntegrityMetadataHash<'a> {
+ pub algorithm: DigestAlgorithm,
+ pub digest: &'a str,
+}
+
+/// Keep the encoded digest for CSP's literal hash-source comparison. Response
+/// integrity verification separately decodes it and selects the strongest hash.
+pub fn integrity_metadata_hashes(
+ integrity: &str,
+) -> impl Iterator<Item = IntegrityMetadataHash<'_>> {
+ integrity
+ .split_ascii_whitespace()
+ .filter_map(parse_integrity_hash)
+}
+
+fn parse_integrity_hash(token: &str) -> Option<IntegrityMetadataHash<'_>> {
+ let (algorithm, digest) = parse_integrity_algorithm_and_digest(token)?;
+ let digest = digest.split_once('?').map_or(digest, |(digest, _)| digest);
+ if !is_integrity_digest_syntax(digest) {
+ return None;
+ }
+ Some(IntegrityMetadataHash { algorithm, digest })
+}
+
+fn is_integrity_digest_syntax(digest: &str) -> bool {
+ // Recognizing metadata and decoding its digest are separate steps. Keep
+ // hashes containing misplaced or excess padding: a decode failure must
+ // fail verification, not erase a supported (possibly stronger) algorithm.
+ !digest.is_empty()
+ && digest.bytes().all(|byte| {
+ byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'-' | b'_' | b'=')
+ })
+}
+
+fn parse_integrity_algorithm_and_digest(token: &str) -> Option<(DigestAlgorithm, &str)> {
+ const PREFIXES: &[(&str, DigestAlgorithm)] = &[
+ ("sha256", DigestAlgorithm::Sha256),
+ ("sha-256", DigestAlgorithm::Sha256),
+ ("sha384", DigestAlgorithm::Sha384),
+ ("sha-384", DigestAlgorithm::Sha384),
+ ("sha512", DigestAlgorithm::Sha512),
+ ("sha-512", DigestAlgorithm::Sha512),
+ ];
+ for (prefix, algorithm) in PREFIXES {
+ let Some(rest) = token.strip_prefix(prefix) else {
+ continue;
+ };
+ let Some(digest) = rest.strip_prefix('-') else {
+ continue;
+ };
+ return Some((*algorithm, digest));
+ }
+ None
+}
diff --git a/moli-csp/src/lib.rs b/moli-csp/src/lib.rs
new file mode 100644
index 000000000..3b53fcf7f
--- /dev/null
+++ b/moli-csp/src/lib.rs
@@ -0,0 +1,18 @@
+//! Content Security Policy parsing, matching, and violation report construction.
+//! Policies retain their delivered text and share immutable parsed directives
+//! across documents, workers, and request snapshots.
+
+mod checks;
+mod integrity;
+mod policy;
+mod reporting;
+mod types;
+
+pub use checks::*;
+pub use integrity::{IntegrityMetadataHash, integrity_metadata_hashes};
+pub use policy::{
+ ContentSecurityPolicy, content_security_policy_headers,
+ content_security_policy_report_only_headers,
+};
+pub use reporting::*;
+pub use types::*;
diff --git a/moli-csp/src/policy.rs b/moli-csp/src/policy.rs
new file mode 100644
index 000000000..65a6b242a
--- /dev/null
+++ b/moli-csp/src/policy.rs
@@ -0,0 +1,157 @@
+use std::{collections::HashSet, sync::Arc};
+
+use crate::ContentSecurityPolicyDisposition;
+use ::content_security_policy::{Policy, PolicyDisposition, PolicySource};
+
+/// A delivered policy keeps its original text for reports and shares its parsed
+/// directives with inherited Documents, workers, and request snapshots.
+#[derive(Clone, Debug)]
+pub struct ContentSecurityPolicy(Arc<ParsedPolicy>);
+
+#[derive(Debug)]
+struct ParsedPolicy {
+ serialized: String,
+ policy: Policy,
+}
+
+impl ContentSecurityPolicy {
+ pub(crate) fn parse(
+ serialized: String,
+ source: PolicySource,
+ disposition: PolicyDisposition,
+ ) -> Self {
+ let mut policy = Policy::parse(&serialized, source, disposition);
+
+ // The upstream parser skips a non-ASCII directive before checking for
+ // duplicates. Moli delivery reserves the first name even when its
+ // value is invalid. Keep that rule without tokenizing valid values a
+ // second time. ASCII invalid values are retained by the parser until
+ // validation below, so they already suppress their later duplicates.
+ let invalid_first_names = if serialized.is_ascii() {
+ HashSet::new()
+ } else {
+ let mut names = HashSet::new();
+ serialized
+ .split(';')
+ .filter_map(|directive| {
+ let name = directive
+ .split_ascii_whitespace()
+ .next()?
+ .to_ascii_lowercase();
+ (names.insert(name.clone()) && !directive.is_ascii()).then_some(name)
+ })
+ .collect()
+ };
+ policy.directive_set.retain(|directive| {
+ directive.is_valid() && !invalid_first_names.contains(&directive.name)
+ });
+
+ Self(Arc::new(ParsedPolicy { serialized, policy }))
+ }
+
+ /// Parse one HTTP policy while retaining its delivered text for reports.
+ pub fn from_header(serialized: String, disposition: ContentSecurityPolicyDisposition) -> Self {
+ Self::parse(
+ serialized,
+ PolicySource::Header,
+ match disposition {
+ ContentSecurityPolicyDisposition::Enforce => PolicyDisposition::Enforce,
+ ContentSecurityPolicyDisposition::Report => PolicyDisposition::Report,
+ },
+ )
+ }
+
+ pub fn from_meta(serialized: String) -> Self {
+ Self::parse(serialized, PolicySource::Meta, PolicyDisposition::Enforce)
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0.serialized
+ }
+
+ fn directives(&self) -> &[::content_security_policy::Directive] {
+ &self.0.policy.directive_set
+ }
+
+ pub(crate) fn sources(&self, name: &str) -> Option<&[String]> {
+ self.directives()
+ .iter()
+ .find(|directive| directive.name == name)
+ .map(|directive| directive.value.as_slice())
+ }
+
+ pub(crate) fn is_empty(&self) -> bool {
+ self.directives().is_empty()
+ }
+}
+
+impl From<String> for ContentSecurityPolicy {
+ fn from(serialized: String) -> Self {
+ Self::from_header(serialized, ContentSecurityPolicyDisposition::Enforce)
+ }
+}
+
+impl From<&str> for ContentSecurityPolicy {
+ fn from(serialized: &str) -> Self {
+ Self::from(serialized.to_owned())
+ }
+}
+
+impl PartialEq for ContentSecurityPolicy {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_str() == other.as_str()
+ && self.0.policy.source == other.0.policy.source
+ && self.0.policy.disposition == other.0.policy.disposition
+ }
+}
+
+impl Eq for ContentSecurityPolicy {}
+
+pub fn content_security_policy_headers(
+ headers: &[(String, Vec<u8>)],
+) -> Vec<ContentSecurityPolicy> {
+ content_security_policy_header_values(headers, "content-security-policy")
+}
+
+pub fn content_security_policy_report_only_headers(
+ headers: &[(String, Vec<u8>)],
+) -> Vec<ContentSecurityPolicy> {
+ content_security_policy_header_values(headers, "content-security-policy-report-only")
+}
+
+pub(crate) fn content_security_policy_header_values(
+ headers: &[(String, Vec<u8>)],
+ header_name: &str,
+) -> Vec<ContentSecurityPolicy> {
+ let headers = moli_header_field::headers_to_byte_strings(headers);
+ // Each HTTP field can contain several independently enforced policies.
+ // Commas are CSP list delimiters even inside quotes in directive values;
+ // the quoted-string rules used by Reporting-Endpoints do not apply here.
+ // https://w3c.github.io/webappsec-csp/#parse-response-csp
+ headers
+ .iter()
+ .filter(|(name, _)| name.eq_ignore_ascii_case(header_name))
+ .flat_map(|(_, value)| value.split(','))
+ .map(str::trim_ascii)
+ .map(|policy| {
+ ContentSecurityPolicy::from_header(
+ policy.to_owned(),
+ if header_name == "content-security-policy-report-only" {
+ ContentSecurityPolicyDisposition::Report
+ } else {
+ ContentSecurityPolicyDisposition::Enforce
+ },
+ )
+ })
+ .filter(|policy| !policy.is_empty())
+ .collect()
+}
+
+pub(crate) fn directive_source_list<'policy>(
+ policy: &'policy ContentSecurityPolicy,
+ name: &str,
+) -> Option<Vec<&'policy str>> {
+ policy
+ .sources(name)
+ .map(|sources| sources.iter().map(String::as_str).collect())
+}
diff --git a/moli-csp/src/reporting.rs b/moli-csp/src/reporting.rs
new file mode 100644
index 000000000..1df2503df
--- /dev/null
+++ b/moli-csp/src/reporting.rs
@@ -0,0 +1,217 @@
+use crate::{
+ ContentSecurityPolicy, ContentSecurityPolicyReportingEndpoints,
+ ContentSecurityPolicyViolationEventFields,
+};
+use serde_json::json;
+use url::Url;
+
+pub fn content_security_policy_report_uri_endpoints(
+ policy: &ContentSecurityPolicy,
+ protected_url: &Url,
+) -> Vec<String> {
+ if policy.sources("report-to").is_some() {
+ return Vec::new();
+ }
+ policy
+ .sources("report-uri")
+ .into_iter()
+ .flatten()
+ .filter_map(|endpoint| protected_url.join(endpoint).ok())
+ .filter(|endpoint| matches!(endpoint.scheme(), "http" | "https"))
+ .map(|endpoint| endpoint.to_string())
+ .collect()
+}
+
+pub fn content_security_policy_reporting_endpoints_from_headers(
+ headers: &[(String, Vec<u8>)],
+ protected_url: &Url,
+) -> ContentSecurityPolicyReportingEndpoints {
+ let mut endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ for (_, value) in headers
+ .iter()
+ .filter(|(name, _)| name.eq_ignore_ascii_case("reporting-endpoints"))
+ {
+ parse_reporting_endpoints_header(
+ &moli_header_field::decode_header_value(value),
+ protected_url,
+ &mut endpoints,
+ );
+ }
+ endpoints
+}
+
+fn parse_reporting_endpoints_header(
+ value: &str,
+ protected_url: &Url,
+ endpoints: &mut ContentSecurityPolicyReportingEndpoints,
+) {
+ for member in split_quoted_header_list(value) {
+ let Some((raw_group, raw_endpoint)) = member.split_once('=') else {
+ continue;
+ };
+ let group = raw_group.trim();
+ if group.is_empty() {
+ continue;
+ }
+ let Some(endpoint) = parse_quoted_header_value(raw_endpoint.trim()) else {
+ continue;
+ };
+ let Ok(endpoint) = protected_url.join(&endpoint) else {
+ continue;
+ };
+ if !matches!(endpoint.scheme(), "http" | "https") {
+ continue;
+ }
+ endpoints.insert(group, endpoint.to_string());
+ }
+}
+
+fn split_quoted_header_list(value: &str) -> Vec<&str> {
+ let mut parts = Vec::new();
+ let mut in_quote = false;
+ let mut escaped = false;
+ let mut start = 0;
+ for (index, ch) in value.char_indices() {
+ if escaped {
+ escaped = false;
+ continue;
+ }
+ match ch {
+ '\\' if in_quote => escaped = true,
+ '"' => in_quote = !in_quote,
+ ',' if !in_quote => {
+ let part = value[start..index].trim();
+ if !part.is_empty() {
+ parts.push(part);
+ }
+ start = index + ch.len_utf8();
+ }
+ _ => {}
+ }
+ }
+ let part = value[start..].trim();
+ if !part.is_empty() {
+ parts.push(part);
+ }
+ parts
+}
+
+fn parse_quoted_header_value(value: &str) -> Option<String> {
+ let value = value.strip_prefix('"')?.strip_suffix('"')?;
+ let mut output = String::with_capacity(value.len());
+ let mut chars = value.chars();
+ while let Some(ch) = chars.next() {
+ if ch == '\\' {
+ output.push(chars.next()?);
+ } else {
+ output.push(ch);
+ }
+ }
+ Some(output)
+}
+
+pub fn content_security_policy_report_to_endpoints(
+ policy: &ContentSecurityPolicy,
+ reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
+) -> Vec<String> {
+ let Some(sources) = policy.sources("report-to") else {
+ return Vec::new();
+ };
+ let Some(group) = sources.first() else {
+ return Vec::new();
+ };
+ reporting_endpoints
+ .endpoint_for_group(group)
+ .map(|endpoint| vec![endpoint.to_owned()])
+ .unwrap_or_default()
+}
+
+pub fn content_security_policy_violation_report_body(
+ fields: &ContentSecurityPolicyViolationEventFields<'_>,
+) -> String {
+ json!({
+ "csp-report": {
+ "document-uri": fields.document_uri,
+ "referrer": fields.referrer,
+ "violated-directive": fields.violated_directive,
+ "effective-directive": fields.effective_directive,
+ "original-policy": fields.original_policy,
+ "disposition": fields.disposition.as_str(),
+ "blocked-uri": fields.blocked_uri,
+ "source-file": fields.source_file,
+ "status-code": fields.status_code,
+ "script-sample": fields.sample,
+ }
+ })
+ .to_string()
+}
+
+pub fn content_security_policy_reporting_api_report_body(
+ fields: &ContentSecurityPolicyViolationEventFields<'_>,
+) -> String {
+ let mut body = serde_json::Map::new();
+ body.insert("documentURL".to_owned(), json!(fields.document_uri));
+ if !fields.referrer.is_empty() {
+ body.insert("referrer".to_owned(), json!(fields.referrer));
+ }
+ if !fields.blocked_uri.is_empty() {
+ body.insert("blockedURL".to_owned(), json!(fields.blocked_uri));
+ }
+ body.insert(
+ "effectiveDirective".to_owned(),
+ json!(fields.effective_directive),
+ );
+ body.insert("originalPolicy".to_owned(), json!(fields.original_policy));
+ if !fields.source_file.is_empty() {
+ body.insert("sourceFile".to_owned(), json!(fields.source_file));
+ }
+ if !fields.sample.is_empty() {
+ body.insert("sample".to_owned(), json!(fields.sample));
+ }
+ body.insert("disposition".to_owned(), json!(fields.disposition.as_str()));
+ body.insert("statusCode".to_owned(), json!(fields.status_code));
+ if fields.line_number != 0 {
+ body.insert("lineNumber".to_owned(), json!(fields.line_number));
+ }
+ if fields.column_number != 0 {
+ body.insert("columnNumber".to_owned(), json!(fields.column_number));
+ }
+ json!([{
+ "age": 0,
+ "type": "csp-violation",
+ "url": fields.document_uri,
+ "body": body,
+ }])
+ .to_string()
+}
+
+pub(crate) fn csp_url_for_report(url: &Url) -> String {
+ if !matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
+ return url.scheme().to_owned();
+ }
+ let mut stripped = url.clone();
+ let _ = stripped.set_username("");
+ let _ = stripped.set_password(None);
+ stripped.set_fragment(None);
+ stripped.to_string()
+}
+
+/// Strip a script source URL before exposing it through a CSP violation report.
+///
+/// This implements the URL-shaping portion of CSP's "Strip URL for use in
+/// reports" algorithm. Script source locations may expose HTTP(S)/WS(S) paths,
+/// but never credentials, queries, or fragments. Other valid schemes are
+/// reduced to the scheme name.
+pub fn content_security_policy_source_file_for_report(source_file: &str) -> String {
+ let Ok(mut source_url) = Url::parse(source_file) else {
+ return String::new();
+ };
+ if !matches!(source_url.scheme(), "http" | "https" | "ws" | "wss") {
+ return source_url.scheme().to_owned();
+ }
+ let _ = source_url.set_username("");
+ let _ = source_url.set_password(None);
+ source_url.set_query(None);
+ source_url.set_fragment(None);
+ source_url.to_string()
+}
diff --git a/moli-csp/src/tests.rs b/moli-csp/src/tests.rs
new file mode 100644
index 000000000..e2bc583a0
--- /dev/null
+++ b/moli-csp/src/tests.rs
@@ -0,0 +1,2748 @@
+use super::*;
+use crate::policy::{
+ content_security_policy_header_values, content_security_policy_headers,
+ content_security_policy_report_only_headers,
+};
+use crate::reporting::*;
+
+fn protected_url() -> Url {
+ Url::parse("https://app.test/page.html").unwrap()
+}
+
+fn request_url(raw: &str) -> Url {
+ Url::parse(raw).unwrap()
+}
+
+fn allowed(policy: &str, kind: ContentSecurityPolicyResourceKind, request: &str) -> bool {
+ content_security_policy_allows_url(
+ &[policy.to_owned().into()],
+ &protected_url(),
+ &request_url(request),
+ kind,
+ )
+}
+
+fn script_element_request_allowed(
+ policy: &str,
+ request: ContentSecurityPolicyScriptElementRequest<'_>,
+) -> bool {
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &[policy.to_owned().into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ request,
+ )
+ .is_none()
+}
+
+fn frame_ancestors_violation(
+ policies: &[&str],
+ protected_url: &str,
+ ancestor_origins: &[Option<&str>],
+) -> Option<ContentSecurityPolicyUrlViolation> {
+ content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ &request_url(protected_url),
+ &ancestor_origins
+ .iter()
+ .map(|ancestor| ancestor.map(request_url))
+ .collect::<Vec<_>>(),
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+}
+
+#[test]
+fn content_security_policy_headers_collect_enforce_headers_only() {
+ let headers: Vec<(String, Vec<u8>)> = vec![
+ (
+ "Content-Security-Policy-Report-Only".to_owned(),
+ b"worker-src 'none'".to_vec(),
+ ),
+ (
+ "content-security-policy".to_owned(),
+ b" worker-src 'self' ".to_vec(),
+ ),
+ ("Content-Security-Policy".to_owned(), Vec::new()),
+ ];
+
+ assert_eq!(
+ content_security_policy_headers(&headers)
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
+ vec!["worker-src 'self'".to_owned()]
+ );
+ assert_eq!(
+ content_security_policy_report_only_headers(&headers)
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
+ vec!["worker-src 'none'".to_owned()]
+ );
+}
+
+#[test]
+fn csp_headers_preserve_policy_order_and_disposition() {
+ let headers: Vec<(String, Vec<u8>)> = vec![
+ (
+ "CONTENT-SECURITY-POLICY".to_owned(),
+ b" , img-src *; report-uri /first, img-src 'none'; report-uri /second, ".to_vec(),
+ ),
+ (
+ "Content-Security-Policy-Report-Only".to_owned(),
+ b"script-src * , script-src 'none'".to_vec(),
+ ),
+ (
+ "content-security-policy".to_owned(),
+ b"worker-src 'self'".to_vec(),
+ ),
+ ];
+ assert_eq!(
+ content_security_policy_headers(&headers)
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
+ [
+ "img-src *; report-uri /first",
+ "img-src 'none'; report-uri /second",
+ "worker-src 'self'",
+ ]
+ );
+ assert_eq!(
+ content_security_policy_report_only_headers(&headers)
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
+ ["script-src *", "script-src 'none'"]
+ );
+}
+
+#[test]
+fn csp_header_policy_lists_enforce_every_policy() {
+ for (value, request, expected) in [
+ (
+ "img-src * , img-src 'none'",
+ "https://cdn.test/asset",
+ false,
+ ),
+ ("img-src *,img-src 'none'", "https://cdn.test/asset", false),
+ (
+ "img-src *; ignored first, img-src 'none'; ignored second",
+ "https://cdn.test/asset",
+ false,
+ ),
+ (
+ "img-src https://cdn.test/foo,ignored",
+ "https://cdn.test/foo",
+ true,
+ ),
+ (
+ "img-src https://cdn.test/foo,ignored",
+ "https://cdn.test/foo,ignored",
+ false,
+ ),
+ (
+ "img-src https://cdn.test/foo%2cbar",
+ "https://cdn.test/foo%2cbar",
+ true,
+ ),
+ (
+ "img-src https://cdn.test/foo%2cbar",
+ "https://cdn.test/foo,bar",
+ true,
+ ),
+ (
+ ", , img-src * , , img-src 'none', ,",
+ "https://cdn.test/asset",
+ false,
+ ),
+ (
+ "img-src *; img-src 'none', img-src *",
+ "https://cdn.test/asset",
+ true,
+ ),
+ (
+ "img-src https://cdn.test/foo, img-src https://cdn.test/bar",
+ "https://cdn.test/foo",
+ false,
+ ),
+ (
+ "img-src https://cdn.test/foo, img-src https://cdn.test/bar",
+ "https://cdn.test/bar",
+ false,
+ ),
+ (
+ "img-src *; ignored \"start, img-src 'none'; ignored end\"",
+ "https://cdn.test/asset",
+ false,
+ ),
+ ] {
+ let policies = content_security_policy_headers(&[(
+ "Content-Security-Policy".to_owned(),
+ value.as_bytes().to_vec(),
+ )]);
+ assert_eq!(
+ content_security_policy_allows_url(
+ &policies,
+ &protected_url(),
+ &request_url(request),
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ),
+ expected,
+ "{value:?} with {request}"
+ );
+ }
+}
+
+#[test]
+fn csp_header_lists_keep_report_only_violations_with_their_policy() {
+ let headers: Vec<(String, Vec<u8>)> = vec![
+ ("Content-Security-Policy".to_owned(), b"img-src *".to_vec()),
+ (
+ "Content-Security-Policy-Report-Only".to_owned(),
+ b"img-src *; report-uri /allowed, img-src 'none'; report-uri /blocked".to_vec(),
+ ),
+ ];
+ let protected = protected_url();
+ let request = request_url("https://cdn.test/asset");
+ assert!(content_security_policy_allows_url(
+ &content_security_policy_headers(&headers),
+ &protected,
+ &request,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ));
+ let violation = content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ &content_security_policy_report_only_headers(&headers),
+ &protected,
+ &request,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Report,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ).expect("the second report-only policy must produce a violation");
+ assert_eq!(
+ violation.disposition,
+ ContentSecurityPolicyDisposition::Report
+ );
+ assert_eq!(
+ violation.original_policy,
+ "img-src 'none'; report-uri /blocked"
+ );
+ assert_eq!(violation.report_uri_endpoints, ["https://app.test/blocked"]);
+}
+
+#[test]
+fn csp_header_lists_preserve_invalid_whitespace_and_skip_empty_policies() {
+ for name in [
+ "content-security-policy",
+ "content-security-policy-report-only",
+ ] {
+ let collect = |value: &[u8]| {
+ content_security_policy_header_values(&[(name.to_owned(), value.to_vec())], name)
+ };
+ assert!(collect(b", ; ; , \t , img-src 'none'\xa0,").is_empty());
+ assert_eq!(
+ collect(b"\t\n\r\x0c img-src 'none' , \t")
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
+ ["img-src 'none'"]
+ );
+ assert_eq!(
+ collect(b"img-src *\x0b, img-src 'none'")
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
+ ["img-src 'none'"]
+ );
+ let policies = collect(b"img-src *\x0b");
+ assert!(policies.is_empty());
+ assert!(content_security_policy_allows_url(
+ &policies,
+ &protected_url(),
+ &request_url("https://cdn.test/asset"),
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ));
+ assert!(!content_security_policy_allows_url(
+ &collect(b"img-src *\x0b, img-src 'none'"),
+ &protected_url(),
+ &request_url("https://cdn.test/asset"),
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ));
+ }
+}
+
+#[test]
+fn csp_single_directive_values_reject_commas() {
+ let directives = ContentSecurityPolicy::from("img-src https://cdn.test/a,b; script-src 'none'");
+ assert!(directive_source_list(&directives, IMG_SRC).is_none());
+ assert_eq!(
+ directive_source_list(&directives, SCRIPT_SRC),
+ Some(vec!["'none'"])
+ );
+}
+
+#[test]
+fn csp_invalid_directive_characters_do_not_block_resources_or_discard_other_directives() {
+ for invalid in ('\0'..='\u{0008}')
+ .chain(['\u{000b}'])
+ .chain('\u{000e}'..='\u{001f}')
+ .chain(['\u{007f}', '\u{0080}', '\u{00a0}', '\u{feff}', '中'])
+ {
+ for value in [
+ format!("{invalid}'none'"),
+ format!("'no{invalid}ne'"),
+ format!("'none'{invalid}"),
+ ] {
+ let policy = format!("img-src {value}; script-src 'none'; report-uri /blocked");
+ let policies = [policy.clone().into()];
+ for disposition in [
+ ContentSecurityPolicyDisposition::Enforce,
+ ContentSecurityPolicyDisposition::Report,
+ ] {
+ let violation = |kind| {
+ content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ &policies,
+ &protected_url(),
+ &request_url("https://cdn.test/asset"),
+ kind,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ disposition,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+ };
+ assert!(
+ violation(ContentSecurityPolicyResourceKind::DocumentImage).is_none(),
+ "{policy:?}",
+ );
+ let blocked = violation(ContentSecurityPolicyResourceKind::DocumentScriptElement)
+ .expect("the valid script-src directive must still block");
+ assert_eq!(blocked.effective_directive, SCRIPT_SRC_ELEM);
+ assert_eq!(blocked.disposition, disposition);
+ assert_eq!(blocked.original_policy, policy);
+ assert_eq!(blocked.report_uri_endpoints, ["https://app.test/blocked"]);
+ }
+ }
+ }
+}
+
+#[test]
+fn csp_invalid_directives_preserve_fallbacks_and_trusted_types_requirements() {
+ for invalid in ['\0', '\u{000b}', '\u{001f}', '\u{007f}', '\u{00a0}'] {
+ let policy = format!(
+ "default-src 'self'; img-src *{invalid}; \
+ script-src 'unsafe-eval'{invalid}; trusted-types *{invalid}; \
+ require-trusted-types-for 'script'"
+ );
+ assert!(!allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ "https://cdn.test/asset",
+ ));
+ assert!(allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ "https://app.test/asset",
+ ));
+ assert!(
+ content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::Eval,
+ None,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+ .is_some(),
+ "{policy:?}",
+ );
+ assert!(policy_requires_trusted_types_for_script(
+ &ContentSecurityPolicy::from(policy.as_str())
+ ));
+ assert!(policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ "unlisted"
+ ));
+
+ let policy = format!(
+ "trusted-types allowed; require-trusted-types-for 'script'{invalid}; img-src 'none'"
+ );
+ assert!(!policy_requires_trusted_types_for_script(
+ &ContentSecurityPolicy::from(policy.as_str())
+ ));
+ assert!(policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ "allowed"
+ ));
+ assert!(!policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ "unlisted"
+ ));
+ assert!(!allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ "https://app.test/asset",
+ ));
+ }
+}
+
+#[test]
+fn csp_invalid_first_values_do_not_activate_later_duplicate_directives() {
+ for invalid in ['\0', '\u{000b}', '\u{001f}', '\u{007f}', '\u{00a0}', '中'] {
+ let policy = format!("default-src 'none'; img-src *{invalid}; IMG-SRC *");
+ assert!(!allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ "https://cdn.test/asset",
+ ));
+ let policy = format!("img-src 'none'{invalid}; IMG-SRC 'none'");
+ assert!(allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ "https://cdn.test/asset",
+ ));
+ for policy in [
+ format!("default-src 'none'; img-src{invalid} 'none'; img-src *"),
+ format!("default-src 'none'; {invalid}img-src 'none'; img-src *"),
+ ] {
+ assert!(
+ allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ "https://cdn.test/asset",
+ ),
+ "{policy:?}"
+ );
+ }
+ let policy = format!("trusted-types *{invalid}; TRUSTED-TYPES allowed");
+ assert!(policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ "unlisted"
+ ));
+ let policy = format!("trusted-types allowed; TRUSTED-TYPES *{invalid}");
+ assert!(policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ "allowed"
+ ));
+ assert!(!policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ "unlisted"
+ ));
+ }
+}
+
+#[test]
+fn csp_keywords_do_not_strip_control_characters_from_source_tokens() {
+ use ContentSecurityPolicyNonUrlKind::*;
+ for (kind, keyword) in [
+ (DocumentInlineScript, "unsafe-inline"),
+ (DocumentInlineStyleElement, "unsafe-inline"),
+ (DocumentInlineEventHandler, "unsafe-inline"),
+ (DocumentInlineNavigation, "unsafe-inline"),
+ (DocumentInlineStyleAttribute, "unsafe-inline"),
+ (Eval, "unsafe-eval"),
+ (TrustedTypesEval, "unsafe-eval"),
+ (TrustedTypesEval, "trusted-types-eval"),
+ (WasmEval, "unsafe-eval"),
+ (WasmEval, "wasm-unsafe-eval"),
+ ] {
+ for padding in [
+ "",
+ " \t\n\r\u{000c}",
+ "\0",
+ "\u{000b}",
+ "\u{001f}",
+ "\u{007f}",
+ ] {
+ let valid = padding.is_empty() || padding.starts_with(' ');
+ for source in [
+ format!("{padding}'{keyword}'"),
+ format!("'{keyword}'{padding}"),
+ ] {
+ let policy = format!(
+ "default-src 'none'; {} {source}",
+ kind.effective_directive()
+ );
+ let violation = content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ &protected_url(),
+ kind,
+ None,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ );
+ assert_eq!(violation.is_none(), valid, "{kind:?}: {policy:?}");
+ }
+ }
+ }
+}
+
+#[test]
+fn csp_nonce_and_hash_tokens_preserve_their_boundaries() {
+ let source = "t1.done();";
+ let integrity = "sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps=";
+ for expression in ["'nonce-abc'".to_owned(), format!("'{integrity}'")] {
+ for (prefix, suffix, valid) in [
+ ("", "", true),
+ ("\t\n", " \r\u{000c}", true),
+ ("\u{000b}", "", false),
+ ("", "\u{000b}", false),
+ ] {
+ let token = format!("{prefix}{expression}{suffix}");
+ let policy = format!("default-src 'none'; script-src {token}; style-src {token}");
+ let request = ContentSecurityPolicyScriptElementRequest {
+ nonce: Some("abc"),
+ integrity: Some(integrity),
+ parser_inserted: true,
+ };
+ assert_eq!(
+ script_element_request_allowed(&policy, request),
+ valid,
+ "{policy:?}"
+ );
+ let endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let script = content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy.as_str()), &protected_url(), source, request,
+ ContentSecurityPolicyDisposition::Enforce, &endpoints,
+ );
+ assert_eq!(script.is_none(), valid, "inline script: {policy:?}");
+ let style = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy.as_str()), &protected_url(), source,
+ ContentSecurityPolicyStyleElementRequest { nonce: Some("abc") },
+ ContentSecurityPolicyDisposition::Enforce, &endpoints,
+ );
+ assert_eq!(style.is_none(), valid, "inline style: {policy:?}");
+
+ // Invalid nonce/hash tokens must not disable unsafe-inline or
+ // activate strict-dynamic and erase a URL allowlist either.
+ let inline_sources = format!("'unsafe-inline' {token}");
+ let inline_sources: Vec<_> = inline_sources.split_ascii_whitespace().collect();
+ assert_eq!(
+ inline_event_handler_source_list_allows(&inline_sources, "untrusted()"),
+ !valid,
+ "{inline_sources:?}",
+ );
+ let dynamic_sources = format!("'strict-dynamic' https://cdn.test {token}");
+ let dynamic_sources: Vec<_> = dynamic_sources.split_ascii_whitespace().collect();
+ assert_eq!(
+ source_list_activates_strict_dynamic(&dynamic_sources),
+ valid,
+ "{dynamic_sources:?}",
+ );
+ }
+ }
+}
+
+#[test]
+fn csp_unsafe_hashes_requires_an_exact_keyword_and_hash_token() {
+ let hash = "'sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps='";
+ for (sources, allowed) in [
+ (format!("'unsafe-hashes' {hash}"), true),
+ (format!("\u{000b}'unsafe-hashes' {hash}"), false),
+ (format!("'unsafe-hashes'\u{000b} {hash}"), false),
+ (format!("'unsafe-hashes' \u{000b}{hash}"), false),
+ (format!("'unsafe-hashes' {hash}\u{000b}"), false),
+ ] {
+ for kind in [
+ ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
+ ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
+ ] {
+ let violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &format!("default-src 'none'; {} {sources}", kind.effective_directive()).into(),
+ &protected_url(), kind, "t1.done();",
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ );
+ assert_eq!(violation.is_none(), allowed, "{kind:?}: {sources:?}");
+ }
+ }
+}
+
+#[test]
+fn csp_report_sample_and_trusted_types_eval_preserve_source_tokens() {
+ for (prefix, suffix, valid) in [
+ ("", "", true),
+ ("\t", "\r\u{000c}", true),
+ ("\u{000b}", "", false),
+ ("", "\u{000b}", false),
+ ] {
+ let policy = format!("default-src 'none'; script-src {prefix}'report-sample'{suffix}");
+ for disposition in [
+ ContentSecurityPolicyDisposition::Enforce,
+ ContentSecurityPolicyDisposition::Report,
+ ] {
+ let violation = content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::Eval,
+ Some("blocked()"),
+ disposition,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+ .expect("report-sample does not authorize evaluation");
+ assert_eq!(violation.original_policy, policy);
+ assert_eq!(violation.disposition, disposition);
+ assert_eq!(
+ violation.sample,
+ if valid { "blocked()" } else { "" },
+ "{policy:?}"
+ );
+ }
+ let policy = format!(
+ "require-trusted-types-for 'script'; script-src {prefix}'trusted-types-eval'{suffix}"
+ );
+ assert_eq!(
+ content_security_policy_allows_trusted_types_eval(std::slice::from_ref(
+ &ContentSecurityPolicy::from(policy.as_str())
+ )),
+ valid,
+ "{policy:?}"
+ );
+ }
+}
+
+#[test]
+fn frame_ancestors_requires_every_ancestor_to_match() {
+ let protected_url = "https://child.test/frame.html";
+ let ancestors = [Some("https://child.test"), Some("https://top.test")];
+
+ let violation =
+ frame_ancestors_violation(&["frame-ancestors 'self'"], protected_url, &ancestors)
+ .expect("a cross-origin top ancestor must violate 'self'");
+ assert_eq!(violation.effective_directive, "frame-ancestors");
+ assert_eq!(violation.blocked_uri, protected_url);
+
+ assert!(frame_ancestors_violation(&["frame-ancestors *"], protected_url, &ancestors).is_none());
+ assert!(
+ frame_ancestors_violation(
+ &["frame-ancestors https://child.test https://top.test"],
+ protected_url,
+ &ancestors,
+ )
+ .is_none()
+ );
+ assert!(
+ frame_ancestors_violation(
+ &["frame-ancestors https://child.test"],
+ protected_url,
+ &ancestors,
+ )
+ .is_some()
+ );
+}
+
+#[test]
+fn frame_ancestors_has_no_fallback_and_allows_top_level_documents() {
+ assert!(
+ frame_ancestors_violation(
+ &["default-src 'none'"],
+ "https://child.test/frame.html",
+ &[Some("https://top.test")],
+ )
+ .is_none()
+ );
+ assert!(
+ frame_ancestors_violation(
+ &["frame-ancestors 'none'"],
+ "https://child.test/frame.html",
+ &[],
+ )
+ .is_none()
+ );
+}
+
+#[test]
+fn every_frame_ancestors_policy_must_allow_embedding() {
+ let violation = frame_ancestors_violation(
+ &["frame-ancestors *", "frame-ancestors 'none'"],
+ "https://child.test/frame.html",
+ &[Some("https://top.test")],
+ )
+ .expect("one blocking policy must block the response");
+ assert_eq!(violation.original_policy, "frame-ancestors 'none'");
+}
+
+#[test]
+fn frame_ancestors_matches_origins_and_rejects_opaque_ancestors() {
+ assert!(
+ frame_ancestors_violation(
+ &["frame-ancestors https://top.test/path"],
+ "https://child.test/frame.html",
+ &[Some("https://top.test")],
+ )
+ .is_some(),
+ "a host source containing a path must not match an ancestor origin"
+ );
+ assert!(
+ frame_ancestors_violation(
+ &["frame-ancestors *"],
+ "https://child.test/frame.html",
+ &[None],
+ )
+ .is_some(),
+ "an opaque ancestor origin must not match a source expression"
+ );
+}
+
+#[test]
+fn worker_src_none_blocks_shared_worker_script() {
+ assert!(!allowed(
+ "worker-src 'none'; script-src 'self'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+}
+
+#[test]
+fn shared_worker_script_uses_script_src_and_default_src_fallbacks() {
+ assert!(!allowed(
+ "script-src 'none'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+ assert!(!allowed(
+ "default-src 'none'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+ assert!(allowed(
+ "default-src 'self'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+}
+
+#[test]
+fn shared_worker_script_uses_child_src_before_script_src_fallback() {
+ assert!(!allowed(
+ "child-src 'none'; script-src 'self'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+ assert!(allowed(
+ "child-src https://workers.test; script-src 'none'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://workers.test/worker.js"
+ ));
+}
+
+#[test]
+fn document_script_element_uses_script_src_elem_fallbacks() {
+ assert!(!allowed(
+ "script-src-elem 'none'; script-src 'self'",
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ "https://app.test/app.js"
+ ));
+ assert!(allowed(
+ "script-src 'self'; default-src 'none'",
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ "https://app.test/app.js"
+ ));
+ assert!(!allowed(
+ "default-src 'none'",
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ "https://app.test/app.js"
+ ));
+}
+
+#[test]
+fn worker_src_takes_precedence_for_shared_worker_scripts() {
+ assert!(allowed(
+ "default-src 'none'; script-src 'none'; worker-src 'self'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+ assert!(!allowed(
+ "default-src *; script-src *; worker-src 'none'",
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ "https://app.test/worker.js"
+ ));
+}
+
+#[test]
+fn url_violation_reports_effective_directive_and_original_policy() {
+ let violation = content_security_policy_url_violation_with_redirect_status(
+ &[
+ "connect-src https://api.test".into(),
+ "default-src 'none'".into(),
+ ],
+ &protected_url(),
+ &request_url("https://blocked.test/data.json"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+ .expect("blocked worker connect should produce violation");
+
+ assert_eq!(violation.effective_directive, "connect-src");
+ assert_eq!(violation.blocked_uri, "https://blocked.test/data.json");
+ assert_eq!(violation.document_uri, "https://app.test/page.html");
+ assert_eq!(violation.original_policy, "connect-src https://api.test");
+ assert_eq!(
+ violation.disposition,
+ ContentSecurityPolicyDisposition::Enforce
+ );
+}
+
+#[test]
+fn url_violation_strips_credentials_and_fragments_from_report_urls() {
+ let protected_url =
+ request_url("https://user:[email protected]/page.html?document=1#current-section");
+ let blocked_url =
+ request_url("https://other:[email protected]/image.png?asset=1#pixel-fragment");
+ let violation = content_security_policy_url_violation_with_redirect_status(
+ &["img-src 'none'".into()],
+ &protected_url,
+ &blocked_url,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+ .expect("blocked image should produce violation");
+
+ assert_eq!(
+ violation.document_uri,
+ "https://app.test/page.html?document=1"
+ );
+ assert_eq!(
+ violation.blocked_uri,
+ "https://blocked.test/image.png?asset=1"
+ );
+ assert_eq!(
+ violation.source_file,
+ "https://app.test/page.html?document=1"
+ );
+}
+
+#[test]
+fn url_violation_redacts_data_and_blob_urls_to_their_schemes() {
+ for (policy, url, expected) in [
+ ("media-src 'self'", "data:video/mp4;base64,AAAA", "data"),
+ (
+ "media-src https://example.com",
+ "blob:https://app.test/id",
+ "blob",
+ ),
+ ] {
+ let violation = content_security_policy_url_violation_with_redirect_status(
+ &[policy.to_owned().into()],
+ &protected_url(),
+ &request_url(url),
+ ContentSecurityPolicyResourceKind::DocumentMedia,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+ .expect("blocked media URL should produce violation");
+
+ assert_eq!(violation.effective_directive, "media-src");
+ assert_eq!(violation.blocked_uri, expected);
+ }
+}
+
+#[test]
+fn redirected_url_violation_reports_original_blocked_uri() {
+ let original_url = request_url("https://app.test/redirect");
+ let final_url = request_url("https://blocked.test/data.json");
+ let violation = content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints(
+ &["connect-src 'self'".into()],
+ &protected_url(),
+ &final_url,
+ &original_url,
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyRedirectStatus::FollowedRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+ .expect("redirected blocked worker connect should produce violation");
+
+ assert_eq!(violation.effective_directive, "connect-src");
+ assert_eq!(violation.blocked_uri, "https://app.test/redirect");
+}
+
+#[test]
+fn self_source_matches_same_origin_only() {
+ assert!(allowed(
+ "script-src 'self'",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://app.test/worker-import.js"
+ ));
+ assert!(!allowed(
+ "script-src 'self'",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://cdn.test/worker-import.js"
+ ));
+}
+
+#[test]
+fn worker_module_imports_use_their_request_specific_directive_fallbacks() {
+ let cross_origin = "https://cdn.test/worker-import.js";
+
+ assert!(!allowed(
+ "worker-src 'self'; script-src *",
+ ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
+ cross_origin,
+ ));
+ assert!(allowed(
+ "worker-src *; script-src 'self'",
+ ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
+ cross_origin,
+ ));
+ assert!(!allowed(
+ "script-src-elem 'self'; script-src *",
+ ContentSecurityPolicyResourceKind::WorkerDynamicModuleImport,
+ cross_origin,
+ ));
+ assert!(allowed(
+ "worker-src 'self'; script-src *",
+ ContentSecurityPolicyResourceKind::WorkerDynamicModuleImport,
+ cross_origin,
+ ));
+
+ let violation = content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ &["script-src 'self'".into()],
+ &protected_url(),
+ &request_url(cross_origin),
+ ContentSecurityPolicyResourceKind::WorkerDynamicModuleImport,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+ .expect("script-src fallback should block the cross-origin dynamic import");
+ assert_eq!(violation.effective_directive, "script-src-elem");
+}
+
+#[test]
+fn self_source_uses_csp_secure_upgrade_rules() {
+ let protected = Url::parse("http://app.test/page.html").unwrap();
+ assert!(content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &protected,
+ &request_url("https://app.test/api"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ));
+ assert!(content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &protected,
+ &request_url("ws://app.test/socket"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ));
+ assert!(content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &protected,
+ &request_url("wss://app.test/socket"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ));
+
+ let protected = Url::parse("https://app.test/page.html").unwrap();
+ assert!(content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &protected,
+ &request_url("wss://app.test/socket"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ));
+ assert!(!content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &protected,
+ &request_url("ws://app.test/socket"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ));
+ assert!(!content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &Url::parse("http://app.test/page.html").unwrap(),
+ &request_url("ftp://app.test/resource"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ));
+}
+
+#[test]
+fn connect_src_and_default_src_control_worker_connect_requests() {
+ assert!(!allowed(
+ "connect-src 'none'",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "https://app.test/api"
+ ));
+ assert!(!allowed(
+ "default-src 'none'",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "https://app.test/api"
+ ));
+ assert!(allowed(
+ "connect-src 'self'; default-src 'none'",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "https://app.test/api"
+ ));
+}
+
+#[test]
+fn wildcard_source_does_not_match_local_schemes() {
+ assert!(allowed(
+ "script-src *",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://app.test/worker-import.js"
+ ));
+ assert!(!allowed(
+ "script-src *",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "data:text/javascript,onconnect=()=>{}"
+ ));
+}
+
+#[test]
+fn scheme_sources_use_csp_secure_upgrade_rules() {
+ assert!(allowed(
+ "connect-src http:",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "https://cdn.test/api"
+ ));
+ assert!(allowed(
+ "connect-src ws:",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "wss://cdn.test/socket"
+ ));
+ assert!(!allowed(
+ "connect-src https:",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "wss://cdn.test/socket"
+ ));
+ assert!(!allowed(
+ "connect-src http:",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "ws://cdn.test/socket"
+ ));
+}
+
+#[test]
+fn websocket_source_schemes_match_http_without_allowing_reverse_transitions() {
+ for (source_scheme, matches) in [
+ ("http", [true, true, false, false]),
+ ("https", [false, true, false, false]),
+ ("ws", [true, true, true, true]),
+ ("wss", [false, true, false, true]),
+ ] {
+ for (request_scheme, expected) in ["http", "https", "ws", "wss"].into_iter().zip(matches) {
+ for kind in [
+ ContentSecurityPolicyResourceKind::DocumentConnect,
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ] {
+ for scheme in [source_scheme.to_owned(), source_scheme.to_ascii_uppercase()] {
+ let request = format!("{request_scheme}://cdn.test:8443/socket");
+ for source in [
+ format!("{scheme}:"),
+ format!("{scheme}://cdn.test:*/socket"),
+ format!("{scheme}://*.test:*/socket"),
+ ] {
+ assert_eq!(
+ allowed(&format!("connect-src {source}"), kind, &request),
+ expected,
+ "{source} with {request} for {kind:?}",
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn websocket_to_http_host_sources_preserve_port_host_and_path_checks() {
+ for authority in ["cdn.test", "*.test"] {
+ for (source_scheme, source_port, request, expected) in [
+ ("ws", "", "http://cdn.test/socket", true),
+ ("ws", ":80", "http://cdn.test/socket", true),
+ ("ws", ":8080", "http://cdn.test:8080/socket", true),
+ ("ws", ":8080", "http://cdn.test:8081/socket", false),
+ ("ws", "", "https://cdn.test/socket", true),
+ ("wss", "", "https://cdn.test/socket", true),
+ ("wss", ":443", "https://cdn.test/socket", true),
+ ("wss", ":8443", "https://cdn.test:8443/socket", true),
+ ("wss", ":8443", "https://cdn.test:9443/socket", false),
+ ("ws", ":*", "https://other.example:8443/socket", false),
+ ("ws", ":*", "https://cdn.test:8443/other", false),
+ ("wss", ":*", "http://cdn.test:8443/socket", false),
+ ] {
+ let policy = format!("connect-src {source_scheme}://{authority}{source_port}/socket");
+ for kind in [
+ ContentSecurityPolicyResourceKind::DocumentConnect,
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ] {
+ assert_eq!(
+ allowed(&policy, kind, request),
+ expected,
+ "{policy} with {request}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn websocket_scheme_compatibility_does_not_make_self_origins_equal() {
+ for (protected, request, expected) in [
+ ("ws://app.test/", "ws://app.test/socket", true),
+ ("ws://app.test/", "http://app.test/socket", false),
+ ("ws://app.test/", "https://app.test/socket", true),
+ ("wss://app.test/", "https://app.test/socket", true),
+ ("wss://app.test/", "http://app.test/socket", false),
+ ] {
+ assert_eq!(
+ content_security_policy_allows_url(
+ &["connect-src 'self'".into()],
+ &Url::parse(protected).unwrap(),
+ &request_url(request),
+ ContentSecurityPolicyResourceKind::DocumentConnect,
+ ),
+ expected,
+ "'self' in {protected} with {request}",
+ );
+ }
+}
+
+#[test]
+fn source_path_matching_uses_encoded_paths() {
+ assert!(allowed(
+ "script-src https://app.test/trusted/",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://app.test/trusted/worker.js"
+ ));
+ assert!(!allowed(
+ "script-src https://app.test/trusted/",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://app.test/trusted%2Fevil.js"
+ ));
+}
+
+#[test]
+fn host_sources_reject_scheme_relative_urls() {
+ for source in ["//cdn.test", "//cdn.test:*", "//*.test", "//*.test:*"] {
+ for scheme in ["https", "http"] {
+ assert!(!allowed(
+ &format!("script-src {source}"),
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ &format!("{scheme}://cdn.test/app.js")
+ ));
+ }
+ }
+}
+
+#[test]
+fn invalid_host_sources_cannot_allow_initial_or_redirected_requests() {
+ for (source, request) in [
+ (
+ "https://cdn.test:*/foo,bar",
+ "https://cdn.test:8443/foo,bar",
+ ),
+ ("https://*.test/foo,bar", "https://cdn.test/foo,bar"),
+ ("https://cdn.test/foo,bar", "https://cdn.test/foo,bar"),
+ ("https://[email protected]", "https://cdn.test/asset"),
+ ("https://%63dn.test", "https://cdn.test/asset"),
+ ("https://bad_host.test", "https://bad_host.test/asset"),
+ (
+ "https://*.bad_host.test:*",
+ "https://cdn.bad_host.test:8443/asset",
+ ),
+ ("https://bad..test", "https://bad..test/asset"),
+ ("https://*.test..:*", "https://cdn.test:8443/asset"),
+ ("https://cdn.test:", "https://cdn.test/asset"),
+ ("https://cdn.test:+443", "https://cdn.test/asset"),
+ ("https://cdn.test:65536", "https://cdn.test/asset"),
+ ("https://cdn.test/%", "https://cdn.test/%"),
+ ("https://cdn.test:*/%6g", "https://cdn.test:8443/%6g"),
+ ("https://*.test/%a", "https://cdn.test/%a"),
+ ("https://cdn.test//asset", "https://cdn.test//asset"),
+ (
+ "https://cdn.test/asset\\file",
+ "https://cdn.test/asset/file",
+ ),
+ ("https://cdn.test/[asset]", "https://cdn.test/[asset]"),
+ ("https://cdn.test/asset\u{000b}", "https://cdn.test/asset"),
+ ("\u{000b}https://cdn.test", "https://cdn.test/asset"),
+ ("https://127.1", "https://127.0.0.1/asset"),
+ ] {
+ for redirect_status in [
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyRedirectStatus::FollowedRedirect,
+ ] {
+ assert!(
+ !source_expression_matches(
+ source,
+ &protected_url(),
+ &request_url(request),
+ redirect_status,
+ ),
+ "{source:?} must not match {request:?} ({redirect_status:?})"
+ );
+ assert!(
+ !content_security_policy_allows_url_with_redirect_status(
+ &[format!("default-src 'none'; img-src {source}").into()],
+ &protected_url(),
+ &request_url(request),
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ redirect_status,
+ ),
+ "{source:?} must not allow {request:?} ({redirect_status:?})"
+ );
+ }
+ }
+}
+
+#[test]
+fn host_source_paths_decode_segments_for_exact_and_wildcard_sources() {
+ for authority in ["cdn.test", "cdn.test:*", "*.test", "*.test:*", "*", "*:*"] {
+ for (source_path, request_path, expected) in [
+ ("/%61sset", "/asset", true),
+ ("/asset", "/%61sset", true),
+ ("/%61sset/", "/asset/file", true),
+ ("/%61sset/", "/asset", false),
+ ("/asset", "/ASSET", false),
+ ("/asset", "/asset/", false),
+ ("/a%2fb", "/a%2Fb", true),
+ ("/a%2fb", "/a/b", false),
+ ("/a/", "/a%2Fb", false),
+ ("/a/", "/a//b", true),
+ ("/a//", "/a/b", false),
+ ("/a%252fb", "/a%2fb", false),
+ ("/a+b", "/a%20b", false),
+ ("/a%2bb", "/a+b", true),
+ ("/a%2cb", "/a,b", true),
+ ("/a%3bb", "/a;b", true),
+ ("/%ff", "/%FF", true),
+ ("/%ff", "/%fe", false),
+ ("/%e4%b8%ad", "/中", true),
+ ("/a/../asset", "/asset", false),
+ ("/a/%2e%2e/asset", "/asset", false),
+ ("/./asset", "/asset", false),
+ ("/path://asset", "/path://asset", true),
+ ] {
+ let policy = format!("img-src https://{authority}{source_path}");
+ let request = format!("https://cdn.test{request_path}");
+ assert_eq!(
+ allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ &request
+ ),
+ expected,
+ "{policy} with {request}"
+ );
+ }
+ }
+}
+
+#[test]
+fn valid_host_source_grammar_preserves_ports_and_raw_hostnames() {
+ for (source, request, expected) in [
+ ("HTTPS://CDN.TEST:00443", "https://cdn.test/asset", true),
+ (
+ "cdn.test/path://asset",
+ "https://cdn.test/path://asset",
+ true,
+ ),
+ ("https://cdn.test:0", "https://cdn.test:0/asset", true),
+ (
+ "https://cdn.test:65535",
+ "https://cdn.test:65535/asset",
+ true,
+ ),
+ (
+ "https://xn--bcher-kva.test",
+ "https://bücher.test/asset",
+ true,
+ ),
+ ("https://*.TEST.", "https://cdn.test./asset", true),
+ ("https://*.TEST.", "https://cdn.test/asset", false),
+ ("https://*.test", "https://cdn.test./asset", false),
+ ("ftp://cdn.test", "ftp://cdn.test/asset", true),
+ ("https://192.0.2.1", "https://192.0.2.1/asset", true),
+ (
+ "https://192.0.2.1:8443",
+ "https://192.0.2.1:8443/asset",
+ true,
+ ),
+ ] {
+ assert_eq!(
+ allowed(
+ &format!("img-src {source}"),
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ request
+ ),
+ expected,
+ "{source} with {request}"
+ );
+ }
+}
+
+#[test]
+fn csp_path_matching_preserves_empty_segments_and_byte_boundaries() {
+ for (source, request, expected) in [
+ ("", "", true),
+ ("", "/asset", true),
+ ("/", "", true),
+ ("/", "/asset", true),
+ ("/a/", "/a", false),
+ ("/a/", "/a/", true),
+ ("/a//", "/a/", false),
+ ("/a//", "/a//b", true),
+ ("/a%2fb/", "/a/b/file", false),
+ ("/a%2fb/", "/a%2Fb/file", true),
+ ("/%00", "/%00", true),
+ ("/%00", "/", false),
+ ("/%ff", "/%fe", false),
+ ] {
+ assert_eq!(
+ csp_path_part_matches(source, request),
+ expected,
+ "{source:?} with {request:?}"
+ );
+ }
+}
+
+#[test]
+fn host_sources_reject_query_and_fragment_components() {
+ assert!(!allowed(
+ "script-src https://cdn.test?ignored",
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ "https://cdn.test/app.js"
+ ));
+ assert!(!allowed(
+ "script-src https://cdn.test/app.js#fragment",
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ "https://cdn.test/app.js"
+ ));
+}
+
+#[test]
+fn redirected_source_url_matching_ignores_path_but_not_host() {
+ assert!(content_security_policy_allows_url_with_redirect_status(
+ &["script-src https://cdn.test/trusted/".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/evil.js"),
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ ContentSecurityPolicyRedirectStatus::FollowedRedirect,
+ ));
+ assert!(!content_security_policy_allows_url_with_redirect_status(
+ &["script-src https://cdn.test/trusted/".into()],
+ &protected_url(),
+ &request_url("https://evil.test/evil.js"),
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ ContentSecurityPolicyRedirectStatus::FollowedRedirect,
+ ));
+}
+
+#[test]
+fn wildcard_host_source_matches_subdomains_only() {
+ assert!(allowed(
+ "script-src *.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://assets.cdn.example.com/worker-import.js"
+ ));
+ assert!(allowed(
+ "script-src https://*.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://assets.cdn.example.com/worker-import.js"
+ ));
+ assert!(!allowed(
+ "script-src *.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://cdn.example.com/worker-import.js"
+ ));
+ assert!(!allowed(
+ "script-src *.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://evilcdn.example.com/worker-import.js"
+ ));
+}
+
+#[test]
+fn wildcard_host_source_honors_port_and_path() {
+ assert!(allowed(
+ "script-src https://*.cdn.example.com:*",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://assets.cdn.example.com:8443/worker-import.js"
+ ));
+ assert!(!allowed(
+ "script-src https://*.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://assets.cdn.example.com:8443/worker-import.js"
+ ));
+ assert!(allowed(
+ "script-src https://*.cdn.example.com/trusted/",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://assets.cdn.example.com/trusted/worker-import.js"
+ ));
+ assert!(!allowed(
+ "script-src https://*.cdn.example.com/trusted/",
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ "https://assets.cdn.example.com/trusted%2Fevil.js"
+ ));
+}
+
+#[test]
+fn exact_host_port_wildcards_apply_across_resource_kinds() {
+ for kind in [
+ ContentSecurityPolicyResourceKind::DocumentConnect,
+ ContentSecurityPolicyResourceKind::DocumentFrame,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ ContentSecurityPolicyResourceKind::DocumentManifest,
+ ContentSecurityPolicyResourceKind::DocumentMedia,
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ ContentSecurityPolicyResourceKind::DocumentStyleElement,
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ ContentSecurityPolicyResourceKind::SharedWorkerScript,
+ ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
+ ] {
+ for source in ["https://cdn.test:*", "http://cdn.test:*", "CDN.TEST:*"] {
+ for port in ["", ":0", ":80", ":443", ":8443", ":65535"] {
+ let policy = format!("default-src {source}");
+ let request = format!("https://cdn.test{port}/asset");
+ assert!(
+ allowed(&policy, kind, &request),
+ "{policy} should allow {request} for {kind:?}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn exact_host_port_wildcards_preserve_other_source_restrictions() {
+ for (source, request, expected) in [
+ ("http://cdn.test:*", "http://cdn.test:8080/asset", true),
+ ("https://CDN.TEST:*", "https://cdn.test:8443/asset", true),
+ ("cdn.test:*", "https://cdn.test:8443/asset", true),
+ ("cdn.test:*", "http://cdn.test:8080/asset", false),
+ (
+ "https://cdn.test:*",
+ "https://sub.cdn.test:8443/asset",
+ false,
+ ),
+ (
+ "https://cdn.test:*",
+ "https://evilcdn.test:8443/asset",
+ false,
+ ),
+ ("https://cdn.test.:*", "https://cdn.test:8443/asset", false),
+ ("https://cdn.test.:*", "https://cdn.test.:8443/asset", true),
+ ("https://cdn.test:*", "http://cdn.test:8080/asset", false),
+ ("http://cdn.test:*", "ws://cdn.test:8080/asset", false),
+ ("ws://cdn.test:*", "wss://cdn.test:8443/asset", true),
+ ("wss://cdn.test:*", "ws://cdn.test:8080/asset", false),
+ (
+ "https://cdn.test:*/trusted/",
+ "https://cdn.test:8443/trusted/asset",
+ true,
+ ),
+ (
+ "https://cdn.test:*/trusted/",
+ "https://cdn.test:8443/trusted%2Fevil",
+ false,
+ ),
+ (
+ "https://cdn.test:*/trusted/",
+ "https://cdn.test:8443/other/asset",
+ false,
+ ),
+ (
+ "https://cdn.test:*/asset",
+ "https://cdn.test:8443/asset?cache=1",
+ true,
+ ),
+ (
+ "https://cdn.test:*/asset",
+ "https://cdn.test:8443/asset/extra",
+ false,
+ ),
+ (
+ "https://cdn.test:*/asset",
+ "https://cdn.test:8443/ASSET",
+ false,
+ ),
+ ("//cdn.test:*", "https://cdn.test:8443/asset", false),
+ (
+ "https://[email protected]:*",
+ "https://cdn.test:8443/asset",
+ false,
+ ),
+ ("https://%63dn.test:*", "https://cdn.test:8443/asset", false),
+ (
+ "https://cdn.test:*/asset?ignored",
+ "https://cdn.test:8443/asset",
+ false,
+ ),
+ (
+ "https://cdn.test:*/asset#ignored",
+ "https://cdn.test:8443/asset",
+ false,
+ ),
+ ("https://cdn.test:*0", "https://cdn.test:8443/asset", false),
+ (
+ "https://bad_host.test:*",
+ "https://bad_host.test:8443/asset",
+ false,
+ ),
+ (
+ "https://bad..host.test:*",
+ "https://bad..host.test:8443/asset",
+ false,
+ ),
+ ("https://127.0.0.1:*", "https://127.0.0.1:8443/asset", true),
+ ("https://192.0.2.1:*", "https://192.0.2.1:8443/asset", false),
+ ("https://[::1]:*", "https://[::1]:8443/asset", false),
+ ] {
+ let policy = format!("img-src {source}");
+ assert_eq!(
+ allowed(
+ &policy,
+ ContentSecurityPolicyResourceKind::DocumentImage,
+ request
+ ),
+ expected,
+ "{policy} with {request}"
+ );
+ }
+}
+
+#[test]
+fn exact_host_port_wildcards_preserve_redirect_restrictions() {
+ for (request, expected) in [
+ ("https://cdn.test:9443/other/asset", true),
+ ("https://other.test:9443/other/asset", false),
+ ("http://cdn.test:8080/other/asset", false),
+ ] {
+ assert_eq!(
+ content_security_policy_allows_url_with_redirect_status(
+ &["script-src https://cdn.test:*/trusted/".into()],
+ &protected_url(),
+ &request_url(request),
+ ContentSecurityPolicyResourceKind::DocumentScriptElement,
+ ContentSecurityPolicyRedirectStatus::FollowedRedirect,
+ ),
+ expected,
+ "a redirected wildcard-port request must still match scheme and host: {request}"
+ );
+ }
+}
+
+#[test]
+fn host_sources_use_csp_secure_upgrade_rules() {
+ assert!(allowed(
+ "connect-src http://api.example.com",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "https://api.example.com/socket"
+ ));
+ assert!(allowed(
+ "connect-src ws://api.example.com",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "wss://api.example.com/socket"
+ ));
+ assert!(!allowed(
+ "connect-src https://api.example.com",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "wss://api.example.com/socket"
+ ));
+ assert!(!allowed(
+ "connect-src http://api.example.com",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "https://api.example.com:80/socket"
+ ));
+}
+
+#[test]
+fn wildcard_host_sources_use_csp_secure_upgrade_rules() {
+ assert!(allowed(
+ "connect-src ws://*.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "wss://assets.cdn.example.com/socket"
+ ));
+ assert!(!allowed(
+ "connect-src https://*.cdn.example.com",
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ "wss://assets.cdn.example.com/socket"
+ ));
+}
+
+#[test]
+fn all_policies_are_enforced() {
+ let result = ensure_content_security_policy_allows_url(
+ &["script-src 'self'".into(), "script-src 'none'".into()],
+ &protected_url(),
+ &request_url("https://app.test/worker-import.js"),
+ ContentSecurityPolicyResourceKind::WorkerScript,
+ || "blocked".to_owned(),
+ );
+
+ assert!(result.is_err());
+}
+
+#[test]
+fn script_element_nonce_source_allows_external_script_url() {
+ let violation =
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &["script-src 'nonce-abc'".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyScriptElementRequest::parser_inserted_with_nonce(Some("abc")),
+ );
+
+ assert!(
+ violation.is_none(),
+ "matching script nonce should allow the script element request"
+ );
+}
+
+#[test]
+fn style_element_request_uses_style_src_elem_fallbacks_and_nonce() {
+ let protected_url = Url::parse("https://example.test/page").unwrap();
+ let request_url = Url::parse("https://cdn.test/app.css").unwrap();
+ let check = |policy: &str, nonce: Option<&str>| {
+ content_security_policy_style_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &[policy.to_owned().into()],
+ &protected_url,
+ &request_url,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyStyleElementRequest { nonce },
+ )
+ };
+
+ assert!(check("style-src https://cdn.test", None).is_none());
+ assert!(check("default-src https://cdn.test", None).is_none());
+ let violation = check("style-src-elem 'none'; style-src https://cdn.test", None)
+ .expect("style-src-elem must take precedence over style-src");
+ assert_eq!(violation.effective_directive, "style-src-elem");
+ assert!(
+ check(
+ "style-src-elem 'nonce-allowed'; style-src 'none'",
+ Some("allowed")
+ )
+ .is_none(),
+ "a matching link nonce must authorize the external style request"
+ );
+ assert!(
+ check(
+ "style-src-elem 'nonce-allowed'; style-src https://cdn.test",
+ Some("blocked")
+ )
+ .is_some(),
+ "a non-matching nonce must not bypass the operative style-src-elem directive"
+ );
+}
+
+#[test]
+fn script_element_strict_dynamic_allows_non_parser_inserted_script() {
+ let violation =
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &["script-src 'strict-dynamic' 'nonce-abc'".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: None,
+ parser_inserted: false,
+ },
+ );
+
+ assert!(
+ violation.is_none(),
+ "strict-dynamic should allow script elements inserted by a running trusted script"
+ );
+}
+
+#[test]
+fn script_element_strict_dynamic_blocks_parser_inserted_host_source_without_nonce() {
+ let violation =
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &["script-src 'strict-dynamic' 'nonce-abc' https://cdn.test".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: None,
+ parser_inserted: true,
+ },
+ )
+ .expect("parser-inserted script without nonce should be blocked");
+
+ assert_eq!(violation.effective_directive, "script-src-elem");
+}
+
+#[test]
+fn script_element_integrity_hash_source_allows_external_script_url() {
+ let violation =
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &["script-src 'ShA256-testdigest'".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: Some("sha256-testdigest"),
+ parser_inserted: true,
+ },
+ );
+
+ assert!(
+ violation.is_none(),
+ "matching integrity metadata should satisfy a CSP hash source regardless of algorithm case"
+ );
+}
+
+#[test]
+fn script_element_integrity_requires_every_supported_hash_in_the_source_list() {
+ for directive in ["script-src-elem", "script-src", "default-src"] {
+ let policy = format!("{directive} 'ShA256-testdigest' 'sha384-strong' 'sha512-other'");
+ for (integrity, expected) in [
+ ("sha256-testdigest sha384-strong", true),
+ ("sha256-testdigest sha256-testdigest", true),
+ ("sha512-other sha384-strong sha256-testdigest", true),
+ ("sha256-testdigest sha256-unknown", false),
+ ("sha256-unknown sha256-testdigest", false),
+ ("sha256-testdigest sha512-unknown", false),
+ ("sha256-unknown sha384-strong", false),
+ ] {
+ assert_eq!(
+ script_element_request_allowed(
+ &policy,
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: Some(integrity),
+ parser_inserted: true,
+ },
+ ),
+ expected,
+ "{policy}: {integrity}"
+ );
+ }
+ }
+}
+
+#[test]
+fn script_element_integrity_uses_nonempty_parsed_sri_metadata() {
+ for (integrity, expected) in [
+ (None, false),
+ (Some(" \t\r\n\x0c"), false),
+ (Some("sha1-ignored sha512-***"), false),
+ (Some("sha256-***"), false),
+ (Some("SHA256-testdigest"), false),
+ (Some("sha256-testdigest\u{a0}"), false),
+ (Some("sha256-testdigest sha1-ignored"), true),
+ (Some("sha256-testdigest sha512-***"), true),
+ (Some("sha256-testdigest sha512-*** sha512-abc==="), false),
+ (Some("sha256-testdigest sha512-A=AAA"), false),
+ (Some("sha256-testdigest sha512-===="), false),
+ (Some("sha256-testdigest?ignored sha-256-testdigest"), true),
+ (Some(" \tsha256-testdigest\r\n\x0csha256-testdigest "), true),
+ ] {
+ assert_eq!(
+ script_element_request_allowed(
+ "script-src 'sha256-testdigest' 'sha256-***'",
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity,
+ parser_inserted: true,
+ },
+ ),
+ expected,
+ "{integrity:?}"
+ );
+ }
+}
+
+#[test]
+fn script_element_integrity_compares_encoded_digests_literally() {
+ for (source, integrity, expected) in [
+ ("'sha256-YQ=='", "sha256-YQ==", true),
+ ("'sha256-YQ=='", "sha256-YQ", false),
+ ("'sha256-+w=='", "sha256--w==", false),
+ ("'sha256--w=='", "sha256-+w==", false),
+ ("'sha256--w=='", "sha256--w==", true),
+ ("'sha256-/w=='", "sha256-_w==", false),
+ ("'sha256-_w=='", "sha256-/w==", false),
+ ("'sha256-YR=='", "sha256-YR==", true),
+ ] {
+ assert_eq!(
+ script_element_request_allowed(
+ &format!("script-src {source}"),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: Some(integrity),
+ parser_inserted: true,
+ },
+ ),
+ expected,
+ "{source}: {integrity}"
+ );
+ }
+}
+
+#[test]
+fn partial_integrity_match_preserves_other_script_authorizations() {
+ for (other_sources, nonce, parser_inserted, expected) in [
+ ("'nonce-allowed'", Some("allowed"), true, true),
+ ("https://cdn.test", None, true, true),
+ ("'strict-dynamic'", None, false, true),
+ ("'strict-dynamic' https://cdn.test", None, true, false),
+ ] {
+ assert_eq!(
+ script_element_request_allowed(
+ &format!("script-src 'sha256-testdigest' {other_sources}"),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce,
+ integrity: Some("sha256-testdigest sha256-unknown"),
+ parser_inserted,
+ },
+ ),
+ expected,
+ "{other_sources}: nonce={nonce:?}, parser_inserted={parser_inserted}"
+ );
+ }
+}
+
+#[test]
+fn script_src_elem_directive_controls_strict_dynamic_script_element_requests() {
+ let allowed =
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &["script-src-elem 'strict-dynamic' 'nonce-abc'; script-src 'nonce-abc'".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: None,
+ parser_inserted: false,
+ },
+ );
+ assert!(
+ allowed.is_none(),
+ "script-src-elem strict-dynamic should control script element requests"
+ );
+
+ let violation =
+ content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
+ &["script-src 'strict-dynamic' 'nonce-abc'; script-src-elem 'nonce-abc'".into()],
+ &protected_url(),
+ &request_url("https://cdn.test/script.js"),
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: None,
+ parser_inserted: false,
+ },
+ )
+ .expect("script-src-elem without strict-dynamic should block this request");
+
+ assert_eq!(violation.effective_directive, "script-src-elem");
+}
+
+#[test]
+fn report_uri_endpoints_resolve_against_protected_url() {
+ let endpoints = content_security_policy_report_uri_endpoints(
+ &ContentSecurityPolicy::from(
+ "connect-src 'none'; report-uri /csp-report https://reports.test/collect",
+ ),
+ &protected_url(),
+ );
+
+ assert_eq!(
+ endpoints,
+ vec![
+ "https://app.test/csp-report".to_owned(),
+ "https://reports.test/collect".to_owned()
+ ]
+ );
+}
+
+#[test]
+fn report_to_suppresses_legacy_report_uri_transport() {
+ let endpoints = content_security_policy_report_uri_endpoints(
+ &ContentSecurityPolicy::from("connect-src 'none'; report-uri /legacy; report-to default"),
+ &protected_url(),
+ );
+
+ assert!(endpoints.is_empty());
+}
+
+#[test]
+fn reporting_endpoints_header_resolves_groups_against_protected_url() {
+ let endpoints = content_security_policy_reporting_endpoints_from_headers(
+ &[
+ (
+ "Reporting-Endpoints".to_owned(),
+ b"default=\"/reports\", csp=\"https://reports.test/csp\"".to_vec(),
+ ),
+ (
+ "reporting-endpoints".to_owned(),
+ b"default=\"/override\", ignored=ftp://reports.test/nope".to_vec(),
+ ),
+ ],
+ &protected_url(),
+ );
+
+ assert_eq!(
+ endpoints.endpoint_for_group("default"),
+ Some("https://app.test/override")
+ );
+ assert_eq!(
+ endpoints.endpoint_for_group("csp"),
+ Some("https://reports.test/csp")
+ );
+ assert_eq!(endpoints.endpoint_for_group("ignored"), None);
+}
+
+#[test]
+fn report_to_uses_first_group_endpoint_and_suppresses_report_uri() {
+ let reporting_endpoints = content_security_policy_reporting_endpoints_from_headers(
+ &[(
+ "Reporting-Endpoints".to_owned(),
+ b"primary=\"/reports/primary\", secondary=\"/reports/secondary\"".to_vec(),
+ )],
+ &protected_url(),
+ );
+ let violation =
+ content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ &[
+ "connect-src 'none'; report-uri /legacy; report-to primary secondary"
+ .to_owned().into(),
+ ],
+ &protected_url(),
+ &request_url("https://api.test/data.json"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .expect("blocked URL should produce violation");
+
+ assert!(violation.report_uri_endpoints.is_empty());
+ assert_eq!(
+ violation.report_to_endpoints,
+ vec!["https://app.test/reports/primary".to_owned()]
+ );
+}
+
+#[test]
+fn violation_report_body_uses_csp_report_shape() {
+ let violation = content_security_policy_url_violation_with_redirect_status(
+ &["connect-src 'none'; report-uri /csp-report".into()],
+ &protected_url(),
+ &request_url("https://api.test/data.json"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+ .expect("blocked URL should produce violation");
+ let body = content_security_policy_violation_report_body(
+ &ContentSecurityPolicyViolationEventFields::from_url_violation(&violation),
+ );
+ let value: serde_json::Value = serde_json::from_str(&body).expect("report body JSON");
+
+ assert_eq!(
+ value,
+ serde_json::json!({
+ "csp-report": {
+ "document-uri": "https://app.test/page.html",
+ "referrer": "",
+ "violated-directive": "connect-src",
+ "effective-directive": "connect-src",
+ "original-policy": "connect-src 'none'; report-uri /csp-report",
+ "disposition": "enforce",
+ "blocked-uri": "https://api.test/data.json",
+ "source-file": "https://app.test/page.html",
+ "status-code": 0,
+ "script-sample": "",
+ }
+ })
+ );
+ assert_eq!(
+ violation.report_uri_endpoints,
+ vec!["https://app.test/csp-report".to_owned()]
+ );
+}
+
+#[test]
+fn reporting_api_report_body_uses_csp_violation_shape() {
+ let violation = content_security_policy_url_violation_with_redirect_status(
+ &["connect-src 'none'".into()],
+ &protected_url(),
+ &request_url("https://api.test/data.json"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ )
+ .expect("blocked URL should produce violation");
+ let body = content_security_policy_reporting_api_report_body(
+ &ContentSecurityPolicyViolationEventFields::from_url_violation(&violation),
+ );
+ let value: serde_json::Value = serde_json::from_str(&body).expect("report body JSON");
+
+ assert_eq!(value[0]["type"], "csp-violation");
+ assert_eq!(value[0]["url"], "https://app.test/page.html");
+ assert_eq!(
+ value[0]["body"]["documentURL"],
+ "https://app.test/page.html"
+ );
+ assert_eq!(value[0]["body"]["blockedURL"], "https://api.test/data.json");
+ assert_eq!(value[0]["body"]["effectiveDirective"], "connect-src");
+ assert_eq!(value[0]["body"]["originalPolicy"], "connect-src 'none'");
+ assert_eq!(value[0]["body"]["disposition"], "enforce");
+}
+
+#[test]
+fn non_url_inline_script_uses_script_src_elem_fallbacks() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ assert!(
+ content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from("script-src-elem 'unsafe-inline'; script-src 'none'"),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineScript,
+ None,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .is_none()
+ );
+
+ let violation = content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from("script-src 'self'; default-src 'unsafe-inline'"),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineScript,
+ None,
+ ContentSecurityPolicyDisposition::Report,
+ &reporting_endpoints,
+ )
+ .expect("script-src should block inline script without unsafe-inline");
+ assert_eq!(violation.effective_directive, "script-src-elem");
+ assert_eq!(violation.blocked_uri, "inline");
+ assert_eq!(
+ violation.disposition,
+ ContentSecurityPolicyDisposition::Report
+ );
+}
+
+#[test]
+fn inline_script_element_accepts_matching_nonce_or_source_hash() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let source = "globalThis.inlineScriptRan = true;";
+ let matching_hash = "'sha256-BAF+pD4OL3OpwYDBVElncnexa2ZpNAjS3yn9BmiJEto='";
+ let check = |policy: &str, nonce: Option<&str>| {
+ content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ source,
+ ContentSecurityPolicyScriptElementRequest {
+ nonce,
+ integrity: None,
+ parser_inserted: true,
+ },
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(check("script-src 'nonce-abc'", Some("abc")).is_none());
+ assert!(check("script-src 'nonce-abc'", Some("wrong")).is_some());
+ assert!(check(&format!("script-src {matching_hash}"), None).is_none());
+ assert!(
+ content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
+ &format!("script-src {matching_hash}").into(),
+ &protected_url(),
+ "globalThis.inlineScriptRan = false;",
+ ContentSecurityPolicyScriptElementRequest::default(),
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .is_some()
+ );
+}
+
+#[test]
+fn inline_script_element_unsafe_inline_obeys_nonce_and_strict_dynamic_precedence() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let check = |policy: &str, parser_inserted: bool| {
+ content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ "globalThis.inlineScriptRan = true;",
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: None,
+ integrity: None,
+ parser_inserted,
+ },
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(check("script-src 'unsafe-inline'", true).is_none());
+ assert!(check("script-src 'unsafe-inline' 'nonce-abc'", true).is_some());
+ assert!(check("script-src 'unsafe-inline' 'strict-dynamic'", true).is_some());
+ assert!(check("script-src 'unsafe-inline' 'strict-dynamic'", false).is_none());
+}
+
+#[test]
+fn inline_style_element_uses_style_src_elem_and_accepts_nonce_or_hash() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let source = "p { color: green; }";
+ let matching_hash = "'sha256-FSRZotz4y83Ib8ZaoVj9eXKaeWXVUawM8zAPfYeYySs='";
+ let check = |policy: &str, nonce: Option<&str>| {
+ content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ source,
+ ContentSecurityPolicyStyleElementRequest { nonce },
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(check("style-src-elem 'nonce-abc'; style-src 'none'", Some("abc")).is_none());
+ assert!(
+ check(
+ "style-src-elem 'nonce-abc'; style-src 'unsafe-inline'",
+ None
+ )
+ .is_some()
+ );
+ assert!(check(&format!("style-src {matching_hash}"), None).is_none());
+ assert!(check("default-src 'unsafe-inline'", None).is_none());
+ assert!(check("style-src 'unsafe-inline' 'nonce-abc'", None).is_some());
+}
+
+#[test]
+fn inline_hash_source_algorithm_names_are_ascii_case_insensitive() {
+ let source = "p { color: green; }";
+ let cases = [
+ ("SHA256", "FSRZotz4y83Ib8ZaoVj9eXKaeWXVUawM8zAPfYeYySs="),
+ (
+ "sHa384",
+ "XObbzlg3meDKX3QpZZz8hg0V39bxZI/QQ3qFg6emWOdBZinTtjOls/GimTwBU+WQ",
+ ),
+ (
+ "Sha512",
+ "yYhoHoYeH6+9nQONNTy2KAd3tps87iT2d7E58PcEnU5YmJh2am3blPT0gLXu3qnVxDvF/qQKibav9lIK3pCz1A==",
+ ),
+ ];
+
+ for (algorithm, digest) in cases {
+ let expression = format!("'{algorithm}-{digest}'");
+ let hash_source = csp_hash_source_value(&expression)
+ .expect("supported hash algorithm should parse case-insensitively");
+ assert!(inline_source_matches_hash(source, hash_source));
+ }
+ assert!(csp_hash_source_value("'SHA1-digest'").is_none());
+}
+
+#[test]
+fn inline_hashes_normalize_base64url_symbols_without_decoding_the_digest() {
+ let source = "globalThis.__inlineHashRuns += 1;/*☃ 8*/";
+ for (algorithm, encoded) in [
+ ("sHa256", "1u5siURgPyHwZ-QAD8UUU8_PSFeCLQfQgff1wmWe30c="),
+ (
+ "sHa384",
+ "dfgfWBTXEJmr8n1u3heMCmQspfZzXztxsa6b_uRqupCtR1-hV5y1NIRIuk1GgyfX",
+ ),
+ (
+ "sHa512",
+ "yuIija81LFQ7iw1A1DtvkYIsDvqIgpOAzeloywzVVvfCZdYs43Z-Dh0lhILbiEstq4O56dtDfie_iALMCVjEMA==",
+ ),
+ ] {
+ let matches = |source: &str, encoded: &str| {
+ let expression = format!("'{algorithm}-{encoded}'");
+ inline_source_matches_hash(source, csp_hash_source_value(&expression).unwrap())
+ };
+ for encoded in [
+ encoded.to_owned(),
+ encoded.replace('-', "+"),
+ encoded.replace('_', "/"),
+ encoded.replace('-', "+").replace('_', "/"),
+ ] {
+ assert!(matches(source, &encoded), "{algorithm}: {encoded}");
+ assert!(!matches(&format!("{source} "), &encoded));
+ assert!(!matches(source, &encoded.to_ascii_uppercase()));
+ assert!(!matches(source, &format!("{encoded}=")));
+ if encoded.ends_with('=') {
+ assert!(!matches(source, encoded.trim_end_matches('=')));
+ }
+ }
+ }
+ // Changing unused padding bits can decode to the same bytes, but CSP
+ // compares encoded strings after replacing only '-' and '_'.
+ assert!(!inline_source_matches_hash(
+ source,
+ csp_hash_source_value("'sha256-1u5siURgPyHwZ-QAD8UUU8_PSFeCLQfQgff1wmWe30d='",).unwrap()
+ ));
+}
+
+#[test]
+fn style_and_navigation_hash_checks_accept_base64url_and_require_unsafe_hashes() {
+ let endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let style_source = ".target { color: green; }/*☃ 0*/";
+ let style_policy = "style-src 'sha256-GIrKCpP-iQOfwzOEC4HO_QF0a8OAlKUdqbDq5l8WXn0='";
+ for (source, allowed) in [
+ (style_source.to_owned(), true),
+ (format!("{style_source} "), false),
+ ] {
+ let violation = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(style_policy), &protected_url(), &source, ContentSecurityPolicyStyleElementRequest::default(),
+ ContentSecurityPolicyDisposition::Enforce, &endpoints,
+ );
+ assert_eq!(violation.is_none(), allowed);
+ }
+ for (kind, source, encoded) in [
+ (
+ ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
+ "color: green;/*☃ 8*/",
+ "GjRTlK2I8F4B9NVwz22_fJvEUruslF4nw-V2jUp0LIM=",
+ ),
+ (
+ ContentSecurityPolicyNonUrlKind::DocumentInlineNavigation,
+ "javascript:/*☃ 0*/void(0)",
+ "r92XonOGS4-_MCpEOXhFyBgS4-xKf3v6fZMeHTK873c=",
+ ),
+ ] {
+ for unsafe_hashes in ["", "'unsafe-hashes'"] {
+ let policy = format!("default-src {unsafe_hashes} 'sha256-{encoded}'");
+ for (source, matching) in [(source.to_owned(), true), (format!("{source} "), false)] {
+ let violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy.as_str()), &protected_url(), kind, &source,
+ ContentSecurityPolicyDisposition::Enforce, &endpoints,
+ );
+ assert_eq!(
+ violation.is_none(),
+ matching && !unsafe_hashes.is_empty(),
+ "{kind:?}: {policy}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn inline_hash_base64url_normalization_does_not_normalize_nonces() {
+ for (nonce, allowed) in [("-_/+", true), ("+//+", false), ("-_--", false)] {
+ assert_eq!(
+ script_element_request_allowed(
+ "script-src 'nonce--_/+'",
+ ContentSecurityPolicyScriptElementRequest {
+ nonce: Some(nonce),
+ ..Default::default()
+ },
+ ),
+ allowed,
+ "{nonce}"
+ );
+ }
+}
+
+#[test]
+fn inline_style_attribute_uses_style_src_attr_and_requires_unsafe_hashes() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let source = "background: green";
+ let matching_hash = "'sha256-S0VSqEOmzmyOifPfat2sJ7ELOgkldAEbaXlvi5iMqjc='";
+ let check = |policy: &str| {
+ content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
+ source,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(check("style-src-attr 'unsafe-inline'; style-src 'none'").is_none());
+ assert!(check("style-src-attr 'none'; style-src 'unsafe-inline'").is_some());
+ assert!(check(&format!("style-src 'unsafe-hashes' {matching_hash}")).is_none());
+ assert!(check(&format!("style-src {matching_hash}")).is_some());
+ assert!(check("default-src 'unsafe-inline'").is_none());
+}
+
+#[test]
+fn inline_style_violation_sample_requires_report_sample_and_is_clipped() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let source = "0123456789012345678901234567890123456789extra";
+ let check_element = |policy: &str| {
+ content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ source,
+ ContentSecurityPolicyStyleElementRequest::default(),
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .expect("inline style should be blocked")
+ };
+ let check_attribute = |policy: &str| {
+ content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
+ source,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .expect("inline style attribute should be blocked")
+ };
+
+ assert_eq!(check_element("style-src 'none'").sample, "");
+ assert_eq!(
+ check_element("style-src 'none' 'report-sample'").sample,
+ "0123456789012345678901234567890123456789"
+ );
+ assert_eq!(
+ check_attribute("style-src-attr 'none' 'report-sample'").sample,
+ "0123456789012345678901234567890123456789"
+ );
+}
+
+#[test]
+fn inline_event_handler_uses_script_src_attr_fallbacks() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let check = |policy: &str, source: &str| {
+ content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
+ source,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(
+ check(
+ "script-src-attr 'unsafe-inline'; script-src 'none'",
+ "run() "
+ )
+ .is_none()
+ );
+ let violation = check(
+ "script-src-attr 'none'; script-src 'unsafe-inline'",
+ "run()",
+ )
+ .expect("script-src-attr should take precedence over script-src");
+ assert_eq!(violation.effective_directive, "script-src-attr");
+ assert_eq!(violation.blocked_uri, "inline");
+ assert!(check("script-src 'unsafe-inline'; default-src 'none'", "run()").is_none());
+ assert!(check("default-src 'unsafe-inline'", "run()").is_none());
+}
+
+#[test]
+fn inline_event_handler_hash_requires_unsafe_hashes_and_an_exact_digest() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let source = "t1.done();";
+ let matching_hash = "'sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps='";
+ let check = |policy: &str, source: &str| {
+ content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
+ source,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(
+ check(
+ &format!("script-src 'unsafe-hashes' {matching_hash}"),
+ source,
+ )
+ .is_none()
+ );
+ assert!(check(&format!("script-src {matching_hash}"), source).is_some());
+ assert!(
+ check(
+ &format!("script-src 'unsafe-hashes' {matching_hash}"),
+ "t1.done()",
+ )
+ .is_some()
+ );
+}
+
+#[test]
+fn inline_navigation_hashes_the_complete_javascript_url() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ let source = "javascript:opener.postMessage('pass', '*')";
+ let matching_hash = "'sha256-IIiAJ8UuliU8o1qAv6CV4P3R8DeTf/v3MrsCwXW171Y='";
+ let check = |policy: &str, source: &str| {
+ content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineNavigation,
+ source,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ };
+
+ assert!(
+ check(
+ &format!("script-src 'unsafe-hashes' {matching_hash}"),
+ source,
+ )
+ .is_none()
+ );
+ assert!(check(&format!("script-src {matching_hash}"), source).is_some());
+ let violation = check(
+ &format!("script-src-elem 'none'; script-src 'unsafe-hashes' {matching_hash}"),
+ source,
+ )
+ .expect("script-src-elem should take precedence for inline navigation");
+ assert_eq!(violation.effective_directive, "script-src-elem");
+ assert_eq!(violation.blocked_uri, "inline");
+}
+
+#[test]
+fn inline_event_handler_unsafe_inline_is_ignored_when_a_nonce_or_hash_is_present() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ for policy in [
+ "script-src 'unsafe-inline' 'nonce-abc'",
+ "script-src 'unsafe-inline' 'sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps='",
+ ] {
+ assert!(
+ content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
+ "untrusted()",
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .is_some(),
+ "{policy}",
+ );
+ }
+}
+
+#[test]
+fn non_url_wasm_eval_uses_script_src_or_default_src() {
+ let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
+ for policy in [
+ "script-src 'wasm-unsafe-eval'; default-src 'none'",
+ "script-src 'unsafe-eval'",
+ "default-src 'unsafe-eval'",
+ ] {
+ assert!(
+ content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from(policy),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::WasmEval,
+ None,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .is_none(),
+ "{policy}"
+ );
+ }
+
+ let violation = content_security_policy_non_url_violation_with_source(
+ &ContentSecurityPolicy::from("default-src 'self'"),
+ &protected_url(),
+ ContentSecurityPolicyNonUrlKind::WasmEval,
+ None,
+ ContentSecurityPolicyDisposition::Enforce,
+ &reporting_endpoints,
+ )
+ .expect("default-src should block wasm eval without unsafe eval source");
+ assert_eq!(violation.effective_directive, "script-src");
+ assert_eq!(violation.blocked_uri, "wasm-eval");
+}
+
+#[test]
+fn trusted_types_directive_filters_policy_names() {
+ let allowed = |policies: &[&str], name: &str| {
+ content_security_policy_allows_trusted_type_policy_name(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ name,
+ )
+ };
+
+ assert!(allowed(&[], "SomeName"));
+ assert!(allowed(&["default-src 'none'"], "SomeName"));
+ assert!(allowed(&["trusted-types SomeName OtherName"], "SomeName"));
+ assert!(allowed(&["trusted-types * 'aLLow-dUPLIcates'"], "SomeName"));
+ assert!(allowed(&["trusted-types 'none' SomeName"], "SomeName"));
+ assert!(!allowed(&["trusted-types"], "SomeName"));
+ assert!(!allowed(&["trusted-types 'nONe'"], "SomeName"));
+ assert!(!allowed(&["trusted-types SomeName"], "default"));
+ assert!(!allowed(
+ &["trusted-types SomeName", "trusted-types OtherName"],
+ "SomeName"
+ ));
+}
+
+#[test]
+fn trusted_types_csp_name_grammar_matches_only_valid_tokens() {
+ // Directive grammar errors and policy delimiters are tested separately: they discard the
+ // directive before its tt-policy-name tokens are interpreted.
+ for byte in [b'\t', b'\n', b'\x0c', b'\r']
+ .into_iter()
+ .chain(b' '..=b'~')
+ .filter(|byte| !matches!(*byte, b',' | b';'))
+ {
+ let name = format!("policy{}name", char::from(byte));
+ let policy = format!("trusted-types {name}");
+ let expected = byte.is_ascii_alphanumeric() || b"-#=_/@.%".contains(&byte);
+ assert_eq!(
+ policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy.as_str()),
+ &name
+ ),
+ expected,
+ "invalid tt-policy-name byte {byte:#04x} must not match literally",
+ );
+ }
+ for name in ["none", "allow-duplicates", "A-z_09#=/@.%"] {
+ assert!(policy_allows_trusted_type_policy_name(
+ &format!("trusted-types {name}").into(),
+ name
+ ));
+ }
+ assert!(policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from("trusted-types valid policy*name"),
+ "valid"
+ ));
+ assert!(!policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from("trusted-types valid policy*name"),
+ "policy*name"
+ ));
+ for wildcard in ["policy*", "**"] {
+ assert!(!policy_allows_trusted_type_policy_name(
+ &format!("trusted-types {wildcard}").into(),
+ "valid"
+ ));
+ }
+}
+
+#[test]
+fn trusted_types_csp_name_grammar_does_not_restrict_unlisted_or_wildcard_names() {
+ for name in [
+ "",
+ "policy*name",
+ "policy$name",
+ "política",
+ "ポリシー",
+ "\0",
+ ] {
+ for policy in ["", "trusted-types *"] {
+ assert!(policy_allows_trusted_type_policy_name(
+ &ContentSecurityPolicy::from(policy),
+ name
+ ));
+ }
+ }
+}
+
+#[test]
+fn csp_directive_parser_discards_invalid_values_without_replacing_first_directives() {
+ for directive in [
+ "trusted-types allowed política",
+ "trusted-types\u{a0}allowed",
+ "\u{a0}trusted-types allowed",
+ "trusted-types allowed\u{a0}",
+ "require-trusted-types-for 'script' ポリシー",
+ "script-src 'none' https://例子.test",
+ ] {
+ assert!(
+ ContentSecurityPolicy::from(directive).is_empty(),
+ "{directive}"
+ );
+ }
+
+ let directives = ContentSecurityPolicy::from(
+ "trusted-types invalid política; TRUSTED-TYPES allowed; trusted-types *; \
+ script-src 'none'; img-src https://例子.test; img-src 'self'",
+ );
+ assert!(directive_source_list(&directives, TRUSTED_TYPES).is_none());
+ assert_eq!(
+ directive_source_list(&directives, SCRIPT_SRC),
+ Some(vec!["'none'"]),
+ );
+ assert!(directive_source_list(&directives, IMG_SRC).is_none());
+}
+
+#[test]
+fn csp_directive_parser_uses_only_ascii_whitespace_around_names() {
+ for space in ['\t', '\n', '\u{000c}', '\r', ' '] {
+ let policy = format!("{space}TrUsTeD-TyPeS{space}allowed{space}");
+ let directives = ContentSecurityPolicy::from(policy.as_str());
+ assert_eq!(
+ directive_source_list(&directives, TRUSTED_TYPES),
+ Some(vec!["allowed"]),
+ );
+ }
+ for invalid in ['\0', '\u{000b}', '\u{001f}', '\u{007f}'] {
+ for policy in [
+ format!("{invalid}trusted-types allowed"),
+ format!("trusted-types{invalid} allowed"),
+ ] {
+ assert!(
+ directive_source_list(&ContentSecurityPolicy::from(policy.as_str()), TRUSTED_TYPES)
+ .is_none(),
+ "{policy:?}",
+ );
+ }
+ }
+}
+
+#[test]
+fn trusted_types_eval_requires_enforcement_and_an_operative_keyword() {
+ let allowed = |policies: &[&str]| {
+ content_security_policy_allows_trusted_types_eval(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ assert!(allowed(&[
+ "require-trusted-types-for 'script'; script-src 'trusted-types-eval'"
+ ]));
+ assert!(allowed(&[
+ "require-trusted-types-for 'script'",
+ "default-src 'trusted-types-eval'"
+ ]));
+ assert!(!allowed(&["script-src 'trusted-types-eval'"]));
+ assert!(!allowed(&[
+ "require-trusted-types-for 'script'; default-src 'trusted-types-eval'; script-src 'self'"
+ ]));
+ assert!(!allowed(&[
+ "require-trusted-types-for 'script'; script-src 'unsafe-eval'"
+ ]));
+}
+
+#[test]
+fn sandbox_directive_forces_opaque_origin_without_allow_same_origin() {
+ let forces_opaque = |policies: &[&str]| {
+ content_security_policy_forces_opaque_origin(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ assert!(!forces_opaque(&[]));
+ assert!(!forces_opaque(&["script-src 'self'"]));
+ assert!(forces_opaque(&["sandbox"]));
+ assert!(forces_opaque(&["sandbox allow-scripts"]));
+ assert!(!forces_opaque(&["sandbox allow-scripts allow-same-origin"]));
+ assert!(!forces_opaque(&["sandbox allow-scripts ALLOW-SAME-ORIGIN"]));
+}
+
+#[test]
+fn sandbox_directive_sandboxes_document_domain_even_with_allow_same_origin() {
+ let sandboxes_document_domain = |policies: &[&str]| {
+ content_security_policy_sandboxes_document_domain(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ assert!(!sandboxes_document_domain(&[]));
+ assert!(!sandboxes_document_domain(&["script-src 'self'"]));
+ assert!(sandboxes_document_domain(&["sandbox"]));
+ assert!(sandboxes_document_domain(&["sandbox allow-scripts"]));
+ assert!(sandboxes_document_domain(&[
+ "sandbox allow-scripts allow-same-origin"
+ ]));
+ assert!(sandboxes_document_domain(&[
+ "sandbox allow-scripts ALLOW-SAME-ORIGIN"
+ ]));
+}
+
+#[test]
+fn sandbox_directive_allows_scripts_only_when_all_active_sandboxes_allow_it() {
+ let allows_scripts = |policies: &[&str]| {
+ content_security_policy_sandbox_allows_scripts(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ assert!(allows_scripts(&[]));
+ assert!(allows_scripts(&["script-src 'self'"]));
+ assert!(!allows_scripts(&["sandbox"]));
+ assert!(allows_scripts(&["sandbox allow-scripts"]));
+ assert!(allows_scripts(&["sandbox ALLOW-SCRIPTS"]));
+ assert!(!allows_scripts(&[
+ "sandbox allow-scripts",
+ "sandbox allow-same-origin"
+ ]));
+}
+
+#[test]
+fn sandbox_directive_allows_modals_only_when_all_active_sandboxes_allow_it() {
+ let allows_modals = |policies: &[&str]| {
+ content_security_policy_sandbox_allows_modals(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ assert!(allows_modals(&[]));
+ assert!(allows_modals(&["script-src 'self'"]));
+ assert!(!allows_modals(&["sandbox"]));
+ assert!(allows_modals(&["sandbox allow-modals"]));
+ assert!(allows_modals(&["sandbox ALLOW-MODALS"]));
+ assert!(!allows_modals(&[
+ "sandbox allow-modals",
+ "sandbox allow-scripts"
+ ]));
+}
+
+#[test]
+fn sandbox_directive_allows_popups_to_escape_only_when_all_active_sandboxes_allow_it() {
+ let allows_popups_to_escape = |policies: &[&str]| {
+ content_security_policy_sandbox_allows_popups_to_escape(
+ &policies
+ .iter()
+ .map(|policy| (*policy).into())
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ assert!(!allows_popups_to_escape(&[]));
+ assert!(!allows_popups_to_escape(&["script-src 'self'"]));
+ assert!(!allows_popups_to_escape(&["sandbox"]));
+ assert!(allows_popups_to_escape(&[
+ "sandbox allow-popups-to-escape-sandbox"
+ ]));
+ assert!(allows_popups_to_escape(&[
+ "sandbox ALLOW-POPUPS-TO-ESCAPE-SANDBOX"
+ ]));
+ assert!(!allows_popups_to_escape(&[
+ "sandbox allow-popups-to-escape-sandbox",
+ "sandbox allow-scripts"
+ ]));
+}
diff --git a/moli-csp/src/types.rs b/moli-csp/src/types.rs
new file mode 100644
index 000000000..4cca81cd5
--- /dev/null
+++ b/moli-csp/src/types.rs
@@ -0,0 +1,181 @@
+use std::collections::BTreeMap;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ContentSecurityPolicyResourceKind {
+ DocumentConnect,
+ DocumentFrame,
+ DocumentImage,
+ DocumentManifest,
+ DocumentMedia,
+ DocumentScriptElement,
+ DocumentStyleElement,
+ SharedWorkerScript,
+ WorkerConnect,
+ WorkerDynamicModuleImport,
+ WorkerScript,
+ WorkerStaticModuleImport,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ContentSecurityPolicyNonUrlKind {
+ DocumentInlineEventHandler,
+ DocumentInlineNavigation,
+ DocumentInlineScript,
+ DocumentInlineStyleAttribute,
+ DocumentInlineStyleElement,
+ Eval,
+ TrustedTypesEval,
+ WasmEval,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ContentSecurityPolicyRedirectStatus {
+ NoRedirect,
+ FollowedRedirect,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ContentSecurityPolicyDisposition {
+ Enforce,
+ Report,
+}
+
+impl ContentSecurityPolicyDisposition {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Enforce => "enforce",
+ Self::Report => "report",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct TrustedTypesForScriptRequirements {
+ enforced: bool,
+ report_only: bool,
+}
+
+impl TrustedTypesForScriptRequirements {
+ pub const fn new(enforced: bool, report_only: bool) -> Self {
+ Self {
+ enforced,
+ report_only,
+ }
+ }
+
+ pub const fn enforced_only(enforced: bool) -> Self {
+ Self::new(enforced, false)
+ }
+
+ pub const fn requires_conversion(self) -> bool {
+ self.enforced || self.report_only
+ }
+
+ pub const fn is_enforced(self) -> bool {
+ self.enforced
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ContentSecurityPolicyScriptElementRequest<'a> {
+ pub nonce: Option<&'a str>,
+ pub integrity: Option<&'a str>,
+ pub parser_inserted: bool,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct ContentSecurityPolicyStyleElementRequest<'a> {
+ pub nonce: Option<&'a str>,
+}
+
+impl Default for ContentSecurityPolicyScriptElementRequest<'_> {
+ fn default() -> Self {
+ Self {
+ nonce: None,
+ integrity: None,
+ parser_inserted: true,
+ }
+ }
+}
+
+impl<'a> ContentSecurityPolicyScriptElementRequest<'a> {
+ pub fn parser_inserted_with_nonce(nonce: Option<&'a str>) -> Self {
+ Self {
+ nonce,
+ integrity: None,
+ parser_inserted: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ContentSecurityPolicyUrlViolation {
+ pub effective_directive: &'static str,
+ pub blocked_uri: String,
+ pub document_uri: String,
+ pub original_policy: String,
+ pub disposition: ContentSecurityPolicyDisposition,
+ pub report_uri_endpoints: Vec<String>,
+ pub report_to_endpoints: Vec<String>,
+ pub sample: String,
+ pub source_file: String,
+ pub line_number: i32,
+ pub column_number: i32,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ContentSecurityPolicyReportingEndpoints {
+ endpoints: BTreeMap<String, String>,
+}
+
+impl ContentSecurityPolicyReportingEndpoints {
+ pub fn endpoint_for_group(&self, group: &str) -> Option<&str> {
+ self.endpoints.get(group).map(String::as_str)
+ }
+
+ pub(crate) fn insert(&mut self, group: impl Into<String>, endpoint: impl Into<String>) {
+ self.endpoints.insert(group.into(), endpoint.into());
+ }
+}
+
+pub struct ContentSecurityPolicyViolationEventFields<'a> {
+ pub document_uri: &'a str,
+ pub referrer: &'a str,
+ pub blocked_uri: &'a str,
+ pub effective_directive: &'a str,
+ pub violated_directive: &'a str,
+ pub original_policy: &'a str,
+ pub disposition: ContentSecurityPolicyDisposition,
+ pub source_file: &'a str,
+ pub sample: &'a str,
+ pub line_number: i32,
+ pub column_number: i32,
+ pub status_code: i32,
+}
+
+impl<'a> ContentSecurityPolicyViolationEventFields<'a> {
+ pub fn from_url_violation(violation: &'a ContentSecurityPolicyUrlViolation) -> Self {
+ Self {
+ document_uri: violation.document_uri.as_str(),
+ referrer: "",
+ blocked_uri: violation.blocked_uri.as_str(),
+ effective_directive: violation.effective_directive,
+ violated_directive: violation.effective_directive,
+ original_policy: violation.original_policy.as_str(),
+ disposition: violation.disposition,
+ source_file: violation.source_file.as_str(),
+ sample: violation.sample.as_str(),
+ line_number: violation.line_number,
+ column_number: violation.column_number,
+ status_code: 0,
+ }
+ }
+}
+
+impl<'a> From<&'a ContentSecurityPolicyUrlViolation>
+ for ContentSecurityPolicyViolationEventFields<'a>
+{
+ fn from(violation: &'a ContentSecurityPolicyUrlViolation) -> Self {
+ Self::from_url_violation(violation)
+ }
+}
diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml
index 5dc657c60..d39264b79 100644
--- a/moli-renderer-v8/Cargo.toml
+++ b/moli-renderer-v8/Cargo.toml
@@ -38,6 +38,7 @@ moli-action-window = { path = "../moli-action-window" }
moli-broadcast-channel = { path = "../moli-broadcast-channel" }
moli-browser-profile = { path = "../moli-browser-profile" }
moli-crypto = { path = "../moli-crypto" }
+moli-csp = { path = "../moli-csp" }
moli-css-parse = { path = "../moli-css-parse" }
moli-dom = { path = "../moli-dom" }
moli-disk-pool = { path = "../moli-disk-pool" }
diff --git a/moli-renderer-v8/src/content_security_policy.rs b/moli-renderer-v8/src/content_security_policy.rs
index c1785706d..234966058 100644
--- a/moli-renderer-v8/src/content_security_policy.rs
+++ b/moli-renderer-v8/src/content_security_policy.rs
@@ -1,211 +1,12 @@
-use std::collections::{BTreeMap, HashSet};
+//! Connect the standalone CSP engine to V8 events and the renderer loader.
+
+pub(crate) use moli_csp::*;
use crate::context_bootstrap::{initialize_event_object, mark_event_trusted};
use crate::network::ResourceRequestClient;
-use crate::subresource_integrity::integrity_metadata_hashes;
-use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
-use moli_crypto::DigestAlgorithm;
use moli_fetch::{
Request, RequestCredentialsMode, RequestMode, RequestRedirectMode, RequestResourceType,
};
-use percent_encoding::percent_decode_str;
-use serde_json::json;
-use url::Url;
-
-const CONNECT_SRC: &str = "connect-src";
-const CHILD_SRC: &str = "child-src";
-const DEFAULT_SRC: &str = "default-src";
-const FRAME_ANCESTORS: &str = "frame-ancestors";
-const FRAME_SRC: &str = "frame-src";
-const IMG_SRC: &str = "img-src";
-const MANIFEST_SRC: &str = "manifest-src";
-const MEDIA_SRC: &str = "media-src";
-const SCRIPT_SRC_ATTR: &str = "script-src-attr";
-const SCRIPT_SRC_ELEM: &str = "script-src-elem";
-const SCRIPT_SRC: &str = "script-src";
-const STYLE_SRC_ATTR: &str = "style-src-attr";
-const STYLE_SRC_ELEM: &str = "style-src-elem";
-const STYLE_SRC: &str = "style-src";
-const WORKER_SRC: &str = "worker-src";
-const REQUIRE_TRUSTED_TYPES_FOR: &str = "require-trusted-types-for";
-const TRUSTED_TYPES: &str = "trusted-types";
-const SANDBOX: &str = "sandbox";
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(crate) enum ContentSecurityPolicyResourceKind {
- DocumentConnect,
- DocumentFrame,
- DocumentImage,
- DocumentManifest,
- DocumentMedia,
- DocumentScriptElement,
- DocumentStyleElement,
- SharedWorkerScript,
- WorkerConnect,
- WorkerDynamicModuleImport,
- WorkerScript,
- WorkerStaticModuleImport,
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(crate) enum ContentSecurityPolicyNonUrlKind {
- DocumentInlineEventHandler,
- DocumentInlineNavigation,
- DocumentInlineScript,
- DocumentInlineStyleAttribute,
- DocumentInlineStyleElement,
- Eval,
- TrustedTypesEval,
- WasmEval,
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(crate) enum ContentSecurityPolicyRedirectStatus {
- NoRedirect,
- FollowedRedirect,
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq, crate::webidl::WebIdlEnum)]
-#[webidl(
- name = "SecurityPolicyViolationEventDisposition",
- rename_all = "kebab-case"
-)]
-pub(crate) enum ContentSecurityPolicyDisposition {
- Enforce,
- Report,
-}
-
-impl ContentSecurityPolicyDisposition {
- pub(crate) fn as_str(self) -> &'static str {
- match self {
- Self::Enforce => "enforce",
- Self::Report => "report",
- }
- }
-}
-
-#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
-pub(crate) struct TrustedTypesForScriptRequirements {
- enforced: bool,
- report_only: bool,
-}
-
-impl TrustedTypesForScriptRequirements {
- pub(crate) const fn new(enforced: bool, report_only: bool) -> Self {
- Self {
- enforced,
- report_only,
- }
- }
-
- pub(crate) const fn enforced_only(enforced: bool) -> Self {
- Self::new(enforced, false)
- }
-
- pub(crate) const fn requires_conversion(self) -> bool {
- self.enforced || self.report_only
- }
-
- pub(crate) const fn is_enforced(self) -> bool {
- self.enforced
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(crate) struct ContentSecurityPolicyScriptElementRequest<'a> {
- pub(crate) nonce: Option<&'a str>,
- pub(crate) integrity: Option<&'a str>,
- pub(crate) parser_inserted: bool,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-pub(crate) struct ContentSecurityPolicyStyleElementRequest<'a> {
- pub(crate) nonce: Option<&'a str>,
-}
-
-impl Default for ContentSecurityPolicyScriptElementRequest<'_> {
- fn default() -> Self {
- Self {
- nonce: None,
- integrity: None,
- parser_inserted: true,
- }
- }
-}
-
-impl<'a> ContentSecurityPolicyScriptElementRequest<'a> {
- pub(crate) fn parser_inserted_with_nonce(nonce: Option<&'a str>) -> Self {
- Self {
- nonce,
- integrity: None,
- parser_inserted: true,
- }
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub(crate) struct ContentSecurityPolicyUrlViolation {
- pub(crate) effective_directive: &'static str,
- pub(crate) blocked_uri: String,
- pub(crate) document_uri: String,
- pub(crate) original_policy: String,
- pub(crate) disposition: ContentSecurityPolicyDisposition,
- pub(crate) report_uri_endpoints: Vec<String>,
- pub(crate) report_to_endpoints: Vec<String>,
- pub(crate) sample: String,
- pub(crate) source_file: String,
- pub(crate) line_number: i32,
- pub(crate) column_number: i32,
-}
-
-#[derive(Clone, Debug, Default, PartialEq, Eq)]
-pub(crate) struct ContentSecurityPolicyReportingEndpoints {
- endpoints: BTreeMap<String, String>,
-}
-
-impl ContentSecurityPolicyReportingEndpoints {
- pub(crate) fn endpoint_for_group(&self, group: &str) -> Option<&str> {
- self.endpoints.get(group).map(String::as_str)
- }
-
- fn insert(&mut self, group: impl Into<String>, endpoint: impl Into<String>) {
- self.endpoints.insert(group.into(), endpoint.into());
- }
-}
-
-pub(crate) struct ContentSecurityPolicyViolationEventFields<'a> {
- pub(crate) document_uri: &'a str,
- pub(crate) referrer: &'a str,
- pub(crate) blocked_uri: &'a str,
- pub(crate) effective_directive: &'a str,
- pub(crate) violated_directive: &'a str,
- pub(crate) original_policy: &'a str,
- pub(crate) disposition: ContentSecurityPolicyDisposition,
- pub(crate) source_file: &'a str,
- pub(crate) sample: &'a str,
- pub(crate) line_number: i32,
- pub(crate) column_number: i32,
- pub(crate) status_code: i32,
-}
-
-impl<'a> ContentSecurityPolicyViolationEventFields<'a> {
- pub(crate) fn from_url_violation(violation: &'a ContentSecurityPolicyUrlViolation) -> Self {
- Self {
- document_uri: violation.document_uri.as_str(),
- referrer: "",
- blocked_uri: violation.blocked_uri.as_str(),
- effective_directive: violation.effective_directive,
- violated_directive: violation.effective_directive,
- original_policy: violation.original_policy.as_str(),
- disposition: violation.disposition,
- source_file: violation.source_file.as_str(),
- sample: violation.sample.as_str(),
- line_number: violation.line_number,
- column_number: violation.column_number,
- status_code: 0,
- }
- }
-}
pub(crate) fn create_security_policy_violation_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
@@ -225,296 +26,6 @@ pub(crate) fn create_security_policy_violation_event<'s>(
crate::context_bootstrap::new_event_wrapper(scope, event)
}
-pub(crate) fn content_security_policy_headers(headers: &[(String, Vec<u8>)]) -> Vec<String> {
- content_security_policy_header_values(headers, "content-security-policy")
-}
-
-pub(crate) fn content_security_policy_report_only_headers(
- headers: &[(String, Vec<u8>)],
-) -> Vec<String> {
- content_security_policy_header_values(headers, "content-security-policy-report-only")
-}
-
-fn content_security_policy_header_values(
- headers: &[(String, Vec<u8>)],
- header_name: &str,
-) -> Vec<String> {
- let headers = moli_fetch::headers_to_byte_strings(headers);
- // Each HTTP field can contain several independently enforced policies.
- // Commas are CSP list delimiters even inside quotes in directive values;
- // the quoted-string rules used by Reporting-Endpoints do not apply here.
- // https://w3c.github.io/webappsec-csp/#parse-response-csp
- headers
- .iter()
- .filter(|(name, _)| name.eq_ignore_ascii_case(header_name))
- .flat_map(|(_, value)| value.split(','))
- .map(str::trim_ascii)
- .filter(|policy| !parsed_directives(policy).is_empty())
- .map(str::to_owned)
- .collect()
-}
-
-pub(crate) fn content_security_policy_requires_trusted_types_for_script(
- policies: &[String],
-) -> bool {
- policies
- .iter()
- .any(|policy| policy_requires_trusted_types_for_script(policy))
-}
-
-pub(crate) fn content_security_policy_allows_trusted_types_eval(policies: &[String]) -> bool {
- // Like Blink's ContentSecurityPolicy::AllowTrustedTypesEval, this only
- // activates the document-global Trusted Types relaxation. It is not the
- // final CSP decision: CSP3 EnsureCSPDoesNotBlockStringCompilation still
- // evaluates every policy through the TrustedTypesEval non-URL gate.
- policies
- .iter()
- .any(|policy| policy_requires_trusted_types_for_script(policy))
- && policies
- .iter()
- .any(|policy| policy_allows_trusted_types_eval(policy))
-}
-
-pub(crate) fn content_security_policy_allows_trusted_type_policy_name(
- policies: &[String],
- policy_name: &str,
-) -> bool {
- policies
- .iter()
- .all(|policy| policy_allows_trusted_type_policy_name(policy, policy_name))
-}
-
-pub(crate) fn content_security_policy_sandboxes_document_domain(policies: &[String]) -> bool {
- policies
- .iter()
- .any(|policy| policy_sandboxes_document_domain(policy))
-}
-
-pub(crate) fn content_security_policy_forces_opaque_origin(policies: &[String]) -> bool {
- policies
- .iter()
- .any(|policy| policy_forces_opaque_origin(policy))
-}
-
-pub(crate) fn content_security_policy_sandbox_allows_scripts(policies: &[String]) -> bool {
- policies
- .iter()
- .all(|policy| policy_sandbox_allows_scripts(policy).unwrap_or(true))
-}
-
-pub(crate) fn content_security_policy_sandbox_allows_modals(policies: &[String]) -> bool {
- policies
- .iter()
- .all(|policy| policy_sandbox_allows_modals(policy).unwrap_or(true))
-}
-
-pub(crate) fn content_security_policy_sandbox_allows_top_navigation(policies: &[String]) -> bool {
- policies.iter().all(|policy| {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, SANDBOX).is_none_or(|sources| {
- sources
- .iter()
- .any(|token| token.eq_ignore_ascii_case("allow-top-navigation"))
- })
- })
-}
-
-pub(crate) fn content_security_policy_sandbox_allows_popups_to_escape(policies: &[String]) -> bool {
- let mut has_sandbox = false;
- for policy in policies {
- let Some(allows) = policy_sandbox_allows_popups_to_escape(policy) else {
- continue;
- };
- has_sandbox = true;
- if !allows {
- return false;
- }
- }
- has_sandbox
-}
-
-pub(crate) fn content_security_policy_report_uri_endpoints(
- policy: &str,
- protected_url: &Url,
-) -> Vec<String> {
- let directives = parsed_directives(policy);
- if directive_source_list(&directives, "report-to").is_some() {
- return Vec::new();
- }
- directives
- .iter()
- .filter(|(name, _)| name.eq_ignore_ascii_case("report-uri"))
- .flat_map(|(_, values)| values.iter())
- .filter_map(|endpoint| protected_url.join(endpoint).ok())
- .filter(|endpoint| matches!(endpoint.scheme(), "http" | "https"))
- .map(|endpoint| endpoint.to_string())
- .collect()
-}
-
-pub(crate) fn content_security_policy_reporting_endpoints_from_headers(
- headers: &[(String, Vec<u8>)],
- protected_url: &Url,
-) -> ContentSecurityPolicyReportingEndpoints {
- let mut endpoints = ContentSecurityPolicyReportingEndpoints::default();
- for (_, value) in headers
- .iter()
- .filter(|(name, _)| name.eq_ignore_ascii_case("reporting-endpoints"))
- {
- parse_reporting_endpoints_header(
- &moli_fetch::decode_header_value(value),
- protected_url,
- &mut endpoints,
- );
- }
- endpoints
-}
-
-fn parse_reporting_endpoints_header(
- value: &str,
- protected_url: &Url,
- endpoints: &mut ContentSecurityPolicyReportingEndpoints,
-) {
- for member in split_quoted_header_list(value) {
- let Some((raw_group, raw_endpoint)) = member.split_once('=') else {
- continue;
- };
- let group = raw_group.trim();
- if group.is_empty() {
- continue;
- }
- let Some(endpoint) = parse_quoted_header_value(raw_endpoint.trim()) else {
- continue;
- };
- let Ok(endpoint) = protected_url.join(&endpoint) else {
- continue;
- };
- if !matches!(endpoint.scheme(), "http" | "https") {
- continue;
- }
- endpoints.insert(group, endpoint.to_string());
- }
-}
-
-fn split_quoted_header_list(value: &str) -> Vec<&str> {
- let mut parts = Vec::new();
- let mut in_quote = false;
- let mut escaped = false;
- let mut start = 0;
- for (index, ch) in value.char_indices() {
- if escaped {
- escaped = false;
- continue;
- }
- match ch {
- '\\' if in_quote => escaped = true,
- '"' => in_quote = !in_quote,
- ',' if !in_quote => {
- let part = value[start..index].trim();
- if !part.is_empty() {
- parts.push(part);
- }
- start = index + ch.len_utf8();
- }
- _ => {}
- }
- }
- let part = value[start..].trim();
- if !part.is_empty() {
- parts.push(part);
- }
- parts
-}
-
-fn parse_quoted_header_value(value: &str) -> Option<String> {
- let value = value.strip_prefix('"')?.strip_suffix('"')?;
- let mut output = String::with_capacity(value.len());
- let mut chars = value.chars();
- while let Some(ch) = chars.next() {
- if ch == '\\' {
- output.push(chars.next()?);
- } else {
- output.push(ch);
- }
- }
- Some(output)
-}
-
-pub(crate) fn content_security_policy_report_to_endpoints(
- policy: &str,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Vec<String> {
- let directives = parsed_directives(policy);
- let Some(sources) = directive_source_list(&directives, "report-to") else {
- return Vec::new();
- };
- let Some(group) = sources.first() else {
- return Vec::new();
- };
- reporting_endpoints
- .endpoint_for_group(group)
- .map(|endpoint| vec![endpoint.to_owned()])
- .unwrap_or_default()
-}
-
-pub(crate) fn content_security_policy_violation_report_body(
- fields: &ContentSecurityPolicyViolationEventFields<'_>,
-) -> String {
- json!({
- "csp-report": {
- "document-uri": fields.document_uri,
- "referrer": fields.referrer,
- "violated-directive": fields.violated_directive,
- "effective-directive": fields.effective_directive,
- "original-policy": fields.original_policy,
- "disposition": fields.disposition.as_str(),
- "blocked-uri": fields.blocked_uri,
- "source-file": fields.source_file,
- "status-code": fields.status_code,
- "script-sample": fields.sample,
- }
- })
- .to_string()
-}
-
-pub(crate) fn content_security_policy_reporting_api_report_body(
- fields: &ContentSecurityPolicyViolationEventFields<'_>,
-) -> String {
- let mut body = serde_json::Map::new();
- body.insert("documentURL".to_owned(), json!(fields.document_uri));
- if !fields.referrer.is_empty() {
- body.insert("referrer".to_owned(), json!(fields.referrer));
- }
- if !fields.blocked_uri.is_empty() {
- body.insert("blockedURL".to_owned(), json!(fields.blocked_uri));
- }
- body.insert(
- "effectiveDirective".to_owned(),
- json!(fields.effective_directive),
- );
- body.insert("originalPolicy".to_owned(), json!(fields.original_policy));
- if !fields.source_file.is_empty() {
- body.insert("sourceFile".to_owned(), json!(fields.source_file));
- }
- if !fields.sample.is_empty() {
- body.insert("sample".to_owned(), json!(fields.sample));
- }
- body.insert("disposition".to_owned(), json!(fields.disposition.as_str()));
- body.insert("statusCode".to_owned(), json!(fields.status_code));
- if fields.line_number != 0 {
- body.insert("lineNumber".to_owned(), json!(fields.line_number));
- }
- if fields.column_number != 0 {
- body.insert("columnNumber".to_owned(), json!(fields.column_number));
- }
- json!([{
- "age": 0,
- "type": "csp-violation",
- "url": fields.document_uri,
- "body": body,
- }])
- .to_string()
-}
-
pub(crate) fn content_security_policy_report_requests(
fields: &ContentSecurityPolicyViolationEventFields<'_>,
report_uri_endpoints: &[String],
@@ -591,3410 +102,54 @@ fn send_content_security_policy_report_request(loader: &ResourceRequestClient, r
}
}
-pub(crate) fn ensure_content_security_policy_allows_url(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- error: impl FnOnce() -> String,
-) -> Result<(), String> {
- ensure_content_security_policy_allows_url_with_redirect_status(
- policies,
- protected_url,
- request_url,
- kind,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- error,
- )
-}
-
-pub(crate) fn ensure_content_security_policy_allows_url_with_redirect_status(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- error: impl FnOnce() -> String,
-) -> Result<(), String> {
- if content_security_policy_allows_url_with_redirect_status(
- policies,
- protected_url,
- request_url,
- kind,
- redirect_status,
- ) {
- Ok(())
- } else {
- Err(error())
- }
-}
-
-#[cfg(test)]
-fn content_security_policy_allows_url(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
-) -> bool {
- content_security_policy_allows_url_with_redirect_status(
- policies,
- protected_url,
- request_url,
- kind,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
-}
-
-pub(crate) fn content_security_policy_allows_url_with_redirect_status(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
-) -> bool {
- policies.iter().all(|policy| {
- let Some((_, source_list)) = effective_source_list_with_directive(policy, kind) else {
- return true;
- };
- source_list_allows(source_list, protected_url, request_url, redirect_status)
- })
-}
-
-#[cfg(test)]
-fn content_security_policy_url_violation_with_redirect_status(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_url_violation_with_redirect_status_and_disposition(
- policies,
- protected_url,
- request_url,
- kind,
- redirect_status,
- ContentSecurityPolicyDisposition::Enforce,
- )
-}
-
-#[cfg(test)]
-fn content_security_policy_url_violation_with_redirect_status_and_disposition(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- disposition: ContentSecurityPolicyDisposition,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
- policies,
- protected_url,
- request_url,
- kind,
- redirect_status,
- disposition,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
-}
-
-pub(crate) fn content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints(
- policies,
- protected_url,
- request_url,
- request_url,
- kind,
- redirect_status,
- disposition,
- reporting_endpoints,
- )
-}
-
-pub(crate) fn content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
- policies: &[String],
- protected_url: &Url,
- ancestor_origins: &[Option<Url>],
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- policies.iter().find_map(|policy| {
- let directives = parsed_directives(policy);
- let source_list =
- normalized_source_list(directive_source_list(&directives, FRAME_ANCESTORS)?.to_vec());
- if ancestor_origins.iter().all(|ancestor_origin| {
- ancestor_origin.as_ref().is_some_and(|ancestor_origin| {
- frame_ancestor_source_list_allows(&source_list, protected_url, ancestor_origin)
- })
- }) {
- return None;
- }
- let document_uri = csp_url_for_report(protected_url);
- Some(ContentSecurityPolicyUrlViolation {
- effective_directive: FRAME_ANCESTORS,
- blocked_uri: document_uri.clone(),
- source_file: document_uri.clone(),
- document_uri,
- original_policy: policy.clone(),
- disposition,
- report_uri_endpoints: content_security_policy_report_uri_endpoints(
- policy,
- protected_url,
- ),
- report_to_endpoints: content_security_policy_report_to_endpoints(
- policy,
- reporting_endpoints,
- ),
- sample: String::new(),
- line_number: 0,
- column_number: 0,
- })
- })
-}
-
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
- request: ContentSecurityPolicyScriptElementRequest<'_>,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
- policies,
- protected_url,
- request_url,
- request_url,
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- redirect_status,
- disposition,
- reporting_endpoints,
- ContentSecurityPolicyUrlRequest::Script(request),
- )
-}
-
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn content_security_policy_style_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- policies: &[String],
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
- request: ContentSecurityPolicyStyleElementRequest<'_>,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
- policies,
- protected_url,
- request_url,
- request_url,
- ContentSecurityPolicyResourceKind::DocumentStyleElement,
- redirect_status,
- disposition,
- reporting_endpoints,
- ContentSecurityPolicyUrlRequest::Style(request),
- )
-}
-
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints(
- policies: &[String],
- protected_url: &Url,
- checked_url: &Url,
- blocked_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
- policies,
- protected_url,
- checked_url,
- blocked_url,
- kind,
- redirect_status,
- disposition,
- reporting_endpoints,
- ContentSecurityPolicyUrlRequest::Standard,
- )
-}
-
-#[derive(Clone, Copy)]
-enum ContentSecurityPolicyUrlRequest<'a> {
- Standard,
- Script(ContentSecurityPolicyScriptElementRequest<'a>),
- Style(ContentSecurityPolicyStyleElementRequest<'a>),
-}
-
-#[allow(clippy::too_many_arguments)]
-fn content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
- policies: &[String],
- protected_url: &Url,
- checked_url: &Url,
- blocked_url: &Url,
- kind: ContentSecurityPolicyResourceKind,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
- request: ContentSecurityPolicyUrlRequest<'_>,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- policies.iter().find_map(|policy| {
- let (effective_directive, source_list) =
- effective_source_list_with_directive(policy, kind)?;
- if source_list_allows_resource_request(
- source_list,
- protected_url,
- checked_url,
- redirect_status,
- request,
- ) {
- return None;
- }
- let document_uri = csp_url_for_report(protected_url);
- Some(ContentSecurityPolicyUrlViolation {
- effective_directive,
- blocked_uri: csp_url_for_report(blocked_url),
- source_file: document_uri.clone(),
- document_uri,
- original_policy: policy.clone(),
- disposition,
- report_uri_endpoints: content_security_policy_report_uri_endpoints(
- policy,
- protected_url,
- ),
- report_to_endpoints: content_security_policy_report_to_endpoints(
- policy,
- reporting_endpoints,
- ),
- sample: String::new(),
- line_number: 0,
- column_number: 0,
- })
- })
-}
-
-fn csp_url_for_report(url: &Url) -> String {
- if !matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
- return url.scheme().to_owned();
- }
- let mut stripped = url.clone();
- let _ = stripped.set_username("");
- let _ = stripped.set_password(None);
- stripped.set_fragment(None);
- stripped.to_string()
-}
-
-/// Strip a script source URL before exposing it through a CSP violation report.
-///
-/// This implements the URL-shaping portion of CSP's "Strip URL for use in
-/// reports" algorithm. Script source locations may expose HTTP(S)/WS(S) paths,
-/// but never credentials, queries, or fragments. Other valid schemes are
-/// reduced to the scheme name.
-pub(crate) fn content_security_policy_source_file_for_report(source_file: &str) -> String {
- let Ok(mut source_url) = Url::parse(source_file) else {
- return String::new();
- };
- if !matches!(source_url.scheme(), "http" | "https" | "ws" | "wss") {
- return source_url.scheme().to_owned();
- }
- let _ = source_url.set_username("");
- let _ = source_url.set_password(None);
- source_url.set_query(None);
- source_url.set_fragment(None);
- source_url.to_string()
-}
-
-pub(crate) fn content_security_policy_trusted_types_sink_violation_with_disposition_and_reporting_endpoints(
- policies: &[String],
- protected_url: &Url,
- sink: &str,
- sample: &str,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- policies.iter().find_map(|policy| {
- if !policy_requires_trusted_types_for_script(policy) {
- return None;
- }
- let document_uri = protected_url.to_string();
- Some(ContentSecurityPolicyUrlViolation {
- effective_directive: REQUIRE_TRUSTED_TYPES_FOR,
- blocked_uri: "trusted-types-sink".to_owned(),
- source_file: document_uri.clone(),
- document_uri,
- original_policy: policy.clone(),
- disposition,
- report_uri_endpoints: content_security_policy_report_uri_endpoints(
- policy,
- protected_url,
- ),
- report_to_endpoints: content_security_policy_report_to_endpoints(
- policy,
- reporting_endpoints,
- ),
- sample: trusted_types_sink_violation_sample(sink, sample),
- line_number: 0,
- column_number: 0,
+pub(crate) fn current_script_violation_location(
+ scope: &mut v8::PinScope<'_, '_>,
+) -> Option<(String, i32, i32)> {
+ let stack = v8::StackTrace::current_stack_trace(scope, 1)?;
+ let frame = stack.get_frame(scope, 0)?;
+ let source_file = frame
+ .get_script_name_or_source_url(scope)
+ .map(|source| source.to_rust_string_lossy(scope))
+ .map(|source| {
+ crate::content_security_policy::content_security_policy_source_file_for_report(&source)
})
- })
-}
-
-pub(crate) fn content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy: &str,
- protected_url: &Url,
- kind: ContentSecurityPolicyNonUrlKind,
- source: &str,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- debug_assert!(matches!(
- kind,
- ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler
- | ContentSecurityPolicyNonUrlKind::DocumentInlineNavigation
- | ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute
- ));
- content_security_policy_non_url_violation_with_source(
- policy,
- protected_url,
- kind,
- Some(source),
- disposition,
- reporting_endpoints,
- )
+ .unwrap_or_default();
+ let line_number = i32::try_from(frame.get_line_number())
+ .unwrap_or_default()
+ .max(0);
+ let column_number = i32::try_from(frame.get_column()).unwrap_or_default().max(0);
+ Some((source_file, line_number, column_number))
}
-pub(crate) fn content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
- policy: &str,
- protected_url: &Url,
- source: &str,
- request: ContentSecurityPolicyScriptElementRequest<'_>,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- let kind = ContentSecurityPolicyNonUrlKind::DocumentInlineScript;
- let directives = parsed_directives(policy);
- let (effective_directive, source_list) =
- kind.directive_fallbacks().iter().find_map(|directive| {
- directive_source_list(&directives, directive)
- .map(|sources| (kind.effective_directive(), sources.to_vec()))
- })?;
- if inline_script_element_source_list_allows(source_list.clone(), source, request) {
- return None;
- }
- let document_uri = protected_url.to_string();
- Some(ContentSecurityPolicyUrlViolation {
- effective_directive,
- blocked_uri: kind.blocked_uri().to_owned(),
- source_file: document_uri.clone(),
- document_uri,
- original_policy: policy.to_owned(),
- disposition,
- report_uri_endpoints: content_security_policy_report_uri_endpoints(policy, protected_url),
- report_to_endpoints: content_security_policy_report_to_endpoints(
- policy,
- reporting_endpoints,
- ),
- sample: inline_source_violation_sample(&source_list, source),
- line_number: 0,
- column_number: 0,
- })
-}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use url::Url;
-pub(crate) fn content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
- policy: &str,
- protected_url: &Url,
- source: &str,
- request: ContentSecurityPolicyStyleElementRequest<'_>,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- let kind = ContentSecurityPolicyNonUrlKind::DocumentInlineStyleElement;
- let directives = parsed_directives(policy);
- let (effective_directive, source_list) =
- kind.directive_fallbacks().iter().find_map(|directive| {
- directive_source_list(&directives, directive)
- .map(|sources| (kind.effective_directive(), sources.to_vec()))
- })?;
- if inline_style_element_source_list_allows(source_list.clone(), source, request) {
- return None;
+ fn protected_url() -> Url {
+ Url::parse("https://app.test/page.html").unwrap()
}
- let document_uri = protected_url.to_string();
- Some(ContentSecurityPolicyUrlViolation {
- effective_directive,
- blocked_uri: kind.blocked_uri().to_owned(),
- source_file: document_uri.clone(),
- document_uri,
- original_policy: policy.to_owned(),
- disposition,
- report_uri_endpoints: content_security_policy_report_uri_endpoints(policy, protected_url),
- report_to_endpoints: content_security_policy_report_to_endpoints(
- policy,
- reporting_endpoints,
- ),
- sample: inline_source_violation_sample(&source_list, source),
- line_number: 0,
- column_number: 0,
- })
-}
-
-pub(crate) fn content_security_policy_non_url_violation_with_source(
- policy: &str,
- protected_url: &Url,
- kind: ContentSecurityPolicyNonUrlKind,
- source: Option<&str>,
- disposition: ContentSecurityPolicyDisposition,
- reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Option<ContentSecurityPolicyUrlViolation> {
- let directives = parsed_directives(policy);
- let (effective_directive, source_list) =
- kind.directive_fallbacks().iter().find_map(|directive| {
- directive_source_list(&directives, directive)
- .map(|sources| (kind.effective_directive(), sources.to_vec()))
- })?;
- if kind.source_list_allows(&source_list, source) {
- return None;
+ fn request_url(raw: &str) -> Url {
+ Url::parse(raw).unwrap()
}
- let document_uri = protected_url.to_string();
- Some(ContentSecurityPolicyUrlViolation {
- effective_directive,
- blocked_uri: kind.blocked_uri().to_owned(),
- source_file: document_uri.clone(),
- document_uri,
- original_policy: policy.to_owned(),
- disposition,
- report_uri_endpoints: content_security_policy_report_uri_endpoints(policy, protected_url),
- report_to_endpoints: content_security_policy_report_to_endpoints(
- policy,
- reporting_endpoints,
- ),
- sample: source
- .map(|source| inline_source_violation_sample(&source_list, source))
- .unwrap_or_default(),
- line_number: 0,
- column_number: 0,
- })
-}
-
-fn policy_requires_trusted_types_for_script(policy: &str) -> bool {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, REQUIRE_TRUSTED_TYPES_FOR).is_some_and(|sources| {
- sources
- .iter()
- .any(|source| csp_keyword_eq(source, "script"))
- })
-}
-
-fn policy_allows_trusted_types_eval(policy: &str) -> bool {
- let directives = parsed_directives(policy);
- [SCRIPT_SRC, DEFAULT_SRC]
- .into_iter()
- .find_map(|directive| directive_source_list(&directives, directive))
- .is_some_and(|sources| {
- sources
- .iter()
- .any(|source| csp_keyword_eq(source, "trusted-types-eval"))
- })
-}
-
-fn policy_allows_trusted_type_policy_name(policy: &str, policy_name: &str) -> bool {
- let directives = parsed_directives(policy);
- let Some(sources) = directive_source_list(&directives, TRUSTED_TYPES) else {
- return true;
- };
- sources.iter().any(|source| {
- let source = *source;
- source == "*"
- || (!source.is_empty()
- && source == policy_name
- && source.bytes().all(|byte| {
- byte.is_ascii_alphanumeric()
- || matches!(byte, b'-' | b'#' | b'=' | b'_' | b'/' | b'@' | b'.' | b'%')
- }))
- })
-}
-
-fn policy_sandboxes_document_domain(policy: &str) -> bool {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, SANDBOX).is_some()
-}
-
-fn policy_forces_opaque_origin(policy: &str) -> bool {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, SANDBOX)
- .is_some_and(|sources| !sandbox_sources_allow_same_origin(sources))
-}
-
-fn policy_sandbox_allows_scripts(policy: &str) -> Option<bool> {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, SANDBOX).map(sandbox_sources_allow_scripts)
-}
-
-fn policy_sandbox_allows_modals(policy: &str) -> Option<bool> {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, SANDBOX).map(sandbox_sources_allow_modals)
-}
-
-fn policy_sandbox_allows_popups_to_escape(policy: &str) -> Option<bool> {
- let directives = parsed_directives(policy);
- directive_source_list(&directives, SANDBOX).map(sandbox_sources_allow_popups_to_escape)
-}
-
-fn sandbox_sources_allow_same_origin(sources: &[&str]) -> bool {
- sources
- .iter()
- .any(|token| token.eq_ignore_ascii_case("allow-same-origin"))
-}
-
-fn sandbox_sources_allow_scripts(sources: &[&str]) -> bool {
- sources
- .iter()
- .any(|token| token.eq_ignore_ascii_case("allow-scripts"))
-}
-
-fn sandbox_sources_allow_modals(sources: &[&str]) -> bool {
- sources
- .iter()
- .any(|token| token.eq_ignore_ascii_case("allow-modals"))
-}
-
-fn sandbox_sources_allow_popups_to_escape(sources: &[&str]) -> bool {
- sources
- .iter()
- .any(|token| token.eq_ignore_ascii_case("allow-popups-to-escape-sandbox"))
-}
-
-fn trusted_types_sink_violation_sample(sink: &str, sample: &str) -> String {
- let clipped = sample.chars().take(40).collect::<String>();
- format!("{sink}|{clipped}")
-}
-
-fn effective_source_list_with_directive(
- policy: &str,
- kind: ContentSecurityPolicyResourceKind,
-) -> Option<(&'static str, Vec<&str>)> {
- let directives = parsed_directives(policy);
- kind.directive_fallbacks().iter().find_map(|directive| {
- directive_source_list(&directives, directive)
- .map(|sources| (kind.effective_directive(), sources.to_vec()))
- })
-}
-
-fn parsed_directives(policy: &str) -> Vec<(&str, Vec<&str>)> {
- let mut names = HashSet::new();
- policy
- .split(';')
- .filter_map(|directive| {
- // Split on exactly CSP's ASCII whitespace. Do not trim controls
- // into a valid directive name or source expression.
- let mut parts = directive.split_ascii_whitespace();
- let name = parts.next()?;
- // The first occurrence takes the name even if its value is invalid.
- // Later duplicates must not override it or suppress a fallback.
- if !names.insert(name.to_ascii_lowercase()) {
- return None;
- }
- // Non-whitespace controls, DEL and non-ASCII characters invalidate
- // the entire directive, without affecting the rest of the policy.
- if !directive
- .bytes()
- .all(|byte| byte != b',' && (byte.is_ascii_whitespace() || byte.is_ascii_graphic()))
- {
- return None;
- }
- Some((name, parts.collect()))
- })
- .collect()
-}
-fn directive_source_list<'policy, 'directives>(
- directives: &'directives [(&'policy str, Vec<&'policy str>)],
- name: &str,
-) -> Option<&'directives [&'policy str]> {
- directives
- .iter()
- .find(|(directive_name, _)| directive_name.eq_ignore_ascii_case(name))
- .map(|(_, sources)| sources.as_slice())
-}
-
-fn source_list_allows(
- sources: Vec<&str>,
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
-) -> bool {
- let sources = normalized_source_list(sources);
- normalized_source_list_allows_url(&sources, protected_url, request_url, redirect_status)
-}
-
-fn frame_ancestor_source_list_allows(
- sources: &[&str],
- protected_url: &Url,
- ancestor_origin: &Url,
-) -> bool {
- if sources.is_empty() || (sources.len() == 1 && csp_keyword_eq(sources[0], "none")) {
- return false;
- }
- sources.iter().any(|source| {
- !csp_keyword_eq(source, "none")
- && !source_has_path(source)
- && source_expression_matches(
- source,
- protected_url,
- ancestor_origin,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- })
-}
-
-fn source_list_allows_script_element_request(
- sources: Vec<&str>,
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- request: ContentSecurityPolicyScriptElementRequest<'_>,
-) -> bool {
- let sources = normalized_source_list(sources);
- if let Some(nonce) = request
- .nonce
- .map(str::trim)
- .filter(|nonce| !nonce.is_empty())
- && sources
- .iter()
- .any(|source| csp_nonce_source_matches(source, nonce))
- {
- return true;
- }
- if script_integrity_matches_hash_source(request.integrity, &sources) {
- return true;
- }
- if source_list_activates_strict_dynamic(&sources) {
- return !request.parser_inserted;
- }
- normalized_source_list_allows_url(&sources, protected_url, request_url, redirect_status)
-}
-
-fn source_list_allows_style_element_request(
- sources: Vec<&str>,
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- request: ContentSecurityPolicyStyleElementRequest<'_>,
-) -> bool {
- let sources = normalized_source_list(sources);
- if let Some(nonce) = request
- .nonce
- .map(str::trim)
- .filter(|nonce| !nonce.is_empty())
- && sources
- .iter()
- .any(|source| csp_nonce_source_matches(source, nonce))
- {
- return true;
- }
- normalized_source_list_allows_url(&sources, protected_url, request_url, redirect_status)
-}
-
-fn source_list_allows_resource_request(
- sources: Vec<&str>,
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
- request: ContentSecurityPolicyUrlRequest<'_>,
-) -> bool {
- match request {
- ContentSecurityPolicyUrlRequest::Standard => source_list_allows_script_element_request(
- sources,
- protected_url,
- request_url,
- redirect_status,
- ContentSecurityPolicyScriptElementRequest::default(),
- ),
- ContentSecurityPolicyUrlRequest::Script(request) => {
- source_list_allows_script_element_request(
- sources,
- protected_url,
- request_url,
- redirect_status,
- request,
- )
- }
- ContentSecurityPolicyUrlRequest::Style(request) => {
- source_list_allows_style_element_request(
- sources,
- protected_url,
- request_url,
- redirect_status,
- request,
- )
- }
- }
-}
-
-fn inline_script_element_source_list_allows(
- sources: Vec<&str>,
- source: &str,
- request: ContentSecurityPolicyScriptElementRequest<'_>,
-) -> bool {
- let sources = normalized_source_list(sources);
- if let Some(nonce) = request
- .nonce
- .map(str::trim)
- .filter(|nonce| !nonce.is_empty())
- && sources
- .iter()
- .any(|source| csp_nonce_source_matches(source, nonce))
- {
- return true;
- }
- if sources
- .iter()
- .filter_map(|source| csp_hash_source_value(source))
- .any(|hash_source| inline_source_matches_hash(source, hash_source))
- {
- return true;
- }
- let has_strict_dynamic = sources
- .iter()
- .any(|source| csp_keyword_eq(source, "strict-dynamic"));
- if has_strict_dynamic && !request.parser_inserted {
- return true;
- }
- let has_nonce_or_hash = sources.iter().any(|source| {
- csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
- });
- !has_nonce_or_hash
- && !has_strict_dynamic
- && sources
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-inline"))
-}
-
-fn inline_style_element_source_list_allows(
- sources: Vec<&str>,
- source: &str,
- request: ContentSecurityPolicyStyleElementRequest<'_>,
-) -> bool {
- let sources = normalized_source_list(sources);
- if let Some(nonce) = request
- .nonce
- .map(str::trim)
- .filter(|nonce| !nonce.is_empty())
- && sources
- .iter()
- .any(|source| csp_nonce_source_matches(source, nonce))
- {
- return true;
- }
- if sources
- .iter()
- .filter_map(|source| csp_hash_source_value(source))
- .any(|hash_source| inline_source_matches_hash(source, hash_source))
- {
- return true;
- }
- let has_nonce_or_hash = sources.iter().any(|source| {
- csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
- });
- !has_nonce_or_hash
- && sources
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-inline"))
-}
-
-fn inline_source_violation_sample(source_list: &[&str], source: &str) -> String {
- if !source_list
- .iter()
- .any(|source| csp_keyword_eq(source, "report-sample"))
- {
- return String::new();
- }
- source.chars().take(40).collect()
-}
-
-fn normalized_source_list(sources: Vec<&str>) -> Vec<&str> {
- // The directive parser already splits on CSP's ASCII whitespace. Trimming
- // again would turn invalid tokens containing vertical tabs into sources.
- sources
- .into_iter()
- .filter(|source| !source.is_empty())
- .collect()
-}
-
-fn normalized_source_list_allows_url(
- sources: &[&str],
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
-) -> bool {
- if sources.is_empty() {
- return false;
- }
- if sources.len() == 1 && csp_keyword_eq(sources[0], "none") {
- return false;
- }
- sources.iter().any(|source| {
- !csp_keyword_eq(source, "none")
- && source_expression_matches(source, protected_url, request_url, redirect_status)
- })
-}
-
-fn csp_nonce_source_matches(source: &str, nonce: &str) -> bool {
- csp_nonce_source_value(source).is_some_and(|value| value == nonce)
-}
-
-fn source_list_activates_strict_dynamic(sources: &[&str]) -> bool {
- sources
- .iter()
- .any(|source| csp_keyword_eq(source, "strict-dynamic"))
- && sources.iter().any(|source| {
- csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
- })
-}
-
-fn csp_nonce_source_value(source: &str) -> Option<&str> {
- source
- .strip_prefix("'nonce-")
- .and_then(|value| value.strip_suffix('\''))
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::EnumString)]
-#[strum(serialize_all = "lowercase", ascii_case_insensitive)]
-enum CspHashAlgorithm {
- Sha256,
- Sha384,
- Sha512,
-}
-
-impl CspHashAlgorithm {
- fn digest_algorithm(self) -> DigestAlgorithm {
- match self {
- Self::Sha256 => DigestAlgorithm::Sha256,
- Self::Sha384 => DigestAlgorithm::Sha384,
- Self::Sha512 => DigestAlgorithm::Sha512,
- }
- }
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-struct CspHashSourceValue<'a> {
- algorithm: CspHashAlgorithm,
- digest: &'a str,
-}
-
-fn hash_source_value(value: &str) -> Option<CspHashSourceValue<'_>> {
- let (algorithm, digest) = value.split_once('-')?;
- if digest.is_empty() {
- return None;
- }
- Some(CspHashSourceValue {
- algorithm: algorithm.parse().ok()?,
- digest,
- })
-}
-
-fn csp_hash_source_value(source: &str) -> Option<CspHashSourceValue<'_>> {
- let source = source.strip_prefix('\'')?.strip_suffix('\'')?;
- hash_source_value(source)
-}
-
-fn script_integrity_matches_hash_source(integrity: Option<&str>, sources: &[&str]) -> bool {
- let Some(integrity) = integrity else {
- return false;
- };
- // CSP requires a nonempty subset of its hash sources, including weaker
- // algorithms. SRI checks the strongest hashes against the response later.
- let mut hashes = integrity_metadata_hashes(integrity).peekable();
- hashes.peek().is_some()
- && hashes.all(|hash| {
- sources
- .iter()
- .filter_map(|source| csp_hash_source_value(source))
- .any(|source| {
- source.algorithm.digest_algorithm() == hash.algorithm
- && source.digest == hash.digest
- })
- })
-}
-
-fn source_expression_matches(
- source: &str,
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
-) -> bool {
- if csp_keyword_eq(source, "self") {
- return self_source_matches(protected_url, request_url);
- }
- if source == "*" {
- return matches!(request_url.scheme(), "http" | "https" | "ws" | "wss");
- }
- if let Some(scheme) = source.strip_suffix(':')
- && !scheme.contains('/')
- && !scheme.is_empty()
- {
- return csp_scheme_match(scheme, request_url.scheme()) != CspSchemeMatch::NotMatching;
- }
- source_url_matches(source, protected_url, request_url, redirect_status)
-}
-
-fn source_url_matches(
- source: &str,
- protected_url: &Url,
- request_url: &Url,
- redirect_status: ContentSecurityPolicyRedirectStatus,
-) -> bool {
- let Some(source) = parse_host_source(source) else {
- return false;
- };
- let source_scheme = source.scheme.unwrap_or_else(|| protected_url.scheme());
- let scheme_match = csp_scheme_match(source_scheme, request_url.scheme());
- if scheme_match == CspSchemeMatch::NotMatching {
- return false;
- }
- let port_match = host_source_port_match(source_scheme, source.port, request_url);
- if !csp_scheme_and_port_match(scheme_match, port_match) {
- return false;
- }
- let Some(request_host) = request_url.host_str() else {
- return false;
- };
- if !csp_host_part_matches(source.host, request_host) {
- return false;
- }
- // Keep the existing wildcard-port IPv4 restriction separate from grammar
- // validation; sources with ordinary ports already accept literal IPv4.
- if source.port == Some("*")
- && source.host != "127.0.0.1"
- && source.host.parse::<std::net::Ipv4Addr>().is_ok()
- {
- return false;
- }
- redirect_status == ContentSecurityPolicyRedirectStatus::FollowedRedirect
- || source
- .path
- .is_none_or(|path| csp_path_part_matches(path, request_url.path()))
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-enum CspSchemeMatch {
- NotMatching,
- Exact,
- WebSocketToHttp,
- Upgrade,
-}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-enum CspPortMatch {
- NotMatching,
- Exact,
- Wildcard,
- Upgrade,
-}
-
-fn self_source_matches(protected_url: &Url, request_url: &Url) -> bool {
- if protected_url.host_str() != request_url.host_str() {
- return false;
- }
- let scheme_match = csp_scheme_match(protected_url.scheme(), request_url.scheme());
- let port_match = csp_port_match(
- protected_url.scheme(),
- protected_url.port_or_known_default(),
- false,
- request_url,
- );
- if scheme_match == CspSchemeMatch::Exact && port_match == CspPortMatch::Exact {
- return true;
- }
- let source_port_is_default = protected_url
- .port_or_known_default()
- .is_some_and(|port| is_default_port_for_scheme(port, protected_url.scheme()));
- let request_port_is_default = request_url
- .port_or_known_default()
- .is_some_and(|port| is_default_port_for_scheme(port, request_url.scheme()));
- let ports_match_or_defaults =
- port_match == CspPortMatch::Exact || (source_port_is_default && request_port_is_default);
- ports_match_or_defaults
- && (request_url.scheme().eq_ignore_ascii_case("https")
- || request_url.scheme().eq_ignore_ascii_case("wss")
- || protected_url.scheme().eq_ignore_ascii_case("http"))
-}
-
-fn csp_scheme_match(source_scheme: &str, request_scheme: &str) -> CspSchemeMatch {
- if source_scheme.eq_ignore_ascii_case(request_scheme) {
- return CspSchemeMatch::Exact;
- }
- // CSP permits WebSocket sources to match HTTP URLs at the same security
- // level. Keep this distinct from exact matching used by 'self' and from
- // secure upgrades, which also participate in port-upgrade checks.
- // https://w3c.github.io/webappsec-csp/#match-schemes
- if (source_scheme.eq_ignore_ascii_case("ws") && request_scheme.eq_ignore_ascii_case("http"))
- || (source_scheme.eq_ignore_ascii_case("wss")
- && request_scheme.eq_ignore_ascii_case("https"))
- {
- return CspSchemeMatch::WebSocketToHttp;
- }
- if (source_scheme.eq_ignore_ascii_case("http") && request_scheme.eq_ignore_ascii_case("https"))
- || (source_scheme.eq_ignore_ascii_case("ws")
- && (request_scheme.eq_ignore_ascii_case("wss")
- || request_scheme.eq_ignore_ascii_case("https")))
- {
- return CspSchemeMatch::Upgrade;
- }
- CspSchemeMatch::NotMatching
-}
-
-fn csp_port_match(
- source_scheme: &str,
- source_port: Option<u16>,
- source_port_wildcard: bool,
- request_url: &Url,
-) -> CspPortMatch {
- if source_port_wildcard {
- return CspPortMatch::Wildcard;
- }
- let request_port = request_url.port_or_known_default();
- if csp_scheme_match(source_scheme, request_url.scheme()) == CspSchemeMatch::Upgrade
- && matches!(source_port, Some(80 | 443))
- && request_port == Some(443)
- {
- return CspPortMatch::Upgrade;
- }
- if source_port.is_some() && source_port == request_port {
- return CspPortMatch::Exact;
- }
- CspPortMatch::NotMatching
-}
-
-fn is_default_port_for_scheme(port: u16, scheme: &str) -> bool {
- matches!(
- (scheme.to_ascii_lowercase().as_str(), port),
- ("http", 80) | ("ws", 80) | ("https", 443) | ("wss", 443)
- )
-}
-
-fn csp_scheme_and_port_match(scheme_match: CspSchemeMatch, port_match: CspPortMatch) -> bool {
- if port_match == CspPortMatch::NotMatching {
- return false;
- }
- let requires_upgrade =
- scheme_match == CspSchemeMatch::Upgrade || port_match == CspPortMatch::Upgrade;
- if !requires_upgrade {
- return true;
- }
- let scheme_can_upgrade = scheme_match == CspSchemeMatch::Upgrade;
- let port_can_upgrade =
- port_match == CspPortMatch::Upgrade || port_match == CspPortMatch::Wildcard;
- scheme_can_upgrade && port_can_upgrade
-}
-
-struct CspHostSource<'a> {
- scheme: Option<&'a str>,
- host: &'a str,
- port: Option<&'a str>,
- path: Option<&'a str>,
-}
-
-fn parse_host_source(source: &str) -> Option<CspHostSource<'_>> {
- // CSP host-source is not a URL: credentials and scheme-relative URLs are
- // invalid, and URL parsing must not normalize hosts or dot segments.
- // https://w3c.github.io/webappsec-csp/#source-lists
- let (scheme, rest) = if let Some((scheme, rest)) = source.split_once("://")
- && !scheme.contains('/')
- {
- let mut bytes = scheme.bytes();
- if !bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic())
- || !bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
- {
- return None;
- }
- (Some(scheme), rest)
- } else {
- (None, source)
- };
- let (authority, path) = split_authority_and_path(rest);
- let (host, port) = if let Some((host, port)) = authority.split_once(':') {
- if port != "*" && (port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit())) {
- return None;
- }
- (host, Some(port))
- } else {
- (authority, None)
- };
- if host != "*" {
- let labels = host.strip_prefix("*.").unwrap_or(host);
- let labels = labels.strip_suffix('.').unwrap_or(labels);
- if !labels.split('.').all(|label| {
- !label.is_empty()
- && label
- .bytes()
- .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
- }) {
- return None;
- }
- }
- if path.is_some_and(|path| !csp_path_part_is_valid(path)) {
- return None;
- }
- Some(CspHostSource {
- scheme,
- host,
- port,
- path,
- })
-}
-
-fn split_authority_and_path(source_rest: &str) -> (&str, Option<&str>) {
- source_rest
- .find('/')
- .map(|path_start| (&source_rest[..path_start], Some(&source_rest[path_start..])))
- .unwrap_or((source_rest, None))
-}
-
-fn csp_host_part_matches(source_host: &str, request_host: &str) -> bool {
- if source_host == "*" {
- return !request_host.is_empty();
- }
- if let Some(suffix) = source_host.strip_prefix('*') {
- return request_host.len() >= suffix.len()
- && request_host.as_bytes()[request_host.len() - suffix.len()..]
- .eq_ignore_ascii_case(suffix.as_bytes());
- }
- source_host.eq_ignore_ascii_case(request_host)
-}
-
-fn csp_path_part_is_valid(path: &str) -> bool {
- // RFC 3986 path-absolute, excluding raw ';' and ',' as required by CSP.
- if !path.starts_with('/') || path.starts_with("//") {
- return false;
- }
- let mut bytes = path.bytes();
- while let Some(byte) = bytes.next() {
- if byte == b'%' {
- if !bytes.next().is_some_and(|byte| byte.is_ascii_hexdigit())
- || !bytes.next().is_some_and(|byte| byte.is_ascii_hexdigit())
- {
- return false;
- }
- } else if !byte.is_ascii_alphanumeric()
- && !matches!(
- byte,
- b'/' | b'-'
- | b'.'
- | b'_'
- | b'~'
- | b'!'
- | b'$'
- | b'&'
- | b'\''
- | b'('
- | b')'
- | b'*'
- | b'+'
- | b'='
- | b':'
- | b'@'
- )
- {
- return false;
- }
- }
- true
-}
-
-fn csp_path_part_matches(source_path: &str, request_path: &str) -> bool {
- if source_path.is_empty() || (source_path == "/" && request_path.is_empty()) {
- return true;
- }
- // Split before decoding so an encoded slash cannot create a path boundary.
- // Compare bytes: distinct invalid UTF-8 sequences must not become equal.
- // https://w3c.github.io/webappsec-csp/#match-paths
- let mut source_segments = source_path.split('/').peekable();
- let mut request_segments = request_path.split('/');
- while let Some(source_segment) = source_segments.next() {
- let Some(request_segment) = request_segments.next() else {
- return false;
- };
- if source_segment.is_empty() && source_segments.peek().is_none() {
- return true;
- }
- if !percent_decode_str(source_segment).eq(percent_decode_str(request_segment)) {
- return false;
- }
- }
- request_segments.next().is_none()
-}
-
-fn host_source_port_match(
- source_scheme: &str,
- source_port: Option<&str>,
- request_url: &Url,
-) -> CspPortMatch {
- match source_port {
- Some("*") => CspPortMatch::Wildcard,
- Some(port) => port
- .parse::<u16>()
- .ok()
- .map(|source_port| csp_port_match(source_scheme, Some(source_port), false, request_url))
- .unwrap_or(CspPortMatch::NotMatching),
- None => csp_port_match(
- source_scheme,
- default_port_for_scheme(source_scheme),
- false,
- request_url,
- ),
- }
-}
-
-fn default_port_for_scheme(scheme: &str) -> Option<u16> {
- match scheme.to_ascii_lowercase().as_str() {
- "http" | "ws" => Some(80),
- "https" | "wss" => Some(443),
- "ftp" => Some(21),
- _ => None,
- }
-}
-
-fn source_has_path(source: &str) -> bool {
- let after_scheme = source
- .split_once("://")
- .map(|(_, rest)| rest)
- .or_else(|| source.strip_prefix("//"))
- .unwrap_or(source);
- after_scheme.contains('/')
-}
-
-fn csp_keyword_eq(source: &str, keyword: &str) -> bool {
- source.len() == keyword.len() + 2
- && source.starts_with('\'')
- && source.ends_with('\'')
- && source[1..source.len() - 1].eq_ignore_ascii_case(keyword)
-}
-
-impl ContentSecurityPolicyResourceKind {
- fn effective_directive(self) -> &'static str {
- match self {
- Self::DocumentConnect => CONNECT_SRC,
- Self::DocumentFrame => FRAME_SRC,
- Self::DocumentImage => IMG_SRC,
- Self::DocumentManifest => MANIFEST_SRC,
- Self::DocumentMedia => MEDIA_SRC,
- Self::DocumentScriptElement | Self::WorkerDynamicModuleImport => SCRIPT_SRC_ELEM,
- Self::DocumentStyleElement => STYLE_SRC_ELEM,
- Self::SharedWorkerScript | Self::WorkerStaticModuleImport => WORKER_SRC,
- Self::WorkerConnect => CONNECT_SRC,
- Self::WorkerScript => SCRIPT_SRC,
- }
- }
-
- fn directive_fallbacks(self) -> &'static [&'static str] {
- match self {
- Self::DocumentConnect => &[CONNECT_SRC, DEFAULT_SRC],
- Self::DocumentFrame => &[FRAME_SRC, CHILD_SRC, DEFAULT_SRC],
- Self::DocumentImage => &[IMG_SRC, DEFAULT_SRC],
- Self::DocumentManifest => &[MANIFEST_SRC, DEFAULT_SRC],
- Self::DocumentMedia => &[MEDIA_SRC, DEFAULT_SRC],
- Self::DocumentScriptElement => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
- Self::DocumentStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC],
- Self::SharedWorkerScript => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
- Self::WorkerConnect => &[CONNECT_SRC, DEFAULT_SRC],
- Self::WorkerDynamicModuleImport => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
- Self::WorkerScript => &[SCRIPT_SRC, DEFAULT_SRC],
- Self::WorkerStaticModuleImport => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
- }
- }
-}
-
-impl ContentSecurityPolicyNonUrlKind {
- fn effective_directive(self) -> &'static str {
- match self {
- Self::DocumentInlineEventHandler => SCRIPT_SRC_ATTR,
- Self::DocumentInlineNavigation | Self::DocumentInlineScript => SCRIPT_SRC_ELEM,
- Self::DocumentInlineStyleAttribute => STYLE_SRC_ATTR,
- Self::DocumentInlineStyleElement => STYLE_SRC_ELEM,
- Self::Eval | Self::TrustedTypesEval => SCRIPT_SRC,
- Self::WasmEval => SCRIPT_SRC,
- }
- }
-
- fn directive_fallbacks(self) -> &'static [&'static str] {
- match self {
- Self::DocumentInlineEventHandler => &[SCRIPT_SRC_ATTR, SCRIPT_SRC, DEFAULT_SRC],
- Self::DocumentInlineNavigation | Self::DocumentInlineScript => {
- &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC]
- }
- Self::DocumentInlineStyleAttribute => &[STYLE_SRC_ATTR, STYLE_SRC, DEFAULT_SRC],
- Self::DocumentInlineStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC],
- Self::Eval | Self::TrustedTypesEval => &[SCRIPT_SRC, DEFAULT_SRC],
- Self::WasmEval => &[SCRIPT_SRC, DEFAULT_SRC],
- }
- }
-
- fn blocked_uri(self) -> &'static str {
- match self {
- Self::DocumentInlineEventHandler
- | Self::DocumentInlineNavigation
- | Self::DocumentInlineScript
- | Self::DocumentInlineStyleAttribute
- | Self::DocumentInlineStyleElement => "inline",
- Self::Eval | Self::TrustedTypesEval => "eval",
- Self::WasmEval => "wasm-eval",
- }
- }
-
- fn source_list_allows(self, source_list: &[&str], source: Option<&str>) -> bool {
- match self {
- Self::DocumentInlineEventHandler
- | Self::DocumentInlineNavigation
- | Self::DocumentInlineStyleAttribute => {
- inline_event_handler_source_list_allows(source_list, source.unwrap_or_default())
- }
- Self::DocumentInlineScript => source_list
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-inline")),
- Self::DocumentInlineStyleElement => source_list
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-inline")),
- Self::Eval => source_list
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-eval")),
- Self::TrustedTypesEval => source_list.iter().any(|source| {
- csp_keyword_eq(source, "unsafe-eval")
- || csp_keyword_eq(source, "trusted-types-eval")
- }),
- Self::WasmEval => source_list.iter().any(|source| {
- csp_keyword_eq(source, "unsafe-eval") || csp_keyword_eq(source, "wasm-unsafe-eval")
- }),
- }
- }
-}
-
-fn inline_event_handler_source_list_allows(source_list: &[&str], source: &str) -> bool {
- let has_nonce_or_hash = source_list.iter().any(|source| {
- csp_nonce_source_value(source).is_some() || csp_hash_source_value(source).is_some()
- });
- if !has_nonce_or_hash
- && source_list
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-inline"))
- {
- return true;
- }
- if !source_list
- .iter()
- .any(|source| csp_keyword_eq(source, "unsafe-hashes"))
- {
- return false;
- }
- source_list
- .iter()
- .filter_map(|source| csp_hash_source_value(source))
- .any(|hash_source| inline_source_matches_hash(source, hash_source))
-}
-
-fn inline_source_matches_hash(source: &str, hash_source: CspHashSourceValue<'_>) -> bool {
- let digest = hash_source
- .algorithm
- .digest_algorithm()
- .digest_bytes(source.as_bytes());
- let actual = BASE64_STANDARD.encode(digest);
- // Inline checks normalize base64url symbols, preserving padding and all
- // other bytes. External script integrity matches remain literal.
- actual
- .bytes()
- .eq(hash_source.digest.bytes().map(|byte| match byte {
- b'-' => b'+',
- b'_' => b'/',
- _ => byte,
- }))
-}
-
-pub(crate) fn current_script_violation_location(
- scope: &mut v8::PinScope<'_, '_>,
-) -> Option<(String, i32, i32)> {
- let stack = v8::StackTrace::current_stack_trace(scope, 1)?;
- let frame = stack.get_frame(scope, 0)?;
- let source_file = frame
- .get_script_name_or_source_url(scope)
- .map(|source| source.to_rust_string_lossy(scope))
- .map(|source| {
- crate::content_security_policy::content_security_policy_source_file_for_report(&source)
- })
- .unwrap_or_default();
- let line_number = i32::try_from(frame.get_line_number())
- .unwrap_or_default()
- .max(0);
- let column_number = i32::try_from(frame.get_column()).unwrap_or_default().max(0);
- Some((source_file, line_number, column_number))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn protected_url() -> Url {
- Url::parse("https://app.test/page.html").unwrap()
- }
-
- fn request_url(raw: &str) -> Url {
- Url::parse(raw).unwrap()
- }
-
- fn allowed(policy: &str, kind: ContentSecurityPolicyResourceKind, request: &str) -> bool {
- content_security_policy_allows_url(
- &[policy.to_owned()],
- &protected_url(),
- &request_url(request),
- kind,
- )
- }
-
- fn script_element_request_allowed(
- policy: &str,
- request: ContentSecurityPolicyScriptElementRequest<'_>,
- ) -> bool {
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &[policy.to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- request,
- )
- .is_none()
- }
-
- fn frame_ancestors_violation(
- policies: &[&str],
- protected_url: &str,
- ancestor_origins: &[Option<&str>],
- ) -> Option<ContentSecurityPolicyUrlViolation> {
- content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
- &policies
- .iter()
- .map(|policy| (*policy).to_owned())
- .collect::<Vec<_>>(),
- &request_url(protected_url),
- &ancestor_origins
- .iter()
- .map(|ancestor| ancestor.map(request_url))
- .collect::<Vec<_>>(),
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
- }
-
- #[test]
- fn content_security_policy_headers_collect_enforce_headers_only() {
- let headers: Vec<(String, Vec<u8>)> = vec![
- (
- "Content-Security-Policy-Report-Only".to_owned(),
- b"worker-src 'none'".to_vec(),
- ),
- (
- "content-security-policy".to_owned(),
- b" worker-src 'self' ".to_vec(),
- ),
- ("Content-Security-Policy".to_owned(), Vec::new()),
- ];
-
- assert_eq!(
- content_security_policy_headers(&headers),
- vec!["worker-src 'self'".to_owned()]
- );
- assert_eq!(
- content_security_policy_report_only_headers(&headers),
- vec!["worker-src 'none'".to_owned()]
- );
- }
-
- #[test]
- fn csp_headers_preserve_policy_order_and_disposition() {
- let headers: Vec<(String, Vec<u8>)> = vec![
- (
- "CONTENT-SECURITY-POLICY".to_owned(),
- b" , img-src *; report-uri /first, img-src 'none'; report-uri /second, ".to_vec(),
- ),
- (
- "Content-Security-Policy-Report-Only".to_owned(),
- b"script-src * , script-src 'none'".to_vec(),
- ),
- (
- "content-security-policy".to_owned(),
- b"worker-src 'self'".to_vec(),
- ),
- ];
- assert_eq!(
- content_security_policy_headers(&headers),
- [
- "img-src *; report-uri /first",
- "img-src 'none'; report-uri /second",
- "worker-src 'self'",
- ]
- );
- assert_eq!(
- content_security_policy_report_only_headers(&headers),
- ["script-src *", "script-src 'none'"]
- );
- }
-
- #[test]
- fn csp_header_policy_lists_enforce_every_policy() {
- for (value, request, expected) in [
- (
- "img-src * , img-src 'none'",
- "https://cdn.test/asset",
- false,
- ),
- ("img-src *,img-src 'none'", "https://cdn.test/asset", false),
- (
- "img-src *; ignored first, img-src 'none'; ignored second",
- "https://cdn.test/asset",
- false,
- ),
- (
- "img-src https://cdn.test/foo,ignored",
- "https://cdn.test/foo",
- true,
- ),
- (
- "img-src https://cdn.test/foo,ignored",
- "https://cdn.test/foo,ignored",
- false,
- ),
- (
- "img-src https://cdn.test/foo%2cbar",
- "https://cdn.test/foo%2cbar",
- true,
- ),
- (
- "img-src https://cdn.test/foo%2cbar",
- "https://cdn.test/foo,bar",
- true,
- ),
- (
- ", , img-src * , , img-src 'none', ,",
- "https://cdn.test/asset",
- false,
- ),
- (
- "img-src *; img-src 'none', img-src *",
- "https://cdn.test/asset",
- true,
- ),
- (
- "img-src https://cdn.test/foo, img-src https://cdn.test/bar",
- "https://cdn.test/foo",
- false,
- ),
- (
- "img-src https://cdn.test/foo, img-src https://cdn.test/bar",
- "https://cdn.test/bar",
- false,
- ),
- (
- "img-src *; ignored \"start, img-src 'none'; ignored end\"",
- "https://cdn.test/asset",
- false,
- ),
- ] {
- let policies = content_security_policy_headers(&[(
- "Content-Security-Policy".to_owned(),
- value.as_bytes().to_vec(),
- )]);
- assert_eq!(
- content_security_policy_allows_url(
- &policies,
- &protected_url(),
- &request_url(request),
- ContentSecurityPolicyResourceKind::DocumentImage,
- ),
- expected,
- "{value:?} with {request}"
- );
- }
- }
-
- #[test]
- fn csp_header_lists_keep_report_only_violations_with_their_policy() {
- let headers: Vec<(String, Vec<u8>)> = vec![
- ("Content-Security-Policy".to_owned(), b"img-src *".to_vec()),
- (
- "Content-Security-Policy-Report-Only".to_owned(),
- b"img-src *; report-uri /allowed, img-src 'none'; report-uri /blocked".to_vec(),
- ),
- ];
- let protected = protected_url();
- let request = request_url("https://cdn.test/asset");
- assert!(content_security_policy_allows_url(
- &content_security_policy_headers(&headers),
- &protected,
- &request,
- ContentSecurityPolicyResourceKind::DocumentImage,
- ));
- let violation = content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
- &content_security_policy_report_only_headers(&headers),
- &protected,
- &request,
- ContentSecurityPolicyResourceKind::DocumentImage,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Report,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ).expect("the second report-only policy must produce a violation");
- assert_eq!(
- violation.disposition,
- ContentSecurityPolicyDisposition::Report
- );
- assert_eq!(
- violation.original_policy,
- "img-src 'none'; report-uri /blocked"
- );
- assert_eq!(violation.report_uri_endpoints, ["https://app.test/blocked"]);
- }
-
- #[test]
- fn csp_header_lists_preserve_invalid_whitespace_and_skip_empty_policies() {
- for name in [
- "content-security-policy",
- "content-security-policy-report-only",
- ] {
- let collect = |value: &[u8]| {
- content_security_policy_header_values(&[(name.to_owned(), value.to_vec())], name)
- };
- assert!(collect(b", ; ; , \t , img-src 'none'\xa0,").is_empty());
- assert_eq!(
- collect(b"\t\n\r\x0c img-src 'none' , \t"),
- ["img-src 'none'"]
- );
- assert_eq!(
- collect(b"img-src *\x0b, img-src 'none'"),
- ["img-src 'none'"]
- );
- let policies = collect(b"img-src *\x0b");
- assert!(policies.is_empty());
- assert!(content_security_policy_allows_url(
- &policies,
- &protected_url(),
- &request_url("https://cdn.test/asset"),
- ContentSecurityPolicyResourceKind::DocumentImage,
- ));
- assert!(!content_security_policy_allows_url(
- &collect(b"img-src *\x0b, img-src 'none'"),
- &protected_url(),
- &request_url("https://cdn.test/asset"),
- ContentSecurityPolicyResourceKind::DocumentImage,
- ));
- }
- }
-
- #[test]
- fn csp_single_directive_values_reject_commas() {
- let directives = parsed_directives("img-src https://cdn.test/a,b; script-src 'none'");
- assert!(directive_source_list(&directives, IMG_SRC).is_none());
- assert_eq!(
- directive_source_list(&directives, SCRIPT_SRC),
- Some(["'none'"].as_slice())
- );
- }
-
- #[test]
- fn csp_invalid_directive_characters_do_not_block_resources_or_discard_other_directives() {
- for invalid in ('\0'..='\u{0008}')
- .chain(['\u{000b}'])
- .chain('\u{000e}'..='\u{001f}')
- .chain(['\u{007f}', '\u{0080}', '\u{00a0}', '\u{feff}', '中'])
- {
- for value in [
- format!("{invalid}'none'"),
- format!("'no{invalid}ne'"),
- format!("'none'{invalid}"),
- ] {
- let policy = format!("img-src {value}; script-src 'none'; report-uri /blocked");
- let policies = [policy.clone()];
- for disposition in [
- ContentSecurityPolicyDisposition::Enforce,
- ContentSecurityPolicyDisposition::Report,
- ] {
- let violation = |kind| {
- content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
- &policies,
- &protected_url(),
- &request_url("https://cdn.test/asset"),
- kind,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- disposition,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
- };
- assert!(
- violation(ContentSecurityPolicyResourceKind::DocumentImage).is_none(),
- "{policy:?}",
- );
- let blocked =
- violation(ContentSecurityPolicyResourceKind::DocumentScriptElement)
- .expect("the valid script-src directive must still block");
- assert_eq!(blocked.effective_directive, SCRIPT_SRC_ELEM);
- assert_eq!(blocked.disposition, disposition);
- assert_eq!(blocked.original_policy, policy);
- assert_eq!(blocked.report_uri_endpoints, ["https://app.test/blocked"]);
- }
- }
- }
- }
-
- #[test]
- fn csp_invalid_directives_preserve_fallbacks_and_trusted_types_requirements() {
- for invalid in ['\0', '\u{000b}', '\u{001f}', '\u{007f}', '\u{00a0}'] {
- let policy = format!(
- "default-src 'self'; img-src *{invalid}; \
- script-src 'unsafe-eval'{invalid}; trusted-types *{invalid}; \
- require-trusted-types-for 'script'"
- );
- assert!(!allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- "https://cdn.test/asset",
- ));
- assert!(allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- "https://app.test/asset",
- ));
- assert!(
- content_security_policy_non_url_violation_with_source(
- &policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::Eval,
- None,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
- .is_some(),
- "{policy:?}",
- );
- assert!(policy_requires_trusted_types_for_script(&policy));
- assert!(policy_allows_trusted_type_policy_name(&policy, "unlisted"));
-
- let policy = format!(
- "trusted-types allowed; require-trusted-types-for 'script'{invalid}; img-src 'none'"
- );
- assert!(!policy_requires_trusted_types_for_script(&policy));
- assert!(policy_allows_trusted_type_policy_name(&policy, "allowed"));
- assert!(!policy_allows_trusted_type_policy_name(&policy, "unlisted"));
- assert!(!allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- "https://app.test/asset",
- ));
- }
- }
-
- #[test]
- fn csp_invalid_first_values_do_not_activate_later_duplicate_directives() {
- for invalid in ['\0', '\u{000b}', '\u{001f}', '\u{007f}', '\u{00a0}', '中'] {
- let policy = format!("default-src 'none'; img-src *{invalid}; IMG-SRC *");
- assert!(!allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- "https://cdn.test/asset",
- ));
- let policy = format!("img-src 'none'{invalid}; IMG-SRC 'none'");
- assert!(allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- "https://cdn.test/asset",
- ));
- for policy in [
- format!("default-src 'none'; img-src{invalid} 'none'; img-src *"),
- format!("default-src 'none'; {invalid}img-src 'none'; img-src *"),
- ] {
- assert!(
- allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- "https://cdn.test/asset",
- ),
- "{policy:?}"
- );
- }
- let policy = format!("trusted-types *{invalid}; TRUSTED-TYPES allowed");
- assert!(policy_allows_trusted_type_policy_name(&policy, "unlisted"));
- let policy = format!("trusted-types allowed; TRUSTED-TYPES *{invalid}");
- assert!(policy_allows_trusted_type_policy_name(&policy, "allowed"));
- assert!(!policy_allows_trusted_type_policy_name(&policy, "unlisted"));
- }
- }
-
- #[test]
- fn csp_keywords_do_not_strip_control_characters_from_source_tokens() {
- use ContentSecurityPolicyNonUrlKind::*;
- for (kind, keyword) in [
- (DocumentInlineScript, "unsafe-inline"),
- (DocumentInlineStyleElement, "unsafe-inline"),
- (DocumentInlineEventHandler, "unsafe-inline"),
- (DocumentInlineNavigation, "unsafe-inline"),
- (DocumentInlineStyleAttribute, "unsafe-inline"),
- (Eval, "unsafe-eval"),
- (TrustedTypesEval, "unsafe-eval"),
- (TrustedTypesEval, "trusted-types-eval"),
- (WasmEval, "unsafe-eval"),
- (WasmEval, "wasm-unsafe-eval"),
- ] {
- for padding in [
- "",
- " \t\n\r\u{000c}",
- "\0",
- "\u{000b}",
- "\u{001f}",
- "\u{007f}",
- ] {
- let valid = padding.is_empty() || padding.starts_with(' ');
- for source in [
- format!("{padding}'{keyword}'"),
- format!("'{keyword}'{padding}"),
- ] {
- let policy = format!(
- "default-src 'none'; {} {source}",
- kind.effective_directive()
- );
- let violation = content_security_policy_non_url_violation_with_source(
- &policy,
- &protected_url(),
- kind,
- None,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- );
- assert_eq!(violation.is_none(), valid, "{kind:?}: {policy:?}");
- }
- }
- }
- }
-
- #[test]
- fn csp_nonce_and_hash_tokens_preserve_their_boundaries() {
- let source = "t1.done();";
- let integrity = "sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps=";
- for expression in ["'nonce-abc'".to_owned(), format!("'{integrity}'")] {
- for (prefix, suffix, valid) in [
- ("", "", true),
- ("\t\n", " \r\u{000c}", true),
- ("\u{000b}", "", false),
- ("", "\u{000b}", false),
- ] {
- let token = format!("{prefix}{expression}{suffix}");
- let policy = format!("default-src 'none'; script-src {token}; style-src {token}");
- let request = ContentSecurityPolicyScriptElementRequest {
- nonce: Some("abc"),
- integrity: Some(integrity),
- parser_inserted: true,
- };
- assert_eq!(
- script_element_request_allowed(&policy, request),
- valid,
- "{policy:?}"
- );
- let endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let script = content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
- &policy, &protected_url(), source, request,
- ContentSecurityPolicyDisposition::Enforce, &endpoints,
- );
- assert_eq!(script.is_none(), valid, "inline script: {policy:?}");
- let style = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
- &policy, &protected_url(), source,
- ContentSecurityPolicyStyleElementRequest { nonce: Some("abc") },
- ContentSecurityPolicyDisposition::Enforce, &endpoints,
- );
- assert_eq!(style.is_none(), valid, "inline style: {policy:?}");
-
- // Invalid nonce/hash tokens must not disable unsafe-inline or
- // activate strict-dynamic and erase a URL allowlist either.
- let inline_sources = format!("'unsafe-inline' {token}");
- let inline_sources: Vec<_> = inline_sources.split_ascii_whitespace().collect();
- assert_eq!(
- inline_event_handler_source_list_allows(&inline_sources, "untrusted()"),
- !valid,
- "{inline_sources:?}",
- );
- let dynamic_sources = format!("'strict-dynamic' https://cdn.test {token}");
- let dynamic_sources: Vec<_> = dynamic_sources.split_ascii_whitespace().collect();
- assert_eq!(
- source_list_activates_strict_dynamic(&dynamic_sources),
- valid,
- "{dynamic_sources:?}",
- );
- }
- }
- }
-
- #[test]
- fn csp_unsafe_hashes_requires_an_exact_keyword_and_hash_token() {
- let hash = "'sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps='";
- for (sources, allowed) in [
- (format!("'unsafe-hashes' {hash}"), true),
- (format!("\u{000b}'unsafe-hashes' {hash}"), false),
- (format!("'unsafe-hashes'\u{000b} {hash}"), false),
- (format!("'unsafe-hashes' \u{000b}{hash}"), false),
- (format!("'unsafe-hashes' {hash}\u{000b}"), false),
- ] {
- for kind in [
- ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
- ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
- ] {
- let violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- &format!("default-src 'none'; {} {sources}", kind.effective_directive()),
- &protected_url(), kind, "t1.done();",
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- );
- assert_eq!(violation.is_none(), allowed, "{kind:?}: {sources:?}");
- }
- }
- }
-
- #[test]
- fn csp_report_sample_and_trusted_types_eval_preserve_source_tokens() {
- for (prefix, suffix, valid) in [
- ("", "", true),
- ("\t", "\r\u{000c}", true),
- ("\u{000b}", "", false),
- ("", "\u{000b}", false),
- ] {
- let policy = format!("default-src 'none'; script-src {prefix}'report-sample'{suffix}");
- for disposition in [
- ContentSecurityPolicyDisposition::Enforce,
- ContentSecurityPolicyDisposition::Report,
- ] {
- let violation = content_security_policy_non_url_violation_with_source(
- &policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::Eval,
- Some("blocked()"),
- disposition,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
- .expect("report-sample does not authorize evaluation");
- assert_eq!(violation.original_policy, policy);
- assert_eq!(violation.disposition, disposition);
- assert_eq!(
- violation.sample,
- if valid { "blocked()" } else { "" },
- "{policy:?}"
- );
- }
- let policy = format!(
- "require-trusted-types-for 'script'; script-src {prefix}'trusted-types-eval'{suffix}"
- );
- assert_eq!(
- content_security_policy_allows_trusted_types_eval(std::slice::from_ref(&policy)),
- valid,
- "{policy:?}"
- );
- }
- }
-
- #[test]
- fn frame_ancestors_requires_every_ancestor_to_match() {
- let protected_url = "https://child.test/frame.html";
- let ancestors = [Some("https://child.test"), Some("https://top.test")];
-
- let violation =
- frame_ancestors_violation(&["frame-ancestors 'self'"], protected_url, &ancestors)
- .expect("a cross-origin top ancestor must violate 'self'");
- assert_eq!(violation.effective_directive, "frame-ancestors");
- assert_eq!(violation.blocked_uri, protected_url);
-
- assert!(
- frame_ancestors_violation(&["frame-ancestors *"], protected_url, &ancestors).is_none()
- );
- assert!(
- frame_ancestors_violation(
- &["frame-ancestors https://child.test https://top.test"],
- protected_url,
- &ancestors,
- )
- .is_none()
- );
- assert!(
- frame_ancestors_violation(
- &["frame-ancestors https://child.test"],
- protected_url,
- &ancestors,
- )
- .is_some()
- );
- }
-
- #[test]
- fn frame_ancestors_has_no_fallback_and_allows_top_level_documents() {
- assert!(
- frame_ancestors_violation(
- &["default-src 'none'"],
- "https://child.test/frame.html",
- &[Some("https://top.test")],
- )
- .is_none()
- );
- assert!(
- frame_ancestors_violation(
- &["frame-ancestors 'none'"],
- "https://child.test/frame.html",
- &[],
- )
- .is_none()
- );
- }
-
- #[test]
- fn every_frame_ancestors_policy_must_allow_embedding() {
- let violation = frame_ancestors_violation(
- &["frame-ancestors *", "frame-ancestors 'none'"],
- "https://child.test/frame.html",
- &[Some("https://top.test")],
- )
- .expect("one blocking policy must block the response");
- assert_eq!(violation.original_policy, "frame-ancestors 'none'");
- }
-
- #[test]
- fn frame_ancestors_matches_origins_and_rejects_opaque_ancestors() {
- assert!(
- frame_ancestors_violation(
- &["frame-ancestors https://top.test/path"],
- "https://child.test/frame.html",
- &[Some("https://top.test")],
- )
- .is_some(),
- "a host source containing a path must not match an ancestor origin"
- );
- assert!(
- frame_ancestors_violation(
- &["frame-ancestors *"],
- "https://child.test/frame.html",
- &[None],
- )
- .is_some(),
- "an opaque ancestor origin must not match a source expression"
- );
- }
-
- #[test]
- fn worker_src_none_blocks_shared_worker_script() {
- assert!(!allowed(
- "worker-src 'none'; script-src 'self'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- }
-
- #[test]
- fn shared_worker_script_uses_script_src_and_default_src_fallbacks() {
- assert!(!allowed(
- "script-src 'none'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- assert!(!allowed(
- "default-src 'none'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- assert!(allowed(
- "default-src 'self'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- }
-
- #[test]
- fn shared_worker_script_uses_child_src_before_script_src_fallback() {
- assert!(!allowed(
- "child-src 'none'; script-src 'self'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- assert!(allowed(
- "child-src https://workers.test; script-src 'none'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://workers.test/worker.js"
- ));
- }
-
- #[test]
- fn document_script_element_uses_script_src_elem_fallbacks() {
- assert!(!allowed(
- "script-src-elem 'none'; script-src 'self'",
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- "https://app.test/app.js"
- ));
- assert!(allowed(
- "script-src 'self'; default-src 'none'",
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- "https://app.test/app.js"
- ));
- assert!(!allowed(
- "default-src 'none'",
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- "https://app.test/app.js"
- ));
- }
-
- #[test]
- fn worker_src_takes_precedence_for_shared_worker_scripts() {
- assert!(allowed(
- "default-src 'none'; script-src 'none'; worker-src 'self'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- assert!(!allowed(
- "default-src *; script-src *; worker-src 'none'",
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- "https://app.test/worker.js"
- ));
- }
-
- #[test]
- fn url_violation_reports_effective_directive_and_original_policy() {
- let violation = content_security_policy_url_violation_with_redirect_status(
- &[
- "connect-src https://api.test".to_owned(),
- "default-src 'none'".to_owned(),
- ],
- &protected_url(),
- &request_url("https://blocked.test/data.json"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- .expect("blocked worker connect should produce violation");
-
- assert_eq!(violation.effective_directive, "connect-src");
- assert_eq!(violation.blocked_uri, "https://blocked.test/data.json");
- assert_eq!(violation.document_uri, "https://app.test/page.html");
- assert_eq!(violation.original_policy, "connect-src https://api.test");
- assert_eq!(
- violation.disposition,
- ContentSecurityPolicyDisposition::Enforce
- );
- }
-
- #[test]
- fn url_violation_strips_credentials_and_fragments_from_report_urls() {
- let protected_url =
- request_url("https://user:[email protected]/page.html?document=1#current-section");
- let blocked_url =
- request_url("https://other:[email protected]/image.png?asset=1#pixel-fragment");
- let violation = content_security_policy_url_violation_with_redirect_status(
- &["img-src 'none'".to_owned()],
- &protected_url,
- &blocked_url,
- ContentSecurityPolicyResourceKind::DocumentImage,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- .expect("blocked image should produce violation");
-
- assert_eq!(
- violation.document_uri,
- "https://app.test/page.html?document=1"
- );
- assert_eq!(
- violation.blocked_uri,
- "https://blocked.test/image.png?asset=1"
- );
- assert_eq!(
- violation.source_file,
- "https://app.test/page.html?document=1"
- );
- }
-
- #[test]
- fn url_violation_redacts_data_and_blob_urls_to_their_schemes() {
- for (policy, url, expected) in [
- ("media-src 'self'", "data:video/mp4;base64,AAAA", "data"),
- (
- "media-src https://example.com",
- "blob:https://app.test/id",
- "blob",
- ),
- ] {
- let violation = content_security_policy_url_violation_with_redirect_status(
- &[policy.to_owned()],
- &protected_url(),
- &request_url(url),
- ContentSecurityPolicyResourceKind::DocumentMedia,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- .expect("blocked media URL should produce violation");
-
- assert_eq!(violation.effective_directive, "media-src");
- assert_eq!(violation.blocked_uri, expected);
- }
- }
-
- #[test]
- fn redirected_url_violation_reports_original_blocked_uri() {
- let original_url = request_url("https://app.test/redirect");
- let final_url = request_url("https://blocked.test/data.json");
- let violation = content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints(
- &["connect-src 'self'".to_owned()],
- &protected_url(),
- &final_url,
- &original_url,
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyRedirectStatus::FollowedRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
- .expect("redirected blocked worker connect should produce violation");
-
- assert_eq!(violation.effective_directive, "connect-src");
- assert_eq!(violation.blocked_uri, "https://app.test/redirect");
- }
-
- #[test]
- fn self_source_matches_same_origin_only() {
- assert!(allowed(
- "script-src 'self'",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://app.test/worker-import.js"
- ));
- assert!(!allowed(
- "script-src 'self'",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://cdn.test/worker-import.js"
- ));
- }
-
- #[test]
- fn worker_module_imports_use_their_request_specific_directive_fallbacks() {
- let cross_origin = "https://cdn.test/worker-import.js";
-
- assert!(!allowed(
- "worker-src 'self'; script-src *",
- ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
- cross_origin,
- ));
- assert!(allowed(
- "worker-src *; script-src 'self'",
- ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
- cross_origin,
- ));
- assert!(!allowed(
- "script-src-elem 'self'; script-src *",
- ContentSecurityPolicyResourceKind::WorkerDynamicModuleImport,
- cross_origin,
- ));
- assert!(allowed(
- "worker-src 'self'; script-src *",
- ContentSecurityPolicyResourceKind::WorkerDynamicModuleImport,
- cross_origin,
- ));
-
- let violation = content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
- &["script-src 'self'".to_owned()],
- &protected_url(),
- &request_url(cross_origin),
- ContentSecurityPolicyResourceKind::WorkerDynamicModuleImport,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- )
- .expect("script-src fallback should block the cross-origin dynamic import");
- assert_eq!(violation.effective_directive, "script-src-elem");
- }
-
- #[test]
- fn self_source_uses_csp_secure_upgrade_rules() {
- let protected = Url::parse("http://app.test/page.html").unwrap();
- assert!(content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &protected,
- &request_url("https://app.test/api"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ));
- assert!(content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &protected,
- &request_url("ws://app.test/socket"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ));
- assert!(content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &protected,
- &request_url("wss://app.test/socket"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ));
-
- let protected = Url::parse("https://app.test/page.html").unwrap();
- assert!(content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &protected,
- &request_url("wss://app.test/socket"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ));
- assert!(!content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &protected,
- &request_url("ws://app.test/socket"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ));
- assert!(!content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &Url::parse("http://app.test/page.html").unwrap(),
- &request_url("ftp://app.test/resource"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ));
- }
-
- #[test]
- fn connect_src_and_default_src_control_worker_connect_requests() {
- assert!(!allowed(
- "connect-src 'none'",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "https://app.test/api"
- ));
- assert!(!allowed(
- "default-src 'none'",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "https://app.test/api"
- ));
- assert!(allowed(
- "connect-src 'self'; default-src 'none'",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "https://app.test/api"
- ));
- }
-
- #[test]
- fn wildcard_source_does_not_match_local_schemes() {
- assert!(allowed(
- "script-src *",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://app.test/worker-import.js"
- ));
- assert!(!allowed(
- "script-src *",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "data:text/javascript,onconnect=()=>{}"
- ));
- }
-
- #[test]
- fn scheme_sources_use_csp_secure_upgrade_rules() {
- assert!(allowed(
- "connect-src http:",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "https://cdn.test/api"
- ));
- assert!(allowed(
- "connect-src ws:",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "wss://cdn.test/socket"
- ));
- assert!(!allowed(
- "connect-src https:",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "wss://cdn.test/socket"
- ));
- assert!(!allowed(
- "connect-src http:",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "ws://cdn.test/socket"
- ));
- }
-
- #[test]
- fn websocket_source_schemes_match_http_without_allowing_reverse_transitions() {
- for (source_scheme, matches) in [
- ("http", [true, true, false, false]),
- ("https", [false, true, false, false]),
- ("ws", [true, true, true, true]),
- ("wss", [false, true, false, true]),
- ] {
- for (request_scheme, expected) in
- ["http", "https", "ws", "wss"].into_iter().zip(matches)
- {
- for kind in [
- ContentSecurityPolicyResourceKind::DocumentConnect,
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ] {
- for scheme in [source_scheme.to_owned(), source_scheme.to_ascii_uppercase()] {
- let request = format!("{request_scheme}://cdn.test:8443/socket");
- for source in [
- format!("{scheme}:"),
- format!("{scheme}://cdn.test:*/socket"),
- format!("{scheme}://*.test:*/socket"),
- ] {
- assert_eq!(
- allowed(&format!("connect-src {source}"), kind, &request),
- expected,
- "{source} with {request} for {kind:?}",
- );
- }
- }
- }
- }
- }
- }
-
- #[test]
- fn websocket_to_http_host_sources_preserve_port_host_and_path_checks() {
- for authority in ["cdn.test", "*.test"] {
- for (source_scheme, source_port, request, expected) in [
- ("ws", "", "http://cdn.test/socket", true),
- ("ws", ":80", "http://cdn.test/socket", true),
- ("ws", ":8080", "http://cdn.test:8080/socket", true),
- ("ws", ":8080", "http://cdn.test:8081/socket", false),
- ("ws", "", "https://cdn.test/socket", true),
- ("wss", "", "https://cdn.test/socket", true),
- ("wss", ":443", "https://cdn.test/socket", true),
- ("wss", ":8443", "https://cdn.test:8443/socket", true),
- ("wss", ":8443", "https://cdn.test:9443/socket", false),
- ("ws", ":*", "https://other.example:8443/socket", false),
- ("ws", ":*", "https://cdn.test:8443/other", false),
- ("wss", ":*", "http://cdn.test:8443/socket", false),
- ] {
- let policy =
- format!("connect-src {source_scheme}://{authority}{source_port}/socket");
- for kind in [
- ContentSecurityPolicyResourceKind::DocumentConnect,
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ] {
- assert_eq!(
- allowed(&policy, kind, request),
- expected,
- "{policy} with {request}"
- );
- }
- }
- }
- }
-
- #[test]
- fn websocket_scheme_compatibility_does_not_make_self_origins_equal() {
- for (protected, request, expected) in [
- ("ws://app.test/", "ws://app.test/socket", true),
- ("ws://app.test/", "http://app.test/socket", false),
- ("ws://app.test/", "https://app.test/socket", true),
- ("wss://app.test/", "https://app.test/socket", true),
- ("wss://app.test/", "http://app.test/socket", false),
- ] {
- assert_eq!(
- content_security_policy_allows_url(
- &["connect-src 'self'".to_owned()],
- &Url::parse(protected).unwrap(),
- &request_url(request),
- ContentSecurityPolicyResourceKind::DocumentConnect,
- ),
- expected,
- "'self' in {protected} with {request}",
- );
- }
- }
-
- #[test]
- fn source_path_matching_uses_encoded_paths() {
- assert!(allowed(
- "script-src https://app.test/trusted/",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://app.test/trusted/worker.js"
- ));
- assert!(!allowed(
- "script-src https://app.test/trusted/",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://app.test/trusted%2Fevil.js"
- ));
- }
-
- #[test]
- fn host_sources_reject_scheme_relative_urls() {
- for source in ["//cdn.test", "//cdn.test:*", "//*.test", "//*.test:*"] {
- for scheme in ["https", "http"] {
- assert!(!allowed(
- &format!("script-src {source}"),
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- &format!("{scheme}://cdn.test/app.js")
- ));
- }
- }
- }
-
- #[test]
- fn invalid_host_sources_cannot_allow_initial_or_redirected_requests() {
- for (source, request) in [
- (
- "https://cdn.test:*/foo,bar",
- "https://cdn.test:8443/foo,bar",
- ),
- ("https://*.test/foo,bar", "https://cdn.test/foo,bar"),
- ("https://cdn.test/foo,bar", "https://cdn.test/foo,bar"),
- ("https://[email protected]", "https://cdn.test/asset"),
- ("https://%63dn.test", "https://cdn.test/asset"),
- ("https://bad_host.test", "https://bad_host.test/asset"),
- (
- "https://*.bad_host.test:*",
- "https://cdn.bad_host.test:8443/asset",
- ),
- ("https://bad..test", "https://bad..test/asset"),
- ("https://*.test..:*", "https://cdn.test:8443/asset"),
- ("https://cdn.test:", "https://cdn.test/asset"),
- ("https://cdn.test:+443", "https://cdn.test/asset"),
- ("https://cdn.test:65536", "https://cdn.test/asset"),
- ("https://cdn.test/%", "https://cdn.test/%"),
- ("https://cdn.test:*/%6g", "https://cdn.test:8443/%6g"),
- ("https://*.test/%a", "https://cdn.test/%a"),
- ("https://cdn.test//asset", "https://cdn.test//asset"),
- (
- "https://cdn.test/asset\\file",
- "https://cdn.test/asset/file",
- ),
- ("https://cdn.test/[asset]", "https://cdn.test/[asset]"),
- ("https://cdn.test/asset\u{000b}", "https://cdn.test/asset"),
- ("\u{000b}https://cdn.test", "https://cdn.test/asset"),
- ("https://127.1", "https://127.0.0.1/asset"),
- ] {
- for redirect_status in [
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyRedirectStatus::FollowedRedirect,
- ] {
- assert!(
- !source_expression_matches(
- source,
- &protected_url(),
- &request_url(request),
- redirect_status,
- ),
- "{source:?} must not match {request:?} ({redirect_status:?})"
- );
- assert!(
- !content_security_policy_allows_url_with_redirect_status(
- &[format!("default-src 'none'; img-src {source}")],
- &protected_url(),
- &request_url(request),
- ContentSecurityPolicyResourceKind::DocumentImage,
- redirect_status,
- ),
- "{source:?} must not allow {request:?} ({redirect_status:?})"
- );
- }
- }
- }
-
- #[test]
- fn host_source_paths_decode_segments_for_exact_and_wildcard_sources() {
- for authority in ["cdn.test", "cdn.test:*", "*.test", "*.test:*", "*", "*:*"] {
- for (source_path, request_path, expected) in [
- ("/%61sset", "/asset", true),
- ("/asset", "/%61sset", true),
- ("/%61sset/", "/asset/file", true),
- ("/%61sset/", "/asset", false),
- ("/asset", "/ASSET", false),
- ("/asset", "/asset/", false),
- ("/a%2fb", "/a%2Fb", true),
- ("/a%2fb", "/a/b", false),
- ("/a/", "/a%2Fb", false),
- ("/a/", "/a//b", true),
- ("/a//", "/a/b", false),
- ("/a%252fb", "/a%2fb", false),
- ("/a+b", "/a%20b", false),
- ("/a%2bb", "/a+b", true),
- ("/a%2cb", "/a,b", true),
- ("/a%3bb", "/a;b", true),
- ("/%ff", "/%FF", true),
- ("/%ff", "/%fe", false),
- ("/%e4%b8%ad", "/中", true),
- ("/a/../asset", "/asset", false),
- ("/a/%2e%2e/asset", "/asset", false),
- ("/./asset", "/asset", false),
- ("/path://asset", "/path://asset", true),
- ] {
- let policy = format!("img-src https://{authority}{source_path}");
- let request = format!("https://cdn.test{request_path}");
- assert_eq!(
- allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- &request
- ),
- expected,
- "{policy} with {request}"
- );
- }
- }
- }
-
- #[test]
- fn valid_host_source_grammar_preserves_ports_and_raw_hostnames() {
- for (source, request, expected) in [
- ("HTTPS://CDN.TEST:00443", "https://cdn.test/asset", true),
- (
- "cdn.test/path://asset",
- "https://cdn.test/path://asset",
- true,
- ),
- ("https://cdn.test:0", "https://cdn.test:0/asset", true),
- (
- "https://cdn.test:65535",
- "https://cdn.test:65535/asset",
- true,
- ),
- (
- "https://xn--bcher-kva.test",
- "https://bücher.test/asset",
- true,
- ),
- ("https://*.TEST.", "https://cdn.test./asset", true),
- ("https://*.TEST.", "https://cdn.test/asset", false),
- ("https://*.test", "https://cdn.test./asset", false),
- ("ftp://cdn.test", "ftp://cdn.test/asset", true),
- ("https://192.0.2.1", "https://192.0.2.1/asset", true),
- (
- "https://192.0.2.1:8443",
- "https://192.0.2.1:8443/asset",
- true,
- ),
- ] {
- assert_eq!(
- allowed(
- &format!("img-src {source}"),
- ContentSecurityPolicyResourceKind::DocumentImage,
- request
- ),
- expected,
- "{source} with {request}"
- );
- }
- }
-
- #[test]
- fn csp_path_matching_preserves_empty_segments_and_byte_boundaries() {
- for (source, request, expected) in [
- ("", "", true),
- ("", "/asset", true),
- ("/", "", true),
- ("/", "/asset", true),
- ("/a/", "/a", false),
- ("/a/", "/a/", true),
- ("/a//", "/a/", false),
- ("/a//", "/a//b", true),
- ("/a%2fb/", "/a/b/file", false),
- ("/a%2fb/", "/a%2Fb/file", true),
- ("/%00", "/%00", true),
- ("/%00", "/", false),
- ("/%ff", "/%fe", false),
- ] {
- assert_eq!(
- csp_path_part_matches(source, request),
- expected,
- "{source:?} with {request:?}"
- );
- }
- }
-
- #[test]
- fn host_sources_reject_query_and_fragment_components() {
- assert!(!allowed(
- "script-src https://cdn.test?ignored",
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- "https://cdn.test/app.js"
- ));
- assert!(!allowed(
- "script-src https://cdn.test/app.js#fragment",
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- "https://cdn.test/app.js"
- ));
- }
-
- #[test]
- fn redirected_source_url_matching_ignores_path_but_not_host() {
- assert!(content_security_policy_allows_url_with_redirect_status(
- &["script-src https://cdn.test/trusted/".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/evil.js"),
- ContentSecurityPolicyResourceKind::WorkerScript,
- ContentSecurityPolicyRedirectStatus::FollowedRedirect,
- ));
- assert!(!content_security_policy_allows_url_with_redirect_status(
- &["script-src https://cdn.test/trusted/".to_owned()],
- &protected_url(),
- &request_url("https://evil.test/evil.js"),
- ContentSecurityPolicyResourceKind::WorkerScript,
- ContentSecurityPolicyRedirectStatus::FollowedRedirect,
- ));
- }
-
- #[test]
- fn wildcard_host_source_matches_subdomains_only() {
- assert!(allowed(
- "script-src *.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://assets.cdn.example.com/worker-import.js"
- ));
- assert!(allowed(
- "script-src https://*.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://assets.cdn.example.com/worker-import.js"
- ));
- assert!(!allowed(
- "script-src *.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://cdn.example.com/worker-import.js"
- ));
- assert!(!allowed(
- "script-src *.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://evilcdn.example.com/worker-import.js"
- ));
- }
-
- #[test]
- fn wildcard_host_source_honors_port_and_path() {
- assert!(allowed(
- "script-src https://*.cdn.example.com:*",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://assets.cdn.example.com:8443/worker-import.js"
- ));
- assert!(!allowed(
- "script-src https://*.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://assets.cdn.example.com:8443/worker-import.js"
- ));
- assert!(allowed(
- "script-src https://*.cdn.example.com/trusted/",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://assets.cdn.example.com/trusted/worker-import.js"
- ));
- assert!(!allowed(
- "script-src https://*.cdn.example.com/trusted/",
- ContentSecurityPolicyResourceKind::WorkerScript,
- "https://assets.cdn.example.com/trusted%2Fevil.js"
- ));
- }
-
- #[test]
- fn exact_host_port_wildcards_apply_across_resource_kinds() {
- for kind in [
- ContentSecurityPolicyResourceKind::DocumentConnect,
- ContentSecurityPolicyResourceKind::DocumentFrame,
- ContentSecurityPolicyResourceKind::DocumentImage,
- ContentSecurityPolicyResourceKind::DocumentManifest,
- ContentSecurityPolicyResourceKind::DocumentMedia,
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- ContentSecurityPolicyResourceKind::DocumentStyleElement,
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyResourceKind::WorkerScript,
- ContentSecurityPolicyResourceKind::SharedWorkerScript,
- ContentSecurityPolicyResourceKind::WorkerStaticModuleImport,
- ] {
- for source in ["https://cdn.test:*", "http://cdn.test:*", "CDN.TEST:*"] {
- for port in ["", ":0", ":80", ":443", ":8443", ":65535"] {
- let policy = format!("default-src {source}");
- let request = format!("https://cdn.test{port}/asset");
- assert!(
- allowed(&policy, kind, &request),
- "{policy} should allow {request} for {kind:?}"
- );
- }
- }
- }
- }
-
- #[test]
- fn exact_host_port_wildcards_preserve_other_source_restrictions() {
- for (source, request, expected) in [
- ("http://cdn.test:*", "http://cdn.test:8080/asset", true),
- ("https://CDN.TEST:*", "https://cdn.test:8443/asset", true),
- ("cdn.test:*", "https://cdn.test:8443/asset", true),
- ("cdn.test:*", "http://cdn.test:8080/asset", false),
- (
- "https://cdn.test:*",
- "https://sub.cdn.test:8443/asset",
- false,
- ),
- (
- "https://cdn.test:*",
- "https://evilcdn.test:8443/asset",
- false,
- ),
- ("https://cdn.test.:*", "https://cdn.test:8443/asset", false),
- ("https://cdn.test.:*", "https://cdn.test.:8443/asset", true),
- ("https://cdn.test:*", "http://cdn.test:8080/asset", false),
- ("http://cdn.test:*", "ws://cdn.test:8080/asset", false),
- ("ws://cdn.test:*", "wss://cdn.test:8443/asset", true),
- ("wss://cdn.test:*", "ws://cdn.test:8080/asset", false),
- (
- "https://cdn.test:*/trusted/",
- "https://cdn.test:8443/trusted/asset",
- true,
- ),
- (
- "https://cdn.test:*/trusted/",
- "https://cdn.test:8443/trusted%2Fevil",
- false,
- ),
- (
- "https://cdn.test:*/trusted/",
- "https://cdn.test:8443/other/asset",
- false,
- ),
- (
- "https://cdn.test:*/asset",
- "https://cdn.test:8443/asset?cache=1",
- true,
- ),
- (
- "https://cdn.test:*/asset",
- "https://cdn.test:8443/asset/extra",
- false,
- ),
- (
- "https://cdn.test:*/asset",
- "https://cdn.test:8443/ASSET",
- false,
- ),
- ("//cdn.test:*", "https://cdn.test:8443/asset", false),
- (
- "https://[email protected]:*",
- "https://cdn.test:8443/asset",
- false,
- ),
- ("https://%63dn.test:*", "https://cdn.test:8443/asset", false),
- (
- "https://cdn.test:*/asset?ignored",
- "https://cdn.test:8443/asset",
- false,
- ),
- (
- "https://cdn.test:*/asset#ignored",
- "https://cdn.test:8443/asset",
- false,
- ),
- ("https://cdn.test:*0", "https://cdn.test:8443/asset", false),
- (
- "https://bad_host.test:*",
- "https://bad_host.test:8443/asset",
- false,
- ),
- (
- "https://bad..host.test:*",
- "https://bad..host.test:8443/asset",
- false,
- ),
- ("https://127.0.0.1:*", "https://127.0.0.1:8443/asset", true),
- ("https://192.0.2.1:*", "https://192.0.2.1:8443/asset", false),
- ("https://[::1]:*", "https://[::1]:8443/asset", false),
- ] {
- let policy = format!("img-src {source}");
- assert_eq!(
- allowed(
- &policy,
- ContentSecurityPolicyResourceKind::DocumentImage,
- request
- ),
- expected,
- "{policy} with {request}"
- );
- }
- }
-
- #[test]
- fn exact_host_port_wildcards_preserve_redirect_restrictions() {
- for (request, expected) in [
- ("https://cdn.test:9443/other/asset", true),
- ("https://other.test:9443/other/asset", false),
- ("http://cdn.test:8080/other/asset", false),
- ] {
- assert_eq!(
- content_security_policy_allows_url_with_redirect_status(
- &["script-src https://cdn.test:*/trusted/".to_owned()],
- &protected_url(),
- &request_url(request),
- ContentSecurityPolicyResourceKind::DocumentScriptElement,
- ContentSecurityPolicyRedirectStatus::FollowedRedirect,
- ),
- expected,
- "a redirected wildcard-port request must still match scheme and host: {request}"
- );
- }
- }
-
- #[test]
- fn host_sources_use_csp_secure_upgrade_rules() {
- assert!(allowed(
- "connect-src http://api.example.com",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "https://api.example.com/socket"
- ));
- assert!(allowed(
- "connect-src ws://api.example.com",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "wss://api.example.com/socket"
- ));
- assert!(!allowed(
- "connect-src https://api.example.com",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "wss://api.example.com/socket"
- ));
- assert!(!allowed(
- "connect-src http://api.example.com",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "https://api.example.com:80/socket"
- ));
- }
-
- #[test]
- fn wildcard_host_sources_use_csp_secure_upgrade_rules() {
- assert!(allowed(
- "connect-src ws://*.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "wss://assets.cdn.example.com/socket"
- ));
- assert!(!allowed(
- "connect-src https://*.cdn.example.com",
- ContentSecurityPolicyResourceKind::WorkerConnect,
- "wss://assets.cdn.example.com/socket"
- ));
- }
-
- #[test]
- fn all_policies_are_enforced() {
- let result = ensure_content_security_policy_allows_url(
- &[
- "script-src 'self'".to_owned(),
- "script-src 'none'".to_owned(),
- ],
- &protected_url(),
- &request_url("https://app.test/worker-import.js"),
- ContentSecurityPolicyResourceKind::WorkerScript,
- || "blocked".to_owned(),
- );
-
- assert!(result.is_err());
- }
-
- #[test]
- fn script_element_nonce_source_allows_external_script_url() {
- let violation =
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &["script-src 'nonce-abc'".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyScriptElementRequest::parser_inserted_with_nonce(Some("abc")),
- );
-
- assert!(
- violation.is_none(),
- "matching script nonce should allow the script element request"
- );
- }
-
- #[test]
- fn style_element_request_uses_style_src_elem_fallbacks_and_nonce() {
- let protected_url = Url::parse("https://example.test/page").unwrap();
- let request_url = Url::parse("https://cdn.test/app.css").unwrap();
- let check = |policy: &str, nonce: Option<&str>| {
- content_security_policy_style_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &[policy.to_owned()],
- &protected_url,
- &request_url,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyStyleElementRequest { nonce },
- )
- };
-
- assert!(check("style-src https://cdn.test", None).is_none());
- assert!(check("default-src https://cdn.test", None).is_none());
- let violation = check("style-src-elem 'none'; style-src https://cdn.test", None)
- .expect("style-src-elem must take precedence over style-src");
- assert_eq!(violation.effective_directive, "style-src-elem");
- assert!(
- check(
- "style-src-elem 'nonce-allowed'; style-src 'none'",
- Some("allowed")
- )
- .is_none(),
- "a matching link nonce must authorize the external style request"
- );
- assert!(
- check(
- "style-src-elem 'nonce-allowed'; style-src https://cdn.test",
- Some("blocked")
- )
- .is_some(),
- "a non-matching nonce must not bypass the operative style-src-elem directive"
- );
- }
-
- #[test]
- fn script_element_strict_dynamic_allows_non_parser_inserted_script() {
- let violation =
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &["script-src 'strict-dynamic' 'nonce-abc'".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: None,
- parser_inserted: false,
- },
- );
-
- assert!(
- violation.is_none(),
- "strict-dynamic should allow script elements inserted by a running trusted script"
- );
- }
-
- #[test]
- fn script_element_strict_dynamic_blocks_parser_inserted_host_source_without_nonce() {
- let violation =
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &["script-src 'strict-dynamic' 'nonce-abc' https://cdn.test".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: None,
- parser_inserted: true,
- },
- )
- .expect("parser-inserted script without nonce should be blocked");
-
- assert_eq!(violation.effective_directive, "script-src-elem");
- }
-
- #[test]
- fn script_element_integrity_hash_source_allows_external_script_url() {
- let violation =
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &["script-src 'ShA256-testdigest'".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: Some("sha256-testdigest"),
- parser_inserted: true,
- },
- );
-
- assert!(
- violation.is_none(),
- "matching integrity metadata should satisfy a CSP hash source regardless of algorithm case"
- );
- }
-
- #[test]
- fn script_element_integrity_requires_every_supported_hash_in_the_source_list() {
- for directive in ["script-src-elem", "script-src", "default-src"] {
- let policy = format!("{directive} 'ShA256-testdigest' 'sha384-strong' 'sha512-other'");
- for (integrity, expected) in [
- ("sha256-testdigest sha384-strong", true),
- ("sha256-testdigest sha256-testdigest", true),
- ("sha512-other sha384-strong sha256-testdigest", true),
- ("sha256-testdigest sha256-unknown", false),
- ("sha256-unknown sha256-testdigest", false),
- ("sha256-testdigest sha512-unknown", false),
- ("sha256-unknown sha384-strong", false),
- ] {
- assert_eq!(
- script_element_request_allowed(
- &policy,
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: Some(integrity),
- parser_inserted: true,
- },
- ),
- expected,
- "{policy}: {integrity}"
- );
- }
- }
- }
-
- #[test]
- fn script_element_integrity_uses_nonempty_parsed_sri_metadata() {
- for (integrity, expected) in [
- (None, false),
- (Some(" \t\r\n\x0c"), false),
- (Some("sha1-ignored sha512-***"), false),
- (Some("sha256-***"), false),
- (Some("SHA256-testdigest"), false),
- (Some("sha256-testdigest\u{a0}"), false),
- (Some("sha256-testdigest sha1-ignored"), true),
- (Some("sha256-testdigest sha512-***"), true),
- (Some("sha256-testdigest sha512-*** sha512-abc==="), false),
- (Some("sha256-testdigest sha512-A=AAA"), false),
- (Some("sha256-testdigest sha512-===="), false),
- (Some("sha256-testdigest?ignored sha-256-testdigest"), true),
- (Some(" \tsha256-testdigest\r\n\x0csha256-testdigest "), true),
- ] {
- assert_eq!(
- script_element_request_allowed(
- "script-src 'sha256-testdigest' 'sha256-***'",
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity,
- parser_inserted: true,
- },
- ),
- expected,
- "{integrity:?}"
- );
- }
- }
-
- #[test]
- fn script_element_integrity_compares_encoded_digests_literally() {
- for (source, integrity, expected) in [
- ("'sha256-YQ=='", "sha256-YQ==", true),
- ("'sha256-YQ=='", "sha256-YQ", false),
- ("'sha256-+w=='", "sha256--w==", false),
- ("'sha256--w=='", "sha256-+w==", false),
- ("'sha256--w=='", "sha256--w==", true),
- ("'sha256-/w=='", "sha256-_w==", false),
- ("'sha256-_w=='", "sha256-/w==", false),
- ("'sha256-YR=='", "sha256-YR==", true),
- ] {
- assert_eq!(
- script_element_request_allowed(
- &format!("script-src {source}"),
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: Some(integrity),
- parser_inserted: true,
- },
- ),
- expected,
- "{source}: {integrity}"
- );
- }
- }
-
- #[test]
- fn partial_integrity_match_preserves_other_script_authorizations() {
- for (other_sources, nonce, parser_inserted, expected) in [
- ("'nonce-allowed'", Some("allowed"), true, true),
- ("https://cdn.test", None, true, true),
- ("'strict-dynamic'", None, false, true),
- ("'strict-dynamic' https://cdn.test", None, true, false),
- ] {
- assert_eq!(
- script_element_request_allowed(
- &format!("script-src 'sha256-testdigest' {other_sources}"),
- ContentSecurityPolicyScriptElementRequest {
- nonce,
- integrity: Some("sha256-testdigest sha256-unknown"),
- parser_inserted,
- },
- ),
- expected,
- "{other_sources}: nonce={nonce:?}, parser_inserted={parser_inserted}"
- );
- }
- }
-
- #[test]
- fn script_src_elem_directive_controls_strict_dynamic_script_element_requests() {
- let allowed =
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &["script-src-elem 'strict-dynamic' 'nonce-abc'; script-src 'nonce-abc'".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: None,
- parser_inserted: false,
- },
- );
- assert!(
- allowed.is_none(),
- "script-src-elem strict-dynamic should control script element requests"
- );
-
- let violation =
- content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request(
- &["script-src 'strict-dynamic' 'nonce-abc'; script-src-elem 'nonce-abc'".to_owned()],
- &protected_url(),
- &request_url("https://cdn.test/script.js"),
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &ContentSecurityPolicyReportingEndpoints::default(),
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: None,
- parser_inserted: false,
- },
- )
- .expect("script-src-elem without strict-dynamic should block this request");
-
- assert_eq!(violation.effective_directive, "script-src-elem");
- }
-
- #[test]
- fn report_uri_endpoints_resolve_against_protected_url() {
- let endpoints = content_security_policy_report_uri_endpoints(
- "connect-src 'none'; report-uri /csp-report https://reports.test/collect",
- &protected_url(),
- );
-
- assert_eq!(
- endpoints,
- vec![
- "https://app.test/csp-report".to_owned(),
- "https://reports.test/collect".to_owned()
- ]
- );
- }
-
- #[test]
- fn report_to_suppresses_legacy_report_uri_transport() {
- let endpoints = content_security_policy_report_uri_endpoints(
- "connect-src 'none'; report-uri /legacy; report-to default",
- &protected_url(),
- );
-
- assert!(endpoints.is_empty());
- }
-
- #[test]
- fn reporting_endpoints_header_resolves_groups_against_protected_url() {
- let endpoints = content_security_policy_reporting_endpoints_from_headers(
- &[
- (
- "Reporting-Endpoints".to_owned(),
- b"default=\"/reports\", csp=\"https://reports.test/csp\"".to_vec(),
- ),
- (
- "reporting-endpoints".to_owned(),
- b"default=\"/override\", ignored=ftp://reports.test/nope".to_vec(),
- ),
- ],
- &protected_url(),
- );
-
- assert_eq!(
- endpoints.endpoint_for_group("default"),
- Some("https://app.test/override")
- );
- assert_eq!(
- endpoints.endpoint_for_group("csp"),
- Some("https://reports.test/csp")
- );
- assert_eq!(endpoints.endpoint_for_group("ignored"), None);
- }
-
- #[test]
- fn report_to_uses_first_group_endpoint_and_suppresses_report_uri() {
- let reporting_endpoints = content_security_policy_reporting_endpoints_from_headers(
- &[(
- "Reporting-Endpoints".to_owned(),
- b"primary=\"/reports/primary\", secondary=\"/reports/secondary\"".to_vec(),
- )],
- &protected_url(),
- );
- let violation =
- content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
- &[
- "connect-src 'none'; report-uri /legacy; report-to primary secondary"
- .to_owned(),
- ],
- &protected_url(),
- &request_url("https://api.test/data.json"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .expect("blocked URL should produce violation");
-
- assert!(violation.report_uri_endpoints.is_empty());
- assert_eq!(
- violation.report_to_endpoints,
- vec!["https://app.test/reports/primary".to_owned()]
- );
- }
-
- #[test]
- fn violation_report_body_uses_csp_report_shape() {
- let violation = content_security_policy_url_violation_with_redirect_status(
- &["connect-src 'none'; report-uri /csp-report".to_owned()],
- &protected_url(),
- &request_url("https://api.test/data.json"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- .expect("blocked URL should produce violation");
- let body = content_security_policy_violation_report_body(
- &ContentSecurityPolicyViolationEventFields::from_url_violation(&violation),
- );
- let value: serde_json::Value = serde_json::from_str(&body).expect("report body JSON");
-
- assert_eq!(
- value,
- serde_json::json!({
- "csp-report": {
- "document-uri": "https://app.test/page.html",
- "referrer": "",
- "violated-directive": "connect-src",
- "effective-directive": "connect-src",
- "original-policy": "connect-src 'none'; report-uri /csp-report",
- "disposition": "enforce",
- "blocked-uri": "https://api.test/data.json",
- "source-file": "https://app.test/page.html",
- "status-code": 0,
- "script-sample": "",
- }
- })
- );
- assert_eq!(
- violation.report_uri_endpoints,
- vec!["https://app.test/csp-report".to_owned()]
- );
- }
-
- #[test]
- fn violation_report_request_uses_csp_fetch_security_modes() {
- let violation = content_security_policy_url_violation_with_redirect_status(
- &["connect-src 'none'; report-uri /csp-report".to_owned()],
- &protected_url(),
- &request_url("https://api.test/data.json"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- .expect("blocked URL should produce violation");
- let requests = content_security_policy_report_requests(
- &ContentSecurityPolicyViolationEventFields::from_url_violation(&violation),
- &violation.report_uri_endpoints,
- &violation.report_to_endpoints,
- );
+ #[test]
+ fn violation_report_request_uses_csp_fetch_security_modes() {
+ let violation = content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints(
+ &["connect-src 'none'; report-uri /csp-report".into()],
+ &protected_url(),
+ &request_url("https://api.test/data.json"),
+ ContentSecurityPolicyResourceKind::WorkerConnect,
+ ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ContentSecurityPolicyDisposition::Enforce,
+ &ContentSecurityPolicyReportingEndpoints::default(),
+ )
+ .expect("blocked URL should produce violation");
+ let requests = content_security_policy_report_requests(
+ &ContentSecurityPolicyViolationEventFields::from_url_violation(&violation),
+ &violation.report_uri_endpoints,
+ &violation.report_to_endpoints,
+ );
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].request_mode, RequestMode::NoCors);
@@ -4004,765 +159,4 @@ mod tests {
);
assert_eq!(requests[0].redirect_mode(), RequestRedirectMode::Error);
}
-
- #[test]
- fn reporting_api_report_body_uses_csp_violation_shape() {
- let violation = content_security_policy_url_violation_with_redirect_status(
- &["connect-src 'none'".to_owned()],
- &protected_url(),
- &request_url("https://api.test/data.json"),
- ContentSecurityPolicyResourceKind::WorkerConnect,
- ContentSecurityPolicyRedirectStatus::NoRedirect,
- )
- .expect("blocked URL should produce violation");
- let body = content_security_policy_reporting_api_report_body(
- &ContentSecurityPolicyViolationEventFields::from_url_violation(&violation),
- );
- let value: serde_json::Value = serde_json::from_str(&body).expect("report body JSON");
-
- assert_eq!(value[0]["type"], "csp-violation");
- assert_eq!(value[0]["url"], "https://app.test/page.html");
- assert_eq!(
- value[0]["body"]["documentURL"],
- "https://app.test/page.html"
- );
- assert_eq!(value[0]["body"]["blockedURL"], "https://api.test/data.json");
- assert_eq!(value[0]["body"]["effectiveDirective"], "connect-src");
- assert_eq!(value[0]["body"]["originalPolicy"], "connect-src 'none'");
- assert_eq!(value[0]["body"]["disposition"], "enforce");
- }
-
- #[test]
- fn non_url_inline_script_uses_script_src_elem_fallbacks() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- assert!(
- content_security_policy_non_url_violation_with_source(
- "script-src-elem 'unsafe-inline'; script-src 'none'",
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineScript,
- None,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .is_none()
- );
-
- let violation = content_security_policy_non_url_violation_with_source(
- "script-src 'self'; default-src 'unsafe-inline'",
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineScript,
- None,
- ContentSecurityPolicyDisposition::Report,
- &reporting_endpoints,
- )
- .expect("script-src should block inline script without unsafe-inline");
- assert_eq!(violation.effective_directive, "script-src-elem");
- assert_eq!(violation.blocked_uri, "inline");
- assert_eq!(
- violation.disposition,
- ContentSecurityPolicyDisposition::Report
- );
- }
-
- #[test]
- fn inline_script_element_accepts_matching_nonce_or_source_hash() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let source = "globalThis.inlineScriptRan = true;";
- let matching_hash = "'sha256-BAF+pD4OL3OpwYDBVElncnexa2ZpNAjS3yn9BmiJEto='";
- let check = |policy: &str, nonce: Option<&str>| {
- content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- source,
- ContentSecurityPolicyScriptElementRequest {
- nonce,
- integrity: None,
- parser_inserted: true,
- },
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(check("script-src 'nonce-abc'", Some("abc")).is_none());
- assert!(check("script-src 'nonce-abc'", Some("wrong")).is_some());
- assert!(check(&format!("script-src {matching_hash}"), None).is_none());
- assert!(
- content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
- &format!("script-src {matching_hash}"),
- &protected_url(),
- "globalThis.inlineScriptRan = false;",
- ContentSecurityPolicyScriptElementRequest::default(),
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .is_some()
- );
- }
-
- #[test]
- fn inline_script_element_unsafe_inline_obeys_nonce_and_strict_dynamic_precedence() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let check = |policy: &str, parser_inserted: bool| {
- content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- "globalThis.inlineScriptRan = true;",
- ContentSecurityPolicyScriptElementRequest {
- nonce: None,
- integrity: None,
- parser_inserted,
- },
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(check("script-src 'unsafe-inline'", true).is_none());
- assert!(check("script-src 'unsafe-inline' 'nonce-abc'", true).is_some());
- assert!(check("script-src 'unsafe-inline' 'strict-dynamic'", true).is_some());
- assert!(check("script-src 'unsafe-inline' 'strict-dynamic'", false).is_none());
- }
-
- #[test]
- fn inline_style_element_uses_style_src_elem_and_accepts_nonce_or_hash() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let source = "p { color: green; }";
- let matching_hash = "'sha256-FSRZotz4y83Ib8ZaoVj9eXKaeWXVUawM8zAPfYeYySs='";
- let check = |policy: &str, nonce: Option<&str>| {
- content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- source,
- ContentSecurityPolicyStyleElementRequest { nonce },
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(check("style-src-elem 'nonce-abc'; style-src 'none'", Some("abc")).is_none());
- assert!(
- check(
- "style-src-elem 'nonce-abc'; style-src 'unsafe-inline'",
- None
- )
- .is_some()
- );
- assert!(check(&format!("style-src {matching_hash}"), None).is_none());
- assert!(check("default-src 'unsafe-inline'", None).is_none());
- assert!(check("style-src 'unsafe-inline' 'nonce-abc'", None).is_some());
- }
-
- #[test]
- fn inline_hash_source_algorithm_names_are_ascii_case_insensitive() {
- let source = "p { color: green; }";
- let cases = [
- ("SHA256", "FSRZotz4y83Ib8ZaoVj9eXKaeWXVUawM8zAPfYeYySs="),
- (
- "sHa384",
- "XObbzlg3meDKX3QpZZz8hg0V39bxZI/QQ3qFg6emWOdBZinTtjOls/GimTwBU+WQ",
- ),
- (
- "Sha512",
- "yYhoHoYeH6+9nQONNTy2KAd3tps87iT2d7E58PcEnU5YmJh2am3blPT0gLXu3qnVxDvF/qQKibav9lIK3pCz1A==",
- ),
- ];
-
- for (algorithm, digest) in cases {
- let expression = format!("'{algorithm}-{digest}'");
- let hash_source = csp_hash_source_value(&expression)
- .expect("supported hash algorithm should parse case-insensitively");
- assert!(inline_source_matches_hash(source, hash_source));
- }
- assert!(csp_hash_source_value("'SHA1-digest'").is_none());
- }
-
- #[test]
- fn inline_hashes_normalize_base64url_symbols_without_decoding_the_digest() {
- let source = "globalThis.__inlineHashRuns += 1;/*☃ 8*/";
- for (algorithm, encoded) in [
- ("sHa256", "1u5siURgPyHwZ-QAD8UUU8_PSFeCLQfQgff1wmWe30c="),
- (
- "sHa384",
- "dfgfWBTXEJmr8n1u3heMCmQspfZzXztxsa6b_uRqupCtR1-hV5y1NIRIuk1GgyfX",
- ),
- (
- "sHa512",
- "yuIija81LFQ7iw1A1DtvkYIsDvqIgpOAzeloywzVVvfCZdYs43Z-Dh0lhILbiEstq4O56dtDfie_iALMCVjEMA==",
- ),
- ] {
- let matches = |source: &str, encoded: &str| {
- let expression = format!("'{algorithm}-{encoded}'");
- inline_source_matches_hash(source, csp_hash_source_value(&expression).unwrap())
- };
- for encoded in [
- encoded.to_owned(),
- encoded.replace('-', "+"),
- encoded.replace('_', "/"),
- encoded.replace('-', "+").replace('_', "/"),
- ] {
- assert!(matches(source, &encoded), "{algorithm}: {encoded}");
- assert!(!matches(&format!("{source} "), &encoded));
- assert!(!matches(source, &encoded.to_ascii_uppercase()));
- assert!(!matches(source, &format!("{encoded}=")));
- if encoded.ends_with('=') {
- assert!(!matches(source, encoded.trim_end_matches('=')));
- }
- }
- }
- // Changing unused padding bits can decode to the same bytes, but CSP
- // compares encoded strings after replacing only '-' and '_'.
- assert!(!inline_source_matches_hash(
- source,
- csp_hash_source_value("'sha256-1u5siURgPyHwZ-QAD8UUU8_PSFeCLQfQgff1wmWe30d='",)
- .unwrap()
- ));
- }
-
- #[test]
- fn style_and_navigation_hash_checks_accept_base64url_and_require_unsafe_hashes() {
- let endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let style_source = ".target { color: green; }/*☃ 0*/";
- let style_policy = "style-src 'sha256-GIrKCpP-iQOfwzOEC4HO_QF0a8OAlKUdqbDq5l8WXn0='";
- for (source, allowed) in [
- (style_source.to_owned(), true),
- (format!("{style_source} "), false),
- ] {
- let violation = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
- style_policy, &protected_url(), &source, ContentSecurityPolicyStyleElementRequest::default(),
- ContentSecurityPolicyDisposition::Enforce, &endpoints,
- );
- assert_eq!(violation.is_none(), allowed);
- }
- for (kind, source, encoded) in [
- (
- ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
- "color: green;/*☃ 8*/",
- "GjRTlK2I8F4B9NVwz22_fJvEUruslF4nw-V2jUp0LIM=",
- ),
- (
- ContentSecurityPolicyNonUrlKind::DocumentInlineNavigation,
- "javascript:/*☃ 0*/void(0)",
- "r92XonOGS4-_MCpEOXhFyBgS4-xKf3v6fZMeHTK873c=",
- ),
- ] {
- for unsafe_hashes in ["", "'unsafe-hashes'"] {
- let policy = format!("default-src {unsafe_hashes} 'sha256-{encoded}'");
- for (source, matching) in [(source.to_owned(), true), (format!("{source} "), false)]
- {
- let violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- &policy, &protected_url(), kind, &source,
- ContentSecurityPolicyDisposition::Enforce, &endpoints,
- );
- assert_eq!(
- violation.is_none(),
- matching && !unsafe_hashes.is_empty(),
- "{kind:?}: {policy}"
- );
- }
- }
- }
- }
-
- #[test]
- fn inline_hash_base64url_normalization_does_not_normalize_nonces() {
- for (nonce, allowed) in [("-_/+", true), ("+//+", false), ("-_--", false)] {
- assert_eq!(
- script_element_request_allowed(
- "script-src 'nonce--_/+'",
- ContentSecurityPolicyScriptElementRequest {
- nonce: Some(nonce),
- ..Default::default()
- },
- ),
- allowed,
- "{nonce}"
- );
- }
- }
-
- #[test]
- fn inline_style_attribute_uses_style_src_attr_and_requires_unsafe_hashes() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let source = "background: green";
- let matching_hash = "'sha256-S0VSqEOmzmyOifPfat2sJ7ELOgkldAEbaXlvi5iMqjc='";
- let check = |policy: &str| {
- content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
- source,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(check("style-src-attr 'unsafe-inline'; style-src 'none'").is_none());
- assert!(check("style-src-attr 'none'; style-src 'unsafe-inline'").is_some());
- assert!(check(&format!("style-src 'unsafe-hashes' {matching_hash}")).is_none());
- assert!(check(&format!("style-src {matching_hash}")).is_some());
- assert!(check("default-src 'unsafe-inline'").is_none());
- }
-
- #[test]
- fn inline_style_violation_sample_requires_report_sample_and_is_clipped() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let source = "0123456789012345678901234567890123456789extra";
- let check_element = |policy: &str| {
- content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- source,
- ContentSecurityPolicyStyleElementRequest::default(),
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .expect("inline style should be blocked")
- };
- let check_attribute = |policy: &str| {
- content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
- source,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .expect("inline style attribute should be blocked")
- };
-
- assert_eq!(check_element("style-src 'none'").sample, "");
- assert_eq!(
- check_element("style-src 'none' 'report-sample'").sample,
- "0123456789012345678901234567890123456789"
- );
- assert_eq!(
- check_attribute("style-src-attr 'none' 'report-sample'").sample,
- "0123456789012345678901234567890123456789"
- );
- }
-
- #[test]
- fn inline_event_handler_uses_script_src_attr_fallbacks() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let check = |policy: &str, source: &str| {
- content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
- source,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(
- check(
- "script-src-attr 'unsafe-inline'; script-src 'none'",
- "run() "
- )
- .is_none()
- );
- let violation = check(
- "script-src-attr 'none'; script-src 'unsafe-inline'",
- "run()",
- )
- .expect("script-src-attr should take precedence over script-src");
- assert_eq!(violation.effective_directive, "script-src-attr");
- assert_eq!(violation.blocked_uri, "inline");
- assert!(check("script-src 'unsafe-inline'; default-src 'none'", "run()").is_none());
- assert!(check("default-src 'unsafe-inline'", "run()").is_none());
- }
-
- #[test]
- fn inline_event_handler_hash_requires_unsafe_hashes_and_an_exact_digest() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let source = "t1.done();";
- let matching_hash = "'sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps='";
- let check = |policy: &str, source: &str| {
- content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
- source,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(
- check(
- &format!("script-src 'unsafe-hashes' {matching_hash}"),
- source,
- )
- .is_none()
- );
- assert!(check(&format!("script-src {matching_hash}"), source).is_some());
- assert!(
- check(
- &format!("script-src 'unsafe-hashes' {matching_hash}"),
- "t1.done()",
- )
- .is_some()
- );
- }
-
- #[test]
- fn inline_navigation_hashes_the_complete_javascript_url() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- let source = "javascript:opener.postMessage('pass', '*')";
- let matching_hash = "'sha256-IIiAJ8UuliU8o1qAv6CV4P3R8DeTf/v3MrsCwXW171Y='";
- let check = |policy: &str, source: &str| {
- content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineNavigation,
- source,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- };
-
- assert!(
- check(
- &format!("script-src 'unsafe-hashes' {matching_hash}"),
- source,
- )
- .is_none()
- );
- assert!(check(&format!("script-src {matching_hash}"), source).is_some());
- let violation = check(
- &format!("script-src-elem 'none'; script-src 'unsafe-hashes' {matching_hash}"),
- source,
- )
- .expect("script-src-elem should take precedence for inline navigation");
- assert_eq!(violation.effective_directive, "script-src-elem");
- assert_eq!(violation.blocked_uri, "inline");
- }
-
- #[test]
- fn inline_event_handler_unsafe_inline_is_ignored_when_a_nonce_or_hash_is_present() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- for policy in [
- "script-src 'unsafe-inline' 'nonce-abc'",
- "script-src 'unsafe-inline' 'sha256-wmuLCpoj8EMqfQlPnt5NIMgKkCK62CxAkAiewI0zZps='",
- ] {
- assert!(
- content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
- "untrusted()",
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .is_some(),
- "{policy}",
- );
- }
- }
-
- #[test]
- fn non_url_wasm_eval_uses_script_src_or_default_src() {
- let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
- for policy in [
- "script-src 'wasm-unsafe-eval'; default-src 'none'",
- "script-src 'unsafe-eval'",
- "default-src 'unsafe-eval'",
- ] {
- assert!(
- content_security_policy_non_url_violation_with_source(
- policy,
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::WasmEval,
- None,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .is_none(),
- "{policy}"
- );
- }
-
- let violation = content_security_policy_non_url_violation_with_source(
- "default-src 'self'",
- &protected_url(),
- ContentSecurityPolicyNonUrlKind::WasmEval,
- None,
- ContentSecurityPolicyDisposition::Enforce,
- &reporting_endpoints,
- )
- .expect("default-src should block wasm eval without unsafe eval source");
- assert_eq!(violation.effective_directive, "script-src");
- assert_eq!(violation.blocked_uri, "wasm-eval");
- }
-
- #[test]
- fn trusted_types_directive_filters_policy_names() {
- let allowed = |policies: &[&str], name: &str| {
- content_security_policy_allows_trusted_type_policy_name(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- name,
- )
- };
-
- assert!(allowed(&[], "SomeName"));
- assert!(allowed(&["default-src 'none'"], "SomeName"));
- assert!(allowed(&["trusted-types SomeName OtherName"], "SomeName"));
- assert!(allowed(&["trusted-types * 'aLLow-dUPLIcates'"], "SomeName"));
- assert!(allowed(&["trusted-types 'none' SomeName"], "SomeName"));
- assert!(!allowed(&["trusted-types"], "SomeName"));
- assert!(!allowed(&["trusted-types 'nONe'"], "SomeName"));
- assert!(!allowed(&["trusted-types SomeName"], "default"));
- assert!(!allowed(
- &["trusted-types SomeName", "trusted-types OtherName"],
- "SomeName"
- ));
- }
-
- #[test]
- fn trusted_types_csp_name_grammar_matches_only_valid_tokens() {
- // Directive grammar errors and policy delimiters are tested separately: they discard the
- // directive before its tt-policy-name tokens are interpreted.
- for byte in [b'\t', b'\n', b'\x0c', b'\r']
- .into_iter()
- .chain(b' '..=b'~')
- .filter(|byte| !matches!(*byte, b',' | b';'))
- {
- let name = format!("policy{}name", char::from(byte));
- let policy = format!("trusted-types {name}");
- let expected = byte.is_ascii_alphanumeric() || b"-#=_/@.%".contains(&byte);
- assert_eq!(
- policy_allows_trusted_type_policy_name(&policy, &name),
- expected,
- "invalid tt-policy-name byte {byte:#04x} must not match literally",
- );
- }
- for name in ["none", "allow-duplicates", "A-z_09#=/@.%"] {
- assert!(policy_allows_trusted_type_policy_name(
- &format!("trusted-types {name}"),
- name
- ));
- }
- assert!(policy_allows_trusted_type_policy_name(
- "trusted-types valid policy*name",
- "valid"
- ));
- assert!(!policy_allows_trusted_type_policy_name(
- "trusted-types valid policy*name",
- "policy*name"
- ));
- for wildcard in ["policy*", "**"] {
- assert!(!policy_allows_trusted_type_policy_name(
- &format!("trusted-types {wildcard}"),
- "valid"
- ));
- }
- }
-
- #[test]
- fn trusted_types_csp_name_grammar_does_not_restrict_unlisted_or_wildcard_names() {
- for name in [
- "",
- "policy*name",
- "policy$name",
- "política",
- "ポリシー",
- "\0",
- ] {
- for policy in ["", "trusted-types *"] {
- assert!(policy_allows_trusted_type_policy_name(policy, name));
- }
- }
- }
-
- #[test]
- fn csp_directive_parser_discards_invalid_values_without_replacing_first_directives() {
- for directive in [
- "trusted-types allowed política",
- "trusted-types\u{a0}allowed",
- "\u{a0}trusted-types allowed",
- "trusted-types allowed\u{a0}",
- "require-trusted-types-for 'script' ポリシー",
- "script-src 'none' https://例子.test",
- ] {
- assert!(parsed_directives(directive).is_empty(), "{directive}");
- }
-
- let directives = parsed_directives(
- "trusted-types invalid política; TRUSTED-TYPES allowed; trusted-types *; \
- script-src 'none'; img-src https://例子.test; img-src 'self'",
- );
- assert!(directive_source_list(&directives, TRUSTED_TYPES).is_none());
- assert_eq!(
- directive_source_list(&directives, SCRIPT_SRC),
- Some(["'none'"].as_slice()),
- );
- assert!(directive_source_list(&directives, IMG_SRC).is_none());
- }
-
- #[test]
- fn csp_directive_parser_uses_only_ascii_whitespace_around_names() {
- for space in ['\t', '\n', '\u{000c}', '\r', ' '] {
- let policy = format!("{space}TrUsTeD-TyPeS{space}allowed{space}");
- let directives = parsed_directives(&policy);
- assert_eq!(
- directive_source_list(&directives, TRUSTED_TYPES),
- Some(["allowed"].as_slice()),
- );
- }
- for invalid in ['\0', '\u{000b}', '\u{001f}', '\u{007f}'] {
- for policy in [
- format!("{invalid}trusted-types allowed"),
- format!("trusted-types{invalid} allowed"),
- ] {
- assert!(
- directive_source_list(&parsed_directives(&policy), TRUSTED_TYPES).is_none(),
- "{policy:?}",
- );
- }
- }
- }
-
- #[test]
- fn trusted_types_eval_requires_enforcement_and_an_operative_keyword() {
- let allowed = |policies: &[&str]| {
- content_security_policy_allows_trusted_types_eval(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- )
- };
-
- assert!(allowed(&[
- "require-trusted-types-for 'script'; script-src 'trusted-types-eval'"
- ]));
- assert!(allowed(&[
- "require-trusted-types-for 'script'",
- "default-src 'trusted-types-eval'"
- ]));
- assert!(!allowed(&["script-src 'trusted-types-eval'"]));
- assert!(!allowed(&[
- "require-trusted-types-for 'script'; default-src 'trusted-types-eval'; script-src 'self'"
- ]));
- assert!(!allowed(&[
- "require-trusted-types-for 'script'; script-src 'unsafe-eval'"
- ]));
- }
-
- #[test]
- fn sandbox_directive_forces_opaque_origin_without_allow_same_origin() {
- let forces_opaque = |policies: &[&str]| {
- content_security_policy_forces_opaque_origin(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- )
- };
-
- assert!(!forces_opaque(&[]));
- assert!(!forces_opaque(&["script-src 'self'"]));
- assert!(forces_opaque(&["sandbox"]));
- assert!(forces_opaque(&["sandbox allow-scripts"]));
- assert!(!forces_opaque(&["sandbox allow-scripts allow-same-origin"]));
- assert!(!forces_opaque(&["sandbox allow-scripts ALLOW-SAME-ORIGIN"]));
- }
-
- #[test]
- fn sandbox_directive_sandboxes_document_domain_even_with_allow_same_origin() {
- let sandboxes_document_domain = |policies: &[&str]| {
- content_security_policy_sandboxes_document_domain(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- )
- };
-
- assert!(!sandboxes_document_domain(&[]));
- assert!(!sandboxes_document_domain(&["script-src 'self'"]));
- assert!(sandboxes_document_domain(&["sandbox"]));
- assert!(sandboxes_document_domain(&["sandbox allow-scripts"]));
- assert!(sandboxes_document_domain(&[
- "sandbox allow-scripts allow-same-origin"
- ]));
- assert!(sandboxes_document_domain(&[
- "sandbox allow-scripts ALLOW-SAME-ORIGIN"
- ]));
- }
-
- #[test]
- fn sandbox_directive_allows_scripts_only_when_all_active_sandboxes_allow_it() {
- let allows_scripts = |policies: &[&str]| {
- content_security_policy_sandbox_allows_scripts(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- )
- };
-
- assert!(allows_scripts(&[]));
- assert!(allows_scripts(&["script-src 'self'"]));
- assert!(!allows_scripts(&["sandbox"]));
- assert!(allows_scripts(&["sandbox allow-scripts"]));
- assert!(allows_scripts(&["sandbox ALLOW-SCRIPTS"]));
- assert!(!allows_scripts(&[
- "sandbox allow-scripts",
- "sandbox allow-same-origin"
- ]));
- }
-
- #[test]
- fn sandbox_directive_allows_modals_only_when_all_active_sandboxes_allow_it() {
- let allows_modals = |policies: &[&str]| {
- content_security_policy_sandbox_allows_modals(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- )
- };
-
- assert!(allows_modals(&[]));
- assert!(allows_modals(&["script-src 'self'"]));
- assert!(!allows_modals(&["sandbox"]));
- assert!(allows_modals(&["sandbox allow-modals"]));
- assert!(allows_modals(&["sandbox ALLOW-MODALS"]));
- assert!(!allows_modals(&[
- "sandbox allow-modals",
- "sandbox allow-scripts"
- ]));
- }
-
- #[test]
- fn sandbox_directive_allows_popups_to_escape_only_when_all_active_sandboxes_allow_it() {
- let allows_popups_to_escape = |policies: &[&str]| {
- content_security_policy_sandbox_allows_popups_to_escape(
- &policies
- .iter()
- .map(|policy| policy.to_string())
- .collect::<Vec<_>>(),
- )
- };
-
- assert!(!allows_popups_to_escape(&[]));
- assert!(!allows_popups_to_escape(&["script-src 'self'"]));
- assert!(!allows_popups_to_escape(&["sandbox"]));
- assert!(allows_popups_to_escape(&[
- "sandbox allow-popups-to-escape-sandbox"
- ]));
- assert!(allows_popups_to_escape(&[
- "sandbox ALLOW-POPUPS-TO-ESCAPE-SANDBOX"
- ]));
- assert!(!allows_popups_to_escape(&[
- "sandbox allow-popups-to-escape-sandbox",
- "sandbox allow-scripts"
- ]));
- }
}
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs
index 61755bd0c..ffc3d3986 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs
@@ -5,6 +5,25 @@ use crate::context_bootstrap::events::EventInit;
use crate::webidl;
use webidl::WebIdlDictionarySerialize;
+#[derive(Clone, Copy, Debug, Eq, PartialEq, webidl::WebIdlEnum)]
+#[webidl(
+ name = "SecurityPolicyViolationEventDisposition",
+ rename_all = "kebab-case"
+)]
+enum SecurityPolicyViolationEventDisposition {
+ Enforce,
+ Report,
+}
+
+impl From<ContentSecurityPolicyDisposition> for SecurityPolicyViolationEventDisposition {
+ fn from(disposition: ContentSecurityPolicyDisposition) -> Self {
+ match disposition {
+ ContentSecurityPolicyDisposition::Enforce => Self::Enforce,
+ ContentSecurityPolicyDisposition::Report => Self::Report,
+ }
+ }
+}
+
// Convert EventInit first, then the derived members in lexical order. Keep
// DOMString code units distinct from the four USVString URL fields.
#[derive(webidl::WebIdlDictionary)]
@@ -16,8 +35,8 @@ pub(super) struct SecurityPolicyViolationEventInit {
blocked_uri: String,
#[webidl(name = "columnNumber", default = 0)]
column_number: u32,
- #[webidl(converter = "enum", default = ContentSecurityPolicyDisposition::Enforce)]
- disposition: ContentSecurityPolicyDisposition,
+ #[webidl(converter = "enum", default = SecurityPolicyViolationEventDisposition::Enforce)]
+ disposition: SecurityPolicyViolationEventDisposition,
#[webidl(name = "documentURI", default = "", converter = "usv_string")]
document_uri: String,
#[webidl(name = "effectiveDirective", default = webidl::DomString16(Vec::new()), converter = "raw")]
@@ -44,7 +63,7 @@ impl Default for SecurityPolicyViolationEventInit {
base: EventInit::default(),
blocked_uri: String::new(),
column_number: 0,
- disposition: ContentSecurityPolicyDisposition::Enforce,
+ disposition: SecurityPolicyViolationEventDisposition::Enforce,
document_uri: String::new(),
effective_directive: webidl::DomString16(Vec::new()),
line_number: 0,
@@ -113,7 +132,7 @@ pub(crate) fn initialize_native_security_policy_violation_event<'s>(
},
blocked_uri: fields.blocked_uri.to_owned(),
column_number: fields.column_number.try_into().unwrap_or_default(),
- disposition: fields.disposition,
+ disposition: fields.disposition.into(),
document_uri: fields.document_uri.to_owned(),
effective_directive: text(fields.effective_directive),
line_number: fields.line_number.try_into().unwrap_or_default(),
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs
index 53054e86b..f3a4c2e92 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs
@@ -7,6 +7,7 @@ use super::navigation_window::{
runtime_window_owner, window_history_for_holder, window_navigation_for_holder,
};
use super::*;
+use crate::content_security_policy::ContentSecurityPolicy;
use crate::native_bridge::{
NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntryId,
NavigationHistoryEntryKey, NavigationHistoryEntrySeed, NavigationHistorySerializedEntry,
@@ -288,7 +289,7 @@ pub(super) fn document_referrer_policy_for_native_document(
pub(super) fn current_document_content_security_policies<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
-) -> Vec<String> {
+) -> Vec<ContentSecurityPolicy> {
let Some(document) = get_own_static_property(scope, owner, "document")
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
else {
@@ -296,13 +297,8 @@ pub(super) fn current_document_content_security_policies<'s>(
};
if let Ok((runtime_ptr, document_handle)) = node_runtime_and_handle_from_object(scope, document)
{
- let mut policies = Vec::new();
- document_content_security_policies_in_subtree(
- unsafe { &*runtime_ptr },
- document_handle,
- &mut policies,
- );
- return policies;
+ return unsafe { &*runtime_ptr }
+ .meta_content_security_policies_for_document(document_handle);
}
let Some(runtime_ptr) = context_host_ptr_from_global_bridge(scope) else {
return Vec::new();
@@ -314,13 +310,7 @@ pub(super) fn current_document_content_security_policies<'s>(
) else {
return Vec::new();
};
- let mut policies = Vec::new();
- document_content_security_policies_in_subtree(
- unsafe { &*runtime_ptr },
- document_handle,
- &mut policies,
- );
- policies
+ unsafe { &*runtime_ptr }.meta_content_security_policies_for_document(document_handle)
}
fn current_entry_referrer_policy<'s>(
@@ -360,31 +350,6 @@ fn document_referrer_policy_in_subtree(
None
}
-fn document_content_security_policies_in_subtree(
- runtime: &crate::native_bridge::JsContextHost,
- handle: DomHandle,
- policies: &mut Vec<String>,
-) {
- if let Some(element) = runtime
- .dom_host()
- .node(handle)
- .and_then(|node| node.as_element())
- && element.local_name().eq_ignore_ascii_case("meta")
- && element
- .attribute("http-equiv")
- .is_some_and(|value| value.eq_ignore_ascii_case("Content-Security-Policy"))
- && let Some(policy) = element.attribute("content")
- {
- policies.push(policy.to_owned());
- }
-
- let mut child = runtime.dom_host().first_child(handle);
- while let Some(child_handle) = child {
- document_content_security_policies_in_subtree(runtime, child_handle, policies);
- child = runtime.dom_host().next_sibling(child_handle);
- }
-}
-
fn normalize_meta_referrer_policy(raw: &str) -> Option<String> {
normalize_referrer_policy(raw)
}
diff --git a/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs b/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs
index 601be528f..7942b1a18 100644
--- a/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs
+++ b/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::{
CHILD_BROWSING_CONTEXT_HANDLE_SLOT, MessagePortRealmBinding,
ensure_message_port_wrapper_for_id_in_realm,
@@ -135,7 +137,7 @@ struct SharedWorkerConstructorContext {
storage_key: MoliStorageKey,
top_level_site: String,
document_referrer_policy: Option<String>,
- document_content_security_policies: Vec<String>,
+ document_content_security_policies: Vec<ContentSecurityPolicy>,
browser_context_runtime: RendererBrowserContextRuntime,
indexed_db_manager: Option<WeakIndexedDbManager>,
storage_bucket_store: SharedStorageBucketStore,
@@ -440,7 +442,7 @@ fn shared_worker_constructor_context(
let top_level_site = storage_key.top_level_site().to_owned();
let mut document_content_security_policies = if let Some(handle) = child_handle {
host.child_browsing_context_content_security_policies(handle)
- .map(<[String]>::to_vec)
+ .map(<[_]>::to_vec)
.unwrap_or_else(|| host.document_content_security_policies().to_vec())
} else if let Some(policies) =
host.active_lightweight_popup_content_security_policies(scope)
diff --git a/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs b/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs
index 9f14bf9ef..ec0f21a51 100644
--- a/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs
+++ b/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs
@@ -180,7 +180,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
let dispatch_scope = crate::native_bridge::OwnerDispatchScope::from(owner_scope);
let mut document_content_security_policies = if let Some(handle) = child_handle {
host.child_browsing_context_content_security_policies(handle)
- .map(<[String]>::to_vec)
+ .map(<[_]>::to_vec)
.unwrap_or_else(|| host.document_content_security_policies().to_vec())
} else if let Some(policies) =
host.active_lightweight_popup_content_security_policies(scope)
diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs
index ab67a0c6d..ecf577aa6 100644
--- a/moli-renderer-v8/src/document_runtime.rs
+++ b/moli-renderer-v8/src/document_runtime.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use std::{
cell::RefCell,
collections::{HashMap, HashSet, VecDeque},
@@ -635,9 +637,9 @@ pub(crate) struct DocumentPolicyContainer {
crate::cross_origin_isolation::CrossOriginEmbedderPolicy,
pub(crate) document_isolation_policy: crate::cross_origin_isolation::DocumentIsolationPolicy,
pub(crate) cross_origin_isolated: bool,
- pub(crate) document_content_security_policies: Vec<String>,
- pub(crate) response_content_security_policies: Vec<String>,
- pub(crate) response_content_security_report_only_policies: Vec<String>,
+ pub(crate) document_content_security_policies: Vec<ContentSecurityPolicy>,
+ pub(crate) response_content_security_policies: Vec<ContentSecurityPolicy>,
+ pub(crate) response_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
pub(crate) content_security_reporting_endpoints:
crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
pub(crate) credentialless: bool,
@@ -670,7 +672,9 @@ impl Default for DocumentSandboxPolicy {
}
impl DocumentSandboxPolicy {
- pub(crate) fn from_response_content_security_policies(policies: &[String]) -> Self {
+ pub(crate) fn from_response_content_security_policies(
+ policies: &[ContentSecurityPolicy],
+ ) -> Self {
Self {
forces_opaque_origin:
crate::content_security_policy::content_security_policy_forces_opaque_origin(
@@ -731,7 +735,8 @@ pub(super) struct DocumentRuntime {
author_styles_disabled: bool,
bypass_content_security_policy: bool,
policy_container: DocumentPolicyContainer,
- delivered_meta_content_security_policies: RefCell<HashMap<DomHandle, Vec<String>>>,
+ delivered_meta_content_security_policies:
+ RefCell<HashMap<DomHandle, Vec<ContentSecurityPolicy>>>,
processed_meta_content_security_policy_handles: RefCell<HashSet<(DomHandle, DomHandle)>>,
resource_loader_binding: Option<DocumentResourceLoaderBinding>,
script_context_stack: Vec<CurrentScriptContext>,
diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs
index acea42bba..43f94b02b 100644
--- a/moli-renderer-v8/src/document_runtime/security_policy.rs
+++ b/moli-renderer-v8/src/document_runtime/security_policy.rs
@@ -82,8 +82,8 @@ pub(crate) enum DocumentNavigationEmbeddingContext<'a> {
#[derive(Debug, Clone)]
pub(crate) struct DocumentConnectPolicySnapshot {
- enforce_policies: Vec<String>,
- report_only_policies: Vec<String>,
+ enforce_policies: Vec<ContentSecurityPolicy>,
+ report_only_policies: Vec<ContentSecurityPolicy>,
reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
}
@@ -559,7 +559,7 @@ impl DocumentRuntime {
self.bypass_content_security_policy
}
- pub(crate) fn document_content_security_policies(&self) -> &[String] {
+ pub(crate) fn document_content_security_policies(&self) -> &[ContentSecurityPolicy] {
self.policy_container
.document_content_security_policies
.as_slice()
@@ -567,12 +567,15 @@ impl DocumentRuntime {
#[cfg(test)]
pub(crate) fn set_response_content_security_policies(&mut self, policies: &[String]) {
- self.policy_container.response_content_security_policies = policies.to_vec();
+ self.policy_container.response_content_security_policies =
+ policies.iter().cloned().map(Into::into).collect();
self.policy_container.sandbox =
- DocumentSandboxPolicy::from_response_content_security_policies(policies);
+ DocumentSandboxPolicy::from_response_content_security_policies(
+ &self.policy_container.response_content_security_policies,
+ );
}
- pub(crate) fn response_content_security_policies(&self) -> &[String] {
+ pub(crate) fn response_content_security_policies(&self) -> &[ContentSecurityPolicy] {
&self.policy_container.response_content_security_policies
}
@@ -582,7 +585,13 @@ impl DocumentRuntime {
policies: &[String],
) {
self.policy_container
- .response_content_security_report_only_policies = policies.to_vec();
+ .response_content_security_report_only_policies = policies
+ .iter()
+ .cloned()
+ .map(|policy| {
+ ContentSecurityPolicy::from_header(policy, ContentSecurityPolicyDisposition::Report)
+ })
+ .collect();
}
#[cfg(test)]
@@ -626,7 +635,9 @@ impl DocumentRuntime {
self.policy_container.sandbox
}
- pub(crate) fn response_content_security_report_only_policies(&self) -> &[String] {
+ pub(crate) fn response_content_security_report_only_policies(
+ &self,
+ ) -> &[ContentSecurityPolicy] {
&self
.policy_container
.response_content_security_report_only_policies
@@ -684,7 +695,7 @@ impl DocumentRuntime {
request: ContentSecurityPolicyScriptElementRequest<'_>,
) -> Option<DocumentContentSecurityPolicyViolation> {
let document_url = self.document_url();
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
Some(self.document_handle()),
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
@@ -756,7 +767,7 @@ impl DocumentRuntime {
redirect_status: ContentSecurityPolicyRedirectStatus,
) -> DocumentContentSecurityPolicyCheck {
let document_url = self.document_url();
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
Some(self.document_handle()),
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
@@ -806,7 +817,7 @@ impl DocumentRuntime {
request_url: &Url,
kind: DocumentSubresourceCspKind,
) -> DocumentContentSecurityPolicyCheck {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
&policy_container.response_content_security_policies,
&policy_container.content_security_reporting_endpoints,
@@ -876,12 +887,11 @@ impl DocumentRuntime {
request: ContentSecurityPolicyStyleElementRequest<'_>,
) -> DocumentContentSecurityPolicyCheck {
let document_url = self.document_url();
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- Some(self.document_handle()),
- &self.policy_container.response_content_security_policies,
- &self.policy_container.content_security_reporting_endpoints,
- );
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ Some(self.document_handle()),
+ &self.policy_container.response_content_security_policies,
+ &self.policy_container.content_security_reporting_endpoints,
+ );
let enforced_violation =
document_inline_style_element_policy_violation_from_document_policies(
enforced_policies,
@@ -890,7 +900,7 @@ impl DocumentRuntime {
request,
ContentSecurityPolicyDisposition::Enforce,
);
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
&self
.policy_container
.response_content_security_report_only_policies,
@@ -916,12 +926,11 @@ impl DocumentRuntime {
request: ContentSecurityPolicyStyleElementRequest<'_>,
) -> DocumentContentSecurityPolicyCheck {
let document_url = self.document_url();
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- Some(self.document_handle()),
- &self.policy_container.response_content_security_policies,
- &self.policy_container.content_security_reporting_endpoints,
- );
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ Some(self.document_handle()),
+ &self.policy_container.response_content_security_policies,
+ &self.policy_container.content_security_reporting_endpoints,
+ );
let enforced_violation = document_style_element_url_policy_violation_from_document_policies(
enforced_policies,
document_url,
@@ -930,7 +939,7 @@ impl DocumentRuntime {
ContentSecurityPolicyDisposition::Enforce,
request,
);
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
&self
.policy_container
.response_content_security_report_only_policies,
@@ -957,7 +966,7 @@ impl DocumentRuntime {
request: ContentSecurityPolicyStyleElementRequest<'_>,
) -> DocumentContentSecurityPolicyCheck {
let document_url = self.document_url();
- let enforced_policies = document_response_content_security_policy_strings(
+ let enforced_policies = document_response_content_security_policies(
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
);
@@ -969,7 +978,7 @@ impl DocumentRuntime {
ContentSecurityPolicyDisposition::Enforce,
request,
);
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
&self
.policy_container
.response_content_security_report_only_policies,
@@ -995,18 +1004,17 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
- response_report_only_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
source: &str,
request: ContentSecurityPolicyScriptElementRequest<'_>,
) -> DocumentContentSecurityPolicyCheck {
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- document_handle,
- response_policies,
- response_reporting_endpoints,
- );
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ document_handle,
+ response_policies,
+ response_reporting_endpoints,
+ );
let enforced_violation =
document_inline_script_element_policy_violation_from_document_policies(
enforced_policies,
@@ -1015,7 +1023,7 @@ impl DocumentRuntime {
request,
ContentSecurityPolicyDisposition::Enforce,
);
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
response_report_only_policies,
response_reporting_endpoints,
);
@@ -1037,18 +1045,17 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
- response_report_only_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
) -> DocumentContentSecurityPolicyCheck {
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- document_handle,
- response_policies,
- response_reporting_endpoints,
- );
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ document_handle,
+ response_policies,
+ response_reporting_endpoints,
+ );
let enforced_violation = document_inline_source_policy_violation_from_document_policies(
enforced_policies,
document_url,
@@ -1056,7 +1063,7 @@ impl DocumentRuntime {
source,
ContentSecurityPolicyDisposition::Enforce,
);
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
response_report_only_policies,
response_reporting_endpoints,
);
@@ -1077,18 +1084,17 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
- response_report_only_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
kind: ContentSecurityPolicyNonUrlKind,
source: Option<&str>,
) -> DocumentContentSecurityPolicyCheck {
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- document_handle,
- response_policies,
- response_reporting_endpoints,
- );
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ document_handle,
+ response_policies,
+ response_reporting_endpoints,
+ );
let enforced_violation = document_non_url_policy_violation_from_document_policies(
enforced_policies,
document_url,
@@ -1096,7 +1102,7 @@ impl DocumentRuntime {
source,
ContentSecurityPolicyDisposition::Enforce,
);
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
response_report_only_policies,
response_reporting_endpoints,
);
@@ -1119,7 +1125,7 @@ impl DocumentRuntime {
request_url: &Url,
) -> Option<DocumentContentSecurityPolicyViolation> {
let document_url = self.document_url();
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
Some(self.document_handle()),
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
@@ -1137,7 +1143,7 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
) -> Option<DocumentContentSecurityPolicyViolation> {
@@ -1156,13 +1162,13 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
nonce: Option<&str>,
) -> Option<DocumentContentSecurityPolicyViolation> {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
@@ -1180,7 +1186,7 @@ impl DocumentRuntime {
pub(crate) fn script_element_request_csp_report_only_violation_for_document(
&self,
document_url: &Url,
- response_report_only_policies: &[String],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
) -> Option<DocumentContentSecurityPolicyViolation> {
@@ -1197,7 +1203,7 @@ impl DocumentRuntime {
pub(crate) fn script_element_request_csp_report_only_violation_for_document_with_redirect_status(
&self,
document_url: &Url,
- response_report_only_policies: &[String],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
@@ -1219,13 +1225,13 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
- response_report_only_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
) -> DocumentContentSecurityPolicyCheck {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
@@ -1255,11 +1261,11 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
) -> Option<DocumentContentSecurityPolicyViolation> {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
@@ -1276,7 +1282,7 @@ impl DocumentRuntime {
pub(crate) fn document_frame_csp_report_only_violation_for_document(
&self,
document_url: &Url,
- response_report_only_policies: &[String],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
request_url: &Url,
) -> Option<DocumentContentSecurityPolicyViolation> {
@@ -1294,10 +1300,10 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
) -> Option<DocumentContentSecurityPolicyViolation> {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
@@ -1314,10 +1320,10 @@ impl DocumentRuntime {
pub(crate) fn inline_script_csp_report_only_violation_for_document(
&self,
document_url: &Url,
- response_report_only_policies: &[String],
+ response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
) -> Option<DocumentContentSecurityPolicyViolation> {
- let policies = document_response_content_security_policy_strings(
+ let policies = document_response_content_security_policies(
response_report_only_policies,
response_reporting_endpoints,
);
@@ -1347,7 +1353,7 @@ impl DocumentRuntime {
disposition: ContentSecurityPolicyDisposition,
) -> Option<DocumentContentSecurityPolicyViolation> {
let document_url = self.document_url();
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
Some(self.document_handle()),
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
@@ -1369,7 +1375,7 @@ impl DocumentRuntime {
disposition: ContentSecurityPolicyDisposition,
) -> Option<DocumentContentSecurityPolicyViolation> {
let document_url = self.document_url();
- let policies = document_response_content_security_policy_strings(
+ let policies = document_response_content_security_policies(
&self
.policy_container
.response_content_security_report_only_policies,
@@ -1402,7 +1408,7 @@ impl DocumentRuntime {
sample: &str,
) -> Option<DocumentContentSecurityPolicyViolation> {
let document_url = self.document_url();
- let policies = document_response_content_security_policy_strings(
+ let policies = document_response_content_security_policies(
&self
.policy_container
.response_content_security_report_only_policies,
@@ -1422,7 +1428,7 @@ impl DocumentRuntime {
&self,
) -> TrustedTypesForScriptRequirements {
let enforced = self.requires_trusted_types_for_script();
- let report_only_policies = document_response_content_security_policy_strings(
+ let report_only_policies = document_response_content_security_policies(
&self
.policy_container
.response_content_security_report_only_policies,
@@ -1437,20 +1443,17 @@ impl DocumentRuntime {
pub(crate) fn trusted_types_for_script_requirements_for_document(
&self,
document_handle: Option<DomHandle>,
- response_policies: &[String],
- report_only_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
+ report_only_policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
) -> TrustedTypesForScriptRequirements {
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- document_handle,
- response_policies,
- reporting_endpoints,
- );
- let report_only_policies = document_response_content_security_policy_strings(
- report_only_policies,
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ document_handle,
+ response_policies,
reporting_endpoints,
);
+ let report_only_policies =
+ document_response_content_security_policies(report_only_policies, reporting_endpoints);
TrustedTypesForScriptRequirements::new(
document_policies_require_trusted_types_for_script(&enforced_policies),
document_policies_require_trusted_types_for_script(&report_only_policies),
@@ -1461,22 +1464,19 @@ impl DocumentRuntime {
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
- response_policies: &[String],
- report_only_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
+ report_only_policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
sink: &str,
sample: &str,
) -> Vec<DocumentContentSecurityPolicyViolation> {
- let report_only_policies = document_response_content_security_policy_strings(
- report_only_policies,
+ let report_only_policies =
+ document_response_content_security_policies(report_only_policies, reporting_endpoints);
+ let enforced_policies = self.document_content_security_policies_for_optional_document(
+ document_handle,
+ response_policies,
reporting_endpoints,
);
- let enforced_policies = self
- .document_content_security_policy_strings_for_optional_document(
- document_handle,
- response_policies,
- reporting_endpoints,
- );
let mut violations = iter_document_trusted_types_sink_policy_violations(
enforced_policies,
document_url,
@@ -1496,7 +1496,7 @@ impl DocumentRuntime {
}
pub(crate) fn requires_trusted_types_for_script(&self) -> bool {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
Some(self.document_handle()),
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
@@ -1507,10 +1507,10 @@ impl DocumentRuntime {
pub(crate) fn allows_trusted_types_eval_for_document(
&self,
document_handle: Option<DomHandle>,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
) -> bool {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
@@ -1521,11 +1521,11 @@ impl DocumentRuntime {
pub(crate) fn allows_trusted_type_policy_name_for_document(
&self,
document_handle: Option<DomHandle>,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
policy_name: &str,
) -> bool {
- let policies = self.document_content_security_policy_strings_for_optional_document(
+ let policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
@@ -1685,21 +1685,21 @@ impl DocumentRuntime {
Ok(())
}
- fn document_content_security_policy_strings_for_optional_document(
+ fn document_content_security_policies_for_optional_document(
&self,
document_handle: Option<DomHandle>,
- response_policies: &[String],
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
- ) -> Vec<DocumentContentSecurityPolicyString> {
- let mut policies = document_response_content_security_policy_strings(
+ ) -> Vec<DocumentContentSecurityPolicy> {
+ let mut policies = document_response_content_security_policies(
response_policies,
response_reporting_endpoints,
);
if let Some(handle) = document_handle {
policies.extend(
- self.meta_content_security_policy_strings_for_document(handle)
+ self.meta_content_security_policies_for_document(handle)
.into_iter()
- .map(|policy| DocumentContentSecurityPolicyString {
+ .map(|policy| DocumentContentSecurityPolicy {
policy,
report_uri_enabled: false,
reporting_endpoints: response_reporting_endpoints.clone(),
@@ -1709,10 +1709,10 @@ impl DocumentRuntime {
policies
}
- fn meta_content_security_policy_strings_for_document(
+ pub(crate) fn meta_content_security_policies_for_document(
&self,
document_handle: DomHandle,
- ) -> Vec<String> {
+ ) -> Vec<ContentSecurityPolicy> {
let candidates = self
.dom_host
.html_elements_by_local_name_in_document_tree_order(document_handle, "meta")
@@ -1736,7 +1736,12 @@ impl DocumentRuntime {
document_handle: DomHandle,
handle: DomHandle,
) {
- if self.dom_host.owner_document_handle(handle) != Some(document_handle) {
+ if self.dom_host.owner_document_handle(handle) != Some(document_handle)
+ || self
+ .processed_meta_content_security_policy_handles
+ .borrow()
+ .contains(&(document_handle, handle))
+ {
return;
}
let policy = {
@@ -1774,13 +1779,13 @@ impl DocumentRuntime {
.borrow_mut()
.entry(document_handle)
.or_default()
- .push(policy);
+ .push(ContentSecurityPolicy::from_meta(policy));
}
}
}
fn document_connect_policy_violation(
- policies: &[String],
+ policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
@@ -1799,7 +1804,7 @@ fn document_connect_policy_violation(
}
fn document_frame_policy_violation(
- policies: &[String],
+ policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
@@ -1818,7 +1823,7 @@ fn document_frame_policy_violation(
}
fn document_url_policy_violation(
- policies: &[String],
+ policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
@@ -1838,7 +1843,7 @@ fn document_url_policy_violation(
}
fn document_script_element_url_policy_violation(
- policies: &[String],
+ policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
@@ -1858,7 +1863,7 @@ fn document_script_element_url_policy_violation(
}
fn document_style_element_url_policy_violation(
- policies: &[String],
+ policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
@@ -1878,19 +1883,19 @@ fn document_style_element_url_policy_violation(
}
#[derive(Debug, Clone)]
-struct DocumentContentSecurityPolicyString {
- policy: String,
+struct DocumentContentSecurityPolicy {
+ policy: ContentSecurityPolicy,
report_uri_enabled: bool,
reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
}
-fn document_response_content_security_policy_strings(
- response_policies: &[String],
+fn document_response_content_security_policies(
+ response_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
-) -> Vec<DocumentContentSecurityPolicyString> {
+) -> Vec<DocumentContentSecurityPolicy> {
response_policies
.iter()
- .map(|policy| DocumentContentSecurityPolicyString {
+ .map(|policy| DocumentContentSecurityPolicy {
policy: policy.to_owned(),
report_uri_enabled: true,
reporting_endpoints: response_reporting_endpoints.clone(),
@@ -1899,7 +1904,7 @@ fn document_response_content_security_policy_strings(
}
fn document_connect_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
@@ -1916,7 +1921,7 @@ fn document_connect_policy_violation_from_document_policies(
}
fn document_frame_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
@@ -1933,7 +1938,7 @@ fn document_frame_policy_violation_from_document_policies(
}
fn document_url_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
request_url: &Url,
kind: ContentSecurityPolicyResourceKind,
@@ -1957,7 +1962,7 @@ fn document_url_policy_violation_from_document_policies(
}
fn document_script_element_url_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
@@ -1981,7 +1986,7 @@ fn document_script_element_url_policy_violation_from_document_policies(
}
fn document_style_element_url_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
@@ -2005,7 +2010,7 @@ fn document_style_element_url_policy_violation_from_document_policies(
}
fn document_non_url_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
kind: ContentSecurityPolicyNonUrlKind,
source: Option<&str>,
@@ -2026,7 +2031,7 @@ fn document_non_url_policy_violation_from_document_policies(
}
fn document_inline_source_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
@@ -2047,7 +2052,7 @@ fn document_inline_source_policy_violation_from_document_policies(
}
fn document_inline_script_element_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
source: &str,
request: ContentSecurityPolicyScriptElementRequest<'_>,
@@ -2068,7 +2073,7 @@ fn document_inline_script_element_policy_violation_from_document_policies(
}
fn document_inline_style_element_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
source: &str,
request: ContentSecurityPolicyStyleElementRequest<'_>,
@@ -2090,7 +2095,7 @@ fn document_inline_style_element_policy_violation_from_document_policies(
#[cfg(test)]
fn document_trusted_types_sink_policy_violation_from_document_policies(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
sink: &str,
sample: &str,
@@ -2107,7 +2112,7 @@ fn document_trusted_types_sink_policy_violation_from_document_policies(
}
fn iter_document_trusted_types_sink_policy_violations<'a>(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
document_url: &'a Url,
sink: &'a str,
sample: &'a str,
@@ -2130,7 +2135,7 @@ fn iter_document_trusted_types_sink_policy_violations<'a>(
}
fn document_policies_allow_trusted_type_policy_name(
- policies: Vec<DocumentContentSecurityPolicyString>,
+ policies: Vec<DocumentContentSecurityPolicy>,
policy_name: &str,
) -> bool {
policies.into_iter().all(|policy| {
@@ -2139,7 +2144,7 @@ fn document_policies_allow_trusted_type_policy_name(
}
fn document_policies_require_trusted_types_for_script(
- policies: &[DocumentContentSecurityPolicyString],
+ policies: &[DocumentContentSecurityPolicy],
) -> bool {
policies.iter().any(|policy| {
content_security_policy_requires_trusted_types_for_script(std::slice::from_ref(
@@ -2148,9 +2153,7 @@ fn document_policies_require_trusted_types_for_script(
})
}
-fn document_policies_allow_trusted_types_eval(
- policies: &[DocumentContentSecurityPolicyString],
-) -> bool {
+fn document_policies_allow_trusted_types_eval(policies: &[DocumentContentSecurityPolicy]) -> bool {
let policies = policies
.iter()
.map(|policy| policy.policy.clone())
@@ -2160,7 +2163,7 @@ fn document_policies_allow_trusted_types_eval(
fn apply_document_policy_reporting_flags(
violation: &mut DocumentContentSecurityPolicyViolation,
- policy: &DocumentContentSecurityPolicyString,
+ policy: &DocumentContentSecurityPolicy,
) {
if !policy.report_uri_enabled {
violation.report_uri_endpoints.clear();
@@ -2208,37 +2211,16 @@ pub(crate) fn create_content_security_policy_violation_event<'s>(
pub(crate) fn response_content_security_policies_from_headers(
headers: &[(String, Vec<u8>)],
-) -> Vec<String> {
+) -> Vec<ContentSecurityPolicy> {
content_security_policy_headers(headers)
}
pub(crate) fn response_content_security_report_only_policies_from_headers(
headers: &[(String, Vec<u8>)],
-) -> Vec<String> {
+) -> Vec<ContentSecurityPolicy> {
content_security_policy_report_only_headers(headers)
}
-impl<'a> From<&'a DocumentContentSecurityPolicyViolation>
- for ContentSecurityPolicyViolationEventFields<'a>
-{
- fn from(violation: &'a DocumentContentSecurityPolicyViolation) -> Self {
- Self {
- document_uri: violation.document_uri.as_str(),
- referrer: "",
- blocked_uri: violation.blocked_uri.as_str(),
- effective_directive: violation.effective_directive,
- violated_directive: violation.effective_directive,
- original_policy: violation.original_policy.as_str(),
- disposition: violation.disposition,
- source_file: violation.source_file.as_str(),
- sample: violation.sample.as_str(),
- line_number: violation.line_number,
- column_number: violation.column_number,
- status_code: 0,
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -2889,7 +2871,7 @@ mod tests {
.inline_script_csp_violation_for_document(
Some(runtime.document_handle()),
runtime.document_url(),
- &["script-src 'none'; report-to csp".to_owned()],
+ &["script-src 'none'; report-to csp".into()],
&reporting_endpoints(),
)
.expect("inline script should violate script-src none");
@@ -3085,7 +3067,7 @@ mod tests {
fn csp_response_header_blocks_child_document_script_requests() {
let runtime = runtime_for_html("<!doctype html>");
let document_url = Url::parse("https://example.test/popup.html").unwrap();
- let response_policies = vec!["script-src 'self'".to_owned()];
+ let response_policies = vec!["script-src 'self'".into()];
let blocked = Url::parse("https://cdn.example.test/popup.js").unwrap();
let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
@@ -3108,8 +3090,8 @@ mod tests {
fn csp_response_header_blocks_child_inline_scripts_without_unsafe_inline() {
let runtime = runtime_for_html("<!doctype html>");
let document_url = Url::parse("https://example.test/popup.html").unwrap();
- let blocking_policies = vec!["script-src 'self'".to_owned()];
- let allowing_policies = vec!["script-src 'unsafe-inline'".to_owned()];
+ let blocking_policies = vec!["script-src 'self'".into()];
+ let allowing_policies = vec!["script-src 'unsafe-inline'".into()];
let reporting_endpoints = ContentSecurityPolicyReportingEndpoints::default();
let violation = runtime
@@ -3148,7 +3130,10 @@ mod tests {
b"default-src 'none'".to_vec()
),
("X-Other".to_owned(), b"ignored".to_vec()),
- ]),
+ ])
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
vec!["default-src 'self'"]
);
assert_eq!(
@@ -3162,7 +3147,10 @@ mod tests {
b" default-src 'none' ".to_vec()
),
("X-Other".to_owned(), b"ignored".to_vec()),
- ]),
+ ])
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
vec!["default-src 'none'"]
);
}
@@ -3202,11 +3190,19 @@ mod tests {
policy.response_content_security_policies
);
assert_eq!(
- policy.response_content_security_policies,
+ policy
+ .response_content_security_policies
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
vec!["sandbox allow-scripts; frame-ancestors 'self'"]
);
assert_eq!(
- policy.response_content_security_report_only_policies,
+ policy
+ .response_content_security_report_only_policies
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
vec!["frame-ancestors https://embedder.test; report-to csp"]
);
assert_eq!(policy.referrer_policy.as_deref(), Some("no-referrer"));
@@ -3229,9 +3225,9 @@ mod tests {
fn navigation_response_frame_ancestors_check_distinguishes_top_level_and_nested() {
let protected_url = Url::parse("https://child.test/frame.html").unwrap();
let policy = DocumentPolicyContainer {
- response_content_security_policies: vec!["frame-ancestors 'self'".to_owned()],
+ response_content_security_policies: vec!["frame-ancestors 'self'".into()],
response_content_security_report_only_policies: vec![
- "frame-ancestors https://reported.test".to_owned(),
+ "frame-ancestors https://reported.test".into(),
],
..Default::default()
};
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 102ac09f7..621d08073 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
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::{
ChildBrowsingContextBootstrap, ChildBrowsingContextSnapshot, ChildFrameAttachmentSnapshot,
JsContextHost, NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntryId,
@@ -292,19 +294,21 @@ impl ChildBrowsingContextEntry {
self.document_sandbox_policy().allows_scripts
}
- pub(super) fn response_content_security_policies(&self) -> &[String] {
+ pub(super) fn response_content_security_policies(&self) -> &[ContentSecurityPolicy] {
self.document_policy_container
.response_content_security_policies
.as_slice()
}
- pub(super) fn document_content_security_policies(&self) -> &[String] {
+ pub(super) fn document_content_security_policies(&self) -> &[ContentSecurityPolicy] {
self.document_policy_container
.document_content_security_policies
.as_slice()
}
- pub(super) fn response_content_security_report_only_policies(&self) -> &[String] {
+ pub(super) fn response_content_security_report_only_policies(
+ &self,
+ ) -> &[ContentSecurityPolicy] {
self.document_policy_container
.response_content_security_report_only_policies
.as_slice()
@@ -1246,7 +1250,7 @@ impl JsContextHost {
pub(crate) fn child_browsing_context_content_security_policies(
&self,
handle: DomHandle,
- ) -> Option<&[String]> {
+ ) -> Option<&[ContentSecurityPolicy]> {
self.child_browsing_contexts
.get(&handle)
.map(|entry| entry.document_content_security_policies())
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 0ec562753..fd62ae2de 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
@@ -1068,7 +1068,7 @@ mod tests {
(vec!["sandbox allow-top-navigation", "sandbox"], false),
] {
let response = crate::document_runtime::DocumentSandboxPolicy::from_response_content_security_policies(
- &policies.iter().map(|policy| (*policy).to_owned()).collect::<Vec<_>>(),
+ &policies.iter().map(|policy| (*policy).into()).collect::<Vec<_>>(),
);
assert_eq!(
document_sandbox_policy_from_attribute(attribute)
@@ -1085,11 +1085,11 @@ mod tests {
fn iframe_and_response_sandboxes_must_both_allow_modals() {
let response_without_modals =
crate::document_runtime::DocumentSandboxPolicy::from_response_content_security_policies(
- &["sandbox allow-scripts".to_owned()],
+ &["sandbox allow-scripts".into()],
);
let response_with_modals =
crate::document_runtime::DocumentSandboxPolicy::from_response_content_security_policies(
- &["sandbox allow-scripts allow-modals".to_owned()],
+ &["sandbox allow-scripts allow-modals".into()],
);
assert!(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
index b691d256f..e1a619cef 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use std::collections::HashSet;
use super::{
@@ -742,7 +744,7 @@ impl JsContextHost {
&self.extra_http_headers
}
- pub(crate) fn document_content_security_policies(&self) -> &[String] {
+ pub(crate) fn document_content_security_policies(&self) -> &[ContentSecurityPolicy] {
unsafe { &*self.runtime }.document_content_security_policies()
}
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 072b4dbb7..f1d716280 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
@@ -1,6 +1,7 @@
mod renderer_owned;
use super::{JsContextHost, NavigationHistoryEntrySeed};
+use crate::content_security_policy::ContentSecurityPolicy;
use crate::web_api_interfaces;
use crate::{
content_security_policy::content_security_policy_forces_opaque_origin,
@@ -208,8 +209,8 @@ struct LightweightPopupClassicScriptContinuation {
document_url: Url,
scripts: Vec<DomHandle>,
next_script_index: usize,
- response_content_security_policies: Vec<String>,
- response_content_security_report_only_policies: Vec<String>,
+ response_content_security_policies: Vec<ContentSecurityPolicy>,
+ response_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
response_content_security_reporting_endpoints:
crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
}
@@ -1305,7 +1306,7 @@ impl JsContextHost {
fn lightweight_popup_response_storage_scope(
&mut self,
final_url: &Url,
- response_content_security_policies: &[String],
+ response_content_security_policies: &[ContentSecurityPolicy],
sandbox_forces_opaque_origin: bool,
) -> LightweightPopupStorageScope {
if sandbox_forces_opaque_origin
@@ -1383,7 +1384,7 @@ impl JsContextHost {
pub(crate) fn active_lightweight_popup_content_security_policies(
&self,
scope: &mut v8::PinScope<'_, '_>,
- ) -> Option<&[String]> {
+ ) -> Option<&[ContentSecurityPolicy]> {
let popup_id = active_lightweight_popup_id(scope)?;
Some(
self.lightweight_popup_document_record(popup_id)?
@@ -3096,8 +3097,8 @@ impl JsContextHost {
task: LightweightPopupNavigationTaskToken,
document_handle: Option<DomHandle>,
scripting_enabled: bool,
- response_content_security_policies: &[String],
- response_content_security_report_only_policies: &[String],
+ response_content_security_policies: &[ContentSecurityPolicy],
+ response_content_security_report_only_policies: &[ContentSecurityPolicy],
response_content_security_reporting_endpoints:
&crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
) -> LightweightPopupClassicScriptAdvance {
@@ -3539,8 +3540,8 @@ impl JsContextHost {
popup_id: u64,
document_handle: Option<crate::document_runtime::DomHandle>,
document_url: &Url,
- response_content_security_policies: &[String],
- response_content_security_report_only_policies: &[String],
+ response_content_security_policies: &[ContentSecurityPolicy],
+ response_content_security_report_only_policies: &[ContentSecurityPolicy],
response_content_security_reporting_endpoints:
&crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
fetched_source: &LoadedChildScriptSource,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
index 8c0e5eb1b..4008f91ef 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::{JsContextHost, OwnerDispatchScope};
use crate::{
content_security_policy::{
@@ -753,7 +755,7 @@ impl JsContextHost {
fn child_effective_response_content_security_policies(
&self,
child_handle: DomHandle,
- ) -> Vec<String> {
+ ) -> Vec<ContentSecurityPolicy> {
let mut policies = Vec::new();
if self
.child_browsing_contexts
@@ -774,7 +776,7 @@ impl JsContextHost {
fn child_effective_response_content_security_report_only_policies(
&self,
child_handle: DomHandle,
- ) -> Vec<String> {
+ ) -> Vec<ContentSecurityPolicy> {
let mut policies = Vec::new();
if self
.child_browsing_contexts
@@ -801,7 +803,7 @@ impl JsContextHost {
fn parent_effective_response_content_security_policies(
&self,
child_handle: DomHandle,
- ) -> Vec<String> {
+ ) -> Vec<ContentSecurityPolicy> {
match self.child_browsing_context_parent_handle(child_handle) {
Some(parent) => self.child_effective_response_content_security_policies(parent),
None => unsafe { &*self.runtime }
@@ -813,7 +815,7 @@ impl JsContextHost {
fn parent_effective_response_content_security_report_only_policies(
&self,
child_handle: DomHandle,
- ) -> Vec<String> {
+ ) -> Vec<ContentSecurityPolicy> {
match self.child_browsing_context_parent_handle(child_handle) {
Some(parent) => {
self.child_effective_response_content_security_report_only_policies(parent)
@@ -1023,14 +1025,20 @@ impl JsContextHost {
)
}
- fn child_response_content_security_policies(&self, handle: DomHandle) -> &[String] {
+ fn child_response_content_security_policies(
+ &self,
+ handle: DomHandle,
+ ) -> &[ContentSecurityPolicy] {
self.child_browsing_contexts
.get(&handle)
.map(|entry| entry.response_content_security_policies())
.unwrap_or_default()
}
- fn child_response_content_security_report_only_policies(&self, handle: DomHandle) -> &[String] {
+ fn child_response_content_security_report_only_policies(
+ &self,
+ handle: DomHandle,
+ ) -> &[ContentSecurityPolicy] {
self.child_browsing_contexts
.get(&handle)
.map(|entry| entry.response_content_security_report_only_policies())
diff --git a/moli-renderer-v8/src/native_bridge/context_host/workers.rs b/moli-renderer-v8/src/native_bridge/context_host/workers.rs
index ef03177ff..b527dc869 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/workers.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/workers.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
mod registration;
use crate::structured_clone::V8StructuredClonePayload;
@@ -13,7 +15,7 @@ pub(crate) enum WorkerOwnerScope {
pub(super) struct WorkerModuleStaticImportPolicySnapshot {
pub(super) initiator_url: url::Url,
- pub(super) content_security_policies: Vec<String>,
+ pub(super) content_security_policies: Vec<ContentSecurityPolicy>,
}
pub(super) enum WorkerExecutionState {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/workers/registration.rs b/moli-renderer-v8/src/native_bridge/context_host/workers/registration.rs
index b08935e1d..e4258ebcb 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/workers/registration.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/workers/registration.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::super::JsContextHost;
use super::{
WorkerConnectionState, WorkerExecutionState, WorkerModuleStaticImportPolicySnapshot,
@@ -28,8 +30,8 @@ struct LoadedWorkerScript {
response_referrer_policy: Option<String>,
network_partition_key: Option<String>,
policy_context: SubresourcePolicyContext,
- content_security_policies: Vec<String>,
- content_security_report_only_policies: Vec<String>,
+ content_security_policies: Vec<ContentSecurityPolicy>,
+ content_security_report_only_policies: Vec<ContentSecurityPolicy>,
content_security_reporting_endpoints:
crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
}
@@ -244,7 +246,7 @@ impl JsContextHost {
script_kind: WorkerScriptKind,
module_credentials_mode: moli_fetch::RequestCredentialsMode,
document_referrer_policy: Option<String>,
- document_content_security_policies: Vec<String>,
+ document_content_security_policies: Vec<ContentSecurityPolicy>,
name: String,
reserved_service_worker_client_id: Option<ServiceWorkerClientId>,
) -> bool {
@@ -430,8 +432,8 @@ impl JsContextHost {
response_referrer_policy: Option<String>,
network_partition_key: Option<String>,
policy_context: SubresourcePolicyContext,
- content_security_policies: Vec<String>,
- content_security_report_only_policies: Vec<String>,
+ content_security_policies: Vec<ContentSecurityPolicy>,
+ content_security_report_only_policies: Vec<ContentSecurityPolicy>,
content_security_reporting_endpoints:
crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
) -> bool {
diff --git a/moli-renderer-v8/src/page_task_queue/dedicated_worker_client_event.rs b/moli-renderer-v8/src/page_task_queue/dedicated_worker_client_event.rs
index 8e116a6b5..140fd137c 100644
--- a/moli-renderer-v8/src/page_task_queue/dedicated_worker_client_event.rs
+++ b/moli-renderer-v8/src/page_task_queue/dedicated_worker_client_event.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use moli_owner_queue::{OwnerReadyTaskRoute, OwnerReadyTaskSource};
use crate::{
@@ -90,8 +92,8 @@ pub(crate) enum RendererDedicatedWorkerClientEvent {
response_referrer_policy: Option<String>,
network_partition_key: Option<String>,
policy_context: SubresourcePolicyContext,
- content_security_policies: Vec<String>,
- content_security_report_only_policies: Vec<String>,
+ content_security_policies: Vec<ContentSecurityPolicy>,
+ content_security_report_only_policies: Vec<ContentSecurityPolicy>,
content_security_reporting_endpoints:
crate::content_security_policy::ContentSecurityPolicyReportingEndpoints,
},
diff --git a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/inserted_resource_lifecycle.rs b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/inserted_resource_lifecycle.rs
index 6fe42a293..9f9c701ca 100644
--- a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/inserted_resource_lifecycle.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/inserted_resource_lifecycle.rs
@@ -10,7 +10,7 @@ fn parser_connected_document_write_inline_script_obeys_csp() {
runtime.block_on(tokio::task::LocalSet::new().run_until(async move {
let env = default_test_page_vm_env_config_with(|env| {
env.document_policy_container
- .response_content_security_policies = vec!["script-src 'nonce-outer'".to_owned()];
+ .response_content_security_policies = vec!["script-src 'nonce-outer'".into()];
});
let mut page_vm = parse_phase_one_html_into_page_vm_for_test_with_env(
r#"<!doctype html><html><head><script nonce="outer">
@@ -102,7 +102,7 @@ fn csp_rejected_document_write_stylesheet_does_not_strand_parser_owner() {
let env = default_test_page_vm_env_config_with(|env| {
env.document_policy_container
.response_content_security_policies =
- vec!["style-src 'none'; script-src 'unsafe-inline'".to_owned()];
+ vec!["style-src 'none'; script-src 'unsafe-inline'".into()];
});
let mut page_vm = tokio::time::timeout(
std::time::Duration::from_secs(2),
@@ -1216,7 +1216,7 @@ fn parser_style_csp_checks_complete_contents_once() {
} else {
&mut env.document_policy_container.response_content_security_policies
};
- *policies = vec![policy.to_owned()];
+ *policies = vec![policy.to_owned().into()];
});
let html = Box::leak(format!("<!doctype html><html><head><script>globalThis.__parserStyleViolations = 0; document.addEventListener('securitypolicyviolation', () => __parserStyleViolations++);</script>{markup}").into_boxed_str());
let mut page_vm = parse_phase_one_html_into_page_vm_for_test_with_env(html, env).await;
diff --git a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_blocking_scripts.rs b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_blocking_scripts.rs
index 6b0ecedc2..e8a36ec00 100644
--- a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_blocking_scripts.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_blocking_scripts.rs
@@ -611,7 +611,7 @@ fn parser_blocking_csp_block_does_not_start_parser_discovered_source_load() {
let env = default_test_page_vm_env_config_with(|env| {
env.document_policy_container
.response_content_security_policies =
- vec!["script-src 'none'".to_owned()];
+ vec!["script-src 'none'".into()];
});
let mut page_vm = PageVm::new(
PageId::new_for_testing(1),
diff --git a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_flow.rs b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_flow.rs
index 21763164c..dcfc64041 100644
--- a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_flow.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/parser_flow.rs
@@ -20,7 +20,7 @@ fn main_document_parser_derives_scripting_state_from_runtime_and_response_sandbo
env.document_settings.script_execution_disabled = script_execution_disabled;
env.document_policy_container
.response_content_security_policies =
- policy.into_iter().map(str::to_owned).collect();
+ policy.into_iter().map(Into::into).collect();
});
let page_vm =
parse_phase_one_html_into_page_vm_for_test_with_env(MARKUP, env).await;
@@ -41,7 +41,7 @@ fn main_document_parser_derives_scripting_state_from_runtime_and_response_sandbo
{
let env = default_test_page_vm_env_config_with(|env| {
env.document_policy_container
- .response_content_security_policies = vec![policy.to_owned()];
+ .response_content_security_policies = vec![policy.to_owned().into()];
});
let page_vm = parse_phase_one_html_into_page_vm_for_test_with_env(
"<!doctype html><script>document.documentElement.setAttribute('data-script-ran', 'yes')</script>",
diff --git a/moli-renderer-v8/src/script_vm/document_environment.rs b/moli-renderer-v8/src/script_vm/document_environment.rs
index 9b82d2518..df4d9fe29 100644
--- a/moli-renderer-v8/src/script_vm/document_environment.rs
+++ b/moli-renderer-v8/src/script_vm/document_environment.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::*;
pub(crate) struct ScriptVmCapturedDocumentEnvironment {
@@ -141,7 +143,7 @@ impl ScriptVm {
});
}
- pub(crate) fn document_content_security_policies(&self) -> Vec<String> {
+ pub(crate) fn document_content_security_policies(&self) -> Vec<ContentSecurityPolicy> {
self._context_host
.borrow()
.document_content_security_policies()
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs
index 0996d8d4e..5e1ecc4c2 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs
@@ -2258,7 +2258,10 @@ async fn popup_javascript_url_string_document_keeps_inherited_frame_src_policy()
.borrow()
.lightweight_popup_policy_container(1)
.expect("popup policy container")
- .response_content_security_policies,
+ .response_content_security_policies
+ .iter()
+ .map(|policy| policy.as_str())
+ .collect::<Vec<_>>(),
["frame-src 'none'".to_owned()]
);
advance_page_task_executor_until_eval_equals(
diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/main_document_lifecycle.rs b/moli-renderer-v8/src/script_vm/tests/extracted/main_document_lifecycle.rs
index 1c1a5a5b7..b474da643 100644
--- a/moli-renderer-v8/src/script_vm/tests/extracted/main_document_lifecycle.rs
+++ b/moli-renderer-v8/src/script_vm/tests/extracted/main_document_lifecycle.rs
@@ -449,9 +449,9 @@ fn main_document_open_fetch_redirect_uses_source_document_csp_report_context() {
let final_url = Url::parse("https://redirected-fetch-csp-owner.test/final").unwrap();
let report_url = Url::parse("https://main-fetch-csp-owner.test/report").unwrap();
let policy = crate::document_runtime::DocumentPolicyContainer {
- response_content_security_report_only_policies: vec![format!(
- "connect-src 'none'; report-uri {report_url}"
- )],
+ response_content_security_report_only_policies: vec![
+ format!("connect-src 'none'; report-uri {report_url}").into(),
+ ],
..Default::default()
};
let registered = vm
diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/page_runtime.rs b/moli-renderer-v8/src/script_vm/tests/extracted/page_runtime.rs
index d2d901f1c..7cd53e447 100644
--- a/moli-renderer-v8/src/script_vm/tests/extracted/page_runtime.rs
+++ b/moli-renderer-v8/src/script_vm/tests/extracted/page_runtime.rs
@@ -41,15 +41,15 @@ async fn detached_keepalive_redirect_reports_source_document_csp_without_v8() {
let enforce_request =
Url::parse("https://detached-fetch-csp-owner.test/enforce-source").unwrap();
let report_only_policy = crate::document_runtime::DocumentPolicyContainer {
- response_content_security_report_only_policies: vec![format!(
- "connect-src 'none'; report-uri {report_url}"
- )],
+ response_content_security_report_only_policies: vec![
+ format!("connect-src 'none'; report-uri {report_url}").into(),
+ ],
..Default::default()
};
let enforce_policy = crate::document_runtime::DocumentPolicyContainer {
- response_content_security_policies: vec![format!(
- "connect-src 'none'; report-uri {report_url}"
- )],
+ response_content_security_policies: vec![
+ format!("connect-src 'none'; report-uri {report_url}").into(),
+ ],
..Default::default()
};
let (report_only_fetch, enforce_fetch) = vm
diff --git a/moli-renderer-v8/src/service_worker_runtime/script_loading.rs b/moli-renderer-v8/src/service_worker_runtime/script_loading.rs
index 2a70b19ba..bebc9dc95 100644
--- a/moli-renderer-v8/src/service_worker_runtime/script_loading.rs
+++ b/moli-renderer-v8/src/service_worker_runtime/script_loading.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use std::time::Instant;
use moli_crypto::sha256_hex;
@@ -104,8 +106,8 @@ pub(super) struct LoadedServiceWorkerScript {
pub(super) resource: ServiceWorkerScriptResource,
pub(super) source: String,
pub(super) response_referrer_policy: Option<String>,
- pub(super) response_content_security_policies: Vec<String>,
- pub(super) response_content_security_report_only_policies: Vec<String>,
+ pub(super) response_content_security_policies: Vec<ContentSecurityPolicy>,
+ pub(super) response_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
pub(super) response_content_security_reporting_endpoints:
ContentSecurityPolicyReportingEndpoints,
}
diff --git a/moli-renderer-v8/src/shared_worker_runtime/loading.rs b/moli-renderer-v8/src/shared_worker_runtime/loading.rs
index 89cb132e5..437abbfac 100644
--- a/moli-renderer-v8/src/shared_worker_runtime/loading.rs
+++ b/moli-renderer-v8/src/shared_worker_runtime/loading.rs
@@ -1,3 +1,5 @@
+use crate::content_security_policy::ContentSecurityPolicy;
+
use moli_fetch::{FetchCancelHandle, Request, RequestCredentialsMode, ScriptFetchRequestMetadata};
use moli_shared_worker::{
SharedWorkerClientOwnerId, SharedWorkerCredentialsMode, SharedWorkerDescriptor,
@@ -37,8 +39,8 @@ pub(super) struct SharedWorkerLoadedScript {
pub(super) source: String,
pub(super) response_referrer_policy: Option<String>,
pub(super) response_policy_context: Option<SubresourcePolicyContext>,
- pub(super) response_content_security_policies: Vec<String>,
- pub(super) response_content_security_report_only_policies: Vec<String>,
+ pub(super) response_content_security_policies: Vec<ContentSecurityPolicy>,
+ pub(super) response_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
pub(super) response_content_security_reporting_endpoints:
ContentSecurityPolicyReportingEndpoints,
}
@@ -85,7 +87,7 @@ pub(crate) struct SharedWorkerLaunchContext {
pub(crate) struct SharedWorkerExecutionPolicy {
pub(super) script_kind: WorkerScriptKind,
pub(super) module_static_import_initiator_url: Url,
- pub(super) module_static_import_content_security_policies: Vec<String>,
+ pub(super) module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
pub(super) network_policy: WorkerNetworkPolicy,
pub(super) policy_context: SubresourcePolicyContext,
pub(super) worker_context_runtime: RendererWorkerContextRuntime,
@@ -102,7 +104,7 @@ pub(crate) struct SharedWorkerScriptRequestPolicy {
pub(super) same_site_cookies: SharedWorkerSameSiteCookies,
pub(super) document_referrer_policy: Option<String>,
pub(super) network_partition_key: Option<String>,
- pub(super) document_content_security_policies: Vec<String>,
+ pub(super) document_content_security_policies: Vec<ContentSecurityPolicy>,
}
impl SharedWorkerLaunchParams {
@@ -217,7 +219,7 @@ impl SharedWorkerExecutionPolicy {
pub(crate) fn new(
script_kind: WorkerScriptKind,
module_static_import_initiator_url: Url,
- module_static_import_content_security_policies: Vec<String>,
+ module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
network_policy: WorkerNetworkPolicy,
policy_context: SubresourcePolicyContext,
worker_context_runtime: RendererWorkerContextRuntime,
@@ -264,7 +266,7 @@ impl SharedWorkerScriptRequestPolicy {
same_site_cookies: SharedWorkerSameSiteCookies,
document_referrer_policy: Option<String>,
network_partition_key: Option<String>,
- document_content_security_policies: Vec<String>,
+ document_content_security_policies: Vec<ContentSecurityPolicy>,
) -> Self {
Self {
credentials_mode: shared_worker_script_credentials_mode(descriptor),
@@ -330,7 +332,7 @@ impl SharedWorkerLoadedScript {
pub(super) fn with_response_content_security_policies(
mut self,
- response_content_security_policies: Vec<String>,
+ response_content_security_policies: Vec<ContentSecurityPolicy>,
) -> Self {
self.response_content_security_policies = response_content_security_policies;
self
@@ -338,7 +340,7 @@ impl SharedWorkerLoadedScript {
pub(super) fn with_response_content_security_report_only_policies(
mut self,
- response_content_security_report_only_policies: Vec<String>,
+ response_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
) -> Self {
self.response_content_security_report_only_policies =
response_content_security_report_only_policies;
diff --git a/moli-renderer-v8/src/subresource_integrity.rs b/moli-renderer-v8/src/subresource_integrity.rs
index dad471809..c970ed1b2 100644
--- a/moli-renderer-v8/src/subresource_integrity.rs
+++ b/moli-renderer-v8/src/subresource_integrity.rs
@@ -1,10 +1,6 @@
use base64::Engine;
use moli_crypto::DigestAlgorithm;
-
-pub(crate) struct IntegrityMetadataHash<'a> {
- pub(crate) algorithm: DigestAlgorithm,
- pub(crate) digest: &'a str,
-}
+use moli_csp::integrity_metadata_hashes;
struct ParsedIntegrityMetadata {
tokens: Vec<ParsedIntegrityToken>,
@@ -61,56 +57,6 @@ fn parse_integrity_metadata(integrity: &str) -> ParsedIntegrityMetadata {
ParsedIntegrityMetadata { tokens }
}
-/// Keep the encoded digest for CSP's literal hash-source comparison. Response
-/// integrity verification separately decodes it and selects the strongest hash.
-pub(crate) fn integrity_metadata_hashes(
- integrity: &str,
-) -> impl Iterator<Item = IntegrityMetadataHash<'_>> {
- integrity
- .split_ascii_whitespace()
- .filter_map(parse_integrity_hash)
-}
-
-fn parse_integrity_hash(token: &str) -> Option<IntegrityMetadataHash<'_>> {
- let (algorithm, digest) = parse_integrity_algorithm_and_digest(token)?;
- let digest = digest.split_once('?').map_or(digest, |(digest, _)| digest);
- if !is_integrity_digest_syntax(digest) {
- return None;
- }
- Some(IntegrityMetadataHash { algorithm, digest })
-}
-
-fn is_integrity_digest_syntax(digest: &str) -> bool {
- // Recognizing metadata and decoding its digest are separate steps. Keep
- // hashes containing misplaced or excess padding: a decode failure must
- // fail verification, not erase a supported (possibly stronger) algorithm.
- !digest.is_empty()
- && digest.bytes().all(|byte| {
- byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'-' | b'_' | b'=')
- })
-}
-
-fn parse_integrity_algorithm_and_digest(token: &str) -> Option<(DigestAlgorithm, &str)> {
- const PREFIXES: &[(&str, DigestAlgorithm)] = &[
- ("sha256", DigestAlgorithm::Sha256),
- ("sha-256", DigestAlgorithm::Sha256),
- ("sha384", DigestAlgorithm::Sha384),
- ("sha-384", DigestAlgorithm::Sha384),
- ("sha512", DigestAlgorithm::Sha512),
- ("sha-512", DigestAlgorithm::Sha512),
- ];
- for (prefix, algorithm) in PREFIXES {
- let Some(rest) = token.strip_prefix(prefix) else {
- continue;
- };
- let Some(digest) = rest.strip_prefix('-') else {
- continue;
- };
- return Some((*algorithm, digest));
- }
- None
-}
-
fn decode_integrity_digest(digest: &str) -> Option<Vec<u8>> {
// SRI accepts unpadded and non-canonical padded representations. Normalize
// only for byte verification; CSP and preload metadata comparison retain
diff --git a/moli-renderer-v8/src/worker/global_scope/nested_workers.rs b/moli-renderer-v8/src/worker/global_scope/nested_workers.rs
index f581efe1e..aedea46e4 100644
--- a/moli-renderer-v8/src/worker/global_scope/nested_workers.rs
+++ b/moli-renderer-v8/src/worker/global_scope/nested_workers.rs
@@ -1,5 +1,7 @@
//! Nested worker ownership, creation snapshots and parent event delivery.
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::*;
pub(crate) struct NestedWorkerContext {
@@ -15,7 +17,7 @@ pub(crate) struct NestedWorkerContext {
pub(crate) creator_storage_key: MoliStorageKey,
pub(crate) indexed_db_manager: Option<crate::context_bootstrap::WeakIndexedDbManager>,
pub(crate) storage_bucket_store: Option<crate::context_bootstrap::SharedStorageBucketStore>,
- pub(crate) module_static_import_content_security_policies: Vec<String>,
+ pub(crate) module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
pub(crate) require_trusted_types_for_script: bool,
pub(crate) network_policy: crate::worker::handle::WorkerNetworkPolicy,
pub(crate) policy_context: crate::types::SubresourcePolicyContext,
diff --git a/moli-renderer-v8/src/worker/global_scope/state.rs b/moli-renderer-v8/src/worker/global_scope/state.rs
index bcb86cd6e..17f23db05 100644
--- a/moli-renderer-v8/src/worker/global_scope/state.rs
+++ b/moli-renderer-v8/src/worker/global_scope/state.rs
@@ -1,5 +1,7 @@
//! WorkerGlobalScope runtime state and native queries for the current worker.
+use crate::content_security_policy::ContentSecurityPolicy;
+
use super::*;
pub(crate) const WORKER_STATE_SLOT: &str = "__workerState";
@@ -47,11 +49,12 @@ pub(crate) struct WorkerGlobalState {
/// Referrer policy parsed from the top-level worker script response.
pub(in crate::worker) referrer_policy: Option<String>,
/// CSP policies from outside settings used for module static imports.
- pub(in crate::worker) module_static_import_content_security_policies: Vec<String>,
+ pub(in crate::worker) module_static_import_content_security_policies:
+ Vec<ContentSecurityPolicy>,
/// Enforce CSP policies parsed from the top-level worker script response.
- pub(in crate::worker) content_security_policies: Vec<String>,
+ pub(in crate::worker) content_security_policies: Vec<ContentSecurityPolicy>,
/// Report-only CSP policies parsed from the top-level worker script response.
- pub(in crate::worker) content_security_report_only_policies: Vec<String>,
+ pub(in crate::worker) content_security_report_only_policies: Vec<ContentSecurityPolicy>,
/// Reporting API endpoints parsed from the top-level worker script response.
pub(in crate::worker) content_security_reporting_endpoints:
ContentSecurityPolicyReportingEndpoints,
diff --git a/moli-renderer-v8/src/worker/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rs
index 0f1fdc82c..243a51e7e 100644
--- a/moli-renderer-v8/src/worker/thread/mod.rs
+++ b/moli-renderer-v8/src/worker/thread/mod.rs
@@ -1,6 +1,8 @@
//! Worker thread — owns a V8 isolate and Tokio `LocalRuntime`, runs the
//! worker event loop, and handles message dispatch.
+use crate::content_security_policy::ContentSecurityPolicy;
+
use std::cell::RefCell;
use std::collections::VecDeque;
use std::pin::pin;
@@ -183,9 +185,9 @@ pub(crate) struct WorkerSpawnOptions {
pub(crate) module_static_import_initiator_url: Option<url::Url>,
pub(crate) module_credentials_mode: RequestCredentialsMode,
pub(crate) referrer_policy: Option<String>,
- pub(crate) module_static_import_content_security_policies: Vec<String>,
- pub(crate) content_security_policies: Vec<String>,
- pub(crate) content_security_report_only_policies: Vec<String>,
+ pub(crate) module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
+ pub(crate) content_security_policies: Vec<ContentSecurityPolicy>,
+ pub(crate) content_security_report_only_policies: Vec<ContentSecurityPolicy>,
pub(crate) content_security_reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
pub(crate) network_policy: WorkerNetworkPolicy,
pub(crate) policy_context: crate::types::SubresourcePolicyContext,
@@ -382,14 +384,17 @@ impl WorkerSpawnOptions {
self
}
- pub(crate) fn with_content_security_policies(mut self, policies: Vec<String>) -> Self {
+ pub(crate) fn with_content_security_policies(
+ mut self,
+ policies: Vec<ContentSecurityPolicy>,
+ ) -> Self {
self.content_security_policies = policies;
self
}
pub(crate) fn with_module_static_import_content_security_policies(
mut self,
- policies: Vec<String>,
+ policies: Vec<ContentSecurityPolicy>,
) -> Self {
self.module_static_import_content_security_policies = policies;
self
@@ -397,7 +402,7 @@ impl WorkerSpawnOptions {
pub(crate) fn with_content_security_report_only_policies(
mut self,
- policies: Vec<String>,
+ policies: Vec<ContentSecurityPolicy>,
) -> Self {
self.content_security_report_only_policies = policies;
self
@@ -584,9 +589,9 @@ fn start_worker_module_graph_fetch(
request: WorkerModuleGraphFetchRequest,
loader: WorkerResourceLoader,
network_partition_key: Option<String>,
- module_static_import_content_security_policies: Vec<String>,
- worker_global_content_security_policies: Vec<String>,
- worker_global_content_security_report_only_policies: Vec<String>,
+ module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
+ worker_global_content_security_policies: Vec<ContentSecurityPolicy>,
+ worker_global_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
worker_global_content_security_reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
completion_tx: mpsc::UnboundedSender<WorkerModuleGraphFetchCompletion>,
) {
@@ -1500,9 +1505,9 @@ async fn worker_main(
module_static_import_initiator_url: Option<url::Url>,
module_credentials_mode: RequestCredentialsMode,
referrer_policy: Option<String>,
- module_static_import_content_security_policies: Vec<String>,
- content_security_policies: Vec<String>,
- content_security_report_only_policies: Vec<String>,
+ module_static_import_content_security_policies: Vec<ContentSecurityPolicy>,
+ content_security_policies: Vec<ContentSecurityPolicy>,
+ content_security_report_only_policies: Vec<ContentSecurityPolicy>,
content_security_reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
network_policy: WorkerNetworkPolicy,
policy_context: crate::types::SubresourcePolicyContext,
diff --git a/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_errors_and_teardown.rs b/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_errors_and_teardown.rs
index 1a4d626be..1b8b79c82 100644
--- a/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_errors_and_teardown.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_errors_and_teardown.rs
@@ -549,7 +549,7 @@ async fn worker_fetch_csp_block_dispatches_securitypolicyviolation_event() {
.into(),
"https://app.example/worker.js".into(),
)
- .with_content_security_policies(vec!["connect-src 'none'".to_owned()]),
+ .with_content_security_policies(vec!["connect-src 'none'".into()]),
);
assert_eq!(
@@ -601,7 +601,7 @@ async fn worker_fetch_report_only_csp_dispatches_without_blocking() {
script_url.clone(),
)
.with_request_client(loader)
- .with_content_security_report_only_policies(vec!["connect-src 'none'".to_owned()]),
+ .with_content_security_report_only_policies(vec!["connect-src 'none'".into()]),
);
assert_eq!(
@@ -659,9 +659,7 @@ async fn worker_fetch_csp_report_uri_posts_violation_body() {
script_url.clone(),
)
.with_request_client(loader.clone())
- .with_content_security_policies(vec![
- "connect-src 'none'; report-uri /csp-report".to_owned(),
- ]),
+ .with_content_security_policies(vec!["connect-src 'none'; report-uri /csp-report".into()]),
);
assert_eq!(recv_post_json(&mut handle).await, r#"{"name":"TypeError"}"#);
@@ -744,7 +742,7 @@ async fn worker_fetch_csp_report_to_posts_reporting_api_body() {
)
.with_request_client(loader.clone())
.with_content_security_policies(vec![
- "connect-src 'none'; report-uri /legacy; report-to csp".to_owned(),
+ "connect-src 'none'; report-uri /legacy; report-to csp".into(),
])
.with_content_security_reporting_endpoints(reporting_endpoints),
);
@@ -827,7 +825,7 @@ async fn worker_xhr_report_only_csp_dispatches_without_blocking() {
script_url.clone(),
)
.with_request_client(loader)
- .with_content_security_report_only_policies(vec!["connect-src 'none'".to_owned()]),
+ .with_content_security_report_only_policies(vec!["connect-src 'none'".into()]),
);
assert_eq!(
@@ -872,7 +870,7 @@ async fn shared_worker_fetch_csp_block_dispatches_securitypolicyviolation_event(
name: "shared".to_owned(),
storage_key,
})
- .with_content_security_policies(vec!["connect-src 'none'".to_owned()]),
+ .with_content_security_policies(vec!["connect-src 'none'".into()]),
);
handle
diff --git a/moli-renderer-v8/src/worker/thread/tests/modules.rs b/moli-renderer-v8/src/worker/thread/tests/modules.rs
index b40cff813..72f749aa8 100644
--- a/moli-renderer-v8/src/worker/thread/tests/modules.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/modules.rs
@@ -186,7 +186,7 @@ async fn worker_importscripts_obeys_response_csp_script_src() {
.into(),
"https://app.test/worker/main.js".into(),
)
- .with_content_security_policies(vec!["script-src 'none'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'none'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -241,7 +241,7 @@ async fn worker_csp_violation_event_survives_mutated_event_globals() {
.into(),
"https://app.test/worker/main.js".into(),
)
- .with_content_security_policies(vec!["script-src 'none'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'none'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -294,7 +294,7 @@ async fn shared_worker_importscripts_csp_block_dispatches_securitypolicyviolatio
name: "shared".to_owned(),
storage_key,
})
- .with_content_security_policies(vec!["script-src 'none'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'none'".into()]),
);
handle
@@ -341,7 +341,7 @@ async fn worker_importscripts_report_only_csp_dispatches_without_blocking() {
.into(),
"https://app.test/worker/main.js".into(),
)
- .with_content_security_report_only_policies(vec!["script-src 'none'".to_owned()]),
+ .with_content_security_report_only_policies(vec!["script-src 'none'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -391,7 +391,7 @@ async fn shared_worker_importscripts_report_only_csp_dispatches_without_blocking
name: "shared".to_owned(),
storage_key,
})
- .with_content_security_report_only_policies(vec!["script-src 'none'".to_owned()]),
+ .with_content_security_report_only_policies(vec!["script-src 'none'".into()]),
);
handle
@@ -626,7 +626,7 @@ async fn worker_trusted_types_importscripts_enforces_script_url_sink() {
),
"https://app.test/worker/main.js".to_owned(),
)
- .with_content_security_policies(vec!["require-trusted-types-for 'script'".to_owned()]),
+ .with_content_security_policies(vec!["require-trusted-types-for 'script'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -669,7 +669,7 @@ async fn worker_trusted_types_rejects_forged_named_properties() {
),
"https://app.test/worker/main.js".to_owned(),
)
- .with_content_security_policies(vec!["require-trusted-types-for 'script'".to_owned()]),
+ .with_content_security_policies(vec!["require-trusted-types-for 'script'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -723,7 +723,7 @@ async fn worker_trusted_types_policy_create_survives_global_constructor_override
.to_owned(),
"https://app.test/worker/main.js".to_owned(),
)
- .with_content_security_policies(vec!["require-trusted-types-for 'script'".to_owned()]),
+ .with_content_security_policies(vec!["require-trusted-types-for 'script'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -827,7 +827,7 @@ async fn worker_csp_string_compilation_keywords_preserve_source_token_boundaries
);
let options =
WorkerSpawnOptions::new(source, "https://app.test/worker/main.js".to_owned())
- .with_content_security_policies(vec![policy.clone()]);
+ .with_content_security_policies(vec![policy.clone().into()]);
let mut handle = spawn_test_worker_with_options(options);
let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
let expected = serde_json::json!([
@@ -882,9 +882,9 @@ async fn worker_string_timer_csp_blocks_and_reports_without_blocking_functions()
"https://app.test/worker/main.js".to_owned(),
);
let options = if report_only {
- options.with_content_security_report_only_policies(vec![policy.to_owned()])
+ options.with_content_security_report_only_policies(vec![policy.to_owned().into()])
} else {
- options.with_content_security_policies(vec![policy.to_owned()])
+ options.with_content_security_policies(vec![policy.to_owned().into()])
};
let mut handle = spawn_test_worker_with_options(options);
let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
@@ -937,7 +937,7 @@ async fn worker_string_timer_csp_converts_arguments_before_policy_and_preserves_
addEventListener('securitypolicyviolation', e => events.push(e.blockedURI));
setTimeout(() => { postMessage({order, errors, events}); close(); }, 50);
"#.to_owned(), "https://app.test/worker/main.js".to_owned())
- .with_content_security_policies(vec!["script-src 'none'; require-trusted-types-for 'script'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'none'; require-trusted-types-for 'script'".into()]),
);
let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
let value: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();
@@ -965,7 +965,7 @@ async fn worker_string_timer_csp_preserves_trusted_types_relaxation_and_default_
const second = setTimeout(trusted, 10);
setTimeout(() => { postMessage({positiveIds: [first > 0, second > 0], ran, order}); close(); }, 50);
"#.to_owned(), "https://app.test/worker/main.js".to_owned())
- .with_content_security_policies(vec!["script-src 'trusted-types-eval'; require-trusted-types-for 'script'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'trusted-types-eval'; require-trusted-types-for 'script'".into()]),
);
let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap();
let value: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();
@@ -1017,7 +1017,7 @@ async fn worker_trusted_types_timers_and_eval_use_script_sink() {
.to_owned(),
"https://app.test/worker/main.js".to_owned(),
)
- .with_content_security_policies(vec!["require-trusted-types-for 'script'".to_owned()]),
+ .with_content_security_policies(vec!["require-trusted-types-for 'script'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -1049,7 +1049,7 @@ async fn worker_trusted_script_eval_is_unwrapped_with_trusted_types_eval_keyword
"https://app.test/worker/main.js".to_owned(),
)
.with_content_security_policies(vec![
- "script-src 'trusted-types-eval'; require-trusted-types-for 'script'".to_owned(),
+ "script-src 'trusted-types-eval'; require-trusted-types-for 'script'".into(),
]),
);
@@ -1571,7 +1571,7 @@ async fn worker_module_redirected_http_dependency_final_url_obeys_script_src() {
)
.with_request_client(loader)
.with_script_kind(WorkerScriptKind::Module)
- .with_module_static_import_content_security_policies(vec!["script-src 'self'".to_owned()]),
+ .with_module_static_import_content_security_policies(vec!["script-src 'self'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -1747,9 +1747,9 @@ async fn worker_module_static_import_uses_outside_csp_not_worker_response_csp()
url::Url::parse("https://app.test/page.html").unwrap(),
)
.with_module_static_import_content_security_policies(vec![
- "worker-src *; script-src 'self'".to_owned(),
+ "worker-src *; script-src 'self'".into(),
])
- .with_content_security_policies(vec!["script-src 'self'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'self'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -2274,9 +2274,9 @@ async fn worker_dynamic_import_uses_worker_response_csp_not_outside_static_csp()
url::Url::parse("https://app.test/page.html").unwrap(),
)
.with_module_static_import_content_security_policies(vec![
- "worker-src *; script-src 'self'".to_owned(),
+ "worker-src *; script-src 'self'".into(),
])
- .with_content_security_policies(vec!["script-src-elem 'self'; script-src *".to_owned()]),
+ .with_content_security_policies(vec!["script-src-elem 'self'; script-src *".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
@@ -2465,7 +2465,7 @@ async fn shared_worker_dynamic_import_csp_block_dispatches_securitypolicyviolati
name: "shared".to_owned(),
storage_key,
})
- .with_content_security_policies(vec!["script-src 'self'".to_owned()]),
+ .with_content_security_policies(vec!["script-src 'self'".into()]),
);
handle
@@ -2871,7 +2871,7 @@ async fn worker_dynamic_import_report_only_csp_dispatches_without_blocking() {
)
.with_request_client(loader)
.with_script_kind(WorkerScriptKind::Module)
- .with_content_security_report_only_policies(vec!["script-src 'none'".to_owned()]),
+ .with_content_security_report_only_policies(vec!["script-src 'none'".into()]),
);
let msg = timeout(TIMEOUT, handle.recv())
diff --git a/moli-renderer-v8/src/worker/thread/tests/network/fetch_network.rs b/moli-renderer-v8/src/worker/thread/tests/network/fetch_network.rs
index a24e85bf9..fad021456 100644
--- a/moli-renderer-v8/src/worker/thread/tests/network/fetch_network.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/network/fetch_network.rs
@@ -2069,7 +2069,7 @@ async fn worker_fetch_cross_origin_redirect_final_url_obeys_connect_src() {
format!("{source_base_url}/worker/main.js"),
)
.with_request_client(loader)
- .with_content_security_policies(vec!["connect-src 'self'".to_owned()]),
+ .with_content_security_policies(vec!["connect-src 'self'".into()]),
);
let mut post = None;
diff --git a/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs b/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs
index be4c26982..71752d27d 100644
--- a/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/network/file_and_xhr.rs
@@ -1848,7 +1848,7 @@ async fn worker_xmlhttprequest_cross_origin_redirect_final_url_obeys_connect_src
format!("{source_base_url}/worker/main.js"),
)
.with_request_client(loader)
- .with_content_security_policies(vec!["connect-src 'self'".to_owned()]),
+ .with_content_security_policies(vec!["connect-src 'self'".into()]),
);
let mut post = None;
diff --git a/moli-renderer-v8/src/worker/thread/tests/network/websockets.rs b/moli-renderer-v8/src/worker/thread/tests/network/websockets.rs
index 6905c1052..fca62a9fb 100644
--- a/moli-renderer-v8/src/worker/thread/tests/network/websockets.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/network/websockets.rs
@@ -82,7 +82,7 @@ async fn worker_classic_websocket_report_only_csp_dispatches_without_blocking()
script_url.to_owned(),
)
.with_request_client(loader)
- .with_content_security_report_only_policies(vec!["connect-src 'none'".to_owned()]),
+ .with_content_security_report_only_policies(vec!["connect-src 'none'".into()]),
);
assert_eq!(
@@ -123,7 +123,7 @@ async fn worker_websocket_csp_block_precedes_mixed_content_rejection() {
.to_owned(),
"http://localhost:8000/worker/main.js".to_owned(),
)
- .with_content_security_policies(vec!["connect-src 'none'".to_owned()]),
+ .with_content_security_policies(vec!["connect-src 'none'".into()]),
);
assert_eq!(
@@ -166,7 +166,7 @@ async fn worker_classic_websocket_connect_src_self_allows_same_host_ws() {
worker_script_url,
)
.with_request_client(loader)
- .with_content_security_policies(vec!["connect-src 'self'".to_owned()]),
+ .with_content_security_policies(vec!["connect-src 'self'".into()]),
);
assert_eq!(recv_post_json(&mut handle).await, r#""self-csp""#);
diff --git a/moli-renderer-v8/src/worker/thread/tests/xhr_failure.rs b/moli-renderer-v8/src/worker/thread/tests/xhr_failure.rs
index 53dbc4fc9..715b15b97 100644
--- a/moli-renderer-v8/src/worker/thread/tests/xhr_failure.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/xhr_failure.rs
@@ -35,7 +35,7 @@ fn rejected_xhr_worker(case: &str, script: String) -> WorkerTestHandle {
WorkerSpawnOptions::new(script, "http://example.test/worker.js".to_owned())
.with_network_policy(policy)
.with_content_security_policies(if case == "csp" {
- vec!["connect-src 'none'".to_owned()]
+ vec!["connect-src 'none'".into()]
} else {
vec![]
}),