fix(cache): enforce opaque response policies on cache reads

This commit is contained in:
ldm0
2026-11-20 22:47:59 +08:00
parent c5305eb696
commit 79fac494de
21 changed files with 786 additions and 45 deletions
@@ -32,6 +32,7 @@ use crate::webidl;
mod bucket_maintenance;
mod cache_add;
mod cache_query;
mod cache_response_policy;
mod cache_results;
use moli_storage_service::StorageBucketCacheName;
mod legacy_storage_quota;
@@ -1305,6 +1306,10 @@ fn storage_bucket_cache_storage_match_callback<'s>(
});
match matched {
Some(Some(Some(response))) => {
if let Err(message) = cache_response_policy::validate(scope, &response) {
reject_type_error(scope, resolver, message);
return;
}
let Some(response) = build_storage_bucket_cached_response_object(scope, response)
else {
reject_type_error(
@@ -1769,6 +1774,10 @@ fn storage_bucket_cache_match_callback<'s>(
});
match matched {
Some(Some(Some(response))) => {
if let Err(message) = cache_response_policy::validate(scope, &response) {
reject_type_error(scope, resolver, message);
return;
}
let Some(response) = build_storage_bucket_cached_response_object(scope, response)
else {
reject_type_error(scope, resolver, "Cache.match failed to build a Response.");
@@ -1830,6 +1839,10 @@ fn storage_bucket_cache_match_all_callback<'s>(
Some(Some(matches)) => {
let mut values = Vec::with_capacity(matches.len());
for matched in matches {
if let Err(message) = cache_response_policy::validate(scope, &matched.response) {
reject_type_error(scope, resolver, message);
return;
}
let Some(response) =
build_storage_bucket_cached_response_object(scope, matched.response)
else {
@@ -0,0 +1,125 @@
//! Cache reads apply the policies of the receiver's relevant settings object.
use super::*;
use crate::cross_origin_isolation::DocumentIsolationPolicy;
use crate::network_host::check_opaque_response_policy;
use crate::types::SubresourcePolicyContext;
use moli_url::WebOrigin;
use url::Url;
struct Environment {
origin: WebOrigin,
url: Url,
policy: SubresourcePolicyContext,
}
fn environment(scope: &mut v8::PinScope<'_, '_>) -> Option<Environment> {
if let Some(policy) = crate::worker::worker_subresource_policy_context(scope) {
return Some(Environment {
origin: crate::worker::worker_global_origin(scope)?,
url: crate::worker::worker_current_script_url(scope)?,
policy,
});
}
let context = scope.get_current_context();
let host_ptr = crate::util::context_host_ptr_from_context_slot(context)?;
// The current callback owns this native host. Policy lookup does not
// execute JS or grant the receiver a replacement Window's task authority.
let host = unsafe { &*host_ptr };
if let Some(identity) = host.window_execution_context_identity_for_v8_context(scope, context)
&& host.window_execution_context_identity_is_current(identity)
{
let owner = identity.dispatch_scope();
let (document, policy) = match owner {
crate::native_bridge::OwnerDispatchScope::Top => (
host.document_handle(),
SubresourcePolicyContext::from_document_policy(host.document_policy_container()),
),
crate::native_bridge::OwnerDispatchScope::Child(handle) => (
host.child_browsing_context_document_handle(handle)?,
host.frame_owner_current_child_snapshot(handle)?
.settings
.subresource_policy_context,
),
crate::native_bridge::OwnerDispatchScope::LightweightPopup(id) => (
host.lightweight_popup_document_handle(id)?,
SubresourcePolicyContext::from_document_policy(
host.lightweight_popup_policy_container(id)?,
),
),
};
return Some(Environment {
origin: WebOrigin::from_serialized(&host.window_document_origin(owner)?),
url: host.dom_host().document_url_for_handle(document)?.clone(),
policy,
});
}
// Cache's existing lifecycle guard rejects retired Window receivers before
// policy evaluation; never borrow a replacement document's settings.
None
}
fn report(
scope: &mut v8::PinScope<'_, '_>,
report_type: &str,
owner: &Environment,
blocked_url: &Url,
disposition: &str,
) {
let mut blocked_url = blocked_url.clone();
let _ = blocked_url.set_username("");
let _ = blocked_url.set_password(None);
blocked_url.set_fragment(None);
crate::context_bootstrap::notify_reporting_observers(
scope,
report_type,
owner.url.as_str(),
serde_json::json!({"blockedURL":blocked_url.as_str(),"type":"corp","disposition":disposition,"destination":""}),
);
}
pub(super) fn validate(
scope: &mut v8::PinScope<'_, '_>,
response: &StorageBucketCachedResponse,
) -> Result<(), &'static str> {
// Opaque-redirect and other filtered response types are not subjected to
// the Cache match algorithm's opaque-response CORP check.
if response.head.metadata.response_type != moli_fetch_types::FetchResponseType::Opaque {
return Ok(());
}
let owner = environment(scope).ok_or("Cache response settings are unavailable.")?;
let url = response
.head
.metadata
.final_url()
.ok_or("Cache entry has no internal response URL.")?;
let report_only = check_opaque_response_policy(
&owner.origin,
url,
&response.head.headers,
response.head.metadata.request_include_credentials,
owner.policy.cross_origin_embedder_policy_report_only,
DocumentIsolationPolicy::None,
);
if report_only.is_err_and(|violation| violation.is_due_to_coep()) {
report(scope, "coep", &owner, url, "reporting");
}
match check_opaque_response_policy(
&owner.origin,
url,
&response.head.headers,
response.head.metadata.request_include_credentials,
owner.policy.cross_origin_embedder_policy,
owner.policy.document_isolation_policy,
) {
Ok(()) => Ok(()),
Err(violation) => {
if violation.is_due_to_coep() {
report(scope, "coep", &owner, url, "enforce");
}
if violation.is_due_to_dip() {
report(scope, "dip", &owner, url, "enforce");
}
Err("Cache response was blocked by Cross-Origin-Resource-Policy.")
}
}
}
+53 -1
View File
@@ -44,7 +44,20 @@ pub(crate) fn response_headers_enable_coop_coep_isolation(
pub(crate) fn cross_origin_embedder_policy_from_headers(
headers: &[(String, Vec<u8>)],
) -> CrossOriginEmbedderPolicy {
match response_header_policy_value(headers, "cross-origin-embedder-policy").as_deref() {
cross_origin_embedder_policy_from_header(headers, "cross-origin-embedder-policy")
}
pub(crate) fn cross_origin_embedder_policy_report_only_from_headers(
headers: &[(String, Vec<u8>)],
) -> CrossOriginEmbedderPolicy {
cross_origin_embedder_policy_from_header(headers, "cross-origin-embedder-policy-report-only")
}
fn cross_origin_embedder_policy_from_header(
headers: &[(String, Vec<u8>)],
name: &str,
) -> CrossOriginEmbedderPolicy {
match response_header_policy_value(headers, name).as_deref() {
Some("require-corp") => CrossOriginEmbedderPolicy::RequireCorp,
Some("credentialless") => CrossOriginEmbedderPolicy::Credentialless,
_ => CrossOriginEmbedderPolicy::None,
@@ -214,4 +227,43 @@ mod tests {
DocumentIsolationPolicy::None
);
}
#[test]
fn report_only_embedder_policy_does_not_grant_isolation_or_omit_credentials() {
let headers = vec![
(
"Cross-Origin-Opener-Policy".to_owned(),
b"same-origin".to_vec(),
),
(
"Cross-Origin-Embedder-Policy-Report-Only".to_owned(),
b"credentialless; report-to=\"coep\"".to_vec(),
),
];
let url = Url::parse("https://example.test/").unwrap();
let container =
crate::document_runtime::DocumentPolicyContainer::from_navigation_response_headers(
&headers, &url,
);
let policy = crate::types::SubresourcePolicyContext::from_document_policy(&container);
assert_eq!(
policy.cross_origin_embedder_policy_report_only,
CrossOriginEmbedderPolicy::Credentialless
);
assert_eq!(
policy.cross_origin_embedder_policy,
CrossOriginEmbedderPolicy::None
);
assert!(!policy.cross_origin_isolated);
assert!(!response_headers_enable_cross_origin_isolation(
&url, &headers
));
assert_eq!(
policy.network_credentials_mode(
moli_fetch::RequestMode::NoCors,
moli_fetch::RequestCredentialsMode::Include
),
moli_fetch::RequestCredentialsMode::Include
);
}
}
+2
View File
@@ -659,6 +659,8 @@ pub(crate) struct DocumentPolicyContainer {
pub(crate) referrer_policy: Option<String>,
pub(crate) cross_origin_embedder_policy:
crate::cross_origin_isolation::CrossOriginEmbedderPolicy,
pub(crate) cross_origin_embedder_policy_report_only:
crate::cross_origin_isolation::CrossOriginEmbedderPolicy,
pub(crate) document_isolation_policy: crate::cross_origin_isolation::DocumentIsolationPolicy,
pub(crate) cross_origin_isolated: bool,
/// The response requested a COOP+COEP isolated group. Keep this separate
@@ -429,6 +429,8 @@ impl DocumentPolicyContainer {
referrer_policy: crate::referrer_policy::response_referrer_policy_from_headers(headers),
cross_origin_embedder_policy:
crate::cross_origin_isolation::cross_origin_embedder_policy_from_headers(headers),
cross_origin_embedder_policy_report_only:
crate::cross_origin_isolation::cross_origin_embedder_policy_report_only_from_headers(headers),
document_isolation_policy:
crate::cross_origin_isolation::document_isolation_policy_from_headers(headers),
cross_origin_isolated:
@@ -445,6 +445,9 @@ impl ChildBrowsingContextEntry {
self.document_policy_container.referrer_policy = policy_container.referrer_policy.clone();
self.document_policy_container.cross_origin_embedder_policy =
policy_container.cross_origin_embedder_policy;
self.document_policy_container
.cross_origin_embedder_policy_report_only =
policy_container.cross_origin_embedder_policy_report_only;
self.document_policy_container.document_isolation_policy =
policy_container.document_isolation_policy;
self.document_policy_container.cross_origin_isolated =
@@ -497,6 +500,10 @@ impl ChildBrowsingContextEntry {
snapshot.policy_container.referrer_policy.clone();
self.document_policy_container.cross_origin_embedder_policy =
snapshot.policy_container.cross_origin_embedder_policy;
self.document_policy_container
.cross_origin_embedder_policy_report_only = snapshot
.policy_container
.cross_origin_embedder_policy_report_only;
self.document_policy_container.document_isolation_policy =
snapshot.policy_container.document_isolation_policy;
self.document_policy_container.cross_origin_isolated =
@@ -536,6 +536,9 @@ impl PageScriptHost {
cross_origin_embedder_policy: refresh_policy_source
.map(|policy| policy.cross_origin_embedder_policy)
.unwrap_or_default(),
cross_origin_embedder_policy_report_only: refresh_policy_source
.map(|policy| policy.cross_origin_embedder_policy_report_only)
.unwrap_or_default(),
document_isolation_policy: refresh_policy_source
.map(|policy| policy.document_isolation_policy)
.unwrap_or_default(),
@@ -1352,6 +1352,10 @@ fn dedicated_worker_policy_context_from_headers(
SubresourcePolicyContext {
cross_origin_embedder_policy:
crate::cross_origin_isolation::cross_origin_embedder_policy_from_headers(headers),
cross_origin_embedder_policy_report_only:
crate::cross_origin_isolation::cross_origin_embedder_policy_report_only_from_headers(
headers,
),
// Chromium's DedicatedWorkerHost currently keeps Document-Isolation-Policy
// aligned with the creator while deriving the worker COEP from the script response.
document_isolation_policy: creator_policy_context.document_isolation_policy,
+1 -1
View File
@@ -188,7 +188,7 @@ pub(crate) use self::response::{
build_fetch_response_object_from_body_source_with_metadata,
build_fetch_response_object_from_stream_with_metadata, build_filtered_cached_response_object,
build_navigation_preload_response_object_from_stream_with_metadata,
cors_preflight_request_headers, fetch_response_needs_orb_body_validation, filter_cors_exposed_response_headers,
check_opaque_response_policy, cors_preflight_request_headers, fetch_response_needs_orb_body_validation, filter_cors_exposed_response_headers,
is_cors_policy_failure_message, materialize_response_object_body,
materialize_response_object_body_preserving_error,
materialize_response_object_body_with_chunk_callback,
@@ -51,6 +51,9 @@ pub(crate) fn effective_subresource_policy_context(
let policy = match owner {
crate::native_bridge::OwnerDispatchScope::Top => crate::types::SubresourcePolicyContext {
cross_origin_embedder_policy: host.cross_origin_embedder_policy(),
cross_origin_embedder_policy_report_only: host
.document_policy_container()
.cross_origin_embedder_policy_report_only,
document_isolation_policy: host.document_isolation_policy(),
cross_origin_isolated: host.cross_origin_isolated(),
},
@@ -63,6 +66,10 @@ pub(crate) fn effective_subresource_policy_context(
crate::types::SubresourcePolicyContext {
cross_origin_embedder_policy: host
.lightweight_popup_cross_origin_embedder_policy(popup_id),
cross_origin_embedder_policy_report_only: host
.lightweight_popup_policy_container(popup_id)
.map(|policy| policy.cross_origin_embedder_policy_report_only)
.unwrap_or_default(),
document_isolation_policy: host
.lightweight_popup_document_isolation_policy(popup_id),
cross_origin_isolated: host.lightweight_popup_cross_origin_isolated(popup_id),
@@ -19,7 +19,7 @@ pub(super) use self::bindings::new_response_with_init;
pub(crate) use self::bindings::{build_error_response_object, response_constructor_callback};
pub(super) use self::body_methods::install_response_body_methods;
pub(crate) use self::cors::{
FetchResponseSecurityViolation, cors_preflight_request_headers,
FetchResponseSecurityViolation, check_opaque_response_policy, cors_preflight_request_headers,
fetch_response_needs_orb_body_validation, filter_cors_exposed_response_headers,
is_cors_policy_failure_message, validate_cors_preflight_response, validate_cors_response_chain,
validate_cross_origin_embedder_and_document_isolation_policy,
@@ -1,3 +1,72 @@
#[derive(Debug)]
pub(crate) enum OpaqueResponsePolicyViolation {
Explicit(String),
Defaulted { due_to_coep: bool, due_to_dip: bool },
}
impl OpaqueResponsePolicyViolation {
pub(crate) fn is_due_to_coep(&self) -> bool {
matches!(
self,
Self::Defaulted {
due_to_coep: true,
..
}
)
}
pub(crate) fn is_due_to_dip(&self) -> bool {
matches!(
self,
Self::Defaulted {
due_to_dip: true,
..
}
)
}
}
pub(crate) fn check_opaque_response_policy(
request_origin: &WebOrigin,
response_url: &url::Url,
response_headers: &[(String, Vec<u8>)],
request_include_credentials: bool,
embedder_policy: CrossOriginEmbedderPolicy,
document_isolation_policy: DocumentIsolationPolicy,
) -> Result<(), OpaqueResponsePolicyViolation> {
if !matches!(response_url.scheme(), "http" | "https")
|| request_origin.same_origin_url(response_url)
{
return Ok(());
}
let policy = moli_fetch::CrossOriginResourcePolicy::from_headers(response_headers);
if let Some(policy) = policy {
policy
.check(request_origin, response_url)
.map_err(OpaqueResponsePolicyViolation::Explicit)?;
}
if policy.is_some() {
return Ok(());
}
let due_to_coep = match embedder_policy {
CrossOriginEmbedderPolicy::None => false,
CrossOriginEmbedderPolicy::RequireCorp => true,
CrossOriginEmbedderPolicy::Credentialless => request_include_credentials,
};
let due_to_dip = match document_isolation_policy {
DocumentIsolationPolicy::None => false,
DocumentIsolationPolicy::IsolateAndRequireCorp => true,
DocumentIsolationPolicy::IsolateAndCredentialless => request_include_credentials,
};
if due_to_coep || due_to_dip {
Err(OpaqueResponsePolicyViolation::Defaulted {
due_to_coep,
due_to_dip,
})
} else {
Ok(())
}
}
use moli_fetch::validate_cors_response_for_origin;
use moli_fetch::{RedirectSource, RequestCredentialsMode, RequestMode};
@@ -309,48 +378,24 @@ pub(crate) fn validate_cross_origin_embedder_and_document_isolation_policy(
embedder_policy: CrossOriginEmbedderPolicy,
document_isolation_policy: DocumentIsolationPolicy,
) -> Result<(), String> {
if request_mode != RequestMode::NoCors {
return Ok(());
}
let request_origin = request_origin.into();
if request_mode != RequestMode::NoCors
|| !matches!(response_url.scheme(), "http" | "https")
|| request_origin.same_origin(&response_url.into())
{
return Ok(());
}
let request_includes_credentials =
request_includes_credentials(&request_origin, response_url, credentials_mode);
let requires_corp_due_to_coep = match embedder_policy {
CrossOriginEmbedderPolicy::None => false,
CrossOriginEmbedderPolicy::RequireCorp => true,
CrossOriginEmbedderPolicy::Credentialless => {
request_mode == RequestMode::Navigate || request_includes_credentials
}
};
let requires_corp_due_to_dip = match document_isolation_policy {
DocumentIsolationPolicy::None => false,
DocumentIsolationPolicy::IsolateAndRequireCorp => true,
DocumentIsolationPolicy::IsolateAndCredentialless => {
request_mode == RequestMode::Navigate || request_includes_credentials
}
};
let requires_corp = requires_corp_due_to_coep || requires_corp_due_to_dip;
if !requires_corp {
return Ok(());
}
let policy_label = defaulted_corp_policy_label(
requires_corp_due_to_coep,
check_opaque_response_policy(
&request_origin,
response_url,
response_headers,
request_includes_credentials(&request_origin, response_url, credentials_mode),
embedder_policy,
requires_corp_due_to_dip,
document_isolation_policy,
);
if let Some(policy) = moli_fetch::CrossOriginResourcePolicy::from_headers(response_headers) {
return policy.check(&request_origin, response_url);
}
Err(format!(
"{policy_label} check failed: requires a valid Cross-Origin-Resource-Policy for {} to load {response_url}",
request_origin.ascii_serialization()
))
).map_err(|violation| match violation {
OpaqueResponsePolicyViolation::Explicit(message) => message,
OpaqueResponsePolicyViolation::Defaulted { due_to_coep, due_to_dip } => {
let label = defaulted_corp_policy_label(due_to_coep, embedder_policy, due_to_dip, document_isolation_policy);
format!("{label} check failed: requires a valid Cross-Origin-Resource-Policy for {} to load {response_url}", request_origin.ascii_serialization())
}
})
}
fn defaulted_corp_policy_label(
@@ -1684,4 +1729,124 @@ mod tests {
.is_ok()
);
}
#[test]
fn opaque_response_policy_distinguishes_explicit_corp_and_policy_defaulting() {
let origin = WebOrigin::from_url(&url("https://example.test/"));
let target = url("https://cdn.test/body");
let explicit = [(
"Cross-Origin-Resource-Policy".to_owned(),
b"same-origin".to_vec(),
)];
let violation = check_opaque_response_policy(
&origin,
&target,
&explicit,
true,
CrossOriginEmbedderPolicy::RequireCorp,
DocumentIsolationPolicy::None,
)
.unwrap_err();
assert!(!violation.is_due_to_coep());
for headers in [
Vec::new(),
vec![(
"Cross-Origin-Resource-Policy".to_owned(),
b"Cross-Origin".to_vec(),
)],
vec![(
"Cross-Origin-Resource-Policy".to_owned(),
b"cross-origin, cross-origin".to_vec(),
)],
vec![
(
"Cross-Origin-Resource-Policy".to_owned(),
b"cross-origin".to_vec(),
),
(
"Cross-Origin-Resource-Policy".to_owned(),
b"cross-origin".to_vec(),
),
],
vec![(
"Cross-Origin-Resource-Policy".to_owned(),
b"\xa0cross-origin\xa0".to_vec(),
)],
] {
let violation = check_opaque_response_policy(
&origin,
&target,
&headers,
true,
CrossOriginEmbedderPolicy::RequireCorp,
DocumentIsolationPolicy::None,
)
.unwrap_err();
assert!(violation.is_due_to_coep());
assert!(
check_opaque_response_policy(
&origin,
&target,
&headers,
false,
CrossOriginEmbedderPolicy::Credentialless,
DocumentIsolationPolicy::None
)
.is_ok()
);
assert!(
check_opaque_response_policy(
&origin,
&target,
&headers,
true,
CrossOriginEmbedderPolicy::None,
DocumentIsolationPolicy::None
)
.is_ok()
);
}
assert!(
check_opaque_response_policy(
&origin,
&target,
&[(
"Cross-Origin-Resource-Policy".to_owned(),
b"\tcross-origin \t".to_vec()
)],
true,
CrossOriginEmbedderPolicy::RequireCorp,
DocumentIsolationPolicy::IsolateAndRequireCorp
)
.is_ok()
);
assert!(
check_opaque_response_policy(
&origin,
&url("https://example.test/body"),
&[],
true,
CrossOriginEmbedderPolicy::RequireCorp,
DocumentIsolationPolicy::IsolateAndRequireCorp
)
.is_ok()
);
let violation = check_opaque_response_policy(
&origin,
&target,
&[],
true,
CrossOriginEmbedderPolicy::None,
DocumentIsolationPolicy::IsolateAndRequireCorp,
)
.unwrap_err();
assert!(matches!(
violation,
OpaqueResponsePolicyViolation::Defaulted {
due_to_coep: false,
due_to_dip: true
}
));
assert!(!violation.is_due_to_coep());
}
}
@@ -0,0 +1,339 @@
use super::*;
use crate::cross_origin_isolation::{
CrossOriginEmbedderPolicy as Coep, DocumentIsolationPolicy as Dip,
};
fn install_responses(vm: &mut ScriptVm, origin: &str) {
let context = &vm.current_main_world().unwrap().context as *const _;
vm.with_context_scope_by_ptr_and_checkpoint_for_test(context, |scope, _| {
let mut values = Vec::new();
for (name, credentials, redirect, corp) in [
("included", true, false, false),
("omitted", false, false, false),
("corp", true, false, true),
("redirect", true, true, false),
] {
let mut headers = Vec::new();
if corp {
headers.push((
"Cross-Origin-Resource-Policy".to_owned(),
b"cross-origin".to_vec(),
));
}
if redirect {
headers.push((
"Location".to_owned(),
b"https://opaque.test/target".to_vec(),
));
}
let head = moli_fetch::ResponseHead {
final_url: url::Url::parse(&format!("https://opaque.test/{name}")).unwrap(),
status: if redirect { 302 } else { 200 },
status_text: None,
headers,
request_cookie_report: None,
request_include_credentials: credentials,
cookie_set_reports: Vec::new(),
redirected: false,
redirect_chain: Vec::new(),
from_cache: false,
cache_state: Default::default(),
preload_state: Default::default(),
negotiated_http_version: None,
};
let response = crate::network_host::build_fetch_response_object_for_request_mode(
scope,
moli_url::WebOrigin::from_url(&url::Url::parse(origin).unwrap()),
crate::network_host::FetchResponseRequest {
method: "GET",
mode: moli_fetch::RequestMode::NoCors,
redirect_mode: if redirect {
moli_fetch::RequestRedirectMode::Manual
} else {
moli_fetch::RequestRedirectMode::Follow
},
},
moli_fetch::Response::from_head_and_text_body(head, "body".to_owned()),
);
values.push(response.into());
}
let values = v8::Array::new_with_elements(scope, &values);
let global = scope.get_current_context().global(scope);
let key = crate::util::v8str(scope, "inputs");
global.create_data_property(scope, key.into(), values.into());
Ok(())
})
.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn cache_read_policy_preserves_credentials_and_reports_only_coep_blocks() {
for (name, coep, dip, report_only, blocked, enforce_reports, reporting_reports) in [
(
"none",
Coep::None,
Dip::None,
Coep::None,
[false, false],
0,
0,
),
(
"require",
Coep::RequireCorp,
Dip::None,
Coep::None,
[true, true],
6,
0,
),
(
"credentialless",
Coep::Credentialless,
Dip::None,
Coep::None,
[true, false],
3,
0,
),
(
"dip-require",
Coep::None,
Dip::IsolateAndRequireCorp,
Coep::None,
[true, true],
0,
0,
),
(
"dip-credentialless",
Coep::None,
Dip::IsolateAndCredentialless,
Coep::None,
[true, false],
0,
0,
),
(
"report-only",
Coep::None,
Dip::None,
Coep::RequireCorp,
[false, false],
0,
6,
),
(
"both",
Coep::RequireCorp,
Dip::None,
Coep::RequireCorp,
[true, true],
6,
6,
),
] {
let loader = static_http_loader(std::iter::empty::<String>());
let url = format!("https://cache-policy.test/{name}");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(&url, &loader);
vm.set_main_navigation_policy_container(crate::document_runtime::DocumentPolicyContainer {
cross_origin_embedder_policy: coep,
cross_origin_embedder_policy_report_only: report_only,
document_isolation_policy: dip,
..Default::default()
});
install_responses(&mut vm, &url);
vm.exec(&format!(r#"
globalThis.reports=[];globalThis.done=false;globalThis.results=[];
globalThis.observer=new ReportingObserver(list=>reports.push(...list.map(report=>report.toJSON())),{{types:['coep']}});
observer.observe();
(async()=>{{
const cache=await caches.open('policy');
const blocked={blocked};
const entries=[...inputs,new Response('basic')];
const types=['opaque','opaque','opaque','opaqueredirect','default'];
for(let index=0;index<entries.length;index++){{
const key=new URL('entry-'+index,location.href).href;
await cache.put(key,entries[index]);
for(const [api,read] of [
['match',()=>cache.match(key)],
['matchAll',async()=>(await cache.matchAll(key))[0]],
['storage',()=>caches.match(key,{{cacheName:'policy'}})],
]){{
const shouldBlock=index<2&&blocked[index];
try{{
const response=await read();
if(shouldBlock||response.type!==types[index])throw new Error('unexpected response '+index+' '+api);
}}catch(error){{
if(!shouldBlock||!(error instanceof TypeError))throw error;
}}
results.push([index,api]);
}}
}}
done=true;
}})().catch(error=>done='error:'+error);
"#, blocked=serde_json::to_string(&blocked).unwrap()),None).unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(done)",
"true",
name,
)
.await;
let count = enforce_reports + reporting_reports;
if count != 0 {
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(reports.length)",
&count.to_string(),
name,
)
.await;
}
let reports: Vec<serde_json::Value> =
serde_json::from_str(&vm.eval("JSON.stringify(reports)").unwrap()).unwrap();
assert_eq!(vm.eval("results.length").unwrap(), "15", "{name}");
assert_eq!(reports.len(), count, "{name}: {reports:?}");
assert_eq!(
reports
.iter()
.filter(|report| report["body"]["disposition"] == "enforce")
.count(),
enforce_reports,
"{name}"
);
assert_eq!(
reports
.iter()
.filter(|report| report["body"]["disposition"] == "reporting")
.count(),
reporting_reports,
"{name}"
);
for report in reports {
assert_eq!(report["type"], "coep", "{name}");
assert_eq!(report["url"], url, "{name}");
assert_eq!(report["body"]["type"], "corp", "{name}");
assert_eq!(report["body"]["destination"], "", "{name}");
assert!(
matches!(
report["body"]["blockedURL"].as_str(),
Some("https://opaque.test/included" | "https://opaque.test/omitted")
),
"{name}: {report}"
);
}
}
}
#[tokio::test(flavor = "current_thread")]
async fn borrowed_cache_reads_use_owner_policy_reports_and_error_realm_after_removal() {
let server = StaticHttpServer::spawn_with_raw_responder(1, |_, _| {
let body="<!doctype html><body><script>parent.postMessage('cache-child-ready','*')</script>";
format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nCross-Origin-Embedder-Policy: require-corp\r\nCross-Origin-Embedder-Policy-Report-Only: require-corp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len())
}).await;
let loader = static_http_loader([server.resolve_entry("localhost")]);
let root_url = server.url_for_host("localhost", "/root");
let child_url = server.url_for_host("localhost", "/child");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(root_url.as_str(), &loader);
install_responses(&mut vm, root_url.as_str());
vm.exec(&format!(r#"
globalThis.frameReady=false;globalThis.parentReports=[];globalThis.childReports=[];
addEventListener('message',event=>{{if(event.data==='cache-child-ready')frameReady=true;}});
const frame=document.createElement('iframe');frame.id='target';frame.src={child};document.body.append(frame);
"#,child=serde_json::to_string(child_url.as_str()).unwrap()),None).unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(frameReady)",
"true",
"cache child response policy",
)
.await;
vm.exec(r#"
globalThis.done=false;
(async()=>{
const child=document.getElementById('target').contentWindow;
globalThis.parentObserver=new ReportingObserver(list=>parentReports.push(...list.map(report=>report.toJSON())),{types:['coep']});
globalThis.childObserver=new child.ReportingObserver(list=>childReports.push(...list.map(report=>report.toJSON())),{types:['coep']});
parentObserver.observe();childObserver.observe();
const ownCache=await caches.open('policy');const otherCache=await child.caches.open('policy');
const key=new URL('/entry',location.href).href;await ownCache.put(key,inputs[0]);
child.origin='https://opaque.test';
const base=child.document.createElement('base');base.href='https://opaque.test/';child.document.head.append(base);
globalThis.completed=0;
for(const [owner,cache] of [[window,ownCache],[child,otherCache]]){
for(const callee of [window,child]){
for(const [api,read] of [
['match',()=>callee.Cache.prototype.match.call(cache,key)],
['all',()=>callee.Cache.prototype.matchAll.call(cache,key)],
['storage',()=>callee.CacheStorage.prototype.match.call(owner.caches,key,{cacheName:'policy'})],
]){
const promise=read();
if(!(promise instanceof owner.Promise))throw new Error('wrong Promise realm');
try{
const value=await promise;
if(owner===child)throw new Error('owner COEP was ignored');
const response=api==='all'?value[0]:value;
if(Object.getPrototypeOf(response)!==owner.Response.prototype)throw new Error('wrong Response realm');
if(api==='all'&&(!Object.isFrozen(value)||Object.getPrototypeOf(value)!==owner.Array.prototype))throw new Error('wrong result array');
}catch(error){
if(owner!==child||!(error instanceof child.TypeError)||error instanceof TypeError)throw error;
if(!error.message.includes('blocked by Cross-Origin-Resource-Policy'))throw error;
}
completed++;
}
}
}
globalThis.savedCache=otherCache;
done=true;
})().catch(error=>done='error:'+error);
"#,None).unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(done)",
"true",
"borrowed Cache read policies",
)
.await;
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(childReports.length)",
"12",
"owner Cache COEP reports",
)
.await;
assert_eq!(vm.eval("completed").unwrap(), "12");
assert_eq!(vm.eval("parentReports.length").unwrap(), "0");
let reports: Vec<serde_json::Value> =
serde_json::from_str(&vm.eval("JSON.stringify(childReports)").unwrap()).unwrap();
for report in reports {
assert_eq!(report["url"], child_url.as_str());
assert_eq!(report["body"]["blockedURL"], "https://opaque.test/included");
}
vm.exec(r#"
globalThis.done=false;document.getElementById('target').remove();
const key=new URL('/entry',location.href).href;
const promise=Cache.prototype.match.call(savedCache,key);
// Retirement is rejected by the pre-existing lifecycle guard before
// result-realm selection or CORP evaluation.
if(!(promise instanceof Promise))throw new Error('retired rejection Promise realm changed');
promise.then(()=>done='unexpected response',error=>{
done=error instanceof DOMException&&error.name==='InvalidStateError'&&error.message.includes('execution context has been destroyed');
});
"#,None).unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(done)",
"true",
"retained Cache response policy",
)
.await;
assert_eq!(vm.eval("parentReports.length").unwrap(), "0");
assert_eq!(server.finish_targets().await, ["/child"]);
}
@@ -2327,6 +2327,7 @@ mod browser_api;
mod cache_dictionary_inheritance;
mod cache_interfaces;
mod cache_response_credentials;
mod cache_response_policy;
mod dom_token_list_native_receivers;
@@ -1066,6 +1066,10 @@ fn service_worker_script_policy_context(
crate::cross_origin_isolation::cross_origin_embedder_policy_from_headers(headers);
SubresourcePolicyContext {
cross_origin_embedder_policy,
cross_origin_embedder_policy_report_only:
crate::cross_origin_isolation::cross_origin_embedder_policy_report_only_from_headers(
headers,
),
document_isolation_policy:
crate::cross_origin_isolation::document_isolation_policy_from_headers(headers),
// A ServiceWorker's own COEP establishes its independent agent's mode;
@@ -639,6 +639,10 @@ fn worker_policy_context_from_response(headers: &[(String, Vec<u8>)]) -> Subreso
SubresourcePolicyContext {
cross_origin_embedder_policy:
crate::cross_origin_isolation::cross_origin_embedder_policy_from_headers(headers),
cross_origin_embedder_policy_report_only:
crate::cross_origin_isolation::cross_origin_embedder_policy_report_only_from_headers(
headers,
),
document_isolation_policy:
crate::cross_origin_isolation::document_isolation_policy_from_headers(headers),
cross_origin_isolated: false,
+4
View File
@@ -1041,6 +1041,8 @@ impl From<moli_fetch::PreloadResponseFilter> for AsyncSubresourceFetchResponseFi
pub(crate) struct SubresourcePolicyContext {
pub(super) cross_origin_embedder_policy:
crate::cross_origin_isolation::CrossOriginEmbedderPolicy,
pub(super) cross_origin_embedder_policy_report_only:
crate::cross_origin_isolation::CrossOriginEmbedderPolicy,
pub(super) document_isolation_policy: crate::cross_origin_isolation::DocumentIsolationPolicy,
pub(super) cross_origin_isolated: bool,
}
@@ -1049,6 +1051,8 @@ impl SubresourcePolicyContext {
pub(super) fn from_document_policy(policy: &DocumentPolicyContainer) -> Self {
Self {
cross_origin_embedder_policy: policy.cross_origin_embedder_policy,
cross_origin_embedder_policy_report_only: policy
.cross_origin_embedder_policy_report_only,
document_isolation_policy: policy.document_isolation_policy,
cross_origin_isolated: policy.cross_origin_isolated
&& policy.allows_cross_origin_isolation(),
@@ -235,6 +235,7 @@ pub(crate) use state::{
worker_current_script_url, worker_exception_report_target, worker_global_is_closed,
worker_realm_secure_context_available, worker_referrer_policy,
worker_service_worker_control_state, worker_shared_memory_agent_cluster, worker_storage_key,
worker_storage_partition_identity, worker_termination_requested,
worker_storage_partition_identity, worker_subresource_policy_context,
worker_termination_requested,
};
pub(super) use timers::{TimerInfo, WorkerIsolateTimerQueues, worker_isolate_timer_queues};
@@ -373,6 +373,12 @@ pub(crate) fn worker_current_script_url(scope: &mut v8::PinScope<'_, '_>) -> Opt
get_worker_state(scope)?.borrow().current_script_url.clone()
}
pub(crate) fn worker_subresource_policy_context(
scope: &mut v8::PinScope<'_, '_>,
) -> Option<crate::types::SubresourcePolicyContext> {
Some(get_worker_state(scope)?.borrow().policy_context)
}
pub(crate) fn worker_exception_report_target(
scope: &mut v8::PinScope<'_, '_>,
) -> Option<(mpsc::UnboundedSender<WorkerToParentMessage>, String)> {
+3 -2
View File
@@ -79,8 +79,9 @@ pub(crate) use global_scope::{
worker_notification_permission_state, worker_opfs_directory_iterator_registry,
worker_opfs_handle_registry, worker_realm_secure_context_available, worker_referrer_policy,
worker_service_worker_control_state, worker_shared_memory_agent_cluster, worker_storage_key,
worker_storage_partition_identity, worker_termination_requested,
worker_trusted_types_for_script_requirements, worker_websocket_wrapper,
worker_storage_partition_identity, worker_subresource_policy_context,
worker_termination_requested, worker_trusted_types_for_script_requirements,
worker_websocket_wrapper,
};
pub(crate) use handle::WorkerMessage;
pub(crate) use handle::{
@@ -112,6 +112,7 @@ async fn check_worker_credentialless_fetch(intercept: bool) {
document_isolation_policy: dip,
// Network policy applies even without an isolated agent cluster.
cross_origin_isolated: false,
..Default::default()
}),
);
if intercept {