Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(fetch): unify redirect handling state

ldm005a1c73fa6d8
diff --git a/moli-fetch/src/blocking/cache.rs b/moli-fetch/src/blocking/cache.rs
index 40745ad34..c9afc8743 100644
--- a/moli-fetch/src/blocking/cache.rs
+++ b/moli-fetch/src/blocking/cache.rs
@@ -157,14 +157,14 @@ pub(crate) fn next_followed_redirect_url_from_parts(
// A browser may follow redirects itself, preserving the full URL list for
// CORS and Fetch Metadata while asking this transport for only one hop.
// Only automatically followed transport requests consume this layer's limit.
- let transport_redirect_count = if request.follow_redirects {
+ let transport_redirect_count = if request.follows_redirects() {
redirect_count
} else {
0
};
let next_url =
next_redirect_url_from_parts(final_url, status, headers, transport_redirect_count)?;
- if request.follow_redirects
+ if request.follows_redirects()
&& let Some(next_url) = next_url.as_ref()
{
ensure_http_network_transport_url(next_url)?;
@@ -229,7 +229,7 @@ mod tests {
Vec::new(),
moli_url::WebOrigin::from_url(&origin_url),
)
- .with_follow_redirects(false);
+ .with_single_hop();
let headers = vec![
("location".to_owned(), b"/next".to_vec()),
(
@@ -249,7 +249,9 @@ mod tests {
super::super::MAX_REDIRECTS,
)?;
assert_eq!(next, Some(current.join("/next")?));
- let automatic = request.clone().with_follow_redirects(true);
+ let automatic = request
+ .clone()
+ .with_redirect_mode(crate::RequestRedirectMode::Follow);
let error = next_followed_redirect_url_from_parts(
&automatic,
&current,
diff --git a/moli-fetch/src/blocking/collectors.rs b/moli-fetch/src/blocking/collectors.rs
index 94135278e..ddaad5036 100644
--- a/moli-fetch/src/blocking/collectors.rs
+++ b/moli-fetch/src/blocking/collectors.rs
@@ -13,6 +13,7 @@ use url::Url;
use crate::{
FetchCancelHandle, FetchConfig, NegotiatedHttpVersion, NetworkRequestExtraInfo, Request,
+ RequestRedirectHandling,
cancellation::ResponseProgress,
client_hints::{ClientHintResponseAction, ClientHintResponsePolicy},
headers::{decode_http_header_bytes, parse_http_response_header_line},
@@ -262,7 +263,7 @@ pub struct RawStreamingResponseCollector {
client_hint_restart_requested: bool,
cancel_handle: FetchCancelHandle,
response_progress: ResponseProgress,
- follow_redirects: bool,
+ redirect_handling: RequestRedirectHandling,
negotiated_http_version: Option<NegotiatedHttpVersion>,
network_request_extra_info: Option<NetworkRequestExtraInfo>,
}
@@ -686,7 +687,7 @@ impl RawStreamingResponseCollector {
client_hint_restart_requested: false,
cancel_handle,
response_progress,
- follow_redirects: true,
+ redirect_handling: RequestRedirectHandling::Follow,
negotiated_http_version: None,
network_request_extra_info: None,
}
@@ -712,7 +713,7 @@ impl RawStreamingResponseCollector {
self.response_bytes_received = 0;
self.declared_identity_body_length = None;
self.response_progress = response_progress;
- self.follow_redirects = true;
+ self.redirect_handling = RequestRedirectHandling::Follow;
self.cache_body_writer = None;
self.cache_plan = None;
self.started = false;
@@ -742,7 +743,7 @@ impl RawStreamingResponseCollector {
cache_plan: Option<StreamingCachePlan>,
defer_not_modified_start: bool,
response_progress: ResponseProgress,
- follow_redirects: bool,
+ redirect_handling: RequestRedirectHandling,
) {
self.begin_request(
max_response_size,
@@ -756,7 +757,7 @@ impl RawStreamingResponseCollector {
self.network_request_extra_info = network_request_extra_info;
self.cache_plan = cache_plan;
self.defer_not_modified_start = defer_not_modified_start;
- self.follow_redirects = follow_redirects;
+ self.redirect_handling = redirect_handling;
}
pub(crate) fn status_text(&self) -> Option<&str> {
@@ -924,7 +925,7 @@ impl RawStreamingResponseCollector {
let Some(current_url) = self.current_url.clone() else {
return;
};
- if self.follow_redirects && is_redirect_response {
+ if self.redirect_handling.follows_redirects() && is_redirect_response {
return;
}
if self.defer_not_modified_start && self.status == 304 {
diff --git a/moli-fetch/src/client.rs b/moli-fetch/src/client.rs
index 6324f904f..a88cb4524 100644
--- a/moli-fetch/src/client.rs
+++ b/moli-fetch/src/client.rs
@@ -116,7 +116,7 @@ impl FetchClientHandle {
request: Request,
cancel_handle: FetchCancelHandle,
) -> Result<Response> {
- if request.auth_requires_buffered_transport() || !request.follow_redirects {
+ if request.auth_requires_buffered_transport() || !request.follows_redirects() {
// Auth retries still need the buffered libcurl path so
// intermediate 401/407 challenge bodies are not exposed as final
// streaming responses. Manual redirect callers also need the
diff --git a/moli-fetch/src/lib.rs b/moli-fetch/src/lib.rs
index c52b51d23..5060b1195 100644
--- a/moli-fetch/src/lib.rs
+++ b/moli-fetch/src/lib.rs
@@ -77,8 +77,8 @@ pub use referrer_policy::{
pub use request::{
BrowserNavigationRequestKind, BrowserRequestMetadata, FetchPriorityHint, Request, RequestAuth,
RequestAuthScheme, RequestAuthTarget, RequestCacheMode, RequestCredentialsMode,
- RequestHeaderOverride, RequestMode, RequestPriorityHints, RequestRedirectMode,
- RequestResourceType, ResourceLoadPriority, ScriptFetchRequestMetadata,
+ RequestHeaderOverride, RequestMode, RequestPriorityHints, RequestRedirectHandling,
+ RequestRedirectMode, RequestResourceType, ResourceLoadPriority, ScriptFetchRequestMetadata,
ScriptFetchSchedulerPriority, SubresourceRequestMetadata,
};
pub use request_policy::{is_bad_port, should_request_be_blocked_due_to_bad_port};
diff --git a/moli-fetch/src/request.rs b/moli-fetch/src/request.rs
index 22a6b30e4..f50cd5f21 100644
--- a/moli-fetch/src/request.rs
+++ b/moli-fetch/src/request.rs
@@ -43,10 +43,9 @@ pub struct Request {
context: RequestContext,
referrer_url: Option<Url>,
pub use_page_network_policy: bool,
- pub follow_redirects: bool,
pub request_mode: RequestMode,
use_cors_preflight: bool,
- pub redirect_mode: RequestRedirectMode,
+ redirect_handling: RequestRedirectHandling,
pub credentials_mode: RequestCredentialsMode,
pub(crate) redirect_chain: Vec<RedirectInfo>,
network_partition_key: Option<String>,
@@ -343,10 +342,50 @@ pub enum RequestRedirectMode {
Manual,
}
-impl RequestRedirectMode {
+/// The valid combinations of Fetch redirect policy and redirect ownership.
+/// Keeping them in one value prevents manual/error requests from accidentally
+/// enabling automatic transport redirects.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RequestRedirectHandling {
+ /// The fetch runtime follows redirects.
+ Follow,
+ /// Return each hop to the caller, which follows under Fetch's follow policy.
+ FollowByCaller,
+ /// Return the redirect response under Fetch's manual policy.
+ Manual,
+ /// Return the hop for the browser to reject under Fetch's error policy.
+ Error,
+}
+
+impl RequestRedirectHandling {
+ pub fn redirect_mode(self) -> RequestRedirectMode {
+ match self {
+ Self::Follow | Self::FollowByCaller => RequestRedirectMode::Follow,
+ Self::Manual => RequestRedirectMode::Manual,
+ Self::Error => RequestRedirectMode::Error,
+ }
+ }
+
pub fn follows_redirects(self) -> bool {
matches!(self, Self::Follow)
}
+
+ fn single_hop(self) -> Self {
+ match self {
+ Self::Follow => Self::FollowByCaller,
+ other => other,
+ }
+ }
+}
+
+impl From<RequestRedirectMode> for RequestRedirectHandling {
+ fn from(mode: RequestRedirectMode) -> Self {
+ match mode {
+ RequestRedirectMode::Follow => Self::Follow,
+ RequestRedirectMode::Manual => Self::Manual,
+ RequestRedirectMode::Error => Self::Error,
+ }
+ }
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -443,10 +482,9 @@ impl Request {
context: RequestContext::Http,
referrer_url: None,
use_page_network_policy: false,
- follow_redirects: true,
request_mode: RequestMode::Navigate,
use_cors_preflight: false,
- redirect_mode: RequestRedirectMode::Follow,
+ redirect_handling: RequestRedirectHandling::Follow,
credentials_mode: RequestCredentialsMode::Include,
redirect_chain: Vec::new(),
network_partition_key: None,
@@ -477,10 +515,9 @@ impl Request {
context: RequestContext::Http,
referrer_url: None,
use_page_network_policy: false,
- follow_redirects: true,
request_mode: RequestMode::Navigate,
use_cors_preflight: false,
- redirect_mode: RequestRedirectMode::Follow,
+ redirect_handling: RequestRedirectHandling::Follow,
credentials_mode: RequestCredentialsMode::Include,
redirect_chain: Vec::new(),
network_partition_key: None,
@@ -544,10 +581,9 @@ impl Request {
context: RequestContext::Http,
referrer_url: None,
use_page_network_policy: false,
- follow_redirects: true,
request_mode: RequestMode::Cors,
use_cors_preflight: false,
- redirect_mode: RequestRedirectMode::Follow,
+ redirect_handling: RequestRedirectHandling::Follow,
credentials_mode: RequestCredentialsMode::Include,
redirect_chain: Vec::new(),
network_partition_key: None,
@@ -804,14 +840,31 @@ impl Request {
self.network_observation_recorder.as_ref()
}
- pub fn with_follow_redirects(mut self, follow_redirects: bool) -> Self {
- self.follow_redirects = follow_redirects;
+ pub fn redirect_handling(&self) -> RequestRedirectHandling {
+ self.redirect_handling
+ }
+
+ pub fn redirect_mode(&self) -> RequestRedirectMode {
+ self.redirect_handling.redirect_mode()
+ }
+
+ pub fn follows_redirects(&self) -> bool {
+ self.redirect_handling.follows_redirects()
+ }
+
+ pub fn with_redirect_handling(mut self, handling: RequestRedirectHandling) -> Self {
+ self.redirect_handling = handling;
+ self
+ }
+
+ /// Stops at this hop while preserving the browser's redirect policy.
+ pub fn with_single_hop(mut self) -> Self {
+ self.redirect_handling = self.redirect_handling.single_hop();
self
}
pub fn with_redirect_mode(mut self, redirect_mode: RequestRedirectMode) -> Self {
- self.redirect_mode = redirect_mode;
- self.follow_redirects = redirect_mode.follows_redirects();
+ self.redirect_handling = redirect_mode.into();
self
}
diff --git a/moli-fetch/src/runtime.rs b/moli-fetch/src/runtime.rs
index d2150912a..b18a82ba1 100644
--- a/moli-fetch/src/runtime.rs
+++ b/moli-fetch/src/runtime.rs
@@ -1349,7 +1349,7 @@ impl RuntimeOwner {
cache_plan,
stale_cached_lookup.is_some(),
job.response_progress.clone(),
- job.request.follow_redirects,
+ job.request.redirect_handling(),
);
collector.set_client_hint_response_policy(prepared_request.response_policy);
@@ -1580,7 +1580,7 @@ impl RuntimeOwner {
Err(error) => return Err((job.response_tx, error)),
};
if let Some(next_url) = next_url
- && job.request.follow_redirects
+ && job.request.follows_redirects()
{
job.request
.update_referrer_for_redirect(&response.final_url, &response.headers);
@@ -1863,7 +1863,7 @@ impl RuntimeOwner {
}
};
if let Some(next_url) = next_url
- && job.request.follow_redirects
+ && job.request.follows_redirects()
{
let cache_body_writer = easy
.get_mut()
@@ -2259,7 +2259,7 @@ impl RuntimeOwner {
}
};
if let Some(next_url) = next_url {
- if job.request.follow_redirects {
+ if job.request.follows_redirects() {
let cache_body_writer = easy
.get_mut()
.raw_streaming_mut()
@@ -2422,7 +2422,7 @@ impl RuntimeOwner {
Err(error) => return Err((Box::new(job), error)),
};
if let Some(next_url) = next_url
- && job.request.follow_redirects
+ && job.request.follows_redirects()
{
job.request
.update_referrer_for_redirect(&final_url, &cached.headers);
@@ -2486,7 +2486,7 @@ impl RuntimeOwner {
Err(error) => return Err((Box::new(job), error)),
};
if let Some(next_url) = next_url
- && job.request.follow_redirects
+ && job.request.follows_redirects()
{
job.request
.update_referrer_for_redirect(&final_url, &cached.headers);
diff --git a/moli-fetch/src/tests/header_bytes.rs b/moli-fetch/src/tests/header_bytes.rs
index 8f904ad7d..a4a4fe22e 100644
--- a/moli-fetch/src/tests/header_bytes.rs
+++ b/moli-fetch/src/tests/header_bytes.rs
@@ -39,10 +39,7 @@ async fn fetch_in_mode(
mode: &str,
) -> Result<(ResponseHead, Vec<u8>)> {
let (head, body) = match mode {
- "buffered" => client
- .fetch(request.with_follow_redirects(false))
- .await?
- .into_body(),
+ "buffered" => client.fetch(request.with_single_hop()).await?.into_body(),
"html" => client.fetch_html_stream(request).await?.into_body(),
"raw" => client
.fetch_raw_stream_with_cancel(request, FetchCancelHandle::new())
diff --git a/moli-fetch/src/tests/header_eof.rs b/moli-fetch/src/tests/header_eof.rs
index 20e6e1bfc..00c22b96a 100644
--- a/moli-fetch/src/tests/header_eof.rs
+++ b/moli-fetch/src/tests/header_eof.rs
@@ -29,10 +29,7 @@ async fn fetch_in_mode(
mode: &str,
) -> Result<(ResponseHead, Vec<u8>)> {
let (head, body) = match mode {
- "buffered" => client
- .fetch(request.with_follow_redirects(false))
- .await?
- .into_body(),
+ "buffered" => client.fetch(request.with_single_hop()).await?.into_body(),
"html" => client.fetch_html_stream(request).await?.into_body(),
"raw" => client
.fetch_raw_stream_with_cancel(request, FetchCancelHandle::new())
@@ -157,12 +154,8 @@ async fn header_eof_keeps_manual_raw_redirects_unfollowed() -> Result<()> {
}
let server = tokio::spawn(serve_responses(listener, vec![response]));
let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());
- let (head, body) = fetch_in_mode(
- &client,
- Request::get(&url)?.with_follow_redirects(false),
- "raw",
- )
- .await?;
+ let (head, body) =
+ fetch_in_mode(&client, Request::get(&url)?.with_single_hop(), "raw").await?;
assert_eq!(head.status, 302);
assert_eq!(head.final_url.path(), "/start");
assert!(!head.redirected);
diff --git a/moli-fetch/src/tests/mod.rs b/moli-fetch/src/tests/mod.rs
index b9a706ade..a8cb678d1 100644
--- a/moli-fetch/src/tests/mod.rs
+++ b/moli-fetch/src/tests/mod.rs
@@ -34,10 +34,10 @@ use crate::{
FetchClientHandle, FetchConfig, FetchPriorityHint, FetchRuntimeJoinStatus,
NegotiatedHttpVersion, NetworkFetchFailureContext, RawResponse, Request, RequestAuth,
RequestAuthScheme, RequestAuthTarget, RequestCacheMode, RequestCredentialsMode, RequestMode,
- RequestRedirectMode, RequestResourceType, Response, ResponseBody, ResponseHead,
- ScriptFetchRequestMetadata, ScriptFetchSchedulerPriority, StreamingResponseCollector,
- SubresourceRequestMetadata, WebBotAuthProfile, WebBotAuthSigner, http_cache_stats,
- runtime::FetchRuntimeOwner,
+ RequestRedirectHandling, RequestRedirectMode, RequestResourceType, Response, ResponseBody,
+ ResponseHead, ScriptFetchRequestMetadata, ScriptFetchSchedulerPriority,
+ StreamingResponseCollector, SubresourceRequestMetadata, WebBotAuthProfile, WebBotAuthSigner,
+ http_cache_stats, runtime::FetchRuntimeOwner,
};
use self::support::{
@@ -200,10 +200,7 @@ async fn http_status_messages_survive_buffered_and_streamed_transport() -> Resul
for mode in ["buffered", "html", "raw"] {
let request = Request::get(&server.url())?;
let (head, body) = match mode {
- "buffered" => client
- .fetch(request.with_follow_redirects(false))
- .await?
- .into_body(),
+ "buffered" => client.fetch(request.with_single_hop()).await?.into_body(),
"html" => client.fetch_html_stream(request).await?.into_body(),
_ => client
.fetch_raw_stream_with_cancel(request, FetchCancelHandle::new())
@@ -262,13 +259,20 @@ async fn http_status_messages_survive_disk_cache_across_streaming_modes() -> Res
}
#[test]
-fn request_redirect_mode_controls_follow_flag() {
- let request = Request::new("GET", "https://example.test/start", None, Vec::new())
- .unwrap()
- .with_redirect_mode(RequestRedirectMode::Manual);
+fn single_hop_requests_preserve_redirect_mode() {
+ for mode in [
+ RequestRedirectMode::Follow,
+ RequestRedirectMode::Manual,
+ RequestRedirectMode::Error,
+ ] {
+ let request = Request::get("https://example.test/start")
+ .unwrap()
+ .with_redirect_mode(mode);
+ let hop = request.with_single_hop();
- assert_eq!(request.redirect_mode, RequestRedirectMode::Manual);
- assert!(!request.follow_redirects);
+ assert_eq!(hop.redirect_mode(), mode);
+ assert!(!hop.follows_redirects());
+ }
}
#[tokio::test]
@@ -281,7 +285,7 @@ async fn http_transport_rejects_file_urls_in_every_response_mode() -> Result<()>
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
let buffered_error = client
- .fetch(Request::get(FILE_URL)?.with_follow_redirects(false))
+ .fetch(Request::get(FILE_URL)?.with_single_hop())
.await
.expect_err("buffered transport must reject file URL");
assert!(format!("{buffered_error:#}").contains(EXPECTED));
@@ -1308,47 +1312,62 @@ async fn manual_http_redirect_to_file_remains_observable_without_being_followed(
}
#[tokio::test]
-async fn fetch_raw_stream_manual_redirect_returns_redirect_response() -> Result<()> {
- let server = ScriptedHttpServer::spawn(vec![
- ScriptedResponse::status(302, "Found")
- .with_header("Location", "/final.bin")
- .with_body("redirect-body"),
- ScriptedResponse::ok("final-body").with_header("Content-Type", "application/octet-stream"),
- ]);
- let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());
- let mut response = client
- .fetch_raw_stream_with_cancel(
- Request::get(&server.url_path("/redirect.bin"))?
- .with_redirect_mode(RequestRedirectMode::Manual),
- FetchCancelHandle::new(),
- )
- .await?;
+async fn fetch_raw_stream_obeys_redirect_handling_for_each_hop() -> Result<()> {
+ for handling in [
+ RequestRedirectHandling::Follow,
+ RequestRedirectHandling::FollowByCaller,
+ RequestRedirectHandling::Manual,
+ RequestRedirectHandling::Error,
+ ] {
+ let server = ScriptedHttpServer::spawn(vec![
+ ScriptedResponse::status(302, "Found")
+ .with_header("Location", "/final.bin")
+ .with_body("redirect-body"),
+ ScriptedResponse::ok("final-body")
+ .with_header("Content-Type", "application/octet-stream"),
+ ]);
+ let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());
+ let mut response = client
+ .fetch_raw_stream_with_cancel(
+ Request::get(&server.url_path("/redirect.bin"))?.with_redirect_handling(handling),
+ FetchCancelHandle::new(),
+ )
+ .await?;
- assert_eq!(response.status, 302);
- assert_eq!(
- response.final_url.as_str(),
- server.url_path("/redirect.bin")
- );
- assert!(!response.redirected);
- assert!(response.redirect_chain.is_empty());
- assert!(
- response.headers.iter().any(|(name, value)| {
- name.eq_ignore_ascii_case("location") && value == b"/final.bin"
- })
- );
+ if handling == RequestRedirectHandling::Follow {
+ assert_eq!(response.status, 200);
+ assert_eq!(response.final_url.as_str(), server.url_path("/final.bin"));
+ assert!(response.redirected);
+ assert_eq!(response.redirect_chain.len(), 1);
+ } else {
+ // This is the raw transport: manual/error policy decisions and
+ // caller-owned redirect loops consume the returned redirect head.
+ assert_eq!(response.status, 302);
+ assert_eq!(
+ response.final_url.as_str(),
+ server.url_path("/redirect.bin")
+ );
+ assert!(!response.redirected);
+ assert!(response.redirect_chain.is_empty());
+ assert!(response.headers.iter().any(|(name, value)| {
+ name.eq_ignore_ascii_case("location") && value == b"/final.bin"
+ }));
+ }
- let mut body = Vec::new();
- while let Some(chunk) = response.next_chunk().await {
- body.extend_from_slice(&chunk);
+ let mut body = Vec::new();
+ while let Some(chunk) = response.next_chunk().await {
+ body.extend_from_slice(&chunk);
+ }
+ response.finish().await?;
+ if handling == RequestRedirectHandling::Follow {
+ assert_eq!(body, b"final-body");
+ assert_eq!(server.requests().len(), 2);
+ } else {
+ assert!(body.is_empty());
+ assert_eq!(server.requests().len(), 1);
+ }
+ server.shutdown();
}
- response.finish().await?;
- assert!(body.is_empty());
- assert_eq!(
- server.requests().len(),
- 1,
- "manual raw redirect must not follow to the final URL"
- );
- server.shutdown();
Ok(())
}
@@ -2339,7 +2358,7 @@ fn fetch_redirect_reselects_direct_or_proxy_endpoint_per_hop() {
&config,
Request::get(direct_url.as_str())
.unwrap()
- .with_follow_redirects(true),
+ .with_redirect_mode(crate::RequestRedirectMode::Follow),
)
.expect("redirect should switch from direct origin DNS to proxy endpoint DNS");
@@ -2540,10 +2559,7 @@ async fn direct_localhost_uses_shared_dns_across_all_curl_transports() -> Result
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
let buffered = client
- .fetch(
- Request::get(&format!("http://localhost:{port}/buffered"))?
- .with_follow_redirects(false),
- )
+ .fetch(Request::get(&format!("http://localhost:{port}/buffered"))?.with_single_hop())
.await?;
assert_eq!(buffered.body_text(), "buffered-dns");
@@ -5835,7 +5851,7 @@ fn fetch_runtime_retries_buffered_get_over_http11_after_http2_protocol_error() -
let mut config = FetchConfig::default();
config.set_tls_verify_host(false);
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
- let request = Request::get(&server.url())?.with_follow_redirects(false);
+ let request = Request::get(&server.url())?.with_single_hop();
let response = fetch_response_for_test(&client, request)?;
@@ -5925,7 +5941,7 @@ fn fetch_runtime_retries_buffered_empty_http_navigation_over_https() -> Result<(
config.set_tls_verify_host(false);
config.set_http_host_resolve(vec![server.resolve_entry()]);
let client = FetchClient::new(&config, new_shared_browser_cookie_store());
- let request = Request::get(&server.url())?.with_follow_redirects(false);
+ let request = Request::get(&server.url())?.with_single_hop();
let response = fetch_response_for_test(&client, request)?;
diff --git a/moli-fetch/src/tests/range_encoding.rs b/moli-fetch/src/tests/range_encoding.rs
index 880d35d5c..f0c8eb79e 100644
--- a/moli-fetch/src/tests/range_encoding.rs
+++ b/moli-fetch/src/tests/range_encoding.rs
@@ -39,10 +39,7 @@ async fn fetch_in_mode(
mode: &str,
) -> Result<(ResponseHead, Vec<u8>)> {
let (head, body) = match mode {
- "buffered" => client
- .fetch(request.with_follow_redirects(false))
- .await?
- .into_body(),
+ "buffered" => client.fetch(request.with_single_hop()).await?.into_body(),
"html" => client.fetch_html_stream(request).await?.into_body(),
"raw" => client
.fetch_raw_stream_with_cancel(request, FetchCancelHandle::new())
diff --git a/moli-fetch/src/tests/referrer_redirects.rs b/moli-fetch/src/tests/referrer_redirects.rs
index b2d83aaf5..f49fb094a 100644
--- a/moli-fetch/src/tests/referrer_redirects.rs
+++ b/moli-fetch/src/tests/referrer_redirects.rs
@@ -258,7 +258,7 @@ async fn manual_redirects_keep_the_current_response_and_referrer() -> Result<()>
referrer_policy: Some("unsafe-url".to_owned()),
..Default::default()
})
- .with_follow_redirects(false);
+ .with_single_hop();
let client = FetchClient::new(&FetchConfig::default(), new_shared_browser_cookie_store());
// Manual responses use the buffered or raw API. Raw streaming intentionally
// returns only the redirect head so its owner need not wait for the body.
diff --git a/moli-fetch/src/tests/response_progress.rs b/moli-fetch/src/tests/response_progress.rs
index d27984ff2..436a7c245 100644
--- a/moli-fetch/src/tests/response_progress.rs
+++ b/moli-fetch/src/tests/response_progress.rs
@@ -15,7 +15,7 @@ async fn buffered_response_commits_completion_before_delivery() -> Result<()> {
for (status, body) in [(200, "body"), (204, ""), (302, "redirect body")] {
let parent = FetchCancelHandle::new();
let child = parent.child_for_subrequest();
- let request = Request::get(&server.url())?.with_follow_redirects(false);
+ let request = Request::get(&server.url())?.with_single_hop();
let response = if use_callback {
let (tx, rx) = oneshot::channel();
let observer = child.clone();
@@ -72,7 +72,7 @@ async fn buffered_redirect_body_wait_is_cancellable_without_committing_completio
let cancel = FetchCancelHandle::new();
let (tx, mut rx) = oneshot::channel();
client.fetch_with_cancel_callback(
- Request::get(&url)?.with_follow_redirects(false),
+ Request::get(&url)?.with_single_hop(),
cancel.clone(),
move |result| {
let _ = tx.send(result);
diff --git a/moli-renderer-v8/src/content_security_policy.rs b/moli-renderer-v8/src/content_security_policy.rs
index fec0df178..79cbad7c5 100644
--- a/moli-renderer-v8/src/content_security_policy.rs
+++ b/moli-renderer-v8/src/content_security_policy.rs
@@ -3896,7 +3896,7 @@ mod tests {
requests[0].credentials_mode,
RequestCredentialsMode::SameOrigin
);
- assert_eq!(requests[0].redirect_mode, RequestRedirectMode::Error);
+ assert_eq!(requests[0].redirect_mode(), RequestRedirectMode::Error);
}
#[test]
diff --git a/moli-renderer-v8/src/network/backend/memory_cache.rs b/moli-renderer-v8/src/network/backend/memory_cache.rs
index 0ded03479..e5da707b7 100644
--- a/moli-renderer-v8/src/network/backend/memory_cache.rs
+++ b/moli-renderer-v8/src/network/backend/memory_cache.rs
@@ -586,7 +586,7 @@ pub(in crate::network) fn script_text_request_is_memory_cacheable(request: &Requ
&& request.method.eq_ignore_ascii_case("GET")
&& request.body.is_none()
&& request.auth().is_none()
- && request.follow_redirects
+ && request.follows_redirects()
}
pub(in crate::network) fn script_text_cache_key(request: &Request) -> ScriptTextCacheKey {
@@ -668,7 +668,7 @@ fn raw_subresource_request_is_memory_cacheable(request: &Request) -> bool {
&& request.method.eq_ignore_ascii_case("GET")
&& request.body.is_none()
&& request.auth().is_none()
- && request.follow_redirects
+ && request.follows_redirects()
&& raw_subresource_memory_cacheable_headers(request)
}
diff --git a/moli-renderer-v8/src/network/request_client.rs b/moli-renderer-v8/src/network/request_client.rs
index 38044b467..e5fc6d993 100644
--- a/moli-renderer-v8/src/network/request_client.rs
+++ b/moli-renderer-v8/src/network/request_client.rs
@@ -273,7 +273,7 @@ impl ResourceRequestClient {
cancel_handle: FetchCancelHandle,
) -> Result<NetworkFetchResult<Response>> {
let request = self.apply_network_policy(request)?;
- if request.auth_requires_buffered_transport() || !request.follow_redirects {
+ if request.auth_requires_buffered_transport() || !request.follows_redirects() {
return self
.resource_runtime
.client()
@@ -649,7 +649,7 @@ impl ResourceRequestClient {
request: Request,
cancel_handle: FetchCancelHandle,
) -> Result<Response> {
- if request.auth_requires_buffered_transport() || !request.follow_redirects {
+ if request.auth_requires_buffered_transport() || !request.follows_redirects() {
// Challenge-response schemes still need libcurl's buffered auth
// retry behavior until the streaming collector models
// intermediate authentication challenges explicitly. Manual
@@ -934,7 +934,7 @@ impl ResourceRequestClient {
cancel_handle: Option<FetchCancelHandle>,
) -> Result<Response> {
let request = self.apply_network_policy(request)?;
- if request.auth_requires_buffered_transport() || !request.follow_redirects {
+ if request.auth_requires_buffered_transport() || !request.follows_redirects() {
// Digest auth retries are still completed inside libcurl on the
// buffered path. Keep auth requests there until the streaming
// collector can distinguish intermediate auth challenges from
diff --git a/moli-renderer-v8/src/network_host/async_fetch.rs b/moli-renderer-v8/src/network_host/async_fetch.rs
index b60a982be..1f835a775 100644
--- a/moli-renderer-v8/src/network_host/async_fetch.rs
+++ b/moli-renderer-v8/src/network_host/async_fetch.rs
@@ -149,7 +149,7 @@ impl ManualCorsRedirectState {
}
fn hop_request(&self) -> Request {
- self.request.clone().with_follow_redirects(false)
+ self.request.clone().with_single_hop()
}
async fn run_current_hop_preflight(
@@ -175,7 +175,7 @@ impl ManualCorsRedirectState {
) -> Result<ManualCorsRedirectTransition, String> {
// Keep redirect-mode error precedence aligned with Fetch: an error-mode
// redirect is rejected before the redirect response is CORS-checked.
- if self.request.redirect_mode == RequestRedirectMode::Error {
+ if self.request.redirect_mode() == RequestRedirectMode::Error {
if next_redirect_url(&head.final_url, head.status, &head.headers, 0)?.is_some() {
return Err(redirect_mode_error_message(&head.final_url));
}
@@ -194,13 +194,13 @@ impl ManualCorsRedirectState {
return Ok(ManualCorsRedirectTransition::FinalResponse);
};
- if self.request.redirect_mode == RequestRedirectMode::Manual {
+ if self.request.redirect_mode() == RequestRedirectMode::Manual {
return Ok(ManualCorsRedirectTransition::ManualResponse {
response_url: head.final_url,
});
}
- match self.request.redirect_mode {
+ match self.request.redirect_mode() {
RequestRedirectMode::Follow => {}
RequestRedirectMode::Error | RequestRedirectMode::Manual => {
unreachable!("redirect modes were handled before the follow transition")
@@ -241,7 +241,7 @@ async fn fetch_browser_subresource_with_manual_preflight_redirects(
preflight_observer: Option<&CorsPreflightNetworkObserver>,
) -> Result<NetworkFetchResult<Response>, String> {
if !request.auth_requires_buffered_transport()
- && request.redirect_mode == RequestRedirectMode::Follow
+ && request.redirect_mode() == RequestRedirectMode::Follow
{
// Materialize only the accepted final response. Waiting for buffered
// intermediate bodies here lets an unfinished redirect block the next
@@ -417,7 +417,7 @@ async fn fetch_browser_subresource_raw_stream_with_preflight_headers_and_observe
)
.await?;
let cancel_handle = cancel_handle.unwrap_or_default();
- let redirect_mode = request.redirect_mode;
+ let redirect_mode = request.redirect_mode();
let result = loader
.fetch_raw_stream_with_cancel_and_network_metadata(
request,
@@ -558,9 +558,10 @@ pub(crate) fn spawn_async_subresource_fetch(
| BrowserRequestMetadata::StyleModule
| BrowserRequestMetadata::Xhr,
)
- ) && request.follow_redirects
+ ) && request.follows_redirects()
&& request.request_mode != RequestMode::NoCors;
- let can_collect_image_body = parkable_image_manager.is_some() && request.follow_redirects;
+ let can_collect_image_body =
+ parkable_image_manager.is_some() && request.follows_redirects();
if moli_trace::cdp_runtime_trace_enabled() {
tracing::info!(
target: "moli_cdp_nav_timing",
@@ -568,8 +569,7 @@ pub(crate) fn spawn_async_subresource_fetch(
method = %request.method,
browser_request_metadata = ?request.browser_request_metadata(),
request_mode = ?request.request_mode,
- redirect_mode = ?request.redirect_mode,
- follow_redirects = request.follow_redirects,
+ redirect_handling = ?request.redirect_handling(),
auth_requires_buffered_transport,
requires_manual_preflight_redirects,
can_stream_subresource_body,
@@ -821,7 +821,7 @@ async fn fetch_once_with_network_metadata(
request: Request,
cancel_handle: Option<FetchCancelHandle>,
) -> Result<NetworkFetchResult<Response>, String> {
- let redirect_mode = request.redirect_mode;
+ let redirect_mode = request.redirect_mode();
let result =
fetch_once_with_network_metadata_unvalidated(loader, request, cancel_handle).await?;
let (response, request_observation) = result.into_parts();
@@ -996,6 +996,64 @@ mod tests {
Ok(())
}
+ #[test]
+ fn single_hop_cors_redirects_preserve_follow_manual_and_error_policy() -> Result<()> {
+ let current_url = Url::parse("https://origin.test/start")?;
+ let next_url = current_url.join("/final")?;
+ for mode in [
+ RequestRedirectMode::Follow,
+ RequestRedirectMode::Manual,
+ RequestRedirectMode::Error,
+ ] {
+ let request = Request::get(current_url.as_str())?
+ .with_request_origin(moli_url::WebOrigin::from_url(&current_url))
+ .with_redirect_mode(mode);
+ let mut redirects = ManualCorsRedirectState::new(request, Vec::new());
+ let hop = redirects.hop_request();
+ assert!(!hop.follows_redirects());
+ assert_eq!(hop.redirect_mode(), mode);
+
+ let transition = redirects.advance(
+ ResponseHead {
+ final_url: current_url.clone(),
+ status: 307,
+ status_text: Some("Temporary Redirect".to_owned()),
+ headers: vec![("location".to_owned(), b"/final".to_vec())],
+ request_cookie_report: None,
+ cookie_set_reports: Vec::new(),
+ redirected: false,
+ redirect_chain: Vec::new(),
+ from_cache: false,
+ negotiated_http_version: None,
+ },
+ false,
+ );
+ match mode {
+ RequestRedirectMode::Follow => {
+ assert_eq!(
+ transition.map_err(anyhow::Error::msg)?,
+ ManualCorsRedirectTransition::FollowedRedirect
+ );
+ assert_eq!(redirects.request().url, next_url);
+ }
+ RequestRedirectMode::Manual => {
+ assert_eq!(
+ transition.map_err(anyhow::Error::msg)?,
+ ManualCorsRedirectTransition::ManualResponse {
+ response_url: current_url.clone(),
+ }
+ );
+ assert_eq!(redirects.request().url, current_url);
+ }
+ RequestRedirectMode::Error => {
+ assert!(transition.unwrap_err().contains("redirect mode error"));
+ assert_eq!(redirects.request().url, current_url);
+ }
+ }
+ }
+ Ok(())
+ }
+
#[tokio::test(flavor = "multi_thread")]
async fn cors_preflight_uses_streaming_head_response_without_a_referrer_url() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
diff --git a/moli-renderer-v8/src/network_host/csp_reports.rs b/moli-renderer-v8/src/network_host/csp_reports.rs
index 75d71b484..3224e31a2 100644
--- a/moli-renderer-v8/src/network_host/csp_reports.rs
+++ b/moli-renderer-v8/src/network_host/csp_reports.rs
@@ -311,7 +311,7 @@ fn dispatch_service_worker_content_security_policy_report(
ServiceWorkerRequestDestination::Report,
request.request_mode,
request.credentials_mode,
- request.redirect_mode,
+ request.redirect_mode(),
request.priority_hints.fetch_priority,
service_worker_fetch_request_metadata(&request),
),
diff --git a/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs b/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs
index 800f7a6d9..4090f6cba 100644
--- a/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs
+++ b/moli-renderer-v8/src/runtime/browser_context_runtime/service_workers.rs
@@ -196,7 +196,7 @@ impl RendererBrowserContextRuntime {
let (direct_completion_tx, main_resource_completion_rx) = tokio::sync::oneshot::channel();
let redirect_mode =
- main_resource_fetch_event_redirect_mode(destination, request.redirect_mode);
+ main_resource_fetch_event_redirect_mode(destination, request.redirect_mode());
let dispatch = ServiceWorkerFetchDispatch {
internal_id: 0,
request: ServiceWorkerFetchRequest {
@@ -280,7 +280,7 @@ impl RendererBrowserContextRuntime {
destination,
request_mode: request.request_mode,
credentials_mode: request.credentials_mode,
- redirect_mode: request.redirect_mode,
+ redirect_mode: request.redirect_mode(),
priority: request.priority_hints.fetch_priority,
is_reload: false,
metadata: service_worker_fetch_request_metadata(request),
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs
index 5dd2df733..234d819ba 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs
@@ -460,7 +460,7 @@ impl ScriptVm {
crate::service_worker_runtime::ServiceWorkerRequestDestination::Report,
request.request_mode,
request.credentials_mode,
- request.redirect_mode,
+ request.redirect_mode(),
request.priority_hints.fetch_priority,
crate::service_worker_runtime::service_worker_fetch_request_metadata(&request),
),
diff --git a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs
index 80bb6dff3..ddfcb904d 100644
--- a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs
+++ b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs
@@ -60,7 +60,7 @@ fn fetch_request_for_job(job: &ServiceWorkerFetchJob) -> ServiceWorkerFetchReque
destination: job.destination,
request_mode: job.request.request_mode,
credentials_mode: job.request.credentials_mode,
- redirect_mode: job.request.redirect_mode,
+ redirect_mode: job.request.redirect_mode(),
priority: job.request.priority_hints.fetch_priority,
is_reload: job.is_reload,
metadata: job.metadata.clone(),
@@ -208,7 +208,7 @@ impl ServiceWorkerRuntimeService {
destination,
request_mode: request.request_mode,
credentials_mode: request.credentials_mode,
- redirect_mode: request.redirect_mode,
+ redirect_mode: request.redirect_mode(),
priority: request.priority_hints.fetch_priority,
is_reload: false,
metadata: service_worker_fetch_request_metadata(request),
@@ -541,10 +541,10 @@ impl ServiceWorkerRuntimeService {
}
}
if is_redirect_status(response.status)
- && job.request.redirect_mode != moli_fetch::RequestRedirectMode::Manual
+ && job.request.redirect_mode() != moli_fetch::RequestRedirectMode::Manual
{
match service_worker_redirect_target(&job, &response) {
- Ok(Some(next_url)) => match job.request.redirect_mode {
+ Ok(Some(next_url)) => match job.request.redirect_mode() {
moli_fetch::RequestRedirectMode::Error => {
self.complete_fetch_with_network_failure(
job,
@@ -859,7 +859,7 @@ fn service_worker_fetch_response_rejection(
}
}
"opaqueredirect"
- if job.request.redirect_mode != moli_fetch::RequestRedirectMode::Manual =>
+ if job.request.redirect_mode() != moli_fetch::RequestRedirectMode::Manual =>
{
return Some(
"FetchEvent.respondWith rejected an opaqueredirect Response for a request whose redirect mode is not manual"
@@ -868,7 +868,8 @@ fn service_worker_fetch_response_rejection(
}
_ => {}
}
- if response.redirected && job.request.redirect_mode != moli_fetch::RequestRedirectMode::Follow {
+ if response.redirected && job.request.redirect_mode() != moli_fetch::RequestRedirectMode::Follow
+ {
return Some(
"FetchEvent.respondWith rejected a redirected Response for a request whose redirect mode is not follow"
.to_owned(),
diff --git a/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs b/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs
index 80f2622f6..6af2d4c78 100644
--- a/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs
+++ b/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs
@@ -366,7 +366,7 @@ fn dispatch_worker_content_security_policy_report_to_service_worker(
destination: ServiceWorkerRequestDestination::Report,
request_mode: request.request_mode,
credentials_mode: request.credentials_mode,
- redirect_mode: request.redirect_mode,
+ redirect_mode: request.redirect_mode(),
priority: request.priority_hints.fetch_priority,
is_reload: false,
metadata: request_metadata,
@@ -543,7 +543,7 @@ pub(in crate::worker) fn continue_pending_worker_csp_report(
.with_resource_type(RequestResourceType::CspReport)
.with_request_mode(pending.request.request_mode)
.with_credentials_mode(pending.request.credentials_mode)
- .with_redirect_mode(pending.request.redirect_mode)
+ .with_redirect_mode(pending.request.redirect_mode())
.with_network_partition_key(pending.request.network_partition_key().map(str::to_owned))
.with_browser_request_metadata(BrowserRequestMetadata::Fetch),
Err(error) => {
diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rs
index 876b58209..b587e63d5 100644
--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs
+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs
@@ -209,7 +209,7 @@ pub(in crate::worker) fn spawn_worker_fetch_network(
}
if request.auth_requires_buffered_transport()
|| request.request_mode == RequestMode::NoCors
- || !request.follow_redirects
+ || !request.follows_redirects()
|| browser_request_needs_manual_preflight_redirects(
&request,
&cors_preflight_request_headers,