From ec596ed626f64eb6c904185104f5243c642f867d Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 27 Sep 2026 20:17:01 +0800 Subject: [PATCH] fix(navigation): preserve history referrer policies at commit --- moli-protocol/src/domains/page/tests/mod.rs | 1 + .../page/tests/navigation_referrer_policy.rs | 229 ++++++++++++++++++ moli-renderer-v8/src/context_bootstrap.rs | 5 +- .../src/context_bootstrap/navigation_entry.rs | 5 +- .../context_bootstrap/navigation_serialize.rs | 2 +- .../context_host/main_document_lifecycle.rs | 4 + .../runtime/page_vm/followed_navigation.rs | 4 + .../page_vm/tests/history_traversal.rs | 66 +++++ .../src/script_vm/child_frame_runtime.rs | 8 + 9 files changed, 319 insertions(+), 5 deletions(-) create mode 100644 moli-protocol/src/domains/page/tests/navigation_referrer_policy.rs diff --git a/moli-protocol/src/domains/page/tests/mod.rs b/moli-protocol/src/domains/page/tests/mod.rs index 2f3befc8ee1..7eb923e2bd5 100644 --- a/moli-protocol/src/domains/page/tests/mod.rs +++ b/moli-protocol/src/domains/page/tests/mod.rs @@ -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; diff --git a/moli-protocol/src/domains/page/tests/navigation_referrer_policy.rs b/moli-protocol/src/domains/page/tests/navigation_referrer_policy.rs new file mode 100644 index 00000000000..cdd66b6b242 --- /dev/null +++ b/moli-protocol/src/domains/page/tests/navigation_referrer_policy.rs @@ -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| async move { + ( + [("Referrer-Policy", policy)], + axum::response::Html("source"), + ) + }, + ), + ) + .fallback(|| async { axum::response::Html("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(); +} diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 90fac962d66..de9916bac36 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -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; diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs index de440e1028f..a4d03a4f8bc 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs @@ -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; diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs index 176dbe080d5..593c6bcddf7 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs @@ -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>, ) { diff --git a/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs b/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs index 73582a66d75..04b412920d7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs @@ -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); diff --git a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs index 92bdc35e737..093db8097d8 100644 --- a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs +++ b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs @@ -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)) diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs b/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs index 2b7e9f29ceb..9fd94bb2820 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs @@ -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", + "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"); + }, + ); +} diff --git a/moli-renderer-v8/src/script_vm/child_frame_runtime.rs b/moli-renderer-v8/src/script_vm/child_frame_runtime.rs index d0aedc2d2df..10db75c39a1 100644 --- a/moli-renderer-v8/src/script_vm/child_frame_runtime.rs +++ b/moli-renderer-v8/src/script_vm/child_frame_runtime.rs @@ -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);