mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
fix(csp): block fetch redirects before network access
This commit is contained in:
@@ -180,6 +180,9 @@ pub(crate) fn next_followed_redirect_url_from_parts(
|
||||
&& let Some(next_url) = next_url.as_ref()
|
||||
{
|
||||
ensure_http_network_transport_url(next_url)?;
|
||||
request
|
||||
.check_redirect_target(next_url)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
if !web_security_disabled {
|
||||
request.validate_request_mode_for_url(next_url)?;
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ pub use request::{
|
||||
BrowserNavigationRequestKind, BrowserRequestMetadata, CookieHeaderPolicy, Request, RequestAuth,
|
||||
RequestAuthScheme, RequestAuthTarget, RequestCacheMode, RequestCredentialsMode,
|
||||
RequestHeaderOverride, RequestMode, RequestOverrides, RequestPriorityHints,
|
||||
RequestRedirectHandling, RequestRedirectMode, RequestRedirectPolicy, RequestResourceType,
|
||||
RequestRedirectCheck, RequestRedirectHandling, RequestRedirectMode, RequestRedirectPolicy, RequestResourceType,
|
||||
ResourceLoadPriority, ScriptFetchRequestMetadata, ScriptFetchSchedulerPriority,
|
||||
SubresourceRequestMetadata,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::time::Duration;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use moli_cookie_jar::{
|
||||
@@ -41,6 +41,27 @@ pub enum CookieHeaderPolicy {
|
||||
PreserveExplicit,
|
||||
}
|
||||
|
||||
type RedirectCheckCallback = dyn Fn(&Url) -> std::result::Result<(), String> + Send + Sync;
|
||||
|
||||
/// An embedder policy checked before following a redirect, including cached
|
||||
/// redirects. A rejected target must never reach the network.
|
||||
#[derive(Clone)]
|
||||
pub struct RequestRedirectCheck(Arc<RedirectCheckCallback>);
|
||||
|
||||
impl RequestRedirectCheck {
|
||||
pub fn new(
|
||||
check: impl Fn(&Url) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self(Arc::new(check))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RequestRedirectCheck {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("RequestRedirectCheck")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Request {
|
||||
pub url: Url,
|
||||
@@ -90,6 +111,7 @@ pub struct Request {
|
||||
browser_identity: Option<std::sync::Arc<moli_browser_profile::BrowserIdentityProfile>>,
|
||||
redirect_policy: Option<RequestRedirectPolicy>,
|
||||
upload_observer: Option<crate::UploadObserver>,
|
||||
redirect_check: Option<RequestRedirectCheck>,
|
||||
}
|
||||
|
||||
/// Request-owned admission check, run before following each redirect target.
|
||||
@@ -642,6 +664,7 @@ impl Request {
|
||||
browser_identity: None,
|
||||
redirect_policy: None,
|
||||
upload_observer: None,
|
||||
redirect_check: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -683,6 +706,7 @@ impl Request {
|
||||
browser_identity: None,
|
||||
redirect_policy: None,
|
||||
upload_observer: None,
|
||||
redirect_check: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -757,6 +781,7 @@ impl Request {
|
||||
browser_identity: None,
|
||||
redirect_policy: None,
|
||||
upload_observer: None,
|
||||
redirect_check: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1039,6 +1064,19 @@ impl Request {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_redirect_check(mut self, check: RequestRedirectCheck) -> Self {
|
||||
self.redirect_check = Some(check);
|
||||
self
|
||||
}
|
||||
|
||||
/// Browser redirect loops call this when the transport fetches one hop at
|
||||
/// a time. Automatically followed transport requests perform the same check.
|
||||
pub fn check_redirect_target(&self, next_url: &Url) -> std::result::Result<(), String> {
|
||||
self.redirect_check
|
||||
.as_ref()
|
||||
.map_or(Ok(()), |check| (check.0)(next_url))
|
||||
}
|
||||
|
||||
pub fn upload_observer(&self) -> Option<&crate::UploadObserver> {
|
||||
self.upload_observer.as_ref()
|
||||
}
|
||||
@@ -1396,7 +1434,7 @@ impl Request {
|
||||
self.redirect_chain.push(redirect);
|
||||
}
|
||||
|
||||
/// Follows an authorized redirect without rebuilding the Fetch request.
|
||||
/// Checks and follows a redirect without rebuilding the Fetch request.
|
||||
pub fn follow_redirect(&mut self, redirect: RedirectInfo) -> Result<()> {
|
||||
self.follow_redirect_with_web_security(redirect, false)
|
||||
}
|
||||
@@ -1407,6 +1445,8 @@ impl Request {
|
||||
redirect: RedirectInfo,
|
||||
disabled: bool,
|
||||
) -> Result<()> {
|
||||
self.check_redirect_target(&redirect.to_url)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
if !disabled {
|
||||
self.validate_request_mode_for_url(&redirect.to_url)?;
|
||||
}
|
||||
|
||||
@@ -212,6 +212,86 @@ async fn configured_cookie_scope_keeps_navigation_redirects_and_excludes_foreign
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redirect_checks_block_before_contact_in_every_transport() -> Result<()> {
|
||||
let target = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("forbidden")]);
|
||||
let source = ScriptedHttpServer::spawn(vec![
|
||||
ScriptedResponse::status(302, "Found")
|
||||
.with_header("Location", &target.url());
|
||||
3
|
||||
]);
|
||||
let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());
|
||||
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let target_url = Url::parse(&target.url())?;
|
||||
let seen = calls.clone();
|
||||
let check = crate::RequestRedirectCheck::new(move |next_url| {
|
||||
assert_eq!(next_url, &target_url);
|
||||
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
Err("redirect denied by embedder".to_owned())
|
||||
});
|
||||
for transport in Transport::ALL {
|
||||
let error = transport
|
||||
.fetch(
|
||||
&client,
|
||||
Request::get(&source.url())?.with_redirect_check(check.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("redirect denied by embedder"),
|
||||
"{transport:?}: {error:#}"
|
||||
);
|
||||
}
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 3);
|
||||
assert_eq!(source.hits(), 3);
|
||||
assert_eq!(target.hits(), 0);
|
||||
source.shutdown();
|
||||
target.shutdown();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_redirects_run_the_current_request_redirect_check() -> Result<()> {
|
||||
for transport in [Transport::Html, Transport::Raw] {
|
||||
let cache_dir = unique_test_cache_dir();
|
||||
let mut config = FetchConfig::default();
|
||||
config.set_http_cache_dir(Some(cache_dir.display().to_string()));
|
||||
let target = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("allowed once")]);
|
||||
let source = ScriptedHttpServer::spawn(vec![
|
||||
ScriptedResponse::status(302, "Found")
|
||||
.with_header("Location", &target.url())
|
||||
.with_header("Cache-Control", "max-age=600"),
|
||||
]);
|
||||
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
|
||||
let request = Request::get(&source.url())?;
|
||||
transport.fetch(&client, request.clone()).await?;
|
||||
let error = transport
|
||||
.fetch(
|
||||
&client,
|
||||
request.with_redirect_check(crate::RequestRedirectCheck::new(|_| {
|
||||
Err("cached redirect denied".to_owned())
|
||||
})),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("cached redirect denied"),
|
||||
"{transport:?}: {error:#}"
|
||||
);
|
||||
assert_eq!(source.hits(), 1, "the redirect response should be cached");
|
||||
assert_eq!(
|
||||
target.hits(),
|
||||
1,
|
||||
"the newly rejected request must not reach the target"
|
||||
);
|
||||
source.shutdown();
|
||||
target.shutdown();
|
||||
drop(client);
|
||||
fs::remove_dir_all(cache_dir)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plain_http_requests_do_not_infer_browser_origin_from_referrer() -> Result<()> {
|
||||
let server = ScriptedHttpServer::spawn(vec![ScriptedResponse::ok("http"); 3]);
|
||||
|
||||
@@ -82,7 +82,7 @@ pub(crate) enum DocumentNavigationEmbeddingContext<'a> {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct DocumentConnectPolicySnapshot {
|
||||
enforce_policies: Vec<ContentSecurityPolicy>,
|
||||
enforce_policies: Vec<DocumentContentSecurityPolicy>,
|
||||
report_only_policies: Vec<ContentSecurityPolicy>,
|
||||
reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
|
||||
}
|
||||
@@ -107,31 +107,84 @@ impl DocumentConnectPolicySnapshot {
|
||||
disposition: ContentSecurityPolicyDisposition,
|
||||
redirect_status: ContentSecurityPolicyRedirectStatus,
|
||||
) -> Option<DocumentContentSecurityPolicyViolation> {
|
||||
let policies = match disposition {
|
||||
ContentSecurityPolicyDisposition::Enforce => &self.enforce_policies,
|
||||
ContentSecurityPolicyDisposition::Report => &self.report_only_policies,
|
||||
};
|
||||
document_url_policy_violation(
|
||||
policies,
|
||||
&self.reporting_endpoints,
|
||||
document_url,
|
||||
request_url,
|
||||
ContentSecurityPolicyResourceKind::DocumentFont,
|
||||
redirect_status,
|
||||
disposition,
|
||||
)
|
||||
match disposition {
|
||||
ContentSecurityPolicyDisposition::Enforce => {
|
||||
document_url_policy_violation_from_document_policies(
|
||||
self.enforce_policies.clone(),
|
||||
document_url,
|
||||
None,
|
||||
request_url,
|
||||
ContentSecurityPolicyResourceKind::DocumentFont,
|
||||
redirect_status,
|
||||
disposition,
|
||||
)
|
||||
}
|
||||
ContentSecurityPolicyDisposition::Report => document_url_policy_violation(
|
||||
&self.report_only_policies,
|
||||
&self.reporting_endpoints,
|
||||
document_url,
|
||||
request_url,
|
||||
ContentSecurityPolicyResourceKind::DocumentFont,
|
||||
redirect_status,
|
||||
disposition,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_policies(
|
||||
enforce_policies: Vec<ContentSecurityPolicy>,
|
||||
report_only_policies: Vec<ContentSecurityPolicy>,
|
||||
reporting_endpoints: ContentSecurityPolicyReportingEndpoints,
|
||||
) -> Self {
|
||||
Self {
|
||||
enforce_policies: document_response_content_security_policies(
|
||||
&enforce_policies,
|
||||
&reporting_endpoints,
|
||||
),
|
||||
report_only_policies,
|
||||
reporting_endpoints,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn has_policies(&self) -> bool {
|
||||
!self.enforce_policies.is_empty() || !self.report_only_policies.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn check_redirect(
|
||||
&self,
|
||||
document_url: &Url,
|
||||
request_url: &Url,
|
||||
) -> DocumentContentSecurityPolicyCheck {
|
||||
DocumentContentSecurityPolicyCheck {
|
||||
report_only_violation: document_connect_policy_violation(
|
||||
&self.report_only_policies,
|
||||
&self.reporting_endpoints,
|
||||
document_url,
|
||||
request_url,
|
||||
ContentSecurityPolicyRedirectStatus::FollowedRedirect,
|
||||
ContentSecurityPolicyDisposition::Report,
|
||||
),
|
||||
enforced_violation: document_connect_policy_violation_from_document_policies(
|
||||
self.enforce_policies.clone(),
|
||||
document_url,
|
||||
None,
|
||||
request_url,
|
||||
ContentSecurityPolicyRedirectStatus::FollowedRedirect,
|
||||
ContentSecurityPolicyDisposition::Enforce,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_policy_container(policy: &DocumentPolicyContainer) -> Self {
|
||||
let mut enforce_policies = policy.response_content_security_policies.clone();
|
||||
enforce_policies.extend(policy.document_content_security_policies.iter().cloned());
|
||||
Self {
|
||||
enforce_policies,
|
||||
report_only_policies: policy
|
||||
let mut enforce = policy.response_content_security_policies.clone();
|
||||
enforce.extend(policy.document_content_security_policies.iter().cloned());
|
||||
Self::from_policies(
|
||||
enforce,
|
||||
policy
|
||||
.response_content_security_report_only_policies
|
||||
.clone(),
|
||||
reporting_endpoints: policy.content_security_reporting_endpoints.clone(),
|
||||
}
|
||||
policy.content_security_reporting_endpoints.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn enforce_violation(
|
||||
@@ -140,11 +193,12 @@ impl DocumentConnectPolicySnapshot {
|
||||
request_url: &Url,
|
||||
redirect_status: ContentSecurityPolicyRedirectStatus,
|
||||
) -> Option<DocumentContentSecurityPolicyViolation> {
|
||||
document_connect_policy_violation(
|
||||
&self.enforce_policies,
|
||||
&self.reporting_endpoints,
|
||||
document_url_policy_violation_from_document_policies(
|
||||
self.enforce_policies.clone(),
|
||||
document_url,
|
||||
None,
|
||||
request_url,
|
||||
ContentSecurityPolicyResourceKind::DocumentConnect,
|
||||
redirect_status,
|
||||
ContentSecurityPolicyDisposition::Enforce,
|
||||
)
|
||||
@@ -1114,6 +1168,31 @@ impl DocumentRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn document_connect_policy_snapshot_for_document(
|
||||
&self,
|
||||
document_handle: Option<DomHandle>,
|
||||
policy: &DocumentPolicyContainer,
|
||||
) -> DocumentConnectPolicySnapshot {
|
||||
if self.bypass_content_security_policy() {
|
||||
return DocumentConnectPolicySnapshot::from_policies(
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
Default::default(),
|
||||
);
|
||||
}
|
||||
DocumentConnectPolicySnapshot {
|
||||
enforce_policies: self.document_content_security_policies_for_optional_document(
|
||||
document_handle,
|
||||
&policy.response_content_security_policies,
|
||||
&policy.content_security_reporting_endpoints,
|
||||
),
|
||||
report_only_policies: policy
|
||||
.response_content_security_report_only_policies
|
||||
.clone(),
|
||||
reporting_endpoints: policy.content_security_reporting_endpoints.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn document_subresource_csp_check(
|
||||
&self,
|
||||
request_url: &Url,
|
||||
@@ -2911,6 +2990,254 @@ mod tests {
|
||||
runtime
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_policy_snapshot_preserves_policy_deliveries_and_meta_reporting_rules() {
|
||||
let runtime = runtime_for_html(
|
||||
r#"<!doctype html><meta http-equiv="Content-Security-Policy"
|
||||
content="connect-src 'self'; report-uri /report">"#,
|
||||
);
|
||||
let policy_text = "connect-src 'self'; report-uri /report".to_owned();
|
||||
let mut headers = Vec::new();
|
||||
for name in [
|
||||
"Content-Security-Policy",
|
||||
"Content-Security-Policy-Report-Only",
|
||||
] {
|
||||
for _ in 0..2 {
|
||||
headers.push((name.to_owned(), policy_text.clone()));
|
||||
}
|
||||
}
|
||||
let policy = DocumentPolicyContainer::from_navigation_response_headers(
|
||||
&headers,
|
||||
runtime.document_url(),
|
||||
);
|
||||
runtime.initialize_inherited_meta_content_security_policies(
|
||||
runtime.document_handle(),
|
||||
std::slice::from_ref(&policy_text),
|
||||
);
|
||||
let snapshot = runtime.document_connect_policy_snapshot_for_document(
|
||||
Some(runtime.document_handle()),
|
||||
&policy,
|
||||
);
|
||||
let (reported, blocked) = snapshot
|
||||
.check_redirect(
|
||||
runtime.document_url(),
|
||||
&Url::parse("https://other.test/target").unwrap(),
|
||||
)
|
||||
.into_violations();
|
||||
assert_eq!(reported.len(), 2);
|
||||
assert_eq!(blocked.len(), 4);
|
||||
for violation in reported.iter().chain(&blocked[..2]) {
|
||||
assert_eq!(
|
||||
violation.report_uri_endpoints,
|
||||
vec!["https://example.test/report"]
|
||||
);
|
||||
}
|
||||
for violation in &blocked[2..] {
|
||||
assert_eq!(violation.original_policy, policy_text);
|
||||
assert!(violation.report_uri_endpoints.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_csp_checks_report_each_violated_header_and_meta_policy() {
|
||||
let mut runtime = runtime_for_html(
|
||||
r#"<!doctype html><meta http-equiv="Content-Security-Policy"
|
||||
content="default-src 'none'; report-uri /ignored-meta">"#,
|
||||
);
|
||||
let enforced = [
|
||||
"default-src 'none'; report-uri /enforce-first",
|
||||
"base-uri 'none'",
|
||||
"default-src https://other.test; report-uri /enforce-second",
|
||||
]
|
||||
.map(str::to_owned);
|
||||
let report_only = [
|
||||
"default-src 'none'; report-uri /report-first",
|
||||
"base-uri 'none'",
|
||||
"default-src https://other.test; report-uri /report-second",
|
||||
]
|
||||
.map(str::to_owned);
|
||||
runtime.set_response_content_security_policies(&enforced);
|
||||
runtime.set_response_content_security_report_only_policies(&report_only);
|
||||
let request_url = Url::parse("https://example.test/resource").unwrap();
|
||||
let mut checks = Vec::from(
|
||||
[
|
||||
DocumentSubresourceCspKind::Image,
|
||||
DocumentSubresourceCspKind::Manifest,
|
||||
DocumentSubresourceCspKind::Media,
|
||||
]
|
||||
.map(|kind| runtime.document_subresource_csp_check(&request_url, kind)),
|
||||
);
|
||||
checks.push(runtime.document_connect_csp_check_with_redirect_status(
|
||||
&request_url,
|
||||
ContentSecurityPolicyRedirectStatus::FollowedRedirect,
|
||||
));
|
||||
checks.push(runtime.style_element_request_csp_check(
|
||||
&request_url,
|
||||
ContentSecurityPolicyStyleElementRequest { nonce: None },
|
||||
));
|
||||
checks.push(runtime.inline_style_element_csp_check(
|
||||
"body { color: red; }",
|
||||
ContentSecurityPolicyStyleElementRequest { nonce: None },
|
||||
));
|
||||
checks.push(runtime.inline_script_element_csp_check(
|
||||
"globalThis.ran = true",
|
||||
ContentSecurityPolicyScriptElementRequest::parser_inserted_with_nonce(None),
|
||||
));
|
||||
for kind in [
|
||||
ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
|
||||
ContentSecurityPolicyNonUrlKind::DocumentInlineStyleAttribute,
|
||||
] {
|
||||
checks.push(runtime.inline_source_csp_check(kind, "blocked inline source"));
|
||||
}
|
||||
for kind in [
|
||||
ContentSecurityPolicyNonUrlKind::Eval,
|
||||
ContentSecurityPolicyNonUrlKind::WasmEval,
|
||||
] {
|
||||
checks.push(runtime.non_url_csp_check_for_document(
|
||||
Some(runtime.document_handle()),
|
||||
runtime.document_url(),
|
||||
&enforced,
|
||||
&report_only,
|
||||
&Default::default(),
|
||||
kind,
|
||||
Some("blocked eval source"),
|
||||
));
|
||||
}
|
||||
for check in checks {
|
||||
let (reported, blocked) = check.into_violations();
|
||||
assert_eq!(reported.len(), 2);
|
||||
assert_eq!(blocked.len(), 3);
|
||||
for (violations, policies, disposition, endpoints) in [
|
||||
(
|
||||
&reported,
|
||||
&report_only,
|
||||
ContentSecurityPolicyDisposition::Report,
|
||||
[
|
||||
"https://example.test/report-first",
|
||||
"https://example.test/report-second",
|
||||
],
|
||||
),
|
||||
(
|
||||
&blocked,
|
||||
&enforced,
|
||||
ContentSecurityPolicyDisposition::Enforce,
|
||||
[
|
||||
"https://example.test/enforce-first",
|
||||
"https://example.test/enforce-second",
|
||||
],
|
||||
),
|
||||
] {
|
||||
for (index, policy_index) in [0, 2].into_iter().enumerate() {
|
||||
let violation = &violations[index];
|
||||
assert_eq!(violation.original_policy, policies[policy_index]);
|
||||
assert_eq!(violation.disposition, disposition);
|
||||
assert_eq!(violation.document_uri, runtime.document_url().as_str());
|
||||
assert_eq!(violation.report_uri_endpoints, vec![endpoints[index]]);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
blocked[2].original_policy,
|
||||
"default-src 'none'; report-uri /ignored-meta"
|
||||
);
|
||||
assert!(blocked[2].report_uri_endpoints.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_csp_checks_preserve_identical_policies_from_separate_deliveries() {
|
||||
let mut runtime = runtime_for_html(
|
||||
r#"<!doctype html><meta http-equiv="Content-Security-Policy" content="img-src 'none'">"#,
|
||||
);
|
||||
let policies = ["img-src 'none'".to_owned(), "img-src 'none'".to_owned()];
|
||||
runtime.set_response_content_security_policies(&policies);
|
||||
runtime.set_response_content_security_report_only_policies(&policies);
|
||||
let (reported, blocked) = runtime
|
||||
.document_subresource_csp_check(
|
||||
&Url::parse("https://example.test/image").unwrap(),
|
||||
DocumentSubresourceCspKind::Image,
|
||||
)
|
||||
.into_violations();
|
||||
assert_eq!(reported.len(), 2);
|
||||
assert_eq!(blocked.len(), 3);
|
||||
assert!(
|
||||
reported
|
||||
.iter()
|
||||
.chain(&blocked)
|
||||
.all(|violation| violation.original_policy == "img-src 'none'")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherited_meta_policies_preserve_reporting_rules_and_duplicate_deliveries() {
|
||||
let mut runtime = runtime_for_html("<!doctype html>");
|
||||
let policy = "img-src 'none'; report-uri /report".to_owned();
|
||||
runtime.initialize_inherited_meta_content_security_policies(
|
||||
runtime.document_handle(),
|
||||
&[policy.clone(), policy.clone()],
|
||||
);
|
||||
runtime.set_response_content_security_policies(std::slice::from_ref(&policy));
|
||||
let (_, blocked) = runtime
|
||||
.document_subresource_csp_check(
|
||||
&Url::parse("https://example.test/image").unwrap(),
|
||||
DocumentSubresourceCspKind::Image,
|
||||
)
|
||||
.into_violations();
|
||||
assert_eq!(blocked.len(), 3);
|
||||
assert!(
|
||||
blocked
|
||||
.iter()
|
||||
.all(|violation| violation.original_policy == policy)
|
||||
);
|
||||
assert_eq!(
|
||||
blocked[0].report_uri_endpoints,
|
||||
vec!["https://example.test/report"]
|
||||
);
|
||||
assert!(
|
||||
blocked[1..]
|
||||
.iter()
|
||||
.all(|violation| violation.report_uri_endpoints.is_empty())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_ancestors_reports_once_per_policy_even_when_multiple_ancestors_fail() {
|
||||
let protected_url = Url::parse("https://child.test/frame").unwrap();
|
||||
let policy = DocumentPolicyContainer::from_navigation_response_headers(
|
||||
&[
|
||||
(
|
||||
"Content-Security-Policy".to_owned(),
|
||||
"frame-ancestors 'none', frame-ancestors 'self'".to_owned(),
|
||||
),
|
||||
(
|
||||
"Content-Security-Policy-Report-Only".to_owned(),
|
||||
"frame-ancestors 'none', frame-ancestors 'self'".to_owned(),
|
||||
),
|
||||
],
|
||||
&protected_url,
|
||||
);
|
||||
let ancestors = [Some(Url::parse("https://parent.test").unwrap()), None];
|
||||
let (reported, blocked) = policy
|
||||
.navigation_response_frame_ancestors_check(
|
||||
&protected_url,
|
||||
DocumentNavigationEmbeddingContext::Nested(&ancestors),
|
||||
)
|
||||
.into_violations();
|
||||
assert_eq!(reported.len(), 2);
|
||||
assert_eq!(blocked.len(), 2);
|
||||
for violations in [&reported, &blocked] {
|
||||
assert_eq!(violations[0].original_policy, "frame-ancestors 'none'");
|
||||
assert_eq!(violations[1].original_policy, "frame-ancestors 'self'");
|
||||
}
|
||||
assert!(
|
||||
policy
|
||||
.navigation_response_frame_ancestors_check(
|
||||
&protected_url,
|
||||
DocumentNavigationEmbeddingContext::TopLevel,
|
||||
)
|
||||
.has_no_violations()
|
||||
);
|
||||
}
|
||||
|
||||
fn runtime_with_response_csp_report_only(policy: &str) -> DocumentRuntime {
|
||||
let mut runtime = runtime_for_html("<!doctype html>");
|
||||
runtime.set_response_content_security_report_only_policies(&[policy.to_owned()]);
|
||||
|
||||
@@ -1621,10 +1621,51 @@ impl PageScriptHost {
|
||||
.streaming_subresource_fetches
|
||||
.get(&internal_id)
|
||||
.is_some_and(|state| state.body_source_id == body_source_id),
|
||||
AsyncSubresourceFetchEventTarget::ObservedNetworkRecord => true,
|
||||
AsyncSubresourceFetchEventTarget::ObservedNetworkRecord
|
||||
| AsyncSubresourceFetchEventTarget::ContentSecurityPolicyViolation => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn window_fetch_redirect_check(
|
||||
&self,
|
||||
internal_id: u64,
|
||||
) -> Option<moli_fetch::RequestRedirectCheck> {
|
||||
let pending = self
|
||||
.pending_subresource_fetches
|
||||
.get(&internal_id)
|
||||
.or_else(|| {
|
||||
self.running_subresource_fetches
|
||||
.get(&internal_id)
|
||||
.map(|state| &state.pending)
|
||||
})?;
|
||||
self.window_fetch_redirect_check_for_pending(pending)
|
||||
}
|
||||
|
||||
pub(crate) fn window_fetch_redirect_check_for_pending(
|
||||
&self,
|
||||
pending: &PendingSubresourceFetchState,
|
||||
) -> Option<moli_fetch::RequestRedirectCheck> {
|
||||
let fetch = pending.continuation.window_fetch()?;
|
||||
if !fetch.connect_policy().has_policies() {
|
||||
return None;
|
||||
}
|
||||
let report_context = fetch.csp_report_context().clone();
|
||||
let completion_tx = self.resource_completion_sender();
|
||||
fetch.redirect_csp_state().redirect_check(
|
||||
fetch.connect_policy().clone(),
|
||||
pending.info.document_url.clone(),
|
||||
pending.info.url.clone(),
|
||||
move |violation| {
|
||||
let _ = completion_tx.send_async_subresource_event(
|
||||
crate::types::AsyncSubresourceFetchEvent::ContentSecurityPolicyViolation {
|
||||
report_context: Box::new(report_context.clone()),
|
||||
violation: Box::new(violation),
|
||||
},
|
||||
);
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn pending_xhr_for_upload(&self, internal_id: u64) -> Option<&PendingSubresourceFetchState> {
|
||||
let pending = self
|
||||
.pending_subresource_fetches
|
||||
|
||||
@@ -208,8 +208,10 @@ impl PageScriptHost {
|
||||
owner: OwnerDispatchScope,
|
||||
) -> Option<crate::document_runtime::DocumentConnectPolicySnapshot> {
|
||||
let snapshot = self.owner_document_policy_snapshot(owner)?;
|
||||
// SAFETY: PageScriptHost belongs to the ScriptVm that owns this runtime.
|
||||
Some(
|
||||
crate::document_runtime::DocumentConnectPolicySnapshot::from_policy_container(
|
||||
unsafe { &*self.runtime }.document_connect_policy_snapshot_for_document(
|
||||
snapshot.document_handle,
|
||||
&snapshot.policy_container,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -7,6 +7,7 @@ mod blob_url_entry;
|
||||
mod body;
|
||||
mod body_source;
|
||||
mod browser_response;
|
||||
mod csp_redirect;
|
||||
mod csp_reports;
|
||||
mod event_source;
|
||||
mod fetch;
|
||||
@@ -81,6 +82,7 @@ pub(crate) use self::browser_response::{
|
||||
LocalUrlError, local_url_response, local_url_response_result,
|
||||
local_url_response_with_blob_entry,
|
||||
};
|
||||
pub(crate) use self::csp_redirect::FetchCspRedirectState;
|
||||
pub(crate) use self::csp_reports::{
|
||||
WindowCspReportRequestContext, capture_window_csp_report_request_context,
|
||||
send_content_security_policy_reports_for_lightweight_popup,
|
||||
|
||||
@@ -19,6 +19,131 @@ async fn request_head(socket: &mut tokio::net::TcpStream) -> Result<String> {
|
||||
Ok(String::from_utf8(bytes)?)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fetch_redirect_csp_precedes_target_cors_and_reports_every_policy() -> Result<()> {
|
||||
use crate::{
|
||||
document_runtime::DocumentConnectPolicySnapshot, network_host::FetchCspRedirectState,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
for enforce in [false, true] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let initial_url = url::Url::parse(&format!("http://localhost:{port}/start"))?;
|
||||
let blocked_url = url::Url::parse(&format!("http://127.0.0.1:{port}/blocked"))?;
|
||||
let next_url = blocked_url.clone();
|
||||
let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut requests = Vec::new();
|
||||
loop {
|
||||
let mut socket = tokio::select! {
|
||||
accepted = listener.accept() => accepted?.0,
|
||||
_ = &mut stop_rx => break,
|
||||
};
|
||||
let head = request_head(&mut socket).await?;
|
||||
let line = head.lines().next().unwrap().to_owned();
|
||||
let location = if line.contains(" /start ") {
|
||||
Some("/middle".to_owned())
|
||||
} else if line.contains(" /middle ") {
|
||||
Some(next_url.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
requests.push(line);
|
||||
let response = if let Some(location) = location {
|
||||
format!(
|
||||
"HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
} else {
|
||||
// Report-Only must still report before this CORS denial.
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_owned()
|
||||
};
|
||||
socket.write_all(response.as_bytes()).await?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(requests)
|
||||
});
|
||||
let policies = vec![
|
||||
"connect-src 'self'".to_owned(),
|
||||
"default-src 'self'".to_owned(),
|
||||
];
|
||||
let policy = if enforce {
|
||||
DocumentConnectPolicySnapshot::from_policies(policies, Vec::new(), Default::default())
|
||||
} else {
|
||||
DocumentConnectPolicySnapshot::from_policies(Vec::new(), policies, Default::default())
|
||||
};
|
||||
let checked = FetchCspRedirectState::new(&policy);
|
||||
let reports = Arc::new(Mutex::new(Vec::new()));
|
||||
let captured = reports.clone();
|
||||
let redirect_check = checked
|
||||
.redirect_check(
|
||||
policy,
|
||||
initial_url.clone(),
|
||||
initial_url.clone(),
|
||||
move |violation| {
|
||||
captured.lock().push(violation);
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let request = Request::new_browser(
|
||||
"GET",
|
||||
initial_url.clone(),
|
||||
None,
|
||||
Vec::new(),
|
||||
(&initial_url).into(),
|
||||
)
|
||||
.with_credentials_mode(RequestCredentialsMode::SameOrigin)
|
||||
.with_browser_request_metadata(BrowserRequestMetadata::Fetch)
|
||||
.with_redirect_check(redirect_check);
|
||||
let mut config = moli_fetch::FetchConfig::default();
|
||||
config.set_http_no_proxy(Some("*".to_owned()));
|
||||
let owner = ResourceRequestClient::new(&config)?;
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
fetch_browser_subresource_raw_stream_with_preflight_headers_and_network_metadata(
|
||||
&owner.handle(),
|
||||
request,
|
||||
None,
|
||||
Vec::new(),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let _ = stop_tx.send(());
|
||||
let requests = server.await??;
|
||||
let Err(error) = result else {
|
||||
panic!("CSP or CORS must reject this fetch")
|
||||
};
|
||||
assert!(
|
||||
error.contains(if enforce {
|
||||
"Content Security Policy"
|
||||
} else {
|
||||
"CORS check failed"
|
||||
}),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(requests.len(), if enforce { 2 } else { 3 });
|
||||
assert_eq!(
|
||||
&requests[..2],
|
||||
["GET /start HTTP/1.1", "GET /middle HTTP/1.1"]
|
||||
);
|
||||
assert!(checked.was_checked(&blocked_url));
|
||||
let reports = reports.lock();
|
||||
assert_eq!(reports.len(), 2);
|
||||
for violation in reports.iter() {
|
||||
assert_eq!(violation.blocked_uri, initial_url.as_str());
|
||||
assert_eq!(
|
||||
(
|
||||
&*violation.source_file,
|
||||
violation.line_number,
|
||||
violation.column_number
|
||||
),
|
||||
("", 0, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cors_redirect_referrer_never_recovers_stripped_information() -> Result<()> {
|
||||
let source = url::Url::parse("https://origin.test/private?token=secret#fragment")?;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
use moli_fetch::RequestRedirectCheck;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
content_security_policy::{
|
||||
ContentSecurityPolicySourceLocation, ContentSecurityPolicyUrlViolation, csp_url_for_report,
|
||||
},
|
||||
document_runtime::{
|
||||
DocumentConnectPolicySnapshot, document_content_security_policy_error_message,
|
||||
},
|
||||
};
|
||||
|
||||
/// The last redirect target checked by this request's network producer. The
|
||||
/// response path still checks synthetic responses whose URL was not checked.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FetchCspRedirectState(Option<Arc<Mutex<Option<Url>>>>);
|
||||
|
||||
impl FetchCspRedirectState {
|
||||
pub(crate) fn new(policy: &DocumentConnectPolicySnapshot) -> Self {
|
||||
Self(policy.has_policies().then(|| Arc::new(Mutex::new(None))))
|
||||
}
|
||||
|
||||
pub(crate) fn was_checked(&self, url: &Url) -> bool {
|
||||
self.0
|
||||
.as_ref()
|
||||
.is_some_and(|checked| checked.lock().as_ref() == Some(url))
|
||||
}
|
||||
|
||||
pub(crate) fn redirect_check(
|
||||
&self,
|
||||
policy: DocumentConnectPolicySnapshot,
|
||||
document_url: Url,
|
||||
request_url: Url,
|
||||
report: impl Fn(ContentSecurityPolicyUrlViolation) + Send + Sync + 'static,
|
||||
) -> Option<RequestRedirectCheck> {
|
||||
let checked = self.0.clone()?;
|
||||
Some(RequestRedirectCheck::new(move |next_url| {
|
||||
let (report_only, enforced) = policy
|
||||
.check_redirect(&document_url, next_url)
|
||||
.into_violations();
|
||||
let mut failure = None;
|
||||
for (is_enforced, mut violation) in report_only
|
||||
.into_iter()
|
||||
.map(|v| (false, v))
|
||||
.chain(enforced.into_iter().map(|v| (true, v)))
|
||||
{
|
||||
violation.blocked_uri = csp_url_for_report(&request_url);
|
||||
ContentSecurityPolicySourceLocation::default().apply_to(&mut violation);
|
||||
if is_enforced && failure.is_none() {
|
||||
failure = Some(document_content_security_policy_error_message(
|
||||
&violation, "fetch",
|
||||
));
|
||||
}
|
||||
report(violation);
|
||||
}
|
||||
*checked.lock() = Some(next_url.clone());
|
||||
failure.map_or(Ok(()), Err)
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,15 @@ pub(crate) struct WindowCspReportRequestContext {
|
||||
client_id: crate::service_worker_runtime::ServiceWorkerClientId,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for WindowCspReportRequestContext {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("WindowCspReportRequestContext")
|
||||
.field("identity", &self.identity)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowCspReportRequestContext {
|
||||
pub(crate) fn identity(&self) -> crate::native_bridge::WindowDocumentNetworkRequestIdentity {
|
||||
self.identity
|
||||
@@ -301,6 +310,7 @@ fn dispatch_service_worker_content_security_policy_report(
|
||||
);
|
||||
let request_body_text = report_request_body_text(&request);
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id,
|
||||
request: host.service_worker_fetch_request(
|
||||
request_context.client_id,
|
||||
|
||||
@@ -380,6 +380,7 @@ fn dispatch_service_worker_event_source<'s>(
|
||||
service_worker_fetch_request_metadata(&native_request),
|
||||
);
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: registered.internal_id,
|
||||
request,
|
||||
cors_preflight_request_headers: prepared.cors_preflight_request_headers.clone(),
|
||||
|
||||
@@ -252,6 +252,9 @@ pub(super) fn spawn_network_fetch(
|
||||
},
|
||||
requires_preflight,
|
||||
);
|
||||
if let Some(check) = host.window_fetch_redirect_check(internal_id) {
|
||||
request = request.with_redirect_check(check);
|
||||
}
|
||||
spawn_async_subresource_fetch(
|
||||
prepared.resource_loader.task_runner(),
|
||||
host.resource_completion_sender(),
|
||||
|
||||
@@ -90,6 +90,7 @@ pub(super) fn dispatch_service_worker_fetch(
|
||||
},
|
||||
);
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: host.window_fetch_redirect_check(internal_id),
|
||||
internal_id,
|
||||
request,
|
||||
cors_preflight_request_headers: prepared.cors_preflight_request_headers.clone(),
|
||||
|
||||
@@ -341,6 +341,7 @@ pub(crate) fn start_image_element_resource_fetch(
|
||||
|
||||
if service_worker_controller.is_some() {
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id,
|
||||
request: host.service_worker_fetch_request(
|
||||
client_id,
|
||||
|
||||
@@ -241,6 +241,7 @@ impl SubresourceRequestDispatch {
|
||||
.is_some()
|
||||
{
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id,
|
||||
request: host.service_worker_fetch_request(
|
||||
self.client_id,
|
||||
|
||||
@@ -119,6 +119,7 @@ pub(super) fn dispatch_service_worker_xhr(
|
||||
crate::service_worker_runtime::service_worker_fetch_request_metadata(&prepared.request()),
|
||||
);
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id,
|
||||
request,
|
||||
cors_preflight_request_headers: prepared.cors_preflight_request_headers.clone(),
|
||||
|
||||
@@ -198,6 +198,7 @@ impl RendererBrowserContextRuntime {
|
||||
let redirect_mode =
|
||||
main_resource_fetch_event_redirect_mode(destination, request.redirect_mode());
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 0,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
@@ -272,6 +273,7 @@ impl RendererBrowserContextRuntime {
|
||||
crate::page_task_queue::RendererResourceCompletionSender::direct_completion_only();
|
||||
let (direct_completion_tx, direct_completion_rx) = tokio::sync::oneshot::channel();
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 0,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
|
||||
@@ -20,12 +20,13 @@ impl PageVm {
|
||||
) -> Result<PageResourceCompletionTurnAction> {
|
||||
let current_owner = self.current_page_resource_completion_owner(owner);
|
||||
if current_owner != Some(owner) {
|
||||
// Observed records are producer-captured historical Network facts;
|
||||
// they remain observable after Document replacement but never
|
||||
// acquire authority over the replacement Document's request state.
|
||||
// Network facts and CSP violations retain their captured source
|
||||
// authority after Document replacement. CSP event delivery checks
|
||||
// the exact source Document separately from network reporting.
|
||||
let output_effect = if matches!(
|
||||
event.target(),
|
||||
AsyncSubresourceFetchEventTarget::ObservedNetworkRecord
|
||||
| AsyncSubresourceFetchEventTarget::ContentSecurityPolicyViolation
|
||||
) {
|
||||
let _ = self
|
||||
.vm_mut()
|
||||
|
||||
@@ -2647,26 +2647,37 @@ async fn window_fetch_cross_origin_redirect_without_cors_rejects_and_records_fai
|
||||
|
||||
#[tokio::test]
|
||||
async fn window_fetch_document_csp_blocks_cross_origin_redirect_and_reports_initial_url() {
|
||||
run_page_vm_async_test(async move {
|
||||
let (source_base_url, _, source_server, target_server) =
|
||||
spawn_cross_origin_redirect_with_cors_http_servers(
|
||||
for use_meta in [false, true] {
|
||||
run_page_vm_async_test(async move {
|
||||
let target_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (source_base_url, source_server) =
|
||||
spawn_single_redirect_http_server(
|
||||
"/fetch-csp-redirect-source",
|
||||
"/fetch-csp-redirect-target",
|
||||
"cors-allowed-target",
|
||||
format!("http://{}/fetch-csp-redirect-target", target_listener.local_addr().unwrap()),
|
||||
)
|
||||
.await;
|
||||
let fetch_url = format!("{source_base_url}/fetch-csp-redirect-source");
|
||||
let document_url =
|
||||
Url::parse(&format!("{source_base_url}/page.html")).expect("document url");
|
||||
let mut page_vm = test_page_vm_with_document_url(document_url);
|
||||
page_vm
|
||||
.vm_mut()
|
||||
.set_response_content_security_policies(&[String::from("connect-src 'self'")]);
|
||||
if !use_meta {
|
||||
page_vm
|
||||
.vm_mut()
|
||||
.set_response_content_security_policies(&[String::from("connect-src 'self'")]);
|
||||
}
|
||||
let local_executor = page_vm.local_executor.clone();
|
||||
let fetch_url_literal = serde_json::to_string(&fetch_url).expect("serialize fetch url");
|
||||
|
||||
let (observed, network_output) = local_executor
|
||||
.run(async move {
|
||||
if use_meta {
|
||||
page_vm.vm_mut().eval(r#"
|
||||
const policy = document.createElement("meta");
|
||||
policy.httpEquiv = "Content-Security-Policy";
|
||||
policy.content = "connect-src 'self'";
|
||||
document.head.append(policy);
|
||||
"#)?;
|
||||
}
|
||||
page_vm.vm_mut().eval(&format!(
|
||||
r#"
|
||||
(() => {{
|
||||
@@ -2734,9 +2745,8 @@ async fn window_fetch_document_csp_blocks_cross_origin_redirect_and_reports_init
|
||||
source_server
|
||||
.await
|
||||
.expect("fetch CSP redirect source server should finish");
|
||||
target_server
|
||||
.await
|
||||
.expect("fetch CSP redirect target server should finish");
|
||||
assert!(tokio::time::timeout(Duration::from_millis(50), target_listener.accept()).await.is_err(),
|
||||
"CSP must block before connecting to the redirect target");
|
||||
let observed: serde_json::Value =
|
||||
serde_json::from_str(&observed).expect("parse fetch CSP redirect observation");
|
||||
assert_eq!(
|
||||
@@ -2768,6 +2778,7 @@ async fn window_fetch_document_csp_blocks_cross_origin_redirect_and_reports_init
|
||||
));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1845,8 +1845,9 @@ async fn spawn_redirect_loop_http_server(path: &'static str) -> (String, JoinHan
|
||||
|
||||
async fn spawn_single_redirect_http_server(
|
||||
path: &'static str,
|
||||
location: &'static str,
|
||||
location: impl Into<String>,
|
||||
) -> (String, JoinHandle<()>) {
|
||||
let location = location.into();
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind single-redirect http server");
|
||||
|
||||
@@ -60,6 +60,9 @@ fn document_connect_csp_redirect_failure_message<'s>(
|
||||
}
|
||||
|
||||
if let Some(fetch) = pending.continuation.window_fetch() {
|
||||
if fetch.redirect_csp_state().was_checked(final_url) {
|
||||
return None;
|
||||
}
|
||||
let redirect_status = ContentSecurityPolicyRedirectStatus::FollowedRedirect;
|
||||
if let Some(mut violation) = fetch.connect_policy().report_only_violation(
|
||||
&pending.info.document_url,
|
||||
@@ -168,6 +171,9 @@ fn detached_window_fetch_csp_redirect_failure_message(
|
||||
final_url: &Url,
|
||||
) -> Option<String> {
|
||||
let fetch = pending.continuation.window_fetch()?;
|
||||
if fetch.redirect_csp_state().was_checked(final_url) {
|
||||
return None;
|
||||
}
|
||||
let redirect_status = ContentSecurityPolicyRedirectStatus::FollowedRedirect;
|
||||
if let Some(mut violation) = fetch.connect_policy().report_only_violation(
|
||||
&pending.info.document_url,
|
||||
@@ -524,6 +530,12 @@ fn async_subresource_trace_fields_for_event(
|
||||
event: &AsyncSubresourceFetchEvent,
|
||||
) -> AsyncSubresourceTraceFields {
|
||||
match event {
|
||||
AsyncSubresourceFetchEvent::ContentSecurityPolicyViolation { .. } => {
|
||||
AsyncSubresourceTraceFields {
|
||||
event_kind: Some("csp_violation"),
|
||||
..AsyncSubresourceTraceFields::default()
|
||||
}
|
||||
}
|
||||
AsyncSubresourceFetchEvent::Upload { internal_id, .. } => AsyncSubresourceTraceFields {
|
||||
event_kind: Some("upload"),
|
||||
internal_id: Some(*internal_id),
|
||||
|
||||
@@ -336,6 +336,7 @@ impl ScriptVm {
|
||||
let request_client = pending.load.request_client();
|
||||
let resource_task_runner = pending.load.task_runner();
|
||||
let dispatch = crate::service_worker_runtime::ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id,
|
||||
request: self._context_host.borrow().service_worker_fetch_request(
|
||||
client_id,
|
||||
@@ -1104,7 +1105,7 @@ impl ScriptVm {
|
||||
pub(in crate::script_vm) fn spawn_running_subresource_fetch(
|
||||
&mut self,
|
||||
request_client: ResourceRequestClient,
|
||||
request: moli_fetch::Request,
|
||||
mut request: moli_fetch::Request,
|
||||
mut state: RunningSubresourceFetchState,
|
||||
cancel_handle: Option<moli_fetch::FetchCancelHandle>,
|
||||
) {
|
||||
@@ -1121,7 +1122,12 @@ impl ScriptVm {
|
||||
&request.method,
|
||||
state.pending.blob_url_entry.as_ref(),
|
||||
);
|
||||
let completion_tx = self._context_host.borrow().resource_completion_sender();
|
||||
let host = self._context_host.borrow();
|
||||
if let Some(check) = host.window_fetch_redirect_check_for_pending(&state.pending) {
|
||||
request = request.with_redirect_check(check);
|
||||
}
|
||||
let completion_tx = host.resource_completion_sender();
|
||||
drop(host);
|
||||
let request = crate::network_host::observe_async_xhr_upload(
|
||||
request,
|
||||
&completion_tx,
|
||||
|
||||
@@ -402,6 +402,10 @@ impl ScriptVm {
|
||||
Some(completed.network_record),
|
||||
)
|
||||
}
|
||||
AsyncSubresourceFetchEvent::ContentSecurityPolicyViolation {
|
||||
report_context,
|
||||
violation,
|
||||
} => self.report_async_fetch_csp_violation(&report_context, &violation),
|
||||
AsyncSubresourceFetchEvent::Upload { internal_id, event } => {
|
||||
self.apply_async_xhr_upload_event(internal_id, event)
|
||||
}
|
||||
@@ -432,6 +436,36 @@ impl ScriptVm {
|
||||
trace_async_subresource_stage("async_subresource_event_done", trace_fields, trace_started);
|
||||
result
|
||||
}
|
||||
fn report_async_fetch_csp_violation(
|
||||
&mut self,
|
||||
report_context: &crate::network_host::WindowCspReportRequestContext,
|
||||
violation: &crate::content_security_policy::ContentSecurityPolicyUrlViolation,
|
||||
) -> Result<AsyncSubresourceFetchBodyActivity> {
|
||||
crate::network_host::send_content_security_policy_violation_report_from_window_context(
|
||||
&mut self._context_host.borrow_mut(),
|
||||
report_context,
|
||||
violation,
|
||||
);
|
||||
let identity = report_context.identity();
|
||||
if !self
|
||||
._context_host
|
||||
.borrow()
|
||||
.window_document_owner_is_current_for_dispatch_scope(
|
||||
identity.owner(),
|
||||
identity.dispatch_scope(),
|
||||
)
|
||||
{
|
||||
return Ok(AsyncSubresourceFetchBodyActivity::NoWindowRealmEntered);
|
||||
}
|
||||
self.with_default_context_scope(|scope, host_ptr| {
|
||||
// SAFETY: the default context scope keeps this ScriptVm's host alive.
|
||||
unsafe { &mut *host_ptr }.dispatch_document_connect_csp_violation_event_for_exact_owner_without_report_best_effort(
|
||||
scope, host_ptr, identity, violation,
|
||||
);
|
||||
Ok(AsyncSubresourceFetchBodyActivity::WindowRealmEntered)
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_async_xhr_upload_event(
|
||||
&mut self,
|
||||
internal_id: u64,
|
||||
|
||||
@@ -2455,3 +2455,93 @@ document.addEventListener('securitypolicyviolation', e => {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_fetch_csp_violation_survives_abort_and_keeps_its_source_document() {
|
||||
for replace_document in [false, true] {
|
||||
let mut vm = new_storage_test_vm("https://fetch-csp-queued.test/source");
|
||||
vm.set_fetch_subresource_interception(
|
||||
crate::types::SubresourceInterceptionClasses::for_resource_type(
|
||||
crate::types::SubresourceResourceType::CspReport,
|
||||
),
|
||||
);
|
||||
let request_url = Url::parse("https://fetch-csp-queued.test/request").unwrap();
|
||||
let policy = crate::document_runtime::DocumentPolicyContainer {
|
||||
response_content_security_policies: vec![
|
||||
"connect-src 'self'; report-uri /report".to_owned(),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let snapshot =
|
||||
crate::document_runtime::DocumentConnectPolicySnapshot::from_policy_container(&policy);
|
||||
let (registered, report_context) = vm
|
||||
.with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| {
|
||||
let host = unsafe { &mut *host_ptr };
|
||||
let report_context =
|
||||
crate::network_host::capture_window_csp_report_request_context(
|
||||
scope,
|
||||
host,
|
||||
crate::native_bridge::OwnerDispatchScope::Top,
|
||||
)
|
||||
.unwrap();
|
||||
Ok((
|
||||
register_pending_window_fetch_with_connect_policy_for_test(
|
||||
scope,
|
||||
host,
|
||||
false,
|
||||
policy,
|
||||
request_url.clone(),
|
||||
),
|
||||
report_context,
|
||||
))
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
vm._context_host
|
||||
.borrow_mut()
|
||||
.abort_subresource_fetch(registered.0)
|
||||
);
|
||||
if replace_document {
|
||||
vm.eval("document.open(); document.write('<!doctype html><body>replacement'); document.close()").unwrap();
|
||||
}
|
||||
vm.eval("globalThis.queuedCspEvents = 0; document.addEventListener('securitypolicyviolation', () => queuedCspEvents++)").unwrap();
|
||||
let mut violation = snapshot.enforce_violation(
|
||||
&Url::parse("https://fetch-csp-queued.test/source").unwrap(),
|
||||
&Url::parse("https://forbidden.test/private").unwrap(),
|
||||
crate::content_security_policy::ContentSecurityPolicyRedirectStatus::FollowedRedirect,
|
||||
).unwrap();
|
||||
violation.blocked_uri = request_url.to_string();
|
||||
crate::content_security_policy::ContentSecurityPolicySourceLocation::default()
|
||||
.apply_to(&mut violation);
|
||||
let activity = vm
|
||||
.complete_async_subresource_fetch_event_body(
|
||||
crate::types::AsyncSubresourceFetchEvent::ContentSecurityPolicyViolation {
|
||||
report_context: Box::new(report_context),
|
||||
violation: Box::new(violation),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
matches!(
|
||||
activity,
|
||||
crate::script_vm::AsyncSubresourceFetchBodyActivity::WindowRealmEntered
|
||||
),
|
||||
!replace_document
|
||||
);
|
||||
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm);
|
||||
assert_eq!(
|
||||
vm.eval("String(queuedCspEvents)").unwrap(),
|
||||
if replace_document { "0" } else { "1" }
|
||||
);
|
||||
let reports = vm
|
||||
._context_host
|
||||
.borrow()
|
||||
.pending_window_csp_report_execution_contexts_for_test();
|
||||
assert_eq!(reports.len(), 1);
|
||||
assert_eq!(reports[0].1, registered.4);
|
||||
assert!(
|
||||
!reports[0].2,
|
||||
"network reporting must not retain the source V8 realm"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -683,6 +683,7 @@ pub(crate) struct ServiceWorkerFetchCompletion {
|
||||
pub(crate) struct ServiceWorkerFetchDispatch {
|
||||
pub(crate) internal_id: u64,
|
||||
pub(crate) request: ServiceWorkerFetchRequest,
|
||||
pub(crate) redirect_check: Option<moli_fetch::RequestRedirectCheck>,
|
||||
pub(crate) cors_preflight_request_headers: Vec<(String, String)>,
|
||||
pub(crate) request_cookie_report: Option<moli_cookie_jar::StoredCookieQueryReport>,
|
||||
pub(crate) network_context: AsyncSubresourceNetworkContext,
|
||||
|
||||
@@ -315,7 +315,10 @@ impl ServiceWorkerRuntimeService {
|
||||
let initial_redirect_count = native_request.redirect_count();
|
||||
let fetch_job = ServiceWorkerFetchJob {
|
||||
response_delivery,
|
||||
request: native_request,
|
||||
request: match dispatch.redirect_check {
|
||||
Some(check) => native_request.with_redirect_check(check),
|
||||
None => native_request,
|
||||
},
|
||||
initial_redirect_count,
|
||||
internal_id: dispatch.internal_id,
|
||||
owner: None,
|
||||
|
||||
@@ -220,6 +220,7 @@ impl ServiceWorkerRuntimeService {
|
||||
crate::page_task_queue::RendererResourceCompletionSender::direct_completion_only();
|
||||
let (direct_completion_tx, direct_completion_rx) = tokio::sync::oneshot::channel();
|
||||
let dispatch = ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 0,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
@@ -2146,6 +2147,71 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_redirect_checks_policy_and_retains_it_for_network_fallback() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let event_id = ServiceWorkerEventId(31);
|
||||
let completion_queue = crate::page_task_queue::RendererResourceCompletionTestHarness::new();
|
||||
insert_active_fetch_job(
|
||||
&service,
|
||||
event_id,
|
||||
ServiceWorkerVersionId(1),
|
||||
&RendererServiceWorkerRunIdentity::fresh(),
|
||||
313,
|
||||
completion_queue.sender(),
|
||||
);
|
||||
let mut job = service
|
||||
.inner
|
||||
.state
|
||||
.lock()
|
||||
.pending_fetch_jobs
|
||||
.remove(&event_id)
|
||||
.unwrap();
|
||||
let checked = std::sync::Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
let observed = checked.clone();
|
||||
job.request = job
|
||||
.request
|
||||
.with_redirect_check(moli_fetch::RequestRedirectCheck::new(move |next_url| {
|
||||
observed.lock().push(next_url.clone());
|
||||
if next_url.host_str() == Some("blocked.test") {
|
||||
Err("blocked by redirect policy".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}));
|
||||
let redirect = || ServiceWorkerFetchResponse {
|
||||
head: moli_fetch_types::FetchResponseHead {
|
||||
metadata: moli_fetch_types::FetchResponseMetadata {
|
||||
response_type: moli_fetch_types::FetchResponseType::Default,
|
||||
timing_allow_passed: true,
|
||||
url_list: (None).into_iter().collect(),
|
||||
redirected: false,
|
||||
cors_exposed_header_names: None,
|
||||
},
|
||||
status: 302,
|
||||
status_text: "Found".to_owned(),
|
||||
headers: Vec::new(),
|
||||
},
|
||||
body: Vec::new(),
|
||||
};
|
||||
let allowed = url("https://example.test/app/allowed");
|
||||
let blocked = url("https://blocked.test/target");
|
||||
apply_service_worker_synthetic_redirect(&mut job, redirect(), allowed.clone()).unwrap();
|
||||
let fallback = service_worker_network_fallback_request_for_job(&job);
|
||||
assert_eq!(
|
||||
fallback.check_redirect_target(&blocked).unwrap_err(),
|
||||
"blocked by redirect policy",
|
||||
);
|
||||
assert_eq!(
|
||||
apply_service_worker_synthetic_redirect(&mut job, redirect(), blocked.clone())
|
||||
.unwrap_err(),
|
||||
"blocked by redirect policy",
|
||||
);
|
||||
assert_eq!(job.request.url, allowed);
|
||||
assert_eq!(job.request.redirect_count(), 1);
|
||||
assert_eq!(*checked.lock(), vec![allowed, blocked.clone(), blocked]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_redirect_follow_rewrites_job_and_records_redirect_chain() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
|
||||
@@ -2821,6 +2821,7 @@ async fn controlled_fetch_from_worker_client_dispatches_to_active_worker() {
|
||||
let (direct_completion_tx, direct_completion_rx) = tokio::sync::oneshot::channel();
|
||||
assert!(
|
||||
service.dispatch_controlled_fetch(ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 90,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
|
||||
@@ -353,6 +353,7 @@ fn controlled_fetch_prepares_page_headers_while_offline_or_blocked() {
|
||||
timing_allow_passed: true,
|
||||
url_list: (None).into_iter().collect(),
|
||||
redirected: false,
|
||||
cors_exposed_header_names: None,
|
||||
},
|
||||
status: 200,
|
||||
status_text: "OK".to_owned(),
|
||||
@@ -1049,6 +1050,7 @@ fn resource_store_restores_no_fetch_handler_metadata_for_controlled_fetch() {
|
||||
let (direct_completion_tx, mut direct_completion_rx) = tokio::sync::oneshot::channel();
|
||||
assert!(
|
||||
second_service.dispatch_controlled_fetch(ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 89,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
@@ -1536,6 +1538,7 @@ fn navigation_preload_completion_keeps_response_started_preload_alive() {
|
||||
timing_allow_passed: true,
|
||||
url_list: (None).into_iter().collect(),
|
||||
redirected: false,
|
||||
cors_exposed_header_names: None,
|
||||
},
|
||||
status: 200,
|
||||
status_text: "OK".to_owned(),
|
||||
@@ -1838,6 +1841,7 @@ fn abort_controlled_fetch_drops_direct_worker_completion_and_ignores_late_comple
|
||||
timing_allow_passed: true,
|
||||
url_list: (None).into_iter().collect(),
|
||||
redirected: false,
|
||||
cors_exposed_header_names: None,
|
||||
},
|
||||
status: 200,
|
||||
status_text: "OK".to_owned(),
|
||||
@@ -2000,6 +2004,7 @@ fn no_fetch_handler_controlled_fetch_falls_back_without_dispatching_event() {
|
||||
let (direct_completion_tx, mut direct_completion_rx) = tokio::sync::oneshot::channel();
|
||||
assert!(
|
||||
service.dispatch_controlled_fetch(ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 88,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
@@ -2091,6 +2096,7 @@ fn controlled_fetch_waits_for_activating_active_version() {
|
||||
|
||||
assert!(
|
||||
service.dispatch_controlled_fetch(ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 91,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
@@ -2200,6 +2206,7 @@ fn empty_fetch_handler_controlled_fetch_falls_back_without_dispatching_event() {
|
||||
let (direct_completion_tx, mut direct_completion_rx) = tokio::sync::oneshot::channel();
|
||||
assert!(
|
||||
service.dispatch_controlled_fetch(ServiceWorkerFetchDispatch {
|
||||
redirect_check: None,
|
||||
internal_id: 89,
|
||||
request: ServiceWorkerFetchRequest {
|
||||
client_id,
|
||||
|
||||
@@ -245,6 +245,7 @@ pub(super) struct PendingWindowFetchContinuation {
|
||||
cache_mode: moli_fetch::RequestCacheMode,
|
||||
connect_policy: crate::document_runtime::DocumentConnectPolicySnapshot,
|
||||
csp_report_context: crate::network_host::WindowCspReportRequestContext,
|
||||
redirect_csp_state: crate::network_host::FetchCspRedirectState,
|
||||
redirect_mode: moli_fetch::RequestRedirectMode,
|
||||
}
|
||||
|
||||
@@ -270,6 +271,7 @@ impl PendingWindowFetchContinuation {
|
||||
resource_timing,
|
||||
keepalive,
|
||||
cache_mode,
|
||||
redirect_csp_state: crate::network_host::FetchCspRedirectState::new(&connect_policy),
|
||||
connect_policy,
|
||||
csp_report_context,
|
||||
redirect_mode,
|
||||
@@ -338,6 +340,10 @@ impl PendingWindowFetchContinuation {
|
||||
&self.csp_report_context
|
||||
}
|
||||
|
||||
pub(super) fn redirect_csp_state(&self) -> &crate::network_host::FetchCspRedirectState {
|
||||
&self.redirect_csp_state
|
||||
}
|
||||
|
||||
pub(super) fn redirect_mode(&self) -> moli_fetch::RequestRedirectMode {
|
||||
self.redirect_mode
|
||||
}
|
||||
@@ -921,6 +927,9 @@ pub(super) struct AsyncSubresourceStreamingFinished {
|
||||
/// another kind of resident.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum AsyncSubresourceFetchEventTarget {
|
||||
/// The violation carries its source Document's reporting authority and
|
||||
/// remains reportable after the originating fetch has settled or aborted.
|
||||
ContentSecurityPolicyViolation,
|
||||
Upload {
|
||||
internal_id: u64,
|
||||
},
|
||||
@@ -952,6 +961,10 @@ pub(super) enum AsyncSubresourceFetchEvent {
|
||||
started: Box<AsyncSubresourceStreamingStarted>,
|
||||
body: crate::network::ResourceInterceptionBody,
|
||||
},
|
||||
ContentSecurityPolicyViolation {
|
||||
report_context: Box<crate::network_host::WindowCspReportRequestContext>,
|
||||
violation: Box<crate::content_security_policy::ContentSecurityPolicyUrlViolation>,
|
||||
},
|
||||
Upload {
|
||||
internal_id: u64,
|
||||
event: moli_fetch::UploadEvent,
|
||||
@@ -971,6 +984,9 @@ impl AsyncSubresourceFetchEvent {
|
||||
internal_id: completed.info.internal_id,
|
||||
}
|
||||
}
|
||||
Self::ContentSecurityPolicyViolation { .. } => {
|
||||
AsyncSubresourceFetchEventTarget::ContentSecurityPolicyViolation
|
||||
}
|
||||
Self::Upload { internal_id, .. } => AsyncSubresourceFetchEventTarget::Upload {
|
||||
internal_id: *internal_id,
|
||||
},
|
||||
|
||||
@@ -1077,8 +1077,9 @@ async fn spawn_redirect_loop_http_server(path: &'static str) -> (String, JoinHan
|
||||
|
||||
async fn spawn_single_redirect_http_server(
|
||||
path: &'static str,
|
||||
location: &'static str,
|
||||
location: impl Into<String>,
|
||||
) -> (String, JoinHandle<()>) {
|
||||
let location = location.into();
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind worker single-redirect http server");
|
||||
|
||||
@@ -2041,13 +2041,15 @@ async fn worker_fetch_cross_origin_redirect_without_cors_rejects_and_reports_fai
|
||||
#[tokio::test]
|
||||
async fn worker_fetch_cross_origin_redirect_final_url_obeys_connect_src() {
|
||||
ensure_v8();
|
||||
let (source_base_url, _, source_server, target_server) =
|
||||
spawn_cross_origin_redirect_with_cors_http_servers(
|
||||
"/worker-fetch-csp-redirect-deny",
|
||||
"/worker-fetch-csp-target",
|
||||
"worker-csp-target",
|
||||
)
|
||||
.await;
|
||||
let target_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (source_base_url, source_server) = spawn_single_redirect_http_server(
|
||||
"/worker-fetch-csp-redirect-deny",
|
||||
format!(
|
||||
"http://{}/worker-fetch-csp-target",
|
||||
target_listener.local_addr().unwrap()
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let url = format!("{source_base_url}/worker-fetch-csp-redirect-deny");
|
||||
let url_literal = serde_json::to_string(&url).expect("serialize worker fetch url");
|
||||
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("worker fetch loader");
|
||||
|
||||
Reference in New Issue
Block a user