fix(csp): queue Fetch violations for the initiating Document

Use the existing native miscellaneous-platform task source for Fetch admission violations in Window, child, and popup realms. Initiate reports and preserve call-site deduplication before event delivery; queue enforcement violations before report-only violations. Cover Promise rejection order, native event identity, and discarded browsing contexts.
This commit is contained in:
ldm0
2026-11-21 20:03:37 +08:00
parent 86549dc9ed
commit 8bd794268f
6 changed files with 197 additions and 87 deletions
@@ -37,10 +37,10 @@ pub(crate) enum MiscPlatformApiTask {
}
impl PageScriptHost {
/// Inline CSP checks report on the policy's exact Window/Document. The
/// element is retained until the task runs, when its connectivity is
/// checked again; disconnecting or adopting it must retarget the event.
pub(crate) fn queue_inline_csp_violation_task(
/// Report on the policy's exact Window/Document, then queue its event.
/// An optional element is retained until dispatch, when disconnecting or
/// adopting it must retarget the event to that Document.
pub(crate) fn queue_content_security_policy_violation_task(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
owner: OwnerDispatchScope,
@@ -255,7 +255,7 @@ impl PageScriptHost {
MiscPlatformApiTask::EncryptedMediaRequest(task) => task.invoke(scope),
MiscPlatformApiTask::ContentSecurityPolicyViolation { element, violation } => {
// CSP checks the shadow-including root at dispatch time, not
// at the earlier inline check. A stale owner has
// at the earlier policy check. A stale owner has
// already been rejected by the Page task arbiter.
let event_target = element
.filter(|element| {
@@ -281,7 +281,7 @@ impl PageScriptHost {
host_ptr,
target,
event,
"inline securitypolicyviolation",
"securitypolicyviolation",
);
true
})
@@ -353,14 +353,8 @@ impl PageScriptHost {
})
}
OwnerDispatchScope::Child(handle) => {
let mut policy_container =
let policy_container =
self.child_browsing_context_policy_container_snapshot(handle)?;
policy_container.response_content_security_policies =
self.child_effective_enforced_content_security_policies(handle);
policy_container.response_content_security_report_only_policies =
self.child_effective_response_content_security_report_only_policies(handle);
policy_container.content_security_reporting_endpoints =
self.child_effective_content_security_reporting_endpoints(handle);
Some(OwnerDocumentPolicySnapshot {
document_handle: self.child_browsing_context_document_handle(handle),
document_url: self.child_browsing_context_current_url(handle)?,
@@ -1142,7 +1136,7 @@ impl PageScriptHost {
violation.line_number = line;
violation.column_number = column;
}
self.queue_inline_csp_violation_task(scope, owner, element, violation);
self.queue_content_security_policy_violation_task(scope, owner, element, violation);
}
enforced_violations.is_empty()
}
@@ -1250,7 +1244,15 @@ impl PageScriptHost {
}
let location =
crate::content_security_policy::ContentSecurityPolicySourceLocation::capture(scope);
self.dispatch_document_connect_csp_check(scope, owner, check, Some(&location))
let (mut reports, mut enforced) = check.into_violations();
for violation in enforced.iter_mut().chain(&mut reports) {
location.apply_to(violation);
self.queue_content_security_policy_violation_task(scope, owner, None, violation);
}
match enforced.into_iter().next() {
Some(violation) => DocumentCspOutcome::Blocked(violation),
None => DocumentCspOutcome::Allowed,
}
}
pub(crate) fn check_document_connect_csp_for_owner_with_redirect_status<'s>(
@@ -1269,7 +1271,7 @@ impl PageScriptHost {
) else {
return DocumentCspOutcome::Allowed;
};
self.dispatch_document_connect_csp_check(scope, owner, check, None)
self.dispatch_document_connect_csp_check(scope, owner, check)
}
fn dispatch_document_connect_csp_check<'s>(
@@ -1277,34 +1279,16 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'s, '_>,
owner: OwnerDispatchScope,
check: DocumentContentSecurityPolicyCheck,
source_location: Option<
&crate::content_security_policy::ContentSecurityPolicySourceLocation,
>,
) -> DocumentCspOutcome {
let (mut report_only_violation, mut enforced_violation) = check.into_violations();
if let Some(source_location) = source_location {
for violation in report_only_violation
.iter_mut()
.chain(&mut enforced_violation)
{
source_location.apply_to(violation);
}
let (reports, enforced) = check.into_violations();
for violation in reports.iter().chain(&enforced) {
self.queue_content_security_policy_violation_task(scope, owner, None, violation);
}
let host_ptr: *mut PageScriptHost = self;
for violation in report_only_violation {
self.dispatch_content_security_policy_violation_event_for_owner_best_effort(
scope, host_ptr, owner, &violation,
);
match enforced.into_iter().next() {
Some(violation) => DocumentCspOutcome::Blocked(violation),
None => DocumentCspOutcome::Allowed,
}
let Some(first_violation) = enforced_violation.first().cloned() else {
return DocumentCspOutcome::Allowed;
};
for violation in enforced_violation {
self.dispatch_content_security_policy_violation_event_for_owner_best_effort(
scope, host_ptr, owner, &violation,
);
}
DocumentCspOutcome::Blocked(first_violation)
}
fn document_connect_csp_check_for_owner_with_redirect_status(
@@ -1119,31 +1119,33 @@ async fn opener_calling_popup_fetch_uses_popup_response_csp() {
if (event.data !== "popup-ready") {
return;
}
popup.addEventListener("securitypolicyviolation", event => {
globalThis.__popupFetchCspEvents.push({
blockedURI: event.blockedURI,
effectiveDirective: event.effectiveDirective,
disposition: event.disposition,
instance: event instanceof popup.SecurityPolicyViolationEvent,
const reported = new Promise(resolve => {
popup.addEventListener("securitypolicyviolation", event => {
globalThis.__popupFetchCspEvents.push({
blockedURI: event.blockedURI,
effectiveDirective: event.effectiveDirective,
disposition: event.disposition,
instance: event instanceof popup.SecurityPolicyViolationEvent,
});
resolve();
});
});
popup.fetch("data:text/plain,blocked").then(
() => {
globalThis.__popupFetchCspObserved = JSON.stringify({
fulfilled: true,
events: globalThis.__popupFetchCspEvents,
});
},
error => {
globalThis.__popupFetchCspObserved = JSON.stringify({
name: error && error.name,
isTypeError: error instanceof popup.TypeError,
hasCspMessage: String(error && error.message)
.includes("Content Security Policy"),
events: globalThis.__popupFetchCspEvents,
});
}
).finally(() => {
const rejected = popup.fetch("data:text/plain,blocked").then(
() => ({ fulfilled: true }),
error => ({
name: error && error.name,
isTypeError: error instanceof popup.TypeError,
hasCspMessage: String(error && error.message)
.includes("Content Security Policy"),
eventsAtRejection: globalThis.__popupFetchCspEvents.length,
})
);
Promise.all([rejected, reported]).then(([result]) => {
globalThis.__popupFetchCspObserved = JSON.stringify({
...result,
events: globalThis.__popupFetchCspEvents,
});
}).finally(() => {
globalThis.__popupFetchCspDone = true;
});
});
@@ -1174,6 +1176,7 @@ async fn opener_calling_popup_fetch_uses_popup_response_csp() {
"name": "TypeError",
"isTypeError": true,
"hasCspMessage": true,
"eventsAtRejection": 0,
"events": [{
"blockedURI": "data",
"effectiveDirective": "connect-src",
@@ -43,17 +43,25 @@ async fn navigator_service_worker_intercepts_popup_csp_report_destination() {
r#"<!doctype html>
<script>
let violationSeen = false;
self.addEventListener("securitypolicyviolation", event => {
violationSeen = event.type === "securitypolicyviolation" &&
event.effectiveDirective === "connect-src" &&
event.violatedDirective === "connect-src" &&
event.blockedURI.endsWith("/app/blocked-data") &&
event.disposition === "enforce" &&
event instanceof SecurityPolicyViolationEvent;
const reported = new Promise(resolve => {
self.addEventListener("securitypolicyviolation", event => {
violationSeen = event.type === "securitypolicyviolation" &&
event.effectiveDirective === "connect-src" &&
event.violatedDirective === "connect-src" &&
event.blockedURI.endsWith("/app/blocked-data") &&
event.disposition === "enforce" &&
event instanceof SecurityPolicyViolationEvent;
resolve();
});
});
(async () => {
await fetch("blocked-data").catch(() => {});
opener.postMessage("blocked:" + violationSeen, "*");
let eventsAtRejection = -1;
await fetch("blocked-data").catch(error => {
if (!(error instanceof TypeError)) throw error;
eventsAtRejection = violationSeen ? 1 : 0;
});
await reported;
opener.postMessage("blocked:" + (violationSeen && eventsAtRejection === 0), "*");
})().catch(error => {
opener.postMessage("error:" + String(error && error.message), "*");
});
@@ -115,7 +115,8 @@ async fn document_open_keeps_policy_for_lightweight_popup_javascript_execution()
#[test]
fn fetch_csp_violations_preserve_each_call_location_and_report_identity() {
for enforce in [false, true] {
let mut vm = new_storage_test_vm("https://fetch-source-location.test/page.html");
let mut vm =
new_storage_page_task_executor_test_vm("https://fetch-source-location.test/page.html");
vm.set_fetch_subresource_interception(
crate::types::SubresourceInterceptionClasses::for_resource_type(
crate::types::SubresourceResourceType::CspReport,
@@ -147,9 +148,11 @@ fetch('data:text/plain,blocked').catch(() => {});
2,
"different call locations must produce distinct reports, enforce={enforce}"
);
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm);
let locations: Vec<(String, i32, i32)> =
serde_json::from_str(&vm.eval("JSON.stringify(fetchCspLocations)").unwrap()).unwrap();
let locations: Vec<(String, i32, i32)> = serde_json::from_str(
&vm.eval_after_selected_page_tasks("JSON.stringify(fetchCspLocations)")
.unwrap(),
)
.unwrap();
assert_eq!(locations.len(), 6);
assert!(locations.iter().all(|(url, line, column)| url
== "https://fetch-source-location.test/caller.js"
@@ -164,6 +167,121 @@ fetch('data:text/plain,blocked').catch(() => {});
}
}
#[test]
fn fetch_csp_queues_owner_events_after_rejection_in_enforcement_order() {
for owner in ["window", "frame.contentWindow", "popup"] {
for report_only in [false, true] {
let mut vm = new_storage_page_task_executor_test_vm("https://fetch-csp-tasks.test/");
vm.set_response_content_security_policies(&["connect-src 'none'".to_owned()]);
if report_only {
vm.set_response_content_security_report_only_policies(&[
"connect-src 'none'".to_owned()
]);
}
let immediate = vm
.eval(&format!(
r#"
const frame = document.createElement('iframe'); document.body.appendChild(frame);
const popup = open(); const owner = {owner};
const events = []; const topEvents = [];
let duringCall = true; let rejection = null;
if (owner !== window) {{
document.addEventListener('securitypolicyviolation', event => topEvents.push(event.type));
}}
owner.document.addEventListener('securitypolicyviolation', event => {{
events.push({{
disposition: event.disposition,
directive: event.effectiveDirective,
blockedURI: event.blockedURI,
owner: event.target === owner.document,
native: event instanceof owner.SecurityPolicyViolationEvent,
trusted: event.isTrusted,
duringCall,
}});
}});
owner.fetch('data:text/plain,blocked').then(
() => {{ rejection = 'unexpected fulfillment'; }},
error => {{ rejection = {{
name: error.name,
native: error instanceof owner.TypeError,
events: events.length,
}}; }}
);
duringCall = false;
events.length;
"#,
))
.unwrap();
assert_eq!(immediate, "0", "{owner}, report_only={report_only}");
let observed: serde_json::Value = serde_json::from_str(
&vm.eval_after_selected_page_tasks(
"JSON.stringify({rejection, events, topEvents})",
)
.unwrap(),
)
.unwrap();
let event = |disposition| {
serde_json::json!({
"disposition": disposition,
"directive": "connect-src",
"blockedURI": "data",
"owner": true,
"native": true,
"trusted": true,
"duringCall": false,
})
};
let mut events = vec![event("enforce")];
if report_only {
events.push(event("report"));
}
assert_eq!(
observed,
serde_json::json!({
"rejection": {"name": "TypeError", "native": true, "events": 0},
"events": events,
"topEvents": [],
}),
"{owner}, report_only={report_only}",
);
vm.eval("popup.close(); frame.remove()").unwrap();
}
}
}
#[test]
fn retired_fetch_csp_tasks_cannot_dispatch_after_window_discard() {
for (owner, discard) in [
("frame.contentWindow", "frame.remove()"),
("popup", "popup.close()"),
] {
let mut vm = new_storage_page_task_executor_test_vm("https://fetch-csp-retirement.test/");
vm.eval(&format!(
r#"
const frame = document.createElement('iframe'); document.body.appendChild(frame);
const popup = open(); const owner = {owner}; const events = [];
const meta = owner.document.createElement('meta');
meta.httpEquiv = 'Content-Security-Policy'; meta.content = "connect-src 'none'";
owner.document.head.appendChild(meta);
owner.document.addEventListener('securitypolicyviolation', event => events.push('old'));
owner.fetch('data:text/plain,blocked').catch(() => {{}});
{discard};
const replacement = document.createElement('iframe'); document.body.appendChild(replacement);
replacement.contentDocument.addEventListener('securitypolicyviolation', event => events.push('new'));
document.addEventListener('securitypolicyviolation', event => events.push('top'));
"#,
))
.unwrap();
assert_eq!(
vm.eval_after_selected_page_tasks("JSON.stringify(events)")
.unwrap(),
"[]",
"{owner}",
);
vm.eval("popup.close(); frame.remove()").unwrap();
}
}
#[tokio::test]
async fn inline_script_reports_every_policy_and_only_enforced_policies_block() {
let policies = [
@@ -1534,7 +1534,7 @@ fn window_fetch_missing_input_rejects_type_error() {
#[test]
fn window_fetch_document_csp_blocks_connect_src_and_dispatches_event() {
let mut vm = new_storage_test_vm("https://fetch-connect-csp.test/");
let mut vm = new_storage_page_task_executor_test_vm("https://fetch-connect-csp.test/");
vm.set_response_content_security_policies(&[String::from("connect-src 'none'")]);
vm.eval(
@@ -1565,13 +1565,10 @@ fn window_fetch_document_csp_blocks_connect_src_and_dispatches_event() {
)
.expect("fetch CSP block setup should evaluate");
assert_eq!(
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm),
1
);
assert_eq!(vm.eval("String(__fetchCspEvents.length)").unwrap(), "0");
let result = vm
.eval(
.eval_after_selected_page_tasks(
"JSON.stringify({ ...globalThis.__fetchCspResult, events: globalThis.__fetchCspEvents })",
)
.expect("fetch CSP rejection should settle");
@@ -1584,7 +1581,7 @@ fn window_fetch_document_csp_blocks_connect_src_and_dispatches_event() {
#[test]
fn window_fetch_document_csp_report_only_dispatches_without_blocking() {
let mut vm = new_storage_test_vm("https://fetch-connect-report-only.test/");
let mut vm = new_storage_page_task_executor_test_vm("https://fetch-connect-report-only.test/");
vm.set_response_content_security_report_only_policies(&[String::from("connect-src 'none'")]);
vm.eval(
@@ -1613,12 +1610,12 @@ fn window_fetch_document_csp_report_only_dispatches_without_blocking() {
.expect("fetch CSP report-only setup should evaluate");
assert_eq!(
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm),
1
vm.eval("String(__fetchReportOnlyEvents.length)").unwrap(),
"0"
);
let result = vm
.eval(
.eval_after_selected_page_tasks(
"JSON.stringify({ ...globalThis.__fetchReportOnlyResult, events: globalThis.__fetchReportOnlyEvents })",
)
.expect("fetch CSP report-only request should settle");