fix(navigation): preserve history referrer policies at commit

This commit is contained in:
ldm0
2026-11-20 22:47:44 +08:00
parent 5213b86780
commit ec596ed626
9 changed files with 319 additions and 5 deletions
@@ -431,6 +431,7 @@ mod document_content;
mod frame_tree;
mod lifecycle;
mod navigation;
mod navigation_referrer_policy;
mod resources;
mod runtime;
mod same_document_history;
@@ -0,0 +1,229 @@
use super::*;
async fn policy_server() -> (String, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
axum::serve(
listener,
axum::Router::new()
.route(
"/protected/{policy}",
axum::routing::get(
|axum::extract::Path(policy): axum::extract::Path<String>| async move {
(
[("Referrer-Policy", policy)],
axum::response::Html("<!doctype html><body>source"),
)
},
),
)
.fallback(|| async { axum::response::Html("<!doctype html><body>page") }),
)
.await
.unwrap();
});
(origin, server)
}
async fn command(
ctx: &mut TestContext,
method: &str,
params: serde_json::Value,
) -> serde_json::Value {
ctx.process_and_wait_for_response_async(
json!({"id":1,"sessionId":"SID-1","method":method,"params":params}),
)
.await;
let response = take_response_by_id(ctx, 1);
assert!(response.get("error").is_none(), "{method}: {response}");
response["result"].clone()
}
async fn evaluate(ctx: &mut TestContext, expression: &str) -> serde_json::Value {
let result = command(
ctx,
"Runtime.evaluate",
json!({"expression":expression,"returnByValue":true}),
)
.await;
assert!(
result.get("exceptionDetails").is_none(),
"{expression}: {result}"
);
result["result"]["value"].clone()
}
async fn navigate(ctx: &mut TestContext, method: &str, params: serde_json::Value) {
ctx.sent.clear();
let result = command(ctx, method, params).await;
assert!(result.get("errorText").is_none(), "{result}");
wait_until_frame_stopped_loading(ctx, "TID-1").await;
}
async fn context(url: &str) -> TestContext {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
navigate(&mut ctx, "Page.navigate", json!({"url":url})).await;
ctx
}
const SET_POLICY: &str = r#"function setPolicy(value) {
let m = document.getElementById('policy');
if (!m) { m=document.createElement('meta'); m.name='referrer'; m.id='policy'; document.head.append(m); }
m.content=value;
}"#;
const SNAPSHOT: &str = r#"({
urls:navigation.entries().map(e=>e.url),
sameDocument:navigation.entries().map(e=>e.sameDocument),
from:navigation.activation.from?.url ?? null
})"#;
#[tokio::test(flavor = "multi_thread")]
async fn top_level_history_censors_referrer_protected_documents() {
let (origin, server) = policy_server().await;
let destination = format!("{origin}/destination");
for policy in ["no-referrer", "origin"] {
for header in [false, true] {
for method in ["location", "navigation", "anchor", "cdp"] {
let source = if header {
format!("{origin}/protected/{policy}")
} else {
format!("{origin}/source")
};
let mut ctx = context(&source).await;
evaluate(
&mut ctx,
&format!("history.pushState(null,'','#state'); {SET_POLICY}; true"),
)
.await;
if !header {
evaluate(&mut ctx, &format!("setPolicy({}); true", json!(policy))).await;
}
assert_eq!(
evaluate(&mut ctx, "navigation.entries().map(e=>e.url)").await,
json!([source, format!("{source}#state")])
);
ctx.sent.clear();
let url = json!(destination);
let script = match method {
"location" => format!("location.href={url}; true"),
"navigation" => format!("navigation.navigate({url}); true"),
"anchor" => format!(
"const a=document.createElement('a'); a.href={url}; document.body.append(a); a.click(); true"
),
"cdp" => String::new(),
_ => unreachable!(),
};
if method == "cdp" {
command(&mut ctx, "Page.navigate", json!({"url":destination})).await;
} else {
evaluate(&mut ctx, &script).await;
}
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
assert_eq!(
evaluate(&mut ctx, SNAPSHOT).await,
json!({"urls":[null,null,destination],"sameDocument":[false,false,true],"from":null}),
"{policy}, header={header}, {method}"
);
}
}
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_history_preserves_policy_changes_across_traversal_and_reload() {
let (origin, server) = policy_server().await;
let source = format!("{origin}/source");
let destination = format!("{origin}/destination");
let mut ctx = context(&source).await;
let history = command(&mut ctx, "Page.getNavigationHistory", json!({})).await;
let source_id =
history["entries"][history["currentIndex"].as_u64().unwrap() as usize]["id"].clone();
navigate(&mut ctx, "Page.navigate", json!({"url":destination})).await;
let history = command(&mut ctx, "Page.getNavigationHistory", json!({})).await;
let destination_id =
history["entries"][history["currentIndex"].as_u64().unwrap() as usize]["id"].clone();
for policy in ["no-referrer", "same-origin", "origin", "unsafe-url"] {
navigate(
&mut ctx,
"Page.navigateToHistoryEntry",
json!({"entryId":source_id}),
)
.await;
assert_eq!(
evaluate(&mut ctx, "navigation.currentEntry.url").await,
source
);
evaluate(
&mut ctx,
&format!("{SET_POLICY}; setPolicy({}); true", json!(policy)),
)
.await;
navigate(
&mut ctx,
"Page.navigateToHistoryEntry",
json!({"entryId":destination_id}),
)
.await;
let expected_source = if matches!(policy, "no-referrer" | "origin") {
serde_json::Value::Null
} else {
json!(source)
};
assert_eq!(
evaluate(&mut ctx, SNAPSHOT).await,
json!({"urls":[expected_source,destination],"sameDocument":[false,true],"from":expected_source}),
"{policy}"
);
navigate(&mut ctx, "Page.reload", json!({})).await;
assert_eq!(
evaluate(&mut ctx, "navigation.entries().map(e=>e.url)").await,
json!([expected_source, destination]),
"reload: {policy}"
);
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn navigation_api_captures_history_policy_before_unload_callbacks() {
let (origin, server) = policy_server().await;
let source = format!("{origin}/source");
let destination = format!("{origin}/destination");
for event in ["beforeunload", "pagehide", "unload"] {
let mut ctx = context(&source).await;
evaluate(
&mut ctx,
&format!(
"{SET_POLICY}; addEventListener({event:?},()=>{{ setPolicy('no-referrer'); localStorage.setItem('policy-event', document.getElementById('policy').content); }}); true"
),
)
.await;
ctx.sent.clear();
evaluate(
&mut ctx,
&format!("navigation.navigate({}); true", json!(destination)),
)
.await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
assert_eq!(
evaluate(&mut ctx, "localStorage.getItem('policy-event')").await,
"no-referrer",
"{event} must run and update the meta element"
);
let expected_source = if event == "beforeunload" {
serde_json::Value::Null
} else {
json!(source)
};
assert_eq!(
evaluate(&mut ctx, "navigation.entries().map(e=>e.url)").await,
json!([expected_source, destination]),
"{event}"
);
}
server.abort();
}
+3 -2
View File
@@ -108,9 +108,10 @@ mod navigation_result;
mod navigation_seed;
mod navigation_serialize;
pub(crate) use navigation_entry::navigation_entry_public_token;
pub(crate) use navigation_serialize::current_document_referrer_policy;
pub(crate) use navigation_serialize::{
current_document_referrer_policy, document_referrer_policy_for_native_document,
history_document_id_for_holder,
document_referrer_policy_for_native_document, history_document_id_for_holder,
publish_top_level_navigation_history,
};
mod navigation_surface;
mod navigation_transition_worlds;
@@ -351,8 +351,9 @@ fn navigation_entry_url_getter<'s>(
|| navigation_entries_share_document(scope, current, args.this())
});
if !is_current_document
&& navigation_entry_referrer_policy_value(scope, args.this())
.is_some_and(|policy| policy.eq_ignore_ascii_case("no-referrer"))
&& navigation_entry_referrer_policy_value(scope, args.this()).is_some_and(|policy| {
policy.eq_ignore_ascii_case("no-referrer") || policy.eq_ignore_ascii_case("origin")
})
{
rv.set(v8::null(scope).into());
return;
@@ -88,7 +88,7 @@ fn sync_navigation_entry_seed_from_owner_with_document_url<'s>(
}
}
pub(super) fn publish_top_level_navigation_history<'s>(
pub(crate) fn publish_top_level_navigation_history<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
) {
@@ -33,6 +33,10 @@ impl PageScriptHost {
let descendants =
unsafe { &*host_ptr }.child_document_descendants_unload_snapshot(document);
let window = scope.get_current_context().global(scope);
// Preserve the outgoing Document's effective policy before pagehide and
// unload run. Browser-owned navigations resolve their history from this
// published record, including changes made while the response was pending.
crate::context_bootstrap::publish_top_level_navigation_history(scope, window);
// Claim the exact Document before author code runs, and keep the root's
// destructive-write guard active while descendant handlers execute.
let _unload = unsafe { &*host_ptr }.enter_document_unload(document);
@@ -908,6 +908,10 @@ impl PageVm {
LoadedFollowedLocationNavigation::ExternalDocument { final_url, .. } => final_url,
_ => unreachable!("only a Document response reaches navigation commit"),
};
// This path freezes the next Document's seed before retiring the old
// realm. Publish its current policy at the same pre-unload boundary used
// by browser-owned navigation commits.
self.vm_mut().publish_main_document_navigation_history()?;
let navigation_bootstrap_entry = navigation_history
.as_ref()
.map(|history| history.resolve(final_url))
@@ -654,3 +654,69 @@ for (const key of ["committed", "finished"]) {
},
);
}
#[test]
fn followed_navigation_preserves_the_outgoing_history_referrer_policy() {
run_page_vm_large_stack_async_test(
"followed-navigation-history-referrer-policy",
|| async move {
let (base, server) = spawn_path_response_http_server(vec![(
"/destination",
"HTTP/1.1 200 OK",
"<!doctype html><body>destination".to_owned(),
Duration::ZERO,
)])
.await;
let loader =
crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (page_vm, _resource_source, _owner_wake_rx) =
page_vm_with_bound_task_sources_and_owner_wake(
&loader,
Url::parse(&format!("{base}/source")).unwrap(),
);
let executor = page_vm.local_executor.clone();
executor
.run(async move {
let mut page_vm = page_vm;
let destination = format!("{base}/destination");
page_vm.vm_mut().eval(&format!(
r#"
history.pushState(null, '', '#state');
const m=document.createElement('meta'); m.name='referrer'; m.content='origin';
document.documentElement.append(m);
navigation.navigate({destination:?}, {{history:'push'}}); 'queued'
"#
))?;
let outcome = page_vm
.follow_pending_location_navigation_one_turn_async(
&mut None,
PageVmInitStage::Load,
)
.await?;
assert!(matches!(
outcome,
crate::runtime::PageVmFollowNavigationTurnOutcome::Completed
| crate::runtime::PageVmFollowNavigationTurnOutcome::PostParseLifecycle { .. }
));
assert_eq!(
page_vm
.vm_mut()
.eval("JSON.stringify(navigation.entries().map(e=>e.url))")?,
serde_json::json!([null, null, destination]).to_string(),
);
assert_eq!(
page_vm
.vm_mut()
.eval("String(navigation.activation.from.url)")?,
"null"
);
Ok::<_, anyhow::Error>(())
})
.await
.expect("followed navigation should preserve policy");
server
.await
.expect("navigation response server should finish");
},
);
}
@@ -523,6 +523,14 @@ impl ScriptVm {
.take_pending_location_navigation_of_kind(kind)
}
pub(crate) fn publish_main_document_navigation_history(&mut self) -> anyhow::Result<()> {
self.with_default_context_scope(|scope, _host_ptr| {
let window = scope.get_current_context().global(scope);
crate::context_bootstrap::publish_top_level_navigation_history(scope, window);
Ok(())
})
}
pub(crate) fn unload_main_document_for_navigation_commit(&mut self) -> anyhow::Result<()> {
self.with_default_context_scope(|scope, host_ptr| {
PageScriptHost::dispatch_main_document_unload_for_navigation_commit(scope, host_ptr);