fix(trusted-types): enforce policy creation CSP

This commit is contained in:
ldm0
2026-11-24 14:28:13 +08:00
parent 7de1ebf453
commit 0c244d7abb
10 changed files with 389 additions and 89 deletions
+49 -4
View File
@@ -56,7 +56,7 @@ pub fn content_security_policy_allows_trusted_type_policy_name(
) -> bool {
policies
.iter()
.all(|policy| policy_allows_trusted_type_policy_name(policy, policy_name))
.all(|policy| policy_allows_trusted_type_policy_name(policy, policy_name, false))
}
pub fn content_security_policy_sandboxes_document_domain(
@@ -620,11 +620,12 @@ fn policy_allows_trusted_types_eval(policy: &ContentSecurityPolicy) -> bool {
fn policy_allows_trusted_type_policy_name(
policy: &ContentSecurityPolicy,
policy_name: &str,
is_duplicate: bool,
) -> bool {
let Some(sources) = directive_source_list(policy, TRUSTED_TYPES) else {
return true;
};
sources.iter().any(|source| {
let name_is_allowed = sources.iter().any(|source| {
let source = *source;
source == "*"
|| (!source.is_empty()
@@ -633,7 +634,12 @@ fn policy_allows_trusted_type_policy_name(
byte.is_ascii_alphanumeric()
|| matches!(byte, b'-' | b'#' | b'=' | b'_' | b'/' | b'@' | b'.' | b'%')
}))
})
});
let duplicate_is_allowed = !is_duplicate
|| sources
.iter()
.any(|source| csp_keyword_eq(source.trim(), "allow-duplicates"));
name_is_allowed && duplicate_is_allowed
}
fn policy_sandboxes_document_domain(policy: &ContentSecurityPolicy) -> bool {
@@ -683,7 +689,7 @@ fn sandbox_sources_allow_popups_to_escape(sources: &[&str]) -> bool {
}
fn trusted_types_sink_violation_sample(sink: &str, sample: &str) -> String {
let clipped = sample.chars().take(40).collect::<String>();
let clipped = trusted_types_violation_sample(sample);
format!("{sink}|{clipped}")
}
@@ -1502,3 +1508,42 @@ fn inline_source_matches_hash(source: &str, hash_source: CspHashSourceValue<'_>)
#[cfg(test)]
#[path = "tests.rs"]
mod tests;
fn trusted_types_violation_sample(sample: &str) -> String {
sample.chars().take(40).collect()
}
pub fn content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints(
policies: &[ContentSecurityPolicy],
protected_url: &Url,
policy_name: &str,
is_duplicate: bool,
disposition: ContentSecurityPolicyDisposition,
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
) -> Option<ContentSecurityPolicyUrlViolation> {
policies.iter().find_map(|policy| {
if policy_allows_trusted_type_policy_name(policy, policy_name, is_duplicate) {
return None;
}
let document_uri = protected_url.to_string();
Some(ContentSecurityPolicyUrlViolation {
effective_directive: TRUSTED_TYPES,
blocked_uri: "trusted-types-policy".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_violation_sample(policy_name),
line_number: 0,
column_number: 0,
})
})
}
+56 -29
View File
@@ -495,7 +495,8 @@ fn csp_invalid_directives_preserve_fallbacks_and_trusted_types_requirements() {
));
assert!(policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
"unlisted"
"unlisted",
false
));
let policy = format!(
@@ -506,11 +507,13 @@ fn csp_invalid_directives_preserve_fallbacks_and_trusted_types_requirements() {
));
assert!(policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
"allowed"
"allowed",
false
));
assert!(!policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
"unlisted"
"unlisted",
false
));
assert!(!allowed(
&policy,
@@ -551,16 +554,19 @@ fn csp_invalid_first_values_do_not_activate_later_duplicate_directives() {
let policy = format!("trusted-types *{invalid}; TRUSTED-TYPES allowed");
assert!(policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
"unlisted"
"unlisted",
false
));
let policy = format!("trusted-types allowed; TRUSTED-TYPES *{invalid}");
assert!(policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
"allowed"
"allowed",
false
));
assert!(!policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
"unlisted"
"unlisted",
false
));
}
}
@@ -2738,27 +2744,42 @@ fn non_url_wasm_eval_uses_script_src_or_default_src() {
#[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,
)
let allowed = |policies: &[&str], name: &str, is_duplicate: bool| {
policies.iter().all(|policy| {
policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(*policy),
name,
is_duplicate,
)
})
};
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(&[], "SomeName", false));
assert!(allowed(&[], "SomeName", true));
assert!(allowed(&["default-src 'none'"], "SomeName", false));
assert!(allowed(
&["trusted-types SomeName OtherName"],
"SomeName",
false
));
assert!(allowed(
&["trusted-types * 'aLLow-dUPLIcates'"],
"SomeName",
true
));
assert!(allowed(
&["trusted-types 'none' SomeName"],
"SomeName",
false
));
assert!(!allowed(&["trusted-types"], "SomeName", false));
assert!(!allowed(&["trusted-types 'nONe'"], "SomeName", false));
assert!(!allowed(&["trusted-types SomeName"], "SomeName", true));
assert!(!allowed(&["trusted-types SomeName"], "default", false));
assert!(!allowed(
&["trusted-types SomeName", "trusted-types OtherName"],
"SomeName"
"SomeName",
false
));
}
@@ -2778,7 +2799,8 @@ fn trusted_types_csp_name_grammar_matches_only_valid_tokens() {
assert_eq!(
policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy.as_str()),
&name
&name,
false
),
expected,
"invalid tt-policy-name byte {byte:#04x} must not match literally",
@@ -2787,21 +2809,25 @@ fn trusted_types_csp_name_grammar_matches_only_valid_tokens() {
for name in ["none", "allow-duplicates", "A-z_09#=/@.%"] {
assert!(policy_allows_trusted_type_policy_name(
&format!("trusted-types {name}").into(),
name
name,
false
));
}
assert!(policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from("trusted-types valid policy*name"),
"valid"
"valid",
false
));
assert!(!policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from("trusted-types valid policy*name"),
"policy*name"
"policy*name",
false
));
for wildcard in ["policy*", "**"] {
assert!(!policy_allows_trusted_type_policy_name(
&format!("trusted-types {wildcard}").into(),
"valid"
"valid",
false
));
}
}
@@ -2819,7 +2845,8 @@ fn trusted_types_csp_name_grammar_does_not_restrict_unlisted_or_wildcard_names()
for policy in ["", "trusted-types *"] {
assert!(policy_allows_trusted_type_policy_name(
&ContentSecurityPolicy::from(policy),
name
name,
false
));
}
}
@@ -24,6 +24,7 @@ const TRUSTED_TYPES_POLICY_NAME_SLOT: &str = "__moliTrustedTypesPolicyName";
const TRUSTED_TYPE_POLICY_FACTORY_CONSTRUCTOR_SLOT: &str =
"__moliTrustedTypePolicyFactoryConstructor";
const TRUSTED_TYPES_DEFAULT_POLICY_SLOT: &str = "__moliTrustedTypesDefaultPolicy";
const TRUSTED_TYPES_CREATED_POLICY_NAMES_SLOT: &str = "__moliTrustedTypesCreatedPolicyNames";
const TRUSTED_TYPES_EMPTY_HTML_SLOT: &str = "__moliTrustedTypesEmptyHTML";
const TRUSTED_TYPES_EMPTY_SCRIPT_SLOT: &str = "__moliTrustedTypesEmptyScript";
const TRUSTED_TYPES_EMPTY_VALUE_SLOTS: [&str; 2] = [
@@ -97,6 +98,8 @@ struct TrustedTypesFactoryObjectDeclaration<'scope> {
empty_html: v8::Local<'scope, v8::Object>,
#[webapi(slot = TRUSTED_TYPES_EMPTY_SCRIPT_SLOT)]
empty_script: v8::Local<'scope, v8::Object>,
#[webapi(slot = TRUSTED_TYPES_CREATED_POLICY_NAMES_SLOT)]
created_policy_names: v8::Local<'scope, v8::Array>,
}
#[derive(WebApiFunctionTemplate)]
@@ -590,6 +593,7 @@ fn trusted_types_create_policy_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let factory = args.this();
let Some(name) = webidl::required_argument::<webidl::DomString>(
scope,
&args,
@@ -604,13 +608,21 @@ fn trusted_types_create_policy_callback<'s>(
return;
};
if !trusted_types_policy_name_allowed(scope, &name) {
let is_duplicate = trusted_types_policy_name_was_created(scope, factory, &name);
if !trusted_types_policy_name_allowed(scope, &name, is_duplicate) {
throw_type_error(
scope,
"Failed to execute 'createPolicy' on 'TrustedTypePolicyFactory': Content Security Policy disallows creating a policy with the given name.",
);
return;
}
if name == "default" && is_duplicate {
throw_type_error(
scope,
"Failed to execute 'createPolicy' on 'TrustedTypePolicyFactory': Policy with name \"default\" already exists.",
);
return;
}
let policy_name = v8_string(scope, &name).unwrap_or_else(|| v8::String::empty(scope));
let global = scope.get_current_context().global(scope);
@@ -634,17 +646,62 @@ fn trusted_types_create_policy_callback<'s>(
policy.into(),
);
}
trusted_types_record_created_policy_name(scope, factory, &name, is_duplicate);
rv.set(policy.into());
}
fn trusted_types_policy_name_allowed(scope: &mut v8::PinScope<'_, '_>, name: &str) -> bool {
if let Some(allowed) = crate::worker::worker_allows_trusted_type_policy_name(scope, name) {
fn trusted_types_policy_name_was_created<'s>(
scope: &mut v8::PinScope<'s, '_>,
factory: v8::Local<'s, v8::Object>,
name: &str,
) -> bool {
let Some(names) = get_private_value(scope, factory, TRUSTED_TYPES_CREATED_POLICY_NAMES_SLOT)
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
else {
return false;
};
(0..names.length()).any(|index| {
names
.get_index(scope, index)
.and_then(|value| v8::Local::<v8::String>::try_from(value).ok())
.is_some_and(|value| value.to_rust_string_lossy(scope) == name)
})
}
fn trusted_types_record_created_policy_name<'s>(
scope: &mut v8::PinScope<'s, '_>,
factory: v8::Local<'s, v8::Object>,
name: &str,
was_duplicate: bool,
) {
if was_duplicate {
return;
}
let Some(names) = get_private_value(scope, factory, TRUSTED_TYPES_CREATED_POLICY_NAMES_SLOT)
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
else {
return;
};
let Some(name) = v8_string(scope, name) else {
return;
};
let _ = names.set_index(scope, names.length(), name.into());
}
fn trusted_types_policy_name_allowed(
scope: &mut v8::PinScope<'_, '_>,
name: &str,
is_duplicate: bool,
) -> bool {
if let Some(allowed) =
crate::worker::worker_allows_trusted_type_policy_name_by_csp(scope, name, is_duplicate)
{
return allowed;
}
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
return true;
};
unsafe { &*host_ptr }.allows_trusted_type_policy_name(scope, name)
unsafe { &mut *host_ptr }.allows_trusted_type_policy_name_by_csp(scope, name, is_duplicate)
}
fn trusted_type_policy_create_callback<'s>(
@@ -218,6 +218,7 @@ fn build_and_cache_trusted_types_state<'s>(
let factory = TrustedTypesFactoryObjectDeclaration {
empty_html,
empty_script,
created_policy_names: v8::Array::new(scope, 0),
}
.bind(scope)
.map_err(|error| anyhow!("failed to bind TrustedTypePolicyFactory object: {error}"))?;
@@ -6,7 +6,6 @@ use crate::content_security_policy::{
ContentSecurityPolicyResourceKind, ContentSecurityPolicyScriptElementRequest,
ContentSecurityPolicyStyleElementRequest, ContentSecurityPolicyUrlViolation,
ContentSecurityPolicyViolationEventFields, TrustedTypesForScriptRequirements,
content_security_policy_allows_trusted_type_policy_name,
content_security_policy_allows_trusted_types_eval,
content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints,
content_security_policy_headers,
@@ -18,6 +17,7 @@ use crate::content_security_policy::{
content_security_policy_requires_trusted_types_for_script,
content_security_policy_script_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request,
content_security_policy_style_element_url_violation_with_redirect_status_disposition_reporting_endpoints_and_request,
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints,
content_security_policy_trusted_types_sink_violation_with_disposition_and_reporting_endpoints,
content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints,
create_security_policy_violation_event,
@@ -1726,19 +1726,42 @@ impl DocumentRuntime {
document_policies_allow_trusted_types_eval(&policies)
}
pub(crate) fn allows_trusted_type_policy_name_for_document(
#[allow(clippy::too_many_arguments)]
pub(crate) fn trusted_type_policy_name_csp_check_for_document(
&self,
document_handle: Option<DomHandle>,
document_url: &Url,
response_policies: &[ContentSecurityPolicy],
response_report_only_policies: &[ContentSecurityPolicy],
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
policy_name: &str,
) -> bool {
let policies = self.document_content_security_policies_for_optional_document(
is_duplicate: bool,
) -> DocumentContentSecurityPolicyCheck {
let enforced_policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
response_reporting_endpoints,
);
document_policies_allow_trusted_type_policy_name(policies, policy_name)
let report_only_policies = document_response_content_security_policies(
response_report_only_policies,
response_reporting_endpoints,
);
DocumentContentSecurityPolicyCheck {
report_only_violation: document_trusted_types_policy_violation_from_document_policies(
report_only_policies,
document_url,
policy_name,
is_duplicate,
ContentSecurityPolicyDisposition::Report,
),
enforced_violation: document_trusted_types_policy_violation_from_document_policies(
enforced_policies,
document_url,
policy_name,
is_duplicate,
ContentSecurityPolicyDisposition::Enforce,
),
}
}
pub(crate) fn queue_content_security_policy_violation_event_best_effort<'s>(
@@ -2437,12 +2460,26 @@ fn iter_document_trusted_types_sink_policy_violations<'a>(
})
}
fn document_policies_allow_trusted_type_policy_name(
fn document_trusted_types_policy_violation_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
policy_name: &str,
) -> bool {
policies.into_iter().all(|policy| {
content_security_policy_allows_trusted_type_policy_name(&[policy.policy], policy_name)
is_duplicate: bool,
disposition: ContentSecurityPolicyDisposition,
) -> Option<DocumentContentSecurityPolicyViolation> {
policies.into_iter().find_map(|policy| {
let single_policy = [policy.policy.clone()];
let mut violation =
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints(
&single_policy,
document_url,
policy_name,
is_duplicate,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, &policy);
Some(violation)
})
}
@@ -1163,25 +1163,64 @@ impl PageScriptHost {
.1
}
pub(crate) fn allows_trusted_type_policy_name(
&self,
scope: &mut v8::PinScope<'_, '_>,
pub(crate) fn allows_trusted_type_policy_name_by_csp<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
policy_name: &str,
is_duplicate: bool,
) -> bool {
let Some(snapshot) =
self.owner_document_policy_snapshot(policy_owner_dispatch_scope(scope))
else {
let owner = policy_owner_dispatch_scope(scope);
let Some(snapshot) = self.owner_document_policy_snapshot(owner) else {
// A context between documents has no policy owner to report
// against; applying another document's CSP would enforce the
// wrong policy.
return true;
};
// SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime.
unsafe { &*self.document_runtime }.allows_trusted_type_policy_name_for_document(
snapshot.document_handle,
&snapshot.policy_container.response_content_security_policies,
&snapshot
.policy_container
.content_security_reporting_endpoints,
policy_name,
)
let check = unsafe { &*self.document_runtime }
.trusted_type_policy_name_csp_check_for_document(
snapshot.document_handle,
&snapshot.document_url,
&snapshot.policy_container.response_content_security_policies,
&snapshot
.policy_container
.response_content_security_report_only_policies,
&snapshot
.policy_container
.content_security_reporting_endpoints,
policy_name,
is_duplicate,
);
let (mut report_only_violation, mut enforced_violation) = check.into_violations();
if !self.active_inspector_dispatch
&& let Some((source_file, line_number, column_number)) =
crate::content_security_policy::current_script_violation_location(scope)
{
for violation in [&mut enforced_violation, &mut report_only_violation]
.into_iter()
.flatten()
{
violation.source_file.clone_from(&source_file);
violation.line_number = line_number;
violation.column_number = column_number;
}
}
let host_ptr: *mut PageScriptHost = self;
let allowed = enforced_violation.is_none();
// Policy creation reports expose CSP list ordering. Response policy
// state is partitioned by disposition, with enforce policies modeled
// before report-only policies, so preserve that order here.
if let Some(violation) = enforced_violation {
self.dispatch_content_security_policy_violation_event_for_owner_best_effort(
scope, host_ptr, owner, &violation,
);
}
if let Some(violation) = report_only_violation {
self.dispatch_content_security_policy_violation_event_for_owner_best_effort(
scope, host_ptr, owner, &violation,
);
}
allowed
}
pub(crate) fn requires_trusted_types_for_script(
@@ -1281,26 +1320,8 @@ impl PageScriptHost {
capture_current_script_location: bool,
) {
let source_location = (capture_current_script_location && !self.active_inspector_dispatch)
.then(|| v8::StackTrace::current_stack_trace(scope, 1))
.flatten()
.and_then(|stack| stack.get_frame(scope, 0))
.map(|frame| {
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);
(source_file, line_number, column_number)
});
.then(|| crate::content_security_policy::current_script_violation_location(scope))
.flatten();
let owner = policy_owner_dispatch_scope(scope);
for mut violation in self.trusted_types_sink_csp_violations_for_owner(owner, sink, sample) {
if let Some((source_file, line_number, column_number)) = &source_location {
@@ -275,6 +275,72 @@ fn trusted_type_factory_default_policy_getter_tracks_the_branded_policy() {
);
}
#[test]
fn trusted_type_policy_creation_reports_name_and_duplicate_csp_violations() {
let mut vm = new_storage_test_vm("https://trusted-type-policy-csp.test/");
vm.set_response_content_security_policies(&[
"trusted-types allowed reportOnly duplicate".to_owned()
]);
vm.set_response_content_security_report_only_policies(&[
"trusted-types allowed duplicate".to_owned()
]);
let result = vm
.eval(
r#"
(() => {
const violations = [];
document.addEventListener("securitypolicyviolation", event => {
violations.push({
blockedURI: event.blockedURI,
effectiveDirective: event.effectiveDirective,
originalPolicy: event.originalPolicy,
disposition: event.disposition,
sample: event.sample
});
});
globalThis.__trustedTypePolicyCspViolations = violations;
const errorName = callback => {
try {
callback();
return "none";
} catch (error) {
return error.name;
}
};
const allowed = trustedTypes.createPolicy("allowed", {});
const reportOnly = trustedTypes.createPolicy("reportOnly", {});
const duplicate = trustedTypes.createPolicy("duplicate", {});
const duplicateError = errorName(() => trustedTypes.createPolicy("duplicate", {}));
const blockedError = errorName(() => trustedTypes.createPolicy("blocked", {}));
return JSON.stringify({
names: [allowed.name, reportOnly.name, duplicate.name],
duplicateError,
blockedError,
violations
});
})()
"#,
)
.expect("TrustedTypePolicy CSP creation probe should evaluate");
assert_eq!(
result,
r#"{"names":["allowed","reportOnly","duplicate"],"duplicateError":"TypeError","blockedError":"TypeError","violations":[]}"#
);
assert_eq!(
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm),
5
);
assert_eq!(
vm.eval("JSON.stringify(globalThis.__trustedTypePolicyCspViolations)")
.expect("queued TrustedTypePolicy CSP violations should be observable"),
r#"[{"blockedURI":"trusted-types-policy","effectiveDirective":"trusted-types","originalPolicy":"trusted-types allowed duplicate","disposition":"report","sample":"reportOnly"},{"blockedURI":"trusted-types-policy","effectiveDirective":"trusted-types","originalPolicy":"trusted-types allowed reportOnly duplicate","disposition":"enforce","sample":"duplicate"},{"blockedURI":"trusted-types-policy","effectiveDirective":"trusted-types","originalPolicy":"trusted-types allowed duplicate","disposition":"report","sample":"duplicate"},{"blockedURI":"trusted-types-policy","effectiveDirective":"trusted-types","originalPolicy":"trusted-types allowed reportOnly duplicate","disposition":"enforce","sample":"blocked"},{"blockedURI":"trusted-types-policy","effectiveDirective":"trusted-types","originalPolicy":"trusted-types allowed duplicate","disposition":"report","sample":"blocked"}]"#
);
}
#[test]
fn element_markup_sinks_enforce_trusted_html_and_standard_sink_names() {
let mut vm = new_storage_test_vm("https://element-markup-trusted-types.test/");
@@ -7,6 +7,7 @@ use crate::content_security_policy::{
ContentSecurityPolicyDisposition, ContentSecurityPolicyRedirectStatus,
ContentSecurityPolicyResourceKind, ContentSecurityPolicyUrlViolation,
ContentSecurityPolicyViolationEventFields, content_security_policy_report_requests,
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints,
content_security_policy_trusted_types_sink_violation_with_disposition_and_reporting_endpoints,
content_security_policy_url_violation_with_redirect_status_disposition_and_reporting_endpoints,
create_security_policy_violation_event, send_content_security_policy_reports,
@@ -80,6 +81,49 @@ pub(super) fn dispatch_worker_trusted_types_sink_violation_event_for_state<'s>(
}
}
pub(super) fn allows_worker_trusted_type_policy_name_for_state<'s>(
scope: &mut v8::PinScope<'s, '_>,
state: &Rc<RefCell<WorkerGlobalState>>,
policy_name: &str,
is_duplicate: bool,
) -> bool {
let (report_only_violation, enforced_violation) = {
let state_ref = state.borrow();
let Some(protected_url) = state_ref.current_script_url.as_ref() else {
return true;
};
let report_only_violation =
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints(
&state_ref.content_security_report_only_policies,
protected_url,
policy_name,
is_duplicate,
ContentSecurityPolicyDisposition::Report,
&state_ref.content_security_reporting_endpoints,
);
let enforced_violation =
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints(
&state_ref.content_security_policies,
protected_url,
policy_name,
is_duplicate,
ContentSecurityPolicyDisposition::Enforce,
&state_ref.content_security_reporting_endpoints,
);
(report_only_violation, enforced_violation)
};
let allowed = enforced_violation.is_none();
// Match window policy creation reporting: enforce response policies are
// modeled before report-only policies in the partitioned policy state.
if let Some(violation) = enforced_violation {
dispatch_worker_content_security_policy_violation_event_for_state(scope, state, &violation);
}
if let Some(violation) = report_only_violation {
dispatch_worker_content_security_policy_violation_event_for_state(scope, state, &violation);
}
allowed
}
fn create_worker_content_security_policy_violation_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
violation: &ContentSecurityPolicyUrlViolation,
@@ -304,16 +348,18 @@ pub(in crate::worker) fn dispatch_worker_csp_violation_event<'s>(
self::dispatch_worker_content_security_policy_violation_event(scope, loader, violation);
}
pub(crate) fn worker_allows_trusted_type_policy_name(
pub(crate) fn worker_allows_trusted_type_policy_name_by_csp(
scope: &mut v8::PinScope<'_, '_>,
name: &str,
is_duplicate: bool,
) -> Option<bool> {
Some(
crate::content_security_policy::content_security_policy_allows_trusted_type_policy_name(
&get_worker_state(scope)?.borrow().content_security_policies,
name,
),
)
let state = get_worker_state(scope)?;
Some(self::allows_worker_trusted_type_policy_name_for_state(
scope,
&state,
name,
is_duplicate,
))
}
pub(crate) fn worker_trusted_types_for_script_requirements(
@@ -149,7 +149,7 @@ pub(super) use content_security_policy::{
};
pub(crate) use content_security_policy::{
dispatch_worker_trusted_types_sink_violation_event, worker_allows_eval_code_generation_by_csp,
worker_allows_trusted_type_policy_name, worker_allows_trusted_types_eval,
worker_allows_trusted_type_policy_name_by_csp, worker_allows_trusted_types_eval,
worker_allows_wasm_code_generation_by_csp, worker_trusted_types_for_script_requirements,
};
use event_handlers::install_worker_global_event_handler_accessors;
+1 -1
View File
@@ -47,7 +47,7 @@ pub(crate) use global_scope::{
send_worker_websocket_blob, send_worker_websocket_text, service_worker_runtime_identity,
try_worker_xhr_abort_callback, try_worker_xhr_reschedule_timeout_after_timeout_change,
try_worker_xhr_send_callback, worker_allows_eval_code_generation_by_csp,
worker_allows_trusted_type_policy_name, worker_allows_trusted_types_eval,
worker_allows_trusted_type_policy_name_by_csp, worker_allows_trusted_types_eval,
worker_allows_wasm_code_generation_by_csp, worker_broadcast_channel_registry,
worker_broadcast_channel_storage_key, worker_broadcast_channel_wake_sender,
worker_broadcast_channel_wrapper, worker_current_script_url, worker_global_is_closed,