fix(policy): preserve header bounds when delegating opaque sources

This commit is contained in:
ldm0
2026-11-12 05:20:18 +08:00
parent 3891608e1b
commit 2d20fee937
5 changed files with 427 additions and 46 deletions
+143 -46
View File
@@ -2,8 +2,10 @@ use std::sync::Arc;
use url::Url;
mod cross_origin_isolation;
mod document_feature;
mod sensors;
use cross_origin_isolation::CrossOriginIsolationPermission;
use document_feature::DocumentFeaturePolicy;
pub(crate) use sensors::SensorPermission;
use sensors::SensorPermissionsPolicy;
@@ -13,17 +15,17 @@ use sensors::SensorPermissionsPolicy;
/// container cannot delegate tools to an origin excluded by its parent header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct DocumentPermissionsPolicy {
fullscreen: bool,
gamepad: bool,
midi: bool,
fullscreen: DocumentFeaturePolicy,
gamepad: DocumentFeaturePolicy,
midi: DocumentFeaturePolicy,
encrypted_media: bool,
encrypted_media_allowlists: Vec<(url::Origin, OriginAllowlist)>,
payment: bool,
payment_allowlists: Vec<(url::Origin, OriginAllowlist)>,
tools: bool,
tools_allowlist: Option<OriginAllowlist>,
synchronous_xhr: bool,
focus_without_user_activation: bool,
synchronous_xhr: DocumentFeaturePolicy,
focus_without_user_activation: DocumentFeaturePolicy,
sensors: SensorPermissionsPolicy,
cross_origin_isolation: CrossOriginIsolationPermission,
}
@@ -31,17 +33,17 @@ pub(crate) struct DocumentPermissionsPolicy {
impl Default for DocumentPermissionsPolicy {
fn default() -> Self {
Self {
fullscreen: true,
gamepad: true,
midi: true,
fullscreen: DocumentFeaturePolicy::default(),
gamepad: DocumentFeaturePolicy::default(),
midi: DocumentFeaturePolicy::default(),
encrypted_media: true,
encrypted_media_allowlists: Vec::new(),
payment: true,
payment_allowlists: Vec::new(),
tools: true,
tools_allowlist: None,
synchronous_xhr: true,
focus_without_user_activation: true,
synchronous_xhr: DocumentFeaturePolicy::default(),
focus_without_user_activation: DocumentFeaturePolicy::default(),
sensors: SensorPermissionsPolicy::default(),
cross_origin_isolation: CrossOriginIsolationPermission::default(),
}
@@ -57,24 +59,24 @@ impl DocumentPermissionsPolicy {
self.sensors.enabled(sensor)
}
pub(crate) const fn fullscreen_enabled(&self) -> bool {
self.fullscreen
pub(crate) fn fullscreen_enabled(&self) -> bool {
self.fullscreen.enabled()
}
pub(crate) const fn synchronous_xhr_enabled(&self) -> bool {
self.synchronous_xhr
pub(crate) fn synchronous_xhr_enabled(&self) -> bool {
self.synchronous_xhr.enabled()
}
pub(crate) const fn gamepad_enabled(&self) -> bool {
self.gamepad
pub(crate) fn gamepad_enabled(&self) -> bool {
self.gamepad.enabled()
}
pub(crate) const fn focus_without_user_activation_enabled(&self) -> bool {
self.focus_without_user_activation
pub(crate) fn focus_without_user_activation_enabled(&self) -> bool {
self.focus_without_user_activation.enabled()
}
pub(crate) const fn midi_enabled(&self) -> bool {
self.midi
pub(crate) fn midi_enabled(&self) -> bool {
self.midi.enabled()
}
pub(crate) const fn encrypted_media_enabled(&self) -> bool {
@@ -91,9 +93,9 @@ impl DocumentPermissionsPolicy {
pub(crate) fn intersect(&self, other: &Self) -> Self {
Self {
fullscreen: self.fullscreen && other.fullscreen,
gamepad: self.gamepad && other.gamepad,
midi: self.midi && other.midi,
fullscreen: self.fullscreen.intersect(&other.fullscreen),
gamepad: self.gamepad.intersect(&other.gamepad),
midi: self.midi.intersect(&other.midi),
encrypted_media: self.encrypted_media && other.encrypted_media,
encrypted_media_allowlists: self
.encrypted_media_allowlists
@@ -110,9 +112,10 @@ impl DocumentPermissionsPolicy {
.collect(),
tools: self.tools && other.tools,
tools_allowlist: other.tools_allowlist.clone(),
synchronous_xhr: self.synchronous_xhr && other.synchronous_xhr,
focus_without_user_activation: self.focus_without_user_activation
&& other.focus_without_user_activation,
synchronous_xhr: self.synchronous_xhr.intersect(&other.synchronous_xhr),
focus_without_user_activation: self
.focus_without_user_activation
.intersect(&other.focus_without_user_activation),
sensors: self.sensors.intersect(&other.sensors),
cross_origin_isolation: self
.cross_origin_isolation
@@ -138,18 +141,20 @@ impl DocumentPermissionsPolicy {
policy.sensors.declare(sensor, allowlist, document_url);
}
if feature.trim().eq_ignore_ascii_case("fullscreen") {
policy.fullscreen = allowed;
policy.fullscreen.declare(allowlist, document_url);
} else if feature.trim().eq_ignore_ascii_case("gamepad") {
policy.gamepad = allowed;
policy.gamepad.declare(allowlist, document_url);
} else if feature.trim().eq_ignore_ascii_case("midi") {
policy.midi = allowed;
policy.midi.declare(allowlist, document_url);
} else if feature.trim().eq_ignore_ascii_case("sync-xhr") {
policy.synchronous_xhr = allowed;
policy.synchronous_xhr.declare(allowlist, document_url);
} else if feature
.trim()
.eq_ignore_ascii_case("focus-without-user-activation")
{
policy.focus_without_user_activation = allowed;
policy
.focus_without_user_activation
.declare(allowlist, document_url);
}
if feature.trim().eq_ignore_ascii_case("payment") {
policy.payment = allowed;
@@ -254,9 +259,15 @@ impl DocumentPermissionsPolicy {
)
.unwrap_or(same_origin);
Self {
fullscreen: self.fullscreen && fullscreen,
gamepad: self.gamepad && gamepad,
midi: self.midi && midi,
fullscreen: self
.fullscreen
.delegated_to_child(parent_origin, child_origin, fullscreen),
gamepad: self
.gamepad
.delegated_to_child(parent_origin, child_origin, gamepad),
midi: self
.midi
.delegated_to_child(parent_origin, child_origin, midi),
encrypted_media: self.encrypted_media
&& self.encrypted_media_allows_origin(child_origin)
&& encrypted_media,
@@ -268,9 +279,16 @@ impl DocumentPermissionsPolicy {
&& self.tools_allows_origin(child_origin, parent_origin)
&& tools,
tools_allowlist: None,
synchronous_xhr: self.synchronous_xhr && synchronous_xhr,
focus_without_user_activation: self.focus_without_user_activation
&& focus_without_user_activation,
synchronous_xhr: self.synchronous_xhr.delegated_to_child(
parent_origin,
child_origin,
synchronous_xhr,
),
focus_without_user_activation: self.focus_without_user_activation.delegated_to_child(
parent_origin,
child_origin,
focus_without_user_activation,
),
sensors: self.sensors.delegated_to_child(
parent_origin,
child_origin,
@@ -288,6 +306,13 @@ impl DocumentPermissionsPolicy {
pub(crate) fn for_document_origin(&self, origin: &url::Origin) -> Self {
Self {
fullscreen: self.fullscreen.for_document_origin(origin),
gamepad: self.gamepad.for_document_origin(origin),
midi: self.midi.for_document_origin(origin),
synchronous_xhr: self.synchronous_xhr.for_document_origin(origin),
focus_without_user_activation: self
.focus_without_user_activation
.for_document_origin(origin),
tools: self.tools && self.tools_allows_origin(origin, origin),
payment: self.payment && self.payment_allows_origin(origin),
encrypted_media: self.encrypted_media && self.encrypted_media_allows_origin(origin),
@@ -392,7 +417,7 @@ fn iframe_allow_feature(
}
let allowlist = tokens.collect::<Vec<_>>();
if allowlist.is_empty() {
return Some(child_origin == source_origin);
return Some(iframe_src_origin_matches(child_origin, source_origin));
}
if allowlist
.iter()
@@ -402,7 +427,8 @@ fn iframe_allow_feature(
}
Some(allowlist.into_iter().any(|token| {
token == "*"
|| (token.eq_ignore_ascii_case("'src'") && child_origin == source_origin)
|| (token.eq_ignore_ascii_case("'src'")
&& iframe_src_origin_matches(child_origin, source_origin))
|| (token.eq_ignore_ascii_case("'self'") && child_origin == parent_origin)
|| Url::parse(token.trim_matches(['\'', '"']))
.ok()
@@ -414,6 +440,16 @@ fn iframe_allow_feature(
})
}
// 'src' may designate an opaque document. That allowlist permission does not
// change origin identity or make unrelated opaque origins match 'self'.
fn iframe_src_origin_matches(child: &url::Origin, source: &url::Origin) -> bool {
child == source
|| matches!(
(child, source),
(url::Origin::Opaque(_), url::Origin::Opaque(_))
)
}
fn token_origin_matches(token: &str, url: &Url) -> bool {
let token = token.trim_matches(['\'', '"']);
Url::parse(token)
@@ -425,6 +461,66 @@ fn token_origin_matches(token: &str, url: &Url) -> bool {
mod tests {
use super::*;
#[test]
fn opaque_src_permissions_do_not_override_parent_feature_declarations() {
let parent_url = url("https://parent.test/");
let parent = parent_url.origin();
let child = url::Origin::new_opaque();
let declared = url::Origin::new_opaque();
assert_ne!(child, declared);
let features: [(&str, fn(&DocumentPermissionsPolicy) -> bool); 5] = [
("fullscreen", DocumentPermissionsPolicy::fullscreen_enabled),
("gamepad", DocumentPermissionsPolicy::gamepad_enabled),
("midi", DocumentPermissionsPolicy::midi_enabled),
(
"sync-xhr",
DocumentPermissionsPolicy::synchronous_xhr_enabled,
),
(
"focus-without-user-activation",
DocumentPermissionsPolicy::focus_without_user_activation_enabled,
),
];
for (feature, enabled) in features {
for allow in [
feature.to_owned(),
format!("{feature} 'src'"),
format!("{feature} *"),
] {
let delegate = |policy: &DocumentPermissionsPolicy| {
policy.delegated_to_child(&parent, &child, &declared, Some(&allow), false)
};
assert!(
enabled(&delegate(&DocumentPermissionsPolicy::default())),
"{allow}"
);
for restriction in ["()", "(self)"] {
let policy = DocumentPermissionsPolicy::from_navigation_response_headers(
&[(
"Permissions-Policy".to_owned(),
format!("{feature}={restriction}").into_bytes(),
)],
&parent_url,
);
assert!(
!enabled(&delegate(&policy)),
"{feature}={restriction}; {allow}"
);
}
}
let allow = format!("{feature} 'self'");
assert!(!enabled(
&DocumentPermissionsPolicy::default().delegated_to_child(
&parent,
&child,
&declared,
Some(&allow),
false,
)
));
}
}
impl DocumentPermissionsPolicy {
fn delegated_to_child_urls(
&self,
@@ -793,13 +889,14 @@ mod tests {
assert!(!denied.synchronous_xhr_enabled());
assert!(!denied.focus_without_user_activation_enabled());
let parent_denied = DocumentPermissionsPolicy {
fullscreen: false,
gamepad: false,
synchronous_xhr: false,
focus_without_user_activation: false,
..Default::default()
};
let parent_denied = DocumentPermissionsPolicy::from_navigation_response_headers(
&[(
"Permissions-Policy".to_owned(),
b"fullscreen=(), gamepad=(), sync-xhr=(), focus-without-user-activation=()"
.to_vec(),
)],
&parent,
);
let delegated = parent_denied.delegated_to_child_urls_with_fullscreen(
&parent,
&url("https://other.test/child"),
@@ -0,0 +1,135 @@
use super::{OriginAllowlist, response_origin_allowlist};
use url::{Origin, Url};
/// A Document's own declarations remain separate from its inherited decision.
/// A child receives the evaluated decision, rather than its parent's header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct DocumentFeaturePolicy {
inherited: bool,
origin: Option<Origin>,
declarations: Vec<OriginAllowlist>,
}
impl Default for DocumentFeaturePolicy {
fn default() -> Self {
Self {
inherited: true,
origin: None,
declarations: Vec::new(),
}
}
}
impl DocumentFeaturePolicy {
pub(super) fn enabled(&self) -> bool {
self.origin
.as_ref()
.map_or(self.inherited, |origin| self.allows_origin(origin, origin))
}
fn allows_origin(&self, declaring_origin: &Origin, origin: &Origin) -> bool {
self.inherited
&& self.declarations.iter().all(|allowed| {
allowed.matches_self && origin == declaring_origin
|| allowed.origins.contains(origin)
})
}
pub(super) fn declare(&mut self, allowlist: &str, url: &Url) {
self.declarations = response_origin_allowlist(allowlist).into_iter().collect();
self.origin = (!self.declarations.is_empty()).then(|| url.origin());
}
pub(super) fn for_document_origin(&self, origin: &Origin) -> Self {
Self {
origin: (!self.declarations.is_empty()).then(|| origin.clone()),
..self.clone()
}
}
pub(super) fn intersect(&self, other: &Self) -> Self {
Self {
inherited: self.inherited && other.inherited,
origin: other.origin.clone().or_else(|| self.origin.clone()),
declarations: self
.declarations
.iter()
.chain(&other.declarations)
.cloned()
.collect(),
}
}
pub(super) fn delegated_to_child(
&self,
parent: &Origin,
child: &Origin,
container_allows: bool,
) -> Self {
Self {
inherited: self.allows_origin(parent, parent)
&& self.allows_origin(parent, child)
&& container_allows,
..Self::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn declarations_constrain_parent_and_child_before_container_delegation() {
let url = Url::parse("https://parent.test/").unwrap();
let parent = url.origin();
let other = Url::parse("https://other.test/").unwrap().origin();
let opaque = Origin::new_opaque();
for (header, same, cross, data) in [
("()", false, false, false),
("(self)", true, false, false),
("*", true, true, true),
("(self \"https://other.test\")", true, true, false),
("(\"https://other.test\")", false, false, false),
] {
let mut policy = DocumentFeaturePolicy::default();
policy.declare(header, &url);
for (child, expected) in [(&parent, same), (&other, cross), (&opaque, data)] {
assert_eq!(
policy.delegated_to_child(&parent, child, true).enabled(),
expected,
"{header}: {child:?}"
);
assert!(!policy.delegated_to_child(&parent, child, false).enabled());
}
}
}
#[test]
fn self_refers_to_its_document_and_does_not_merge_distinct_opaque_origins() {
let url = Url::parse("https://parent.test/").unwrap();
let parent = Origin::new_opaque();
let different = Origin::new_opaque();
let mut declared = DocumentFeaturePolicy::default();
declared.declare("(self)", &url);
let policy = declared.for_document_origin(&parent);
assert!(policy.enabled());
assert!(policy.delegated_to_child(&parent, &parent, true).enabled());
assert!(
!policy
.delegated_to_child(&parent, &different, true)
.enabled()
);
assert_eq!(
DocumentFeaturePolicy::default().for_document_origin(&parent),
DocumentFeaturePolicy::default()
);
let denied = policy.delegated_to_child(&parent, &different, true);
assert!(denied.declarations.is_empty());
assert!(
!denied
.intersect(&DocumentFeaturePolicy::default())
.enabled()
);
}
}
@@ -2456,3 +2456,5 @@ mod rtc_data_channel_init;
mod rtc_data_channel_send;
mod rtc_stats;
mod rtp_transceivers;
mod opaque_permissions_policy;
@@ -0,0 +1,112 @@
use super::*;
const PROBE: &str = include_str!("../../../../tests/fixtures/opaque-permissions-policy.js");
const CHILD: &str = "<!doctype html><script>onmessage=event=>event.source.postMessage({enabled:document.fullscreenEnabled,origin:origin,url:location.href},'*')</script>";
#[tokio::test]
async fn iframe_src_delegation_preserves_parent_headers_for_opaque_and_tuple_origins() {
run_page_vm_async_test(async move {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let server_origin = origin.clone();
let (stop, mut stopped) = tokio::sync::oneshot::channel::<()>();
let server = std::thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async move {
let listener = TcpListener::from_std(listener).unwrap();
let mut connections = tokio::task::JoinSet::new();
loop {
let accepted = tokio::select! {
result = listener.accept() => result.ok(),
_ = &mut stopped => None,
_ = tokio::time::sleep(Duration::from_secs(30)) => None,
};
let Some((mut stream, _)) = accepted else { break };
let server_origin = server_origin.clone();
connections.spawn(async move {
let request = read_http_request_with_body(&mut stream).await.unwrap();
let path = request.lines().next().unwrap().split_whitespace().nth(1).unwrap();
let url = Url::parse(&format!("{server_origin}{path}")).unwrap();
let header = url.query_pairs().find(|(key, _)| key == "policy").map(|(_, value)| value.into_owned()).unwrap_or_default();
assert!(["", "fullscreen=()", "fullscreen=(self)", "fullscreen=*"].contains(&header.as_str()));
let body = if url.path() == "/child" {
CHILD.to_owned()
} else {
assert_eq!(url.path(), "/page");
let probe = PROBE.replace("</script>", "<\\/script>");
format!("<!doctype html><body><script>{probe}\n(async()=>{{while(!policyDone)await new Promise(resolve=>setTimeout(resolve,0));parent.postMessage({{rows:policyRows,error:policyError}},'*');}})();</script>")
};
let extra = if header.is_empty() { String::new() } else { format!("Permissions-Policy: {header}\r\n") };
let response = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n{extra}\r\n{body}", body.len());
let _ = stream.write_all(response.as_bytes()).await;
});
}
connections.abort_all();
while connections.join_next().await.is_some() {}
});
});
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let mut hooks = PageVmRuntimeHooks::standalone_without_owner_reservation_for_test();
hooks.resource_task_runner = Some(loader.browser_resource_runtime().resource_task_runner());
let mut page = test_page_vm_with_loader_document_url_and_hooks(
&loader,
Vec::new(),
Url::parse(&format!("{origin}/root")).unwrap(),
hooks,
);
page.retain_standalone_request_client_owner_for_test(loader);
let local = page.local_executor.clone();
local.run(async move {
page.vm_mut().eval(r#"
globalThis.policyResult=null;
(async()=>{
const html=document.documentElement||document.appendChild(document.createElement('html'));
const body=document.body||html.appendChild(document.createElement('body'));
const rows=[];
for(const header of ['', 'fullscreen=()', 'fullscreen=(self)', 'fullscreen=*']) {
const frame=document.createElement('iframe');
const response=new Promise(resolve=>{
const listener=event=>{
if(event.source!==frame.contentWindow)return;
removeEventListener('message',listener);resolve(event.data);
};addEventListener('message',listener);
});
frame.src='/page?policy='+encodeURIComponent(header);body.appendChild(frame);
const value=await response;
if(value.error!==null)throw Error(value.error);
for(const row of value.rows)rows.push({header,...row});
frame.remove();
}
policyResult={rows};
})().catch(error=>policyResult={error:String(error)});
void 0;
"#)?;
drive_page_work_until_done_with_explicit_producer_admission(
&mut page,
"String(globalThis.policyResult !== null)",
"Real iframe permission reports must finish",
|_| {},
).await?;
let result: serde_json::Value = serde_json::from_str(&page.vm_mut().eval("JSON.stringify(policyResult)")?)?;
assert_eq!(result["error"], serde_json::Value::Null, "{result}");
let rows = result["rows"].as_array().unwrap();
assert_eq!(rows.len(), 64);
for row in rows {
let allow = row["allow"].as_str();
let parent_allows = matches!(row["header"].as_str().unwrap(), "" | "fullscreen=*");
let container_allows = row["fullscreenAttribute"] == true
|| matches!(allow, Some("fullscreen" | "fullscreen 'src'" | "fullscreen *" | "payment;fullscreen"));
assert_eq!(row["observed"]["enabled"], parent_allows && container_allows, "{row}");
assert_eq!(row["sourceMatches"], true);
assert_eq!(row["observed"]["origin"], if row["source"] == "data" { "null".to_owned() } else { origin.replace("127.0.0.1", "localhost") });
}
anyhow::Ok(())
}).await.unwrap();
let _ = stop.send(());
server.join().unwrap();
}).await;
}
@@ -0,0 +1,35 @@
globalThis.policyRows=[];globalThis.policyError=null;globalThis.policyDone=false;
(async()=>{
const childSource='<script>onmessage=event=>event.source.postMessage({enabled:document.fullscreenEnabled,origin:origin,url:location.href},"*")</script>';
for(const source of ['data','tuple']) {
for(const allow of [null, "fullscreen", "fullscreen 'src'", "fullscreen 'self'", "fullscreen 'none'", "fullscreen *", "payment;fullscreen"]) {
const frame=document.createElement('iframe');
if(allow!==null)frame.setAttribute('allow',allow);
const result=new Promise((resolve,reject)=>{
const listener=event=>{
if(event.source!==frame.contentWindow)return;
removeEventListener('message',listener);
resolve({source,allow,fullscreenAttribute:false,observed:event.data,sourceMatches:true});
};
addEventListener('message',listener);
frame.onerror=()=>reject(Error('frame loading failed'));
});
frame.onload=()=>frame.contentWindow.postMessage('inspect','*');
frame.src=source==='tuple'?location.origin.replace('127.0.0.1','localhost')+'/child':'data:text/html,'+encodeURIComponent(childSource);
document.body.appendChild(frame);
policyRows.push(await result);frame.remove();
}
const frame=document.createElement('iframe');frame.setAttribute('allowfullscreen','');
const result=new Promise(resolve=>{
const listener=event=>{
if(event.source!==frame.contentWindow)return;
removeEventListener('message',listener);
resolve({source,allow:null,fullscreenAttribute:true,observed:event.data,sourceMatches:true});
};addEventListener('message',listener);
});
frame.onload=()=>frame.contentWindow.postMessage('inspect','*');
frame.src=source==='tuple'?location.origin.replace('127.0.0.1','localhost')+'/child':'data:text/html,'+encodeURIComponent(childSource);document.body.appendChild(frame);
policyRows.push(await result);frame.remove();}
policyDone=true;
})().catch(error=>{policyError=String(error);policyDone=true;});