Skip to main content

net/
http_loader.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::collections::HashSet;
6use std::iter::FromIterator;
7use std::sync::Arc as StdArc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::{Duration, SystemTime};
10
11use async_recursion::async_recursion;
12use content_security_policy::percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
13#[cfg(feature = "devtools")]
14use devtools_traits::HttpResponseBody as DevtoolsHttpResponseBody;
15use embedder_traits::{AuthenticationResponse, GenericEmbedderProxy};
16use futures::{TryFutureExt, TryStreamExt, future};
17use headers::authorization::Basic;
18use headers::{
19    AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowMethods,
20    AccessControlMaxAge, AccessControlRequestMethod, Authorization, CacheControl, ContentLength,
21    HeaderMapExt, IfModifiedSince, LastModified, Pragma, Referer, StrictTransportSecurity,
22    UserAgent,
23};
24use http::header::{
25    self, ACCEPT, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_REQUEST_HEADERS, AUTHORIZATION,
26    CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LOCATION, CONTENT_TYPE, HeaderValue, RANGE,
27    WWW_AUTHENTICATE,
28};
29use http::{HeaderMap, Method, Request as HyperRequest, StatusCode};
30use http_body_util::combinators::BoxBody;
31use http_body_util::{BodyExt, Full};
32use hyper::Response as HyperResponse;
33use hyper::body::{Bytes, Frame};
34use hyper::ext::ReasonPhrase;
35use hyper::header::{HeaderName, TRANSFER_ENCODING};
36use ipc_channel::IpcError;
37use ipc_channel::ipc::{self, IpcSender};
38use ipc_channel::router::ROUTER;
39use log::{debug, error, info, log_enabled, warn};
40use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
41use net_traits::blob_url_store::UrlWithBlobClaim;
42use net_traits::fetch::headers::get_value_from_header_list;
43use net_traits::http_status::HttpStatus;
44use net_traits::policy_container::{EmbedderPolicyValue, RequestPolicyContainer};
45use net_traits::pub_domains::{is_same_site, reg_suffix};
46use net_traits::request::{
47    BodyChunkRequest, BodyChunkResponse, CacheMode, CredentialsMode, Destination, Initiator,
48    Origin, RedirectMode, Referrer, Request, RequestBuilder, RequestClient, RequestMode,
49    ResponseTainting, ServiceWorkersMode, TraversableForUserPrompts, get_cors_unsafe_header_names,
50    is_cors_non_wildcard_request_header_name, is_cors_safelisted_method,
51    is_cors_safelisted_request_header,
52};
53use net_traits::response::{CacheState, RedirectTaint, Response, ResponseBody, ResponseType};
54use net_traits::{
55    CookieSource, DOCUMENT_ACCEPT_HEADER_VALUE, DiscardFetch, NetworkError, RedirectEndValue,
56    RedirectStartValue, ReferrerPolicy, ResourceAttribute, ResourceFetchTiming,
57    ResourceFetchTimingContainer, ResourceTimeValue, ResourceTimingType, ServoCipherSuite,
58    ServoNamedGroup, ServoProtocolVersion, TlsSecurityInfo, TlsSecurityState,
59};
60use parking_lot::{Mutex, RwLock};
61use profile_traits::mem::{Report, ReportKind};
62use profile_traits::path;
63#[cfg(feature = "tracing")]
64use profile_traits::trace_span;
65use rustc_hash::FxHashMap;
66use servo_base::cross_process_instant::CrossProcessInstant;
67use servo_base::generic_channel::GenericSharedMemory;
68use servo_base::id::HistoryStateId;
69use servo_config::pref;
70use servo_url::{ImmutableOrigin, ServoUrl};
71use tokio::sync::mpsc::{
72    Receiver as TokioReceiver, Sender as TokioSender, UnboundedReceiver, UnboundedSender, channel,
73    unbounded_channel,
74};
75use tokio_stream::wrappers::ReceiverStream;
76#[cfg(feature = "tracing")]
77use tracing::Instrument;
78use uuid::Uuid;
79
80use crate::async_runtime::spawn_task;
81use crate::connector::{
82    CertificateErrorOverrideManager, ServoClient, TlsHandshakeInfo, create_tls_config,
83};
84use crate::cookie::ServoCookie;
85use crate::cookie_storage::CookieStorage;
86use crate::decoder::Decoder;
87#[cfg(feature = "devtools")]
88use crate::devtools::{
89    body_for_devtools, prepare_devtools_request, send_request_to_devtools,
90    send_response_values_to_devtools,
91};
92use crate::devtools::{
93    send_early_httprequest_to_devtools, send_response_to_devtools, send_security_info_to_devtools,
94};
95use crate::embedder::NetToEmbedderMsg;
96use crate::fetch::cors_cache::CorsCache;
97use crate::fetch::fetch_params::FetchParams;
98use crate::fetch::headers::{SecFetchDest, SecFetchMode, SecFetchSite, SecFetchUser};
99use crate::fetch::methods::{Data, DoneChannel, FetchContext, Target, fetch, main_fetch};
100use crate::hsts::HstsList;
101use crate::http_cache::{
102    CacheKey, CachedResourcesOrGuard, HttpCache, ValidationStatus, construct_response,
103    invalidate_cached_resources, refresh,
104};
105use crate::resource_thread::{AuthCache, AuthCacheEntry};
106use crate::websocket_loader::start_websocket;
107
108#[cfg(feature = "devtools")]
109type DevtoolsResponse = Option<devtools_traits::ChromeToDevtoolsControlMsg>;
110
111#[cfg(not(feature = "devtools"))]
112type DevtoolsResponse = Option<()>;
113
114/// The various states an entry of the HttpCache can be in.
115#[derive(Clone, Debug, Eq, PartialEq)]
116pub enum HttpCacheEntryState {
117    /// The entry is fully up-to-date,
118    /// there are no pending concurrent stores,
119    /// and it is ready to construct cached responses.
120    ReadyToConstruct,
121    /// The entry is pending a number of concurrent stores.
122    PendingStore(usize),
123}
124
125pub struct HttpState {
126    pub hsts_list: RwLock<HstsList>,
127    pub cookie_jar: RwLock<CookieStorage>,
128    pub http_cache: HttpCache,
129    pub auth_cache: RwLock<AuthCache>,
130    pub cors_cache: RwLock<CorsCache>,
131    pub history_states: RwLock<FxHashMap<HistoryStateId, Vec<u8>>>,
132    pub client: ServoClient,
133    pub override_manager: CertificateErrorOverrideManager,
134    pub embedder_proxy: GenericEmbedderProxy<NetToEmbedderMsg>,
135}
136
137impl HttpState {
138    pub(crate) fn memory_reports(&self, suffix: &str, ops: &mut MallocSizeOfOps) -> Vec<Report> {
139        vec![
140            Report {
141                path: path!["memory-cache", suffix],
142                kind: ReportKind::ExplicitJemallocHeapSize,
143                size: self.http_cache.size_of(ops),
144            },
145            Report {
146                path: path!["hsts-list", suffix],
147                kind: ReportKind::ExplicitJemallocHeapSize,
148                size: self.hsts_list.read().size_of(ops),
149            },
150            Report {
151                path: path!["auth cache", suffix],
152                kind: ReportKind::ExplicitJemallocHeapSize,
153                size: self.auth_cache.read().size_of(ops),
154            },
155            Report {
156                path: path!["cookie storage", suffix],
157                kind: ReportKind::ExplicitJemallocHeapSize,
158                size: self.cookie_jar.read().size_of(ops),
159            },
160        ]
161    }
162
163    async fn request_authentication(
164        &self,
165        request: &Request,
166        response: &Response,
167    ) -> Option<AuthenticationResponse> {
168        // We do not make an authentication request for non-WebView associated HTTP requests.
169        let webview_id = request.target_webview_id?;
170        let for_proxy = response.status == StatusCode::PROXY_AUTHENTICATION_REQUIRED;
171
172        // If this is not actually a navigation request return None.
173        if request.mode != RequestMode::Navigate {
174            return None;
175        }
176
177        let (sender, receiver) = tokio::sync::oneshot::channel();
178        self.embedder_proxy
179            .send(NetToEmbedderMsg::RequestAuthentication(
180                webview_id,
181                request.url(),
182                for_proxy,
183                sender,
184            ));
185        receiver.await.ok()?
186    }
187}
188
189/// Step 11 of <https://fetch.spec.whatwg.org/#concept-fetch>.
190pub(crate) fn set_default_accept(request: &mut Request) {
191    // Step 11. If request’s header list does not contain `Accept`, then:
192    if request.headers.contains_key(header::ACCEPT) {
193        return;
194    }
195
196    // Step 11.2. If request’s initiator is "prefetch", then set value to the document `Accept` header value.
197    let value = if request.initiator == Initiator::Prefetch {
198        DOCUMENT_ACCEPT_HEADER_VALUE
199    } else {
200        // Step 11.3. Otherwise, the user agent should set value to the first matching statement,
201        // if any, switching on request’s destination:
202        match request.destination {
203            Destination::Document | Destination::Frame | Destination::IFrame => {
204                DOCUMENT_ACCEPT_HEADER_VALUE
205            },
206            Destination::Image => {
207                HeaderValue::from_static("image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5")
208            },
209            Destination::Json => HeaderValue::from_static("application/json,*/*;q=0.5"),
210            Destination::Style => HeaderValue::from_static("text/css,*/*;q=0.1"),
211            Destination::Text => HeaderValue::from_static("text/plain,*/*;q=0.5"),
212            // Step 11.1. Let value be `*/*`.
213            _ => HeaderValue::from_static("*/*"),
214        }
215    };
216
217    // Step 11.4. Append (`Accept`, value) to request’s header list.
218    request.headers.insert(header::ACCEPT, value);
219}
220
221fn set_default_accept_encoding(headers: &mut HeaderMap) {
222    if headers.contains_key(header::ACCEPT_ENCODING) {
223        return;
224    }
225
226    // TODO(eijebong): Change this once typed headers are done
227    headers.insert(
228        header::ACCEPT_ENCODING,
229        HeaderValue::from_static("gzip, deflate, br, zstd"),
230    );
231}
232
233/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-state-no-referrer-when-downgrade>
234fn no_referrer_when_downgrade(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
235    // Step 1
236    if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
237        return None;
238    }
239    // Step 2
240    strip_url_for_use_as_referrer(referrer_url, false)
241}
242
243/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin>
244fn strict_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
245    // Step 1
246    if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
247        return None;
248    }
249    // Step 2
250    strip_url_for_use_as_referrer(referrer_url, true)
251}
252
253/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin>
254fn strict_origin_when_cross_origin(
255    referrer_url: ServoUrl,
256    current_url: ServoUrl,
257) -> Option<ServoUrl> {
258    // Step 1
259    if referrer_url.origin() == current_url.origin() {
260        return strip_url_for_use_as_referrer(referrer_url, false);
261    }
262    // Step 2
263    if referrer_url.is_potentially_trustworthy() && !current_url.is_potentially_trustworthy() {
264        return None;
265    }
266    // Step 3
267    strip_url_for_use_as_referrer(referrer_url, true)
268}
269
270/// <https://html.spec.whatwg.org/multipage/#schemelessly-same-site>
271fn is_schemelessy_same_site(site_a: &ImmutableOrigin, site_b: &ImmutableOrigin) -> bool {
272    // Step 1
273    if !site_a.is_tuple() && !site_b.is_tuple() && site_a == site_b {
274        true
275    } else if site_a.is_tuple() && site_b.is_tuple() {
276        // Step 2.1
277        let host_a = site_a.host().map(|h| h.to_string()).unwrap_or_default();
278        let host_b = site_b.host().map(|h| h.to_string()).unwrap_or_default();
279
280        let host_a_reg = reg_suffix(&host_a);
281        let host_b_reg = reg_suffix(&host_b);
282
283        // Step 2.2-2.3
284        (site_a.host() == site_b.host() && host_a_reg.is_empty()) ||
285            (host_a_reg == host_b_reg && !host_a_reg.is_empty())
286    } else {
287        // Step 3
288        false
289    }
290}
291
292/// <https://w3c.github.io/webappsec-referrer-policy/#strip-url>
293fn strip_url_for_use_as_referrer(mut url: ServoUrl, origin_only: bool) -> Option<ServoUrl> {
294    const MAX_REFERRER_URL_LENGTH: usize = 4096;
295    // Step 2
296    if url.is_local_scheme() {
297        return None;
298    }
299    // Step 3-6
300    {
301        let url = url.as_mut_url();
302        let _ = url.set_username("");
303        let _ = url.set_password(None);
304        url.set_fragment(None);
305        // Note: The result of serializing referrer url should not be
306        // greater than 4096 as specified in Step 6 of
307        // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
308        if origin_only || url.as_str().len() > MAX_REFERRER_URL_LENGTH {
309            url.set_path("");
310            url.set_query(None);
311        }
312    }
313    // Step 7
314    Some(url)
315}
316
317/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-same-origin>
318fn same_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
319    // Step 1
320    if referrer_url.origin() == current_url.origin() {
321        return strip_url_for_use_as_referrer(referrer_url, false);
322    }
323    // Step 2
324    None
325}
326
327/// <https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-origin-when-cross-origin>
328fn origin_when_cross_origin(referrer_url: ServoUrl, current_url: ServoUrl) -> Option<ServoUrl> {
329    // Step 1
330    if referrer_url.origin() == current_url.origin() {
331        return strip_url_for_use_as_referrer(referrer_url, false);
332    }
333    // Step 2
334    strip_url_for_use_as_referrer(referrer_url, true)
335}
336
337/// <https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer>
338pub fn determine_requests_referrer(
339    referrer_policy: ReferrerPolicy,
340    referrer_source: ServoUrl,
341    current_url: ServoUrl,
342) -> Option<ServoUrl> {
343    match referrer_policy {
344        ReferrerPolicy::EmptyString | ReferrerPolicy::NoReferrer => None,
345        ReferrerPolicy::Origin => strip_url_for_use_as_referrer(referrer_source, true),
346        ReferrerPolicy::UnsafeUrl => strip_url_for_use_as_referrer(referrer_source, false),
347        ReferrerPolicy::StrictOrigin => strict_origin(referrer_source, current_url),
348        ReferrerPolicy::StrictOriginWhenCrossOrigin => {
349            strict_origin_when_cross_origin(referrer_source, current_url)
350        },
351        ReferrerPolicy::SameOrigin => same_origin(referrer_source, current_url),
352        ReferrerPolicy::OriginWhenCrossOrigin => {
353            origin_when_cross_origin(referrer_source, current_url)
354        },
355        ReferrerPolicy::NoReferrerWhenDowngrade => {
356            no_referrer_when_downgrade(referrer_source, current_url)
357        },
358    }
359}
360
361fn set_request_cookies(
362    url: &ServoUrl,
363    headers: &mut HeaderMap,
364    cookie_jar: &RwLock<CookieStorage>,
365) {
366    let mut cookie_jar = cookie_jar.write();
367    cookie_jar.remove_expired_cookies_for_url(url);
368    if let Some(cookie_list) = cookie_jar.cookies_for_url(url, CookieSource::HTTP) &&
369        let Ok(cookie_list_header_value) = HeaderValue::from_bytes(cookie_list.as_bytes())
370    {
371        headers.insert(header::COOKIE, cookie_list_header_value);
372    }
373}
374
375fn set_cookie_for_url(cookie_jar: &RwLock<CookieStorage>, request: &ServoUrl, cookie_val: &str) {
376    let mut cookie_jar = cookie_jar.write();
377    let source = CookieSource::HTTP;
378
379    if let Some(cookie) = ServoCookie::from_cookie_string(cookie_val, request, source) {
380        cookie_jar.push(cookie, request, source);
381    }
382}
383
384fn set_cookies_from_headers(
385    url: &ServoUrl,
386    headers: &HeaderMap,
387    cookie_jar: &RwLock<CookieStorage>,
388) {
389    for cookie in headers.get_all(header::SET_COOKIE) {
390        let cookie_bytes = cookie.as_bytes();
391        if !ServoCookie::is_valid_name_or_value(cookie_bytes) {
392            continue;
393        }
394        if let Ok(cookie_str) = std::str::from_utf8(cookie_bytes) {
395            set_cookie_for_url(cookie_jar, url, cookie_str);
396        }
397    }
398}
399
400fn build_tls_security_info(handshake: &TlsHandshakeInfo, hsts_enabled: bool) -> TlsSecurityInfo {
401    // Simplified security state determination:
402    // Servo uses rustls, which only supports TLS 1.2+ and secure cipher suites (GCM, ChaCha20-Poly1305).
403    // rustls does NOT support TLS 1.0, TLS 1.1, SSL, or weak ciphers (RC4, 3DES, CBC, etc).
404    // Therefore, any successful TLS connection is secure by design.
405    //
406    // We only check for missing handshake information as a defensive measure.
407
408    let state = if handshake.protocol_version.is_none() || handshake.cipher_suite.is_none() {
409        // Missing handshake information indicates an incomplete or failed connection
410        TlsSecurityState::Insecure
411    } else {
412        // rustls guarantees TLS 1.2+ with secure ciphers
413        TlsSecurityState::Secure
414    };
415
416    TlsSecurityInfo {
417        state,
418        weakness_reasons: Vec::new(), // rustls never negotiates weak crypto
419        protocol_version: handshake.protocol_version.map(ServoProtocolVersion),
420        cipher_suite: handshake.cipher_suite.map(ServoCipherSuite),
421        kea_group_name: handshake.kea_group_name.map(ServoNamedGroup),
422        signature_scheme_name: handshake.signature_scheme_name.clone(),
423        alpn_protocol: handshake.alpn_protocol.clone(),
424        certificate_chain_der: handshake.certificate_chain_der.clone(),
425        certificate_transparency: None,
426        hsts: hsts_enabled,
427        hpkp: false,
428        used_ech: handshake.used_ech,
429        used_delegated_credentials: false,
430        used_ocsp: false,
431        used_private_dns: false,
432    }
433}
434
435fn auth_from_cache(
436    auth_cache: &RwLock<AuthCache>,
437    origin: &ImmutableOrigin,
438) -> Option<Authorization<Basic>> {
439    if let Some(auth_entry) = auth_cache
440        .read()
441        .entries
442        .get(origin.ascii_serialization().as_ref())
443    {
444        let user_name = &auth_entry.user_name;
445        let password = &auth_entry.password;
446        Some(Authorization::basic(user_name, password))
447    } else {
448        None
449    }
450}
451
452/// Messages from the IPC route to the fetch worker,
453/// used to fill the body with bytes coming-in over IPC.
454enum BodyChunk {
455    /// A chunk of bytes.
456    Chunk(GenericSharedMemory),
457    /// Body is done.
458    Done,
459}
460
461/// The stream side of the body passed to hyper.
462enum BodyStream {
463    /// A receiver that can be used in Body::wrap_stream,
464    /// for streaming the request over the network.
465    Chunked(TokioReceiver<Result<Frame<Bytes>, hyper::Error>>),
466    /// A body whose bytes are buffered
467    /// and sent in one chunk over the network.
468    Buffered(UnboundedReceiver<BodyChunk>),
469}
470
471/// The sink side of the body passed to hyper,
472/// used to enqueue chunks.
473enum BodySink {
474    /// A Tokio sender used to feed chunks to the network stream.
475    Chunked(TokioSender<Result<Frame<Bytes>, hyper::Error>>),
476    /// A Crossbeam sender used to send chunks to the fetch worker,
477    /// where they will be buffered
478    /// in order to ensure they are not streamed them over the network.
479    Buffered(UnboundedSender<BodyChunk>),
480}
481
482impl BodySink {
483    fn transmit_bytes(&self, bytes: GenericSharedMemory) {
484        match self {
485            BodySink::Chunked(sender) => {
486                let sender = sender.clone();
487                spawn_task(async move {
488                    let _ = sender
489                        .send(Ok(Frame::data(Bytes::copy_from_slice(&bytes))))
490                        .await;
491                });
492            },
493            BodySink::Buffered(sender) => {
494                let _ = sender.send(BodyChunk::Chunk(bytes));
495            },
496        }
497    }
498
499    fn close(self) {
500        match self {
501            BodySink::Chunked(_) => {},
502            BodySink::Buffered(sender) => {
503                let _ = sender.send(BodyChunk::Done);
504            },
505        }
506    }
507}
508
509fn request_body_stream_closed_error(action: &str) -> NetworkError {
510    NetworkError::Crash(format!(
511        "Request body stream has already been closed while trying to {action}."
512    ))
513}
514
515fn log_request_body_stream_closed(action: &str, error: Option<&IpcError>) {
516    match error {
517        Some(error) => {
518            error!("Request body stream has already been closed while trying to {action}: {error}")
519        },
520        None => error!("Request body stream has already been closed while trying to {action}."),
521    }
522}
523
524fn log_fetch_terminated_send_failure(terminated_with_error: bool, context: &str) {
525    warn!(
526        "Failed to notify request-body stream termination state ({terminated_with_error}) while {context} because the receiver was already dropped."
527    );
528}
529
530const FRAGMENT: &AsciiSet = &CONTROLS.add(b'|').add(b'{').add(b'}');
531
532#[servo_tracing::instrument(skip_all, fields(url=url.as_str()))]
533/// This sets up the callback infrastructure to send body frames to `body_sender` and fires the client request.
534async fn obtain_response(
535    fetch_params: &mut FetchParams,
536    client: &ServoClient,
537    url: &ServoUrl,
538    body_sender: Option<StdArc<Mutex<Option<IpcSender<BodyChunkRequest>>>>>,
539    request_id: Option<&Uuid>,
540    context: &FetchContext,
541    fetch_terminated: UnboundedSender<bool>,
542) -> Result<(HyperResponse<Decoder>, DevtoolsResponse), NetworkError> {
543    #[cfg(feature = "devtools")]
544    let (destination, pipeline_id, browsing_context_id) = {
545        let request = &fetch_params.request;
546
547        (
548            request.destination,
549            request.pipeline_id,
550            request.target_webview_id.map(Into::into),
551        )
552    };
553
554    let method = &fetch_params.request.method;
555    let source_is_null = fetch_params
556        .request
557        .body
558        .as_ref()
559        .is_some_and(|body| body.source_is_null());
560    let headers = &mut fetch_params.request.headers;
561
562    #[cfg(feature = "devtools")]
563    let devtools_bytes = StdArc::new(Mutex::new(vec![]));
564
565    // https://url.spec.whatwg.org/#percent-encoded-bytes
566    let encoded_url = utf8_percent_encode(url.as_str(), FRAGMENT).to_string();
567
568    let request = if let Some(chunk_requester) = body_sender {
569        let (sink, stream) = if source_is_null {
570            // Step 4.2 of https://fetch.spec.whatwg.org/#concept-http-network-fetch
571            // TODO: this should not be set for HTTP/2(currently not supported?).
572            headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
573
574            let (sender, receiver) = channel(1);
575            (BodySink::Chunked(sender), BodyStream::Chunked(receiver))
576        } else {
577            // Note: Hyper seems to already buffer bytes when the request appears not stream-able,
578            // see https://github.com/hyperium/hyper/issues/2232#issuecomment-644322104
579            //
580            // However since this doesn't appear documented, and we're using an ancient version,
581            // for now we buffer manually to ensure we don't stream requests
582            // to servers that might not know how to handle them.
583            let (sender, receiver) = unbounded_channel();
584            (BodySink::Buffered(sender), BodyStream::Buffered(receiver))
585        };
586
587        #[cfg(feature = "devtools")]
588        obtain_response_setup_router_callback(
589            Some(devtools_bytes.clone()),
590            chunk_requester,
591            sink,
592            fetch_terminated,
593        )?;
594
595        #[cfg(not(feature = "devtools"))]
596        obtain_response_setup_router_callback(None, chunk_requester, sink, fetch_terminated)?;
597
598        let body = match stream {
599            BodyStream::Chunked(receiver) => {
600                let stream = ReceiverStream::new(receiver);
601                BoxBody::new(http_body_util::StreamBody::new(stream))
602            },
603            BodyStream::Buffered(mut receiver) => {
604                // Accumulate bytes received over IPC into a vector.
605                let mut body = vec![];
606                loop {
607                    match receiver.recv().await {
608                        Some(BodyChunk::Chunk(bytes)) => {
609                            body.extend_from_slice(&bytes);
610                        },
611                        Some(BodyChunk::Done) => break,
612                        None => warn!("Failed to read all chunks from request body."),
613                    }
614                }
615                Full::new(body.into()).map_err(|_| unreachable!()).boxed()
616            },
617        };
618        HyperRequest::builder()
619            .method(method)
620            .uri(encoded_url)
621            .body(body)
622    } else {
623        HyperRequest::builder()
624            .method(method)
625            .uri(encoded_url)
626            .body(
627                http_body_util::Empty::new()
628                    .map_err(|_| unreachable!())
629                    .boxed(),
630            )
631    };
632
633    // TODO(#21261) connect_start: set if a persistent connection is *not* used and the last non-redirected
634    // fetch passes the timing allow check
635    let connect_start = CrossProcessInstant::now();
636    fetch_params.timing_info.set_attributes(&[
637        ResourceAttribute::DomainLookupStart,
638        ResourceAttribute::ConnectStart(connect_start),
639    ]);
640
641    // TODO: We currently don't know when the handhhake before the connection is done
642    // so our best bet would be to set `secure_connection_start` here when we are currently
643    // fetching on a HTTPS url.
644    if url.scheme() == "https" {
645        fetch_params
646            .timing_info
647            .set_attribute(ResourceAttribute::SecureConnectionStart);
648    }
649
650    let mut request = match request {
651        Ok(request) => request,
652        Err(error) => return Err(NetworkError::HttpError(error.to_string())),
653    };
654    *request.headers_mut() = headers.clone();
655
656    let connect_end = CrossProcessInstant::now();
657    fetch_params
658        .timing_info
659        .set_attribute(ResourceAttribute::ConnectEnd(connect_end));
660
661    let host = request.uri().host().unwrap_or("").to_owned();
662    let override_manager = context.state.override_manager.clone();
663    #[cfg(feature = "devtools")]
664    let (request_id, pipeline_id, closure_url, method, send_start, headers) = (
665        request_id.map(|value| value.to_owned()),
666        pipeline_id,
667        url.clone(),
668        method.clone(),
669        CrossProcessInstant::now(),
670        headers.clone(),
671    );
672    let is_secure_scheme = url.is_secure_scheme();
673
674    // Generally, we use a persistent connection, so we will also set other PerformanceResourceTiming
675    //   attributes to this as well (domain_lookup_start, domain_lookup_end, connect_start, connect_end,
676    //   secure_connection_start)
677    fetch_params
678        .timing_info
679        .set_attribute(ResourceAttribute::RequestStart);
680
681    let client_future = client
682        .request(request)
683        .and_then(move |res| {
684            // TODO(#21271) response_start: immediately after receiving first byte of response
685            #[cfg(feature = "devtools")]
686            let msg = if let Some(request_id) = request_id {
687                let send_end = CrossProcessInstant::now();
688                if let Some(pipeline_id) = pipeline_id {
689                    if let Some(browsing_context_id) = browsing_context_id {
690                        // XHR uses the default destination;
691                        // other kinds of fetches (which haven't been implemented yet) do not.
692                        // Once we support other kinds of fetches we'll need to be more fine grained here
693                        // since things like image fetches are classified differently by devtools
694                        let is_xhr = destination == Destination::None;
695
696                        Some(prepare_devtools_request(
697                            request_id,
698                            closure_url,
699                            method.clone(),
700                            headers,
701                            Some(devtools_bytes.lock().clone()),
702                            pipeline_id,
703                            (connect_end - connect_start).unsigned_abs(),
704                            (send_end - send_start).unsigned_abs(),
705                            destination,
706                            is_xhr,
707                            browsing_context_id,
708                        ))
709                    } else {
710                        debug!("Not notifying devtools (no browsing_context_id)");
711                        None
712                    }
713                    // TODO: ^This is not right, connect_start is taken before contructing the
714                    // request and connect_end at the end of it. send_start is takend before the
715                    // connection too. I'm not sure it's currently possible to get the time at the
716                    // point between the connection and the start of a request.
717                } else {
718                    debug!("Not notifying devtools (no pipeline_id)");
719                    None
720                }
721            } else {
722                debug!("Not notifying devtools (no request_id)");
723                None
724            };
725
726            future::ready(Ok((
727                Decoder::detect(res.map(|r| r.boxed()), is_secure_scheme),
728                #[cfg(feature = "devtools")]
729                msg,
730                #[cfg(not(feature = "devtools"))]
731                None,
732            )))
733        })
734        .map_err(move |error| {
735            warn!("network error: {error:?}");
736            NetworkError::from_hyper_error(
737                &error,
738                override_manager.remove_certificate_failing_verification(host.as_str()),
739            )
740        });
741
742    #[cfg(feature = "tracing")]
743    {
744        client_future.instrument(trace_span!("HyperRequest")).await
745    }
746
747    #[cfg(not(feature = "tracing"))]
748    {
749        client_future.await
750    }
751}
752
753/// Setup the callback mechanism to forward chunks from the request received to the `chunk_requester`.
754fn obtain_response_setup_router_callback(
755    devtools_bytes: Option<StdArc<Mutex<Vec<u8>>>>,
756    chunk_requester: StdArc<Mutex<Option<IpcSender<BodyChunkRequest>>>>,
757    sink: BodySink,
758    fetch_terminated: UnboundedSender<bool>,
759) -> Result<(), NetworkError> {
760    let (body_chan, body_port) = ipc::channel().unwrap();
761
762    {
763        let mut lock = chunk_requester.lock();
764        if let Some(chunk_requester) = lock.as_mut() {
765            if let Err(error) = chunk_requester.send(BodyChunkRequest::Connect(body_chan)) {
766                log_request_body_stream_closed("connect to the request body stream", Some(&error));
767                return Err(request_body_stream_closed_error(
768                    "connect to the request body stream",
769                ));
770            }
771
772            // https://fetch.spec.whatwg.org/#concept-request-transmit-body
773            // Request the first chunk, corresponding to Step 3 and 4.
774            if let Err(error) = chunk_requester.send(BodyChunkRequest::Chunk) {
775                log_request_body_stream_closed(
776                    "request the first request body chunk",
777                    Some(&error),
778                );
779                return Err(request_body_stream_closed_error(
780                    "request the first request body chunk",
781                ));
782            }
783        } else {
784            log_request_body_stream_closed("connect to the request body stream", None);
785            return Err(request_body_stream_closed_error(
786                "connect to the request body stream",
787            ));
788        }
789    }
790
791    let mut sink = Some(sink);
792
793    ROUTER.add_typed_route(
794        body_port,
795        Box::new(move |message| {
796            info!("Received message");
797            let bytes = match message.unwrap() {
798                BodyChunkResponse::Chunk(bytes) => bytes,
799                BodyChunkResponse::Done => {
800                    // Step 2.2.2. If fetchParams’s process request end-of-body is non-null,
801                    // then run fetchParams’s process request end-of-body.
802                    if fetch_terminated.send(false).is_err() {
803                        log_fetch_terminated_send_failure(
804                            false,
805                            "handling request body completion",
806                        );
807                    }
808                    if let Some(sink) = sink.take() {
809                        sink.close();
810                    }
811
812                    return;
813                },
814                BodyChunkResponse::Error => {
815                    // Step 4 and/or 5.
816                    // TODO: differentiate between the two steps,
817                    // where step 5 requires setting an `aborted` flag on the fetch.
818                    if fetch_terminated.send(true).is_err() {
819                        log_fetch_terminated_send_failure(
820                            true,
821                            "handling request body stream error",
822                        );
823                    }
824                    if let Some(sink) = sink.take() {
825                        sink.close();
826                    }
827
828                    return;
829                },
830            };
831
832            #[cfg(feature = "devtools")]
833            if let Some(devtools_bytes) = &devtools_bytes {
834                devtools_bytes.lock().extend_from_slice(&bytes);
835            }
836
837            // Step 5.1.2.2, transmit chunk over the network,
838            // currently implemented by sending the bytes to the fetch worker.
839            {
840                let Some(sink) = sink.as_ref() else {
841                    return;
842                };
843                sink.transmit_bytes(bytes);
844            }
845
846            // Step 5.1.2.3
847            // Request the next chunk.
848            let mut chunk_requester = chunk_requester.lock();
849            if let Some(chunk_requester) = chunk_requester.as_mut() {
850                if let Err(error) = chunk_requester.send(BodyChunkRequest::Chunk) {
851                    log_request_body_stream_closed(
852                        "request the next request body chunk",
853                        Some(&error),
854                    );
855                    if fetch_terminated.send(true).is_err() {
856                        log_fetch_terminated_send_failure(
857                            true,
858                            "handling failure to request the next request body chunk",
859                        );
860                    }
861                    if let Some(sink) = sink.take() {
862                        sink.close();
863                    }
864                }
865            } else {
866                log_request_body_stream_closed("request the next request body chunk", None);
867                if fetch_terminated.send(true).is_err() {
868                    log_fetch_terminated_send_failure(
869                        true,
870                        "handling a closed request body stream while requesting the next chunk",
871                    );
872                }
873                if let Some(sink) = sink.take() {
874                    sink.close();
875                }
876            }
877        }),
878    );
879
880    Ok(())
881}
882
883/// [HTTP fetch](https://fetch.spec.whatwg.org/#concept-http-fetch)
884#[async_recursion]
885pub(crate) async fn http_fetch(
886    fetch_params: &mut FetchParams,
887    cors_flag: bool,
888    cors_preflight_flag: bool,
889    authentication_fetch_flag: bool,
890    target: Target<'async_recursion>,
891    done_chan: &mut DoneChannel,
892    context: &FetchContext,
893) -> Response {
894    // This is a new async fetch, reset the channel we are waiting on
895    *done_chan = None;
896    // Step 1. Let request be fetchParams’s request.
897    let request = &mut fetch_params.request;
898
899    // Step 2. Let response and internalResponse be null.
900    let mut response: Option<Response> = None;
901
902    // Step 3. If request’s service-workers mode is "all", then
903    if request.service_workers_mode == ServiceWorkersMode::All {
904        // Note: Most of these steps can't be implemented and don't make sense to
905        // implement until we have and implementation of "handle fetch" that is called
906        // below.
907        //
908        // Step 3.1. Let requestForServiceWorker be a clone of request.
909        // Step 3.2. If requestForServiceWorker’s body is non-null, then:
910        // Step 3.2.1. Let transformStream be a new TransformStream.
911        // Step 3.2.2. Let transformAlgorithm given chunk be these steps:
912        // Step 3.2.2.1. If fetchParams is canceled, then abort these steps.
913        // Step 3.2.2.2. If chunk is not a Uint8Array object, then terminate fetchParams’s
914        // controller.
915        // Step 3.2.2.3. Otherwise, enqueue chunk in transformStream. The user agent may
916        // split the chunk into implementation-defined practical sizes and enqueue each of
917        // them. The user agent also may concatenate the chunks into an
918        // implementation-defined practical size and enqueue it.
919        // Step 3.2.3. Set up transformStream with transformAlgorithm set to transformAlgorithm.
920        // Step 3.2.4. Set requestForServiceWorker’s body’s stream to the result of
921        // requestForServiceWorker’s body’s stream piped through transformStream.
922        // Step 3.3. Let serviceWorkerStartTime be the coarsened shared current time given
923        // fetchParams’s cross-origin isolated capability.
924        // Step 3.4. Let fetchResponse be the result of invoking handle fetch for
925        // requestForServiceWorker, with fetchParams’s controller and fetchParams’s
926        // cross-origin isolated capability. [HTML] [SW]
927        // Step 3.5. If fetchResponse is a response:
928        // Step 3.5.1. Set response to fetchResponse.
929        // Step 3.5.2. Set fetchParams’s timing info’s final service worker start time
930        // to serviceWorkerStartTime.
931        // Step 3.5.3. Set fetchParams’s timing info’s service worker timing info to
932        // response’s service worker timing info.
933        // Step 3.5.4. If request’s body is non-null, then cancel request’s body with undefined.
934        // Step 3.5.5. Set internalResponse to response, if response is not a filtered
935        // response; otherwise to response’s internal response.
936        // Step 3.5.6. Run the WebDriver BiDi response started steps with request and
937        // response.
938        // Step 3.5.7. If one of the following is true
939        //  - response’s type is "error"
940        //  - request’s mode is "same-origin" and response’s type is "cors"
941        //  - request’s mode is not "no-cors" and response’s type is "opaque"
942        //  - request’s redirect mode is not "manual" and response’s type is "opaqueredirect"
943        //  - request’s redirect mode is not "follow" and response’s URL list has more than one item
944        // then return a network error.
945        // Step 3.6. Otherwise, if fetchResponse is a service worker timing info, then
946        // set fetchParams’s timing info’s service worker timing info to
947        // fetchResponse.
948    }
949
950    // Step 4. If response is null, then:
951    if response.is_none() {
952        // Step 4.1. If makeCORSPreflight is true and one of these conditions is true:
953        if cors_preflight_flag {
954            let (method_mismatch, header_mismatch) = {
955                let mut cors_cache = context.state.cors_cache.write();
956                let method_cache_match = cors_cache.match_method(request, &request.method);
957
958                // > There is no method cache entry match for request's method using request, and either
959                // > request's method is not a CORS-safelisted method or request's use-CORS-preflight flag
960                // > is set.
961                let method_mismatch = !method_cache_match &&
962                    (!is_cors_safelisted_method(&request.method) || request.use_cors_preflight);
963
964                // > There is at least one item in the CORS-unsafe request-header names with request's
965                // > header list for which there is no header-name cache entry match using request.
966                let header_mismatch = request.headers.iter().any(|(name, value)| {
967                    !cors_cache.match_header(request, name) &&
968                        !is_cors_safelisted_request_header(&name, &value)
969                });
970                (method_mismatch, header_mismatch)
971            };
972
973            // Then:
974            if method_mismatch || header_mismatch {
975                // Step 4.1.1. Let preflightResponse be the result of running
976                // CORS-preflight fetch given request.
977                let preflight_response = cors_preflight_fetch(request, context).await;
978                // Step 4.1.2. If preflightResponse is a network error, then return preflightResponse.
979                if let Some(error) = preflight_response.get_network_error() {
980                    return Response::network_error(error.clone());
981                }
982            }
983        }
984
985        // Step 4.2. If request’s redirect mode is "follow",
986        // then set request’s service-workers mode to "none".
987        if request.redirect_mode == RedirectMode::Follow {
988            request.service_workers_mode = ServiceWorkersMode::None;
989        }
990
991        // Step 4.3. Set response and internalResponse to the result of
992        // running HTTP-network-or-cache fetch given fetchParams.
993        let mut fetch_result = http_network_or_cache_fetch(
994            fetch_params,
995            authentication_fetch_flag,
996            cors_flag,
997            done_chan,
998            context,
999        )
1000        .await;
1001
1002        // Step 4.4. If request’s response tainting is "cors" and a CORS check for request
1003        // and response returns failure, then return a network error.
1004        if cors_flag && cors_check(&fetch_params.request, &fetch_result).is_err() {
1005            return Response::network_error(NetworkError::CorsGeneral);
1006        }
1007
1008        // Step 4.5. If the TAO check for request and response returns failure,
1009        // then set request’s timing allow failed flag.
1010        if let Err(()) = tao_check(&fetch_params.request, &fetch_result) {
1011            fetch_params.timing_info.inner().mark_timing_check_failed();
1012        }
1013        fetch_result.return_internal = false;
1014        response = Some(fetch_result);
1015    }
1016
1017    let request = &mut fetch_params.request;
1018
1019    // response is guaranteed to be something by now
1020    let mut response = response.unwrap();
1021
1022    // Step 5: If either request’s response tainting or response’s type is "opaque",
1023    // and the cross-origin resource policy check with request’s origin, request’s client,
1024    // request’s destination, and internalResponse returns blocked, then return a network error.
1025    if (request.response_tainting == ResponseTainting::Opaque ||
1026        response.response_type == ResponseType::Opaque) &&
1027        request.client.as_ref().is_some_and(|client| {
1028            cross_origin_resource_policy_check(
1029                &request.origin,
1030                client,
1031                &response,
1032                ForNavigation::No,
1033            ) == CrossOriginResourcePolicy::Blocked
1034        })
1035    {
1036        return Response::network_error(NetworkError::CrossOriginResponse);
1037    }
1038
1039    // Step 6. If internalResponse’s status is a redirect status:
1040    if response
1041        .actual_response()
1042        .status
1043        .try_code()
1044        .is_some_and(is_redirect_status)
1045    {
1046        // TODO Step 6.1. If request is a navigation request, then append to a request’s navigation
1047        // timing allow values list given request and internalResponse.
1048
1049        // Step 6.2. If internalResponse’s status is not 303, request’s body is non-null,
1050        // and the connection uses HTTP/2, then user agents may, and are even encouraged to,
1051        // transmit an RST_STREAM frame.
1052        if response.actual_response().status != StatusCode::SEE_OTHER {
1053            // TODO: send RST_STREAM frame
1054        }
1055
1056        // Step 6.3. Switch on request’s redirect mode:
1057        response = match request.redirect_mode {
1058            // Step 6.3."error".1. Set response to a network error.
1059            RedirectMode::Error => Response::network_error(NetworkError::RedirectError),
1060            RedirectMode::Manual => {
1061                // Step 6.3."manual".1. If request’s mode is "navigate", then set fetchParams’s controller’s
1062                // next manual redirect steps to run HTTP-redirect fetch given fetchParams and response.
1063                if request.mode == RequestMode::Navigate {
1064                    // TODO: We don't implement Fetch controller. Instead, we update the location url
1065                    // of the response here and don't call `http_redirect_fetch`. That's get called later.
1066                    // Once we have a fetch controller here, we should update the code as specced.
1067                    let location_url =
1068                        location_url_for_response(&response, request.current_url().fragment());
1069                    response.actual_response_mut().location_url = location_url;
1070                    response
1071                } else {
1072                    // Step 6.3."manual".2. Otherwise, set response to an opaque-redirect filtered
1073                    // response whose internal response is internalResponse.
1074                    response.to_filtered(ResponseType::OpaqueRedirect)
1075                }
1076            },
1077            RedirectMode::Follow => {
1078                // TODO Step 6.3."follow".1. Run the WebDriver BiDi response completed steps with
1079                // request and response.
1080                // set back to default
1081                response.return_internal = true;
1082
1083                // Step 6.3."follow".2. Set response to the result of running HTTP-redirect fetch
1084                // given fetchParams and response.
1085                http_redirect_fetch(
1086                    fetch_params,
1087                    response,
1088                    cors_flag,
1089                    target,
1090                    done_chan,
1091                    context,
1092                )
1093                .await
1094            },
1095        };
1096    }
1097
1098    // set back to default
1099    response.return_internal = true;
1100    fetch_params
1101        .timing_info
1102        .set_attribute(ResourceAttribute::RedirectCount(
1103            fetch_params.request.redirect_count as u16,
1104        ));
1105
1106    response.resource_timing = fetch_params.timing_info.clone();
1107
1108    // Step 7. Return response
1109    response
1110}
1111
1112/// <https://fetch.spec.whatwg.org/#concept-tao-check>
1113fn tao_check(request: &Request, response: &Response) -> Result<(), ()> {
1114    // Step 1. Assert: request’s origin is not "client".
1115    let Origin::Origin(ref request_origin) = request.origin else {
1116        unreachable!("origin cannot be \"client\" at this point");
1117    };
1118
1119    // Step 2. If request’s timing allow failed flag is set, then return failure.
1120
1121    // Step 3. Let values be the result of getting, decoding, and splitting `Timing-Allow-Origin`
1122    // from response’s header list.
1123    let values: Vec<&str> = response
1124        .headers
1125        .get_all("Timing-Allow-Origin")
1126        .iter()
1127        .map(|header_value| header_value.to_str().unwrap_or(""))
1128        .collect();
1129
1130    // Step 4. If values contains "*", then return success.
1131    if values.contains(&"*") {
1132        return Ok(());
1133    }
1134
1135    // Step 5. If values contains the result of serializing a request origin with request, then
1136    // return success.
1137    if values
1138        .iter()
1139        .any(|header_str| *header_str == request_origin.ascii_serialization().as_ref())
1140    {
1141        return Ok(());
1142    }
1143
1144    // Step 6. If request’s mode is "navigate" and request’s current URL’s origin is not same origin
1145    // with request’s origin, then return failure.
1146    if request.mode == RequestMode::Navigate && request.current_url().origin() != *request_origin {
1147        return Err(());
1148    }
1149
1150    // Step 7. If request’s response tainting is "basic", then return success.
1151    if request.response_tainting == ResponseTainting::Basic {
1152        return Ok(());
1153    }
1154
1155    // Step 8. Return failure.
1156    Err(())
1157}
1158
1159// Convenience struct that implements Drop, for setting redirectEnd on function return
1160struct RedirectEndTimer(Option<ResourceFetchTimingContainer>);
1161
1162impl RedirectEndTimer {
1163    fn neuter(&mut self) {
1164        self.0 = None;
1165    }
1166}
1167
1168impl Drop for RedirectEndTimer {
1169    fn drop(&mut self) {
1170        let RedirectEndTimer(resource_fetch_timing_opt) = self;
1171
1172        resource_fetch_timing_opt.as_ref().map_or((), |t| {
1173            t.set_attribute(ResourceAttribute::RedirectEnd(RedirectEndValue::Zero));
1174        })
1175    }
1176}
1177
1178/// <https://fetch.spec.whatwg.org/#request-body-header-name>
1179static REQUEST_BODY_HEADER_NAMES: &[HeaderName] = &[
1180    CONTENT_ENCODING,
1181    CONTENT_LANGUAGE,
1182    CONTENT_LOCATION,
1183    CONTENT_TYPE,
1184];
1185
1186/// <https://fetch.spec.whatwg.org/#concept-response-location-url>
1187fn location_url_for_response(
1188    response: &Response,
1189    request_fragment: Option<&str>,
1190) -> Option<Result<ServoUrl, String>> {
1191    // Step 1. If response’s status is not a redirect status, then return null.
1192    assert!(
1193        response
1194            .actual_response()
1195            .status
1196            .try_code()
1197            .is_some_and(is_redirect_status)
1198    );
1199    // Step 2. Let location be the result of extracting header list values given `Location` and response’s header list.
1200    let mut location = response
1201        .actual_response()
1202        .headers
1203        .get(header::LOCATION)
1204        .and_then(|header_value| {
1205            HeaderValue::to_str(header_value)
1206                .map(|location_string| {
1207                    // Step 3. If location is a header value, then set location to the result of parsing location with response’s URL.
1208                    ServoUrl::parse_with_base(response.actual_response().url(), location_string)
1209                        .map_err(|error| error.to_string())
1210                })
1211                .ok()
1212        });
1213
1214    // Step 4. If location is a URL whose fragment is null, then set location’s fragment to requestFragment.
1215    if let Some(Ok(ref mut location)) = location &&
1216        location.fragment().is_none()
1217    {
1218        location.set_fragment(request_fragment);
1219    }
1220    // Step 5. Return location.
1221    location
1222}
1223
1224/// [HTTP redirect fetch](https://fetch.spec.whatwg.org/#http-redirect-fetch)
1225#[async_recursion]
1226pub async fn http_redirect_fetch(
1227    fetch_params: &mut FetchParams,
1228    mut response: Response,
1229    cors_flag: bool,
1230    target: Target<'async_recursion>,
1231    done_chan: &mut DoneChannel,
1232    context: &FetchContext,
1233) -> Response {
1234    let mut redirect_end_timer = RedirectEndTimer(Some(fetch_params.timing_info.clone()));
1235
1236    // Step 1. Let request be fetchParams’s request.
1237    let request = &mut fetch_params.request;
1238
1239    // Step 2. Let internalResponse be response, if response is not a filtered response; otherwise response’s internal response.
1240    assert!(response.return_internal);
1241
1242    // Step 3. Let locationURL be internalResponse’s location URL given request’s current URL’s fragment.
1243    let location_url = location_url_for_response(&response, request.current_url().fragment());
1244    response.actual_response_mut().location_url = location_url.clone();
1245
1246    let location_url = match location_url {
1247        // Step 4. If locationURL is null, then return response.
1248        None => return response,
1249        // Step 5. If locationURL is failure, then return a network error.
1250        Some(Err(err)) => {
1251            return Response::network_error(NetworkError::ResourceLoadError(
1252                "Location URL parse failure: ".to_owned() + &err,
1253            ));
1254        },
1255        // Step 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network error.
1256        Some(Ok(url)) if !matches!(url.scheme(), "http" | "https") => {
1257            return Response::network_error(NetworkError::UnsupportedScheme);
1258        },
1259        Some(Ok(url)) => url,
1260    };
1261
1262    // Step 1 of https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-fetchstart
1263    // TODO: check origin and timing allow check
1264    // start_time should equal redirect_start if nonzero; else fetch_start
1265    // updates start_time only if redirect_start is nonzero (implying TAO)
1266    fetch_params.timing_info.set_attributes(&[
1267        ResourceAttribute::RedirectStart(RedirectStartValue::FetchStart),
1268        ResourceAttribute::FetchStart,
1269        ResourceAttribute::StartTime(ResourceTimeValue::FetchStart),
1270        ResourceAttribute::StartTime(ResourceTimeValue::RedirectStart),
1271    ]);
1272
1273    // Step 7: If request’s redirect count is 20, then return a network error.
1274    if request.redirect_count >= 20 {
1275        return Response::network_error(NetworkError::TooManyRedirects);
1276    }
1277
1278    // Step 8: Increase request’s redirect count by 1.
1279    request.redirect_count += 1;
1280
1281    // Step 9. If request’s mode is "cors", locationURL includes credentials,
1282    // and request’s origin is not same origin with locationURL’s origin, then return a network error.
1283    let has_credentials = has_credentials(&location_url);
1284    if request.mode == RequestMode::CorsMode {
1285        let same_origin = match request.origin {
1286            Origin::Origin(ref origin) => *origin == location_url.origin(),
1287            Origin::Client => panic!(
1288                "Request origin should not be client for {}",
1289                request.current_url()
1290            ),
1291        };
1292        if !same_origin && has_credentials {
1293            return Response::network_error(NetworkError::CorsCredentials);
1294        }
1295    }
1296
1297    // Step 10. If request’s response tainting is "cors" and locationURL includes credentials, then return a network error.
1298    if cors_flag && has_credentials {
1299        return Response::network_error(NetworkError::CorsCredentials);
1300    }
1301
1302    // Step 11: If internalResponse’s status is not 303, request’s body is non-null, and request’s
1303    // body’s source is null, then return a network error.
1304    if response.actual_response().status != StatusCode::SEE_OTHER &&
1305        request.body.as_ref().is_some_and(|b| b.source_is_null())
1306    {
1307        return Response::network_error(NetworkError::ConnectionFailure);
1308    }
1309
1310    // Step 12. If one of the following is true
1311    if response
1312        .actual_response()
1313        .status
1314        .try_code()
1315        .is_some_and(|code| {
1316            // internalResponse’s status is 301 or 302 and request’s method is `POST`
1317            ((code == StatusCode::MOVED_PERMANENTLY || code == StatusCode::FOUND) &&
1318                request.method == Method::POST) ||
1319                // internalResponse’s status is 303 and request’s method is not `GET` or `HEAD`
1320                (code == StatusCode::SEE_OTHER &&
1321                    request.method != Method::HEAD &&
1322                    request.method != Method::GET)
1323        })
1324    {
1325        // Step 12.1. Set request’s method to `GET` and request’s body to null.
1326        request.method = Method::GET;
1327        request.body = None;
1328        // Step 12.2. For each headerName of request-body-header name, delete headerName from request’s header list.
1329        for name in REQUEST_BODY_HEADER_NAMES {
1330            request.headers.remove(name);
1331        }
1332    }
1333
1334    // Step 13: If request’s current URL’s origin is not same origin with locationURL’s origin, then
1335    // for each headerName of CORS non-wildcard request-header name, delete headerName from
1336    // request’s header list.
1337    if location_url.origin() != request.current_url().origin() {
1338        // This list currently only contains the AUTHORIZATION header
1339        // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
1340        request.headers.remove(AUTHORIZATION);
1341    }
1342
1343    // Step 14: If request’s body is non-null, then set request’s body to the body of the result of
1344    // safely extracting request’s body’s source.
1345    if let Some(body) = request.body.as_mut() {
1346        body.extract_source();
1347    }
1348
1349    // Steps 15-17 relate to timing, which is not implemented 1:1 with the spec.
1350
1351    // Step 18: Append locationURL to request’s URL list.
1352    request
1353        .url_list
1354        .push(UrlWithBlobClaim::from_url_without_having_claimed_blob(
1355            location_url,
1356        ));
1357
1358    // Step 19: Invoke set request’s referrer policy on redirect on request and internalResponse.
1359    set_requests_referrer_policy_on_redirect(request, response.actual_response());
1360
1361    // Step 20: Let recursive be true.
1362    // Step 21: If request’s redirect mode is "manual", then...
1363    let recursive_flag = request.redirect_mode != RedirectMode::Manual;
1364
1365    // Step 22: Return the result of running main fetch given fetchParams and recursive.
1366    let fetch_response = main_fetch(fetch_params, recursive_flag, target, done_chan, context).await;
1367
1368    // TODO: timing allow check
1369    fetch_params
1370        .timing_info
1371        .set_attribute(ResourceAttribute::RedirectEnd(
1372            RedirectEndValue::ResponseEnd,
1373        ));
1374    redirect_end_timer.neuter();
1375
1376    fetch_response
1377}
1378
1379/// [HTTP network or cache fetch](https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch)
1380#[async_recursion]
1381#[servo_tracing::instrument(skip_all,fields(url=fetch_params.request.url().as_str()))]
1382async fn http_network_or_cache_fetch(
1383    fetch_params: &mut FetchParams,
1384    authentication_fetch_flag: bool,
1385    cors_flag: bool,
1386    done_chan: &mut DoneChannel,
1387    context: &FetchContext,
1388) -> Response {
1389    // Step 2. Let httpFetchParams be null.
1390    let http_fetch_params: &mut FetchParams;
1391    let mut fetch_params_copy: FetchParams;
1392
1393    // Step 3. Let httpRequest be null. (See step 8 for initialization)
1394
1395    // Step 4. Let response be null.
1396    let mut response: Option<Response> = None;
1397
1398    // Step 7. Let the revalidatingFlag be unset.
1399    let mut revalidating_flag = false;
1400
1401    // TODO(#33616): Step 8. Run these steps, but abort when fetchParams is canceled:
1402    // Step 8.1. If request’s traversable for user prompts is "no-traversable"
1403    // and request’s redirect mode is "error", then set httpFetchParams to fetchParams and httpRequest to request.
1404    let http_request = if fetch_params.request.traversable_for_user_prompts ==
1405        TraversableForUserPrompts::NoTraversable &&
1406        fetch_params.request.redirect_mode == RedirectMode::Error
1407    {
1408        http_fetch_params = fetch_params;
1409        &mut http_fetch_params.request
1410    }
1411    // Step 8.2 Otherwise:
1412    else {
1413        // Step 8.2.1 - 8.2.3: Set httpRequest to a clone of request
1414        // and Set httpFetchParams to a copy of fetchParams.
1415        fetch_params_copy = std::mem::replace(
1416            fetch_params,
1417            FetchParams::new(
1418                fetch_params.request.clone(),
1419                fetch_params.timing_info.clone(),
1420            ),
1421        );
1422        http_fetch_params = &mut fetch_params_copy;
1423
1424        &mut http_fetch_params.request
1425    };
1426
1427    // Step 8.3: Let includeCredentials be true if one of:
1428    let include_credentials = match http_request.credentials_mode {
1429        // request’s credentials mode is "include"
1430        CredentialsMode::Include => true,
1431        // request’s credentials mode is "same-origin" and request’s response tainting is "basic"
1432        CredentialsMode::CredentialsSameOrigin
1433            if http_request.response_tainting == ResponseTainting::Basic =>
1434        {
1435            true
1436        },
1437        _ => false,
1438    };
1439
1440    // Step 8.4: If Cross-Origin-Embedder-Policy allows credentials with request returns false, then
1441    // set includeCredentials to false.
1442    // TODO(#33616): Requires request's client object
1443
1444    // Step 8.5 Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null;
1445    // otherwise null.
1446    let content_length = http_request
1447        .body
1448        .as_ref()
1449        .and_then(|body| body.len().map(|size| size as u64));
1450
1451    // Step 8.6 Let contentLengthHeaderValue be null.
1452    let mut content_length_header_value = None;
1453
1454    // Step 8.7 If httpRequest’s body is null and httpRequest’s method is `POST` or `PUT`,
1455    // then set contentLengthHeaderValue to `0`.
1456    if http_request.body.is_none() && matches!(http_request.method, Method::POST | Method::PUT) {
1457        content_length_header_value = Some(0);
1458    }
1459
1460    // Step 8.8 If contentLength is non-null, then set contentLengthHeaderValue to contentLength,
1461    // serialized and isomorphic encoded.
1462    // NOTE: The header will later be serialized using HeaderMap::typed_insert
1463    if let Some(content_length) = content_length {
1464        content_length_header_value = Some(content_length);
1465    };
1466
1467    // Step 8.9 If contentLengthHeaderValue is non-null, then append (`Content-Length`, contentLengthHeaderValue)
1468    // to httpRequest’s header list.
1469    if let Some(content_length_header_value) = content_length_header_value {
1470        http_request
1471            .headers
1472            .typed_insert(ContentLength(content_length_header_value));
1473    }
1474
1475    // Step 8.10 If contentLength is non-null and httpRequest’s keepalive is true, then:
1476    if http_request.keep_alive &&
1477        let Some(content_length) = content_length
1478    {
1479        // Step 8.10.1. Let inflightKeepaliveBytes be 0.
1480        // Step 8.10.2. Let group be httpRequest’s client’s fetch group.
1481        // Step 8.10.3. Let inflightRecords be the set of fetch records
1482        // in group whose request’s keepalive is true and done flag is unset.
1483        let in_flight_keep_alive_bytes: u64 = context
1484            .in_flight_keep_alive_records
1485            .lock()
1486            .get(
1487                &http_request
1488                    .pipeline_id
1489                    .expect("Must always set a pipeline ID for keep-alive requests"),
1490            )
1491            .map(|records| {
1492                // Step 8.10.4. For each fetchRecord of inflightRecords:
1493                // Step 8.10.4.1. Let inflightRequest be fetchRecord’s request.
1494                // Step 8.10.4.2. Increment inflightKeepaliveBytes by inflightRequest’s body’s length.
1495                records
1496                    .iter()
1497                    .map(|record| {
1498                        if record.request_id == http_request.id {
1499                            // Don't double count for this request. We have already added it in
1500                            // `fetch::methods::fetch`
1501                            0
1502                        } else {
1503                            record.keep_alive_body_length
1504                        }
1505                    })
1506                    .sum()
1507            })
1508            .unwrap_or_default();
1509        // Step 8.10.5. If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.
1510        if content_length + in_flight_keep_alive_bytes > 64 * 1024 {
1511            return Response::network_error(NetworkError::TooManyInFlightKeepAliveRequests);
1512        }
1513    }
1514
1515    // Step 8.11: If httpRequest’s referrer is a URL, then:
1516    match http_request.referrer {
1517        Referrer::ReferrerUrl(ref http_request_referrer) |
1518        Referrer::Client(ref http_request_referrer) => {
1519            // Step 8.11.1: Let referrerValue be httpRequest’s referrer, serialized and isomorphic
1520            // encoded.
1521            if let Ok(referer) = http_request_referrer.as_str().parse::<Referer>() {
1522                // Step 8.11.2: Append (`Referer`, referrerValue) to httpRequest’s header list.
1523                http_request.headers.typed_insert(referer);
1524            } else {
1525                // This error should only happen in cases where hyper and rust-url disagree
1526                // about how to parse a referer.
1527                // https://github.com/servo/servo/issues/24175
1528                error!("Failed to parse {} as referrer", http_request_referrer);
1529            }
1530        },
1531        _ => {},
1532    };
1533
1534    // Step 8.12 Append a request `Origin` header for httpRequest.
1535    append_a_request_origin_header(http_request);
1536
1537    // Step 8.13 Append the Fetch metadata headers for httpRequest.
1538    append_the_fetch_metadata_headers(http_request);
1539
1540    // Step 8.14: If httpRequest’s initiator is "prefetch", then set a structured field value given
1541    // (`Sec-Purpose`, the token "prefetch") in httpRequest’s header list.
1542    if http_request.initiator == Initiator::Prefetch &&
1543        let Ok(value) = HeaderValue::from_str("prefetch")
1544    {
1545        http_request.headers.insert("Sec-Purpose", value);
1546    }
1547
1548    // Step 8.15: If httpRequest’s header list does not contain `User-Agent`, then user agents
1549    // should append (`User-Agent`, default `User-Agent` value) to httpRequest’s header list.
1550    if !http_request.headers.contains_key(header::USER_AGENT) {
1551        http_request
1552            .headers
1553            .typed_insert::<UserAgent>(context.user_agent.parse().unwrap());
1554    }
1555
1556    // Steps 8.16 to 8.18
1557    append_cache_data_to_headers(http_request);
1558
1559    // Step 8.19: If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`,
1560    // `identity`) to httpRequest’s header list.
1561    if http_request.headers.contains_key(header::RANGE) &&
1562        let Ok(value) = HeaderValue::from_str("identity")
1563    {
1564        http_request.headers.insert("Accept-Encoding", value);
1565    }
1566
1567    // Step 8.20: Modify httpRequest’s header list per HTTP. Do not append a given header if
1568    // httpRequest’s header list contains that header’s name.
1569    // `Accept`, `Accept-Charset`, and `Accept-Language` must not be included at this point.
1570    http_request.headers.remove(header::HOST);
1571    // unlike http_loader, we should not set the accept header here
1572    set_default_accept_encoding(&mut http_request.headers);
1573
1574    let current_url = http_request.current_url();
1575
1576    // Step 8.21: If includeCredentials is true, then:
1577    // TODO some of this step can't be implemented yet
1578    if include_credentials {
1579        // Substep 1
1580        // TODO http://mxr.mozilla.org/servo/source/components/net/http_loader.rs#504
1581        // XXXManishearth http_loader has block_cookies: support content blocking here too
1582        set_request_cookies(
1583            &current_url,
1584            &mut http_request.headers,
1585            &context.state.cookie_jar,
1586        );
1587        // Substep 2
1588        if !http_request.headers.contains_key(header::AUTHORIZATION) {
1589            // Substep 3
1590            let mut authorization_value = None;
1591
1592            // Substep 4
1593            if let Some(basic) = auth_from_cache(&context.state.auth_cache, &current_url.origin()) &&
1594                (!http_request.use_url_credentials || !has_credentials(&current_url))
1595            {
1596                authorization_value = Some(basic);
1597            }
1598
1599            // Substep 5
1600            if authentication_fetch_flag &&
1601                authorization_value.is_none() &&
1602                has_credentials(&current_url)
1603            {
1604                authorization_value = Some(Authorization::basic(
1605                    current_url.username(),
1606                    current_url.password().unwrap_or(""),
1607                ));
1608            }
1609
1610            // Substep 6
1611            if let Some(basic) = authorization_value {
1612                http_request.headers.typed_insert(basic);
1613            }
1614        }
1615    }
1616
1617    // TODO(#33616) Step 8.22 If there’s a proxy-authentication entry, use it as appropriate.
1618    let should_wait = {
1619        // Enter critical section on cache entry.
1620        let mut cache_guard = block_for_cache_ready(
1621            context,
1622            http_request,
1623            done_chan,
1624            &mut revalidating_flag,
1625            &mut response,
1626        )
1627        .await;
1628
1629        // TODO(#33616): Step 9. If aborted, then return the appropriate network error for fetchParams.
1630
1631        // Step 10. If response is null, then:
1632        if response.is_none() {
1633            // Step 10.1 If httpRequest’s cache mode is "only-if-cached", then return a network error.
1634            if http_request.cache_mode == CacheMode::OnlyIfCached {
1635                // Exit critical section of cache entry.
1636                return Response::network_error(NetworkError::CacheError);
1637            }
1638
1639            // Step 10.2 Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams,
1640            // includeCredentials, and isNewConnectionFetch.
1641            drop(cache_guard);
1642            let forward_response =
1643                http_network_fetch(http_fetch_params, include_credentials, done_chan, context)
1644                    .await;
1645
1646            let http_request = &mut http_fetch_params.request;
1647            let request_key = CacheKey::new(http_request);
1648            cache_guard = context
1649                .state
1650                .http_cache
1651                .get_or_guard(request_key.clone())
1652                .await;
1653            // Step 10.3 If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399,
1654            // inclusive, invalidate appropriate stored responses in httpCache, as per the
1655            // "Invalidating Stored Responses" chapter of HTTP Caching, and set storedResponse to null.
1656            if forward_response.status.in_range(200..=399) && !http_request.method.is_safe() {
1657                if let Some(guard) = cache_guard.try_as_mut() {
1658                    invalidate_cached_resources(guard);
1659                }
1660                context
1661                    .state
1662                    .http_cache
1663                    .invalidate_related_urls(http_request, &forward_response, &request_key)
1664                    .await;
1665            }
1666
1667            // Step 10.4 If the revalidatingFlag is set and forwardResponse’s status is 304, then:
1668            if revalidating_flag && forward_response.status == StatusCode::NOT_MODIFIED {
1669                // Ensure done_chan is None,
1670                // since the network response will be replaced by the revalidated stored one.
1671                *done_chan = None;
1672                if let Some(guard) = cache_guard.try_as_mut() {
1673                    response = refresh(http_request, forward_response.clone(), done_chan, guard);
1674                }
1675
1676                match &mut response {
1677                    Some(response) => {
1678                        response.cache_state = CacheState::Validated;
1679                    },
1680                    // The validated entry was no longer in the cache when we expected it to be.
1681                    None => {
1682                        *done_chan = None;
1683                        return Response::network_error(NetworkError::CacheError);
1684                    },
1685                }
1686            }
1687
1688            // Step 10.5 If response is null, then:
1689            if response.is_none() {
1690                // Step 10.5.1 Set response to forwardResponse.
1691                let forward_response = response.insert(forward_response);
1692
1693                // Per https://httpwg.org/specs/rfc9111.html#response.cacheability we must not cache responses
1694                // if the No-Store directive is present
1695                if http_request.cache_mode != CacheMode::NoStore {
1696                    // Step 10.5.2 Store httpRequest and forwardResponse in httpCache, as per the
1697                    //             "Storing Responses in Caches" chapter of HTTP Caching.
1698                    cache_guard.insert(http_request, forward_response);
1699                }
1700            }
1701            false
1702        } else {
1703            true
1704        }
1705    }; // Exit Critical Section on cache entry
1706
1707    if should_wait {
1708        // If the cache constructed a response, and that is still receiving from the network,
1709        // we must wait for it to finish in case it is still receiving from the network.
1710        // Note: this means only the fetch from which the original network response originated
1711        // will be able to stream it; all others receive a cached response in one chunk.
1712        wait_for_inflight_requests(done_chan, &mut response).await;
1713    }
1714
1715    let http_request = &mut http_fetch_params.request;
1716    let mut response = response.unwrap();
1717
1718    // Step 11. Set response’s URL list to a clone of httpRequest’s URL list.
1719    response.url_list = http_request
1720        .url_list
1721        .iter()
1722        .map(|claimed_url| claimed_url.url())
1723        .collect();
1724
1725    // Step 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.
1726    if http_request.headers.contains_key(RANGE) {
1727        response.range_requested = true;
1728    }
1729
1730    // Step 13. Set response’s request-includes-credentials to includeCredentials.
1731    response.request_includes_credentials = include_credentials;
1732
1733    // Step 14. If response’s status is 401, httpRequest’s response tainting is not "cors",
1734    // includeCredentials is true, and request’s window is an environment settings object, then:
1735    // TODO(#33616): Figure out what to do with request window objects
1736    // NOTE: Requiring a WWW-Authenticate header here is ad-hoc, but seems to match what other browsers are
1737    // doing. See Step 14.1.
1738    if response.status.try_code() == Some(StatusCode::UNAUTHORIZED) &&
1739        !cors_flag &&
1740        include_credentials &&
1741        response.headers.contains_key(WWW_AUTHENTICATE)
1742    {
1743        // TODO: Step 14.1 Spec says requires testing on multiple WWW-Authenticate headers
1744
1745        let request = &mut fetch_params.request;
1746
1747        // Step 14.2 If request’s body is non-null, then:
1748        // “If request’s body’s source is null, then return a network error.”
1749        if request
1750            .body
1751            .as_ref()
1752            .is_some_and(|body| body.source_is_null())
1753        {
1754            return Response::network_error(NetworkError::ConnectionFailure);
1755        }
1756
1757        // Step 14.3 If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
1758        if !request.use_url_credentials || authentication_fetch_flag {
1759            let Some(credentials) = context
1760                .state
1761                .request_authentication(request, &response)
1762                .await
1763            else {
1764                return response;
1765            };
1766
1767            if let Err(err) = request
1768                .current_url_mut()
1769                .set_username(&credentials.username)
1770            {
1771                error!("error setting username for url: {:?}", err);
1772                return response;
1773            };
1774
1775            if let Err(err) = request
1776                .current_url_mut()
1777                .set_password(Some(&credentials.password))
1778            {
1779                error!("error setting password for url: {:?}", err);
1780                return response;
1781            };
1782        }
1783
1784        // Make sure this is set to None,
1785        // since we're about to start a new `http_network_or_cache_fetch`.
1786        *done_chan = None;
1787
1788        // Step 14.4 Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.
1789        response = http_network_or_cache_fetch(
1790            fetch_params,
1791            true, /* authentication flag */
1792            cors_flag,
1793            done_chan,
1794            context,
1795        )
1796        .await;
1797    }
1798
1799    // Step 15. If response’s status is 407, then:
1800    if response.status == StatusCode::PROXY_AUTHENTICATION_REQUIRED {
1801        let request = &mut fetch_params.request;
1802        // Step 15.1 If request’s traversable for user prompts is "no-traversable", then return a network error.
1803
1804        if request.traversable_for_user_prompts == TraversableForUserPrompts::NoTraversable {
1805            return Response::network_error(NetworkError::ResourceLoadError(
1806                "Can't find Window object".into(),
1807            ));
1808        }
1809
1810        // (Step 15.2 does not exist, requires testing on Proxy-Authenticate headers)
1811
1812        // TODO(#33616): Step 15.3 If fetchParams is canceled, then return
1813        // the appropriate network error for fetchParams.
1814
1815        // Step 15.4 Prompt the end user as appropriate in request’s window
1816        // window and store the result as a proxy-authentication entry.
1817        let Some(credentials) = context
1818            .state
1819            .request_authentication(request, &response)
1820            .await
1821        else {
1822            return response;
1823        };
1824
1825        // Store the credentials as a proxy-authentication entry.
1826        let entry = AuthCacheEntry {
1827            user_name: credentials.username,
1828            password: credentials.password,
1829        };
1830        {
1831            let mut auth_cache = context.state.auth_cache.write();
1832            let key = request
1833                .current_url()
1834                .origin()
1835                .ascii_serialization()
1836                .into_owned();
1837            auth_cache.entries.insert(key, entry);
1838        }
1839
1840        // Make sure this is set to None,
1841        // since we're about to start a new `http_network_or_cache_fetch`.
1842        *done_chan = None;
1843
1844        // Step 15.5 Set response to the result of running HTTP-network-or-cache fetch given fetchParams.
1845        response = http_network_or_cache_fetch(
1846            fetch_params,
1847            false, /* authentication flag */
1848            cors_flag,
1849            done_chan,
1850            context,
1851        )
1852        .await;
1853    }
1854
1855    // TODO(#33616): Step 16. If all of the following are true:
1856    // * response’s status is 421
1857    // * isNewConnectionFetch is false
1858    // * request’s body is null, or request’s body is non-null and request’s body’s source is non-null
1859    // then: [..]
1860
1861    // Step 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given realm.
1862    if authentication_fetch_flag {
1863        // TODO(#33616)
1864    }
1865
1866    // Step 18. Return response.
1867    response
1868}
1869
1870/// If the cache is not ready to construct a response, wait.
1871///
1872/// The cache is not ready if a previous fetch checked the cache, found nothing,
1873/// and moved on to a network fetch, and hasn't updated the cache yet with a pending resource.
1874///
1875/// Note that this is a different workflow from the one involving `wait_for_cached_response`.
1876/// That one happens when a fetch gets a cache hit, and the resource is pending completion from the network.
1877#[servo_tracing::instrument(skip_all)]
1878async fn block_for_cache_ready<'a>(
1879    context: &'a FetchContext,
1880    http_request: &mut Request,
1881    done_chan: &mut DoneChannel,
1882    revalidating_flag: &mut bool,
1883    response: &mut Option<Response>,
1884) -> CachedResourcesOrGuard<'a> {
1885    let entry_key = CacheKey::new(http_request);
1886    let guard_result = context.state.http_cache.get_or_guard(entry_key).await;
1887
1888    match guard_result {
1889        CachedResourcesOrGuard::Guard(_) => {
1890            *done_chan = None;
1891        },
1892        CachedResourcesOrGuard::Value(ref cached_resources) => {
1893            // TODO(#33616): Step 8.23 Set httpCache to the result of determining the
1894            // HTTP cache partition, given httpRequest.
1895            // Step 8.25.1 Set storedResponse to the result of selecting a response from the httpCache,
1896            //              possibly needing validation, as per the "Constructing Responses from Caches"
1897            //              chapter of HTTP Caching, if any.
1898            let stored_response = construct_response(http_request, done_chan, cached_resources);
1899            // Step 8.25.2 If storedResponse is non-null, then:
1900            if let Some(response_from_cache) = stored_response {
1901                let validation_status = &response_from_cache.validation_status;
1902                let revalidation_guard = &response_from_cache.revalidation_guard;
1903
1904                // Substep 1, 2, 3, 4
1905                let (cached_response, needs_synchronous_revalidation) =
1906                    match (http_request.cache_mode, &http_request.mode) {
1907                        (CacheMode::ForceCache, _) => (Some(response_from_cache.response), false),
1908                        (CacheMode::OnlyIfCached, &RequestMode::SameOrigin) => {
1909                            (Some(response_from_cache.response), false)
1910                        },
1911                        (CacheMode::OnlyIfCached, _) |
1912                        (CacheMode::NoStore, _) |
1913                        (CacheMode::Reload, _) => (None, false),
1914                        (_, _) => (
1915                            Some(response_from_cache.response),
1916                            *validation_status ==
1917                                (ValidationStatus::Stale {
1918                                    revalidate_in_background: false,
1919                                }),
1920                        ),
1921                    };
1922
1923                if needs_synchronous_revalidation {
1924                    *revalidating_flag = true;
1925                    let response_headers = &cached_response
1926                        .as_ref()
1927                        .expect("needs_synchronous_revalidation implies a cached response")
1928                        .headers;
1929                    // Substep 5
1930                    if let Some(http_date) = response_headers.typed_get::<LastModified>() {
1931                        let http_date: SystemTime = http_date.into();
1932                        http_request
1933                            .headers
1934                            .typed_insert(IfModifiedSince::from(http_date));
1935                    }
1936                    if let Some(entity_tag) = response_headers.get(header::ETAG) {
1937                        http_request
1938                            .headers
1939                            .insert(header::IF_NONE_MATCH, entity_tag.clone());
1940                    }
1941                } else {
1942                    // Substep 6
1943                    // If it's a stale-while-revalidate response, also refresh it in the background.
1944                    let revalidate_in_background = *validation_status ==
1945                        (ValidationStatus::Stale {
1946                            revalidate_in_background: true,
1947                        });
1948                    if revalidate_in_background && cached_response.is_some() {
1949                        spawn_stale_while_revalidate(
1950                            context,
1951                            http_request,
1952                            revalidation_guard.clone(),
1953                        );
1954                    }
1955                    *response = cached_response;
1956                    if let Some(response) = response {
1957                        response.cache_state = CacheState::Local;
1958                    }
1959                }
1960                if response.is_none() {
1961                    // Ensure the done chan is not set if we're not using the cached response,
1962                    // as the cache might have set it to Some if it constructed a pending response.
1963                    *done_chan = None;
1964                }
1965            }
1966        },
1967    }
1968    guard_result
1969}
1970
1971/// The cached (stale) response has already been returned to the caller; here we
1972/// fire off an independent fetch whose only purpose is to refresh the stored response.
1973fn spawn_stale_while_revalidate(
1974    context: &FetchContext,
1975    http_request: &Request,
1976    revalidation_guard: StdArc<AtomicBool>,
1977) {
1978    // Only proceed if we are the one who flips the guard from `false` to `true`.
1979    if revalidation_guard
1980        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
1981        .is_err()
1982    {
1983        return;
1984    }
1985
1986    // By setting `CacheMode::NoCache` to the cloned request,
1987    // we ensure that the background revalidation fetch will always go to the network, and preventing an inifinite loop.
1988    let mut revalidation_request = http_request.clone();
1989    revalidation_request.cache_mode = CacheMode::NoCache;
1990
1991    // A background revalidation must not itself spin up service workers
1992    revalidation_request.service_workers_mode = ServiceWorkersMode::None;
1993
1994    let context = context.clone();
1995    debug!(
1996        "spawning stale-while-revalidate background revalidation for {:?}",
1997        revalidation_request.current_url()
1998    );
1999    spawn_task(async move {
2000        let mut target = DiscardFetch;
2001
2002        let _ = fetch(revalidation_request, &mut target, &context).await;
2003        revalidation_guard.store(false, Ordering::Release);
2004    });
2005}
2006
2007/// Wait for a cached response from channel.
2008/// Happens when a fetch gets a cache hit, and the resource is pending completion from the network.
2009async fn wait_for_inflight_requests(done_chan: &mut DoneChannel, response: &mut Option<Response>) {
2010    if let Some(ref mut ch) = *done_chan {
2011        // The cache constructed a response with a body of ResponseBody::Receiving.
2012        // We wait for the response in the cache to "finish",
2013        // with a body of either Done or Cancelled.
2014        assert!(response.is_some());
2015
2016        loop {
2017            match ch.1.recv().await {
2018                Some(Data::ContentLength(_)) | Some(Data::Payload(_)) | Some(Data::Error(_)) => {},
2019                Some(Data::Done) => break, // Return the full response as if it was initially cached as such.
2020                Some(Data::Cancelled) => {
2021                    // The response was cancelled while the fetch was ongoing.
2022                    break;
2023                },
2024                None => panic!("HTTP cache should always send Done or Cancelled"),
2025            }
2026        }
2027    }
2028    // Set done_chan back to None, it's cache-related usefulness ends here.
2029    *done_chan = None;
2030}
2031
2032/// <https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check>
2033///
2034/// This is obtained from [cross_origin_resource_policy_check]
2035#[derive(PartialEq)]
2036enum CrossOriginResourcePolicy {
2037    Allowed,
2038    Blocked,
2039}
2040
2041enum ForNavigation {
2042    #[expect(dead_code)]
2043    Yes,
2044    No,
2045}
2046
2047/// <https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check>
2048fn cross_origin_resource_policy_check(
2049    origin: &Origin,
2050    request_client: &RequestClient,
2051    response: &Response,
2052    for_navigation: ForNavigation,
2053) -> CrossOriginResourcePolicy {
2054    // Step 1. Set forNavigation to false if it is not given.
2055    //
2056    // That's the default value of the enum
2057
2058    // Step 2. Let embedderPolicy be settingsObject’s policy container’s embedder policy.
2059    let embedder_policy = &request_client.policy_container.embedder_policy;
2060
2061    // Step 3. If the cross-origin resource policy internal check with origin, "unsafe-none",
2062    // response, and forNavigation returns blocked, then return blocked.
2063    if cross_origin_resource_policy_internal_check(
2064        origin,
2065        EmbedderPolicyValue::UnsafeNone,
2066        response,
2067        &for_navigation,
2068    ) == CrossOriginResourcePolicy::Blocked
2069    {
2070        return CrossOriginResourcePolicy::Blocked;
2071    }
2072
2073    // TODO Step 4. If the cross-origin resource policy internal check with origin,
2074    // embedderPolicy’s report only value, response, and forNavigation returns blocked, then queue
2075    // a cross-origin embedder policy CORP violation report with response, settingsObject,
2076    // destination, and true.
2077
2078    // Step 5. If the cross-origin resource policy internal check with origin, embedderPolicy’s
2079    // value, response, and forNavigation returns allowed, then return allowed.
2080    if cross_origin_resource_policy_internal_check(
2081        origin,
2082        embedder_policy.value,
2083        response,
2084        &for_navigation,
2085    ) == CrossOriginResourcePolicy::Allowed
2086    {
2087        return CrossOriginResourcePolicy::Allowed;
2088    }
2089
2090    // TODO Step 6. Queue a cross-origin embedder policy CORP violation report with response,
2091    // settingsObject, destination, and false.
2092
2093    // Step 7. Return blocked.
2094    CrossOriginResourcePolicy::Blocked
2095}
2096
2097/// <https://fetch.spec.whatwg.org/#cross-origin-resource-policy-internal-check>
2098fn cross_origin_resource_policy_internal_check(
2099    origin: &Origin,
2100    embedder_policy_value: EmbedderPolicyValue,
2101    response: &Response,
2102    for_navigation: &ForNavigation,
2103) -> CrossOriginResourcePolicy {
2104    // Step 1. If forNavigation is true and embedderPolicyValue is "unsafe-none", then return allowed.
2105    if let ForNavigation::Yes = for_navigation &&
2106        let EmbedderPolicyValue::UnsafeNone = embedder_policy_value
2107    {
2108        return CrossOriginResourcePolicy::Allowed;
2109    }
2110
2111    // Step 2. Let policy be the result of getting `Cross-Origin-Resource-Policy` from response’s header list.
2112    let policy = response
2113        .headers
2114        .get(HeaderName::from_static("cross-origin-resource-policy"))
2115        .and_then(|h| h.to_str().ok());
2116
2117    // Step 3. If policy is neither `same-origin`, `same-site`, nor `cross-origin`, then set policy to null.
2118    let policy = policy
2119        .filter(|&s| s == "same-origin" || s == "same-site" || s == "cross-origin")
2120        // Step 4. If policy is null, then switch on embedderPolicyValue:
2121        .or(match embedder_policy_value {
2122            // Do nothing.
2123            EmbedderPolicyValue::UnsafeNone => None,
2124            // Set policy to `same-origin`.
2125            EmbedderPolicyValue::RequireCorp => Some("same-origin"),
2126        });
2127
2128    // Step 5. Switch on policy:
2129    match policy {
2130        Some("same-origin") => {
2131            // If origin is same origin with response’s URL’s origin, then return allowed.
2132            if let Origin::Origin(request_origin) = origin &&
2133                response
2134                    .url()
2135                    .is_some_and(|url| request_origin == &url.origin())
2136            {
2137                return CrossOriginResourcePolicy::Allowed;
2138            }
2139
2140            // Otherwise, return blocked.
2141            CrossOriginResourcePolicy::Blocked
2142        },
2143        Some("same-site") => {
2144            if let Some(response_url) = response.url() {
2145                // If all of the following are true
2146                // origin is schemelessly same site with response’s URL’s origin
2147                // origin’s scheme is "https" or response’s URL’s scheme is not "https"
2148                if let Origin::Origin(request_origin) = origin &&
2149                    is_schemelessy_same_site(request_origin, &response_url.origin()) &&
2150                    (request_origin.scheme() == Some("https") ||
2151                        response_url.scheme() != "https")
2152                {
2153                    return CrossOriginResourcePolicy::Allowed;
2154                }
2155            }
2156            // Otherwise, return blocked.
2157            CrossOriginResourcePolicy::Blocked
2158        },
2159        // null / 'cross-origin'
2160        // Return allowed.
2161        _ => CrossOriginResourcePolicy::Allowed,
2162    }
2163}
2164
2165// Convenience struct that implements Done, for setting responseEnd on function return
2166struct ResponseEndTimer(Option<ResourceFetchTimingContainer>);
2167
2168impl ResponseEndTimer {
2169    fn neuter(&mut self) {
2170        self.0 = None;
2171    }
2172}
2173
2174impl Drop for ResponseEndTimer {
2175    fn drop(&mut self) {
2176        let ResponseEndTimer(resource_fetch_timing_opt) = self;
2177
2178        resource_fetch_timing_opt.as_ref().map_or((), |t| {
2179            t.set_attribute(ResourceAttribute::ResponseEnd);
2180        })
2181    }
2182}
2183
2184/// [HTTP network fetch](https://fetch.spec.whatwg.org/#http-network-fetch)
2185#[servo_tracing::instrument(skip_all,fields(url=fetch_params.request.url().as_str()))]
2186async fn http_network_fetch(
2187    fetch_params: &mut FetchParams,
2188    credentials_flag: bool,
2189    done_chan: &mut DoneChannel,
2190    context: &FetchContext,
2191) -> Response {
2192    let mut response_end_timer = ResponseEndTimer(Some(fetch_params.timing_info.clone()));
2193
2194    // Step 1: Let request be fetchParams’s request.
2195    let request = &mut fetch_params.request;
2196
2197    // TODO Step 2. If request’s client is offline, then return a network error.
2198
2199    // TODO Step 3. Let response be null.
2200
2201    // TODO Step 4. Let timingInfo be fetchParams’s timing info.
2202
2203    // TODO Step 5. Let networkPartitionKey be the result of determining the network partition key
2204    // given request.
2205
2206    let url = request.current_url();
2207    let request_id = request.id.0;
2208    if log_enabled!(log::Level::Info) {
2209        info!("{:?} request for {}", request.method, url);
2210        for header in request.headers.iter() {
2211            debug!(" - {:?}", header);
2212        }
2213    }
2214
2215    // The receiver will receive true if there has been an error streaming the request body.
2216    let (fetch_terminated_sender, mut fetch_terminated_receiver) = unbounded_channel();
2217
2218    let body = request.body.as_ref().map(|body| body.clone_stream());
2219
2220    if body.is_none() {
2221        // There cannot be an error streaming a non-existent body.
2222        // However in such a case the channel will remain unused
2223        // and drop inside `obtain_response`.
2224        // Send the confirmation now, ensuring the receiver will not dis-connect first.
2225        let _ = fetch_terminated_sender.send(false);
2226    }
2227
2228    // Step 6. Let newConnection be "yes" if forceNewConnection is true; otherwise "no".
2229
2230    // Step 7. Switch on request’s mode:
2231    let (response_stream, msg) = match &request.mode {
2232        // Let connection be the result of obtaining a WebSocket connection, given request’s current URL.
2233        RequestMode::WebSocket {
2234            protocols,
2235            original_url: _,
2236        } => {
2237            // https://fetch.spec.whatwg.org/#websocket-opening-handshake
2238
2239            let (resource_event_sender, dom_action_receiver) = {
2240                let mut websocket_chan = context.websocket_chan.as_ref().unwrap().lock();
2241                (
2242                    websocket_chan.sender.clone(),
2243                    websocket_chan.receiver.take().unwrap(),
2244                )
2245            };
2246
2247            let mut tls_config = create_tls_config(
2248                context.ca_certificates.clone(),
2249                context.ignore_certificate_errors,
2250                context.state.override_manager.clone(),
2251            );
2252            tls_config.alpn_protocols = vec!["http/1.1".into()];
2253
2254            let response = match start_websocket(
2255                context.state.clone(),
2256                resource_event_sender,
2257                protocols,
2258                request,
2259                tls_config,
2260                dom_action_receiver,
2261            )
2262            .await
2263            {
2264                Ok(response) => response,
2265                Err(error) => {
2266                    return Response::network_error(NetworkError::WebsocketConnectionFailure(
2267                        format!("{error:?}"),
2268                    ));
2269                },
2270            };
2271
2272            let response = response.map(|r| match r {
2273                Some(body) => Full::from(body).map_err(|_| unreachable!()).boxed(),
2274                None => http_body_util::Empty::new()
2275                    .map_err(|_| unreachable!())
2276                    .boxed(),
2277            });
2278            (Decoder::detect(response, url.is_secure_scheme()), None)
2279        },
2280        // Let connection be the result of obtaining a connection, given networkPartitionKey,
2281        // request’s current URL, includeCredentials, and newConnection.
2282        _ => {
2283            let response_future = obtain_response(
2284                fetch_params,
2285                &context.state.client,
2286                &url,
2287                body,
2288                Some(&request_id),
2289                context,
2290                fetch_terminated_sender,
2291            );
2292
2293            // This will only get the headers, the body is read later
2294            let (response_stream, msg) = match response_future.await {
2295                Ok(wrapped_response) => wrapped_response,
2296                Err(error) => return Response::network_error(error),
2297            };
2298            (response_stream, msg)
2299        },
2300    };
2301
2302    let request = &mut fetch_params.request;
2303
2304    if log_enabled!(log::Level::Info) {
2305        debug!("{:?} response for {}", response_stream.version(), url);
2306        for header in response_stream.headers().iter() {
2307            debug!(" - {:?}", header);
2308        }
2309    }
2310
2311    // Check if there was an error while streaming the request body.
2312    //
2313    match fetch_terminated_receiver.recv().await {
2314        Some(true) => return Response::network_error(NetworkError::ConnectionFailure),
2315        Some(false) => {},
2316        _ => warn!("Failed to receive confirmation request was streamed without error."),
2317    }
2318
2319    let timing = fetch_params.timing_info.inner().clone();
2320    let mut response = Response::new(url.clone(), timing);
2321
2322    if let Some(handshake_info) = response_stream.extensions().get::<TlsHandshakeInfo>() {
2323        let mut hsts_enabled = url
2324            .host_str()
2325            .is_some_and(|host| context.state.hsts_list.read().is_host_secure(host));
2326
2327        if url.scheme() == "https" &&
2328            let Some(strict_transport_security) = response_stream
2329                .headers()
2330                .typed_get::<StrictTransportSecurity>()
2331        {
2332            // max-age > 0 enables HSTS, max-age = 0 disables it (RFC 6797 Section 6.1.1)
2333            hsts_enabled = strict_transport_security.max_age().as_secs() > 0;
2334        }
2335        response.tls_security_info = Some(build_tls_security_info(handshake_info, hsts_enabled));
2336    }
2337
2338    let status_text = response_stream
2339        .extensions()
2340        .get::<ReasonPhrase>()
2341        .map(ReasonPhrase::as_bytes)
2342        .or_else(|| {
2343            response_stream
2344                .status()
2345                .canonical_reason()
2346                .map(str::as_bytes)
2347        })
2348        .map(Vec::from)
2349        .unwrap_or_default();
2350    response.status = HttpStatus::new(response_stream.status(), status_text);
2351
2352    info!(
2353        "got {:?} response for {:?}",
2354        response_stream.status(),
2355        request.url()
2356    );
2357    response.headers = response_stream.headers().clone();
2358    response.referrer = request.referrer.to_url().cloned();
2359    response.referrer_policy = request.referrer_policy;
2360
2361    let response_body = response.body.clone();
2362
2363    // We're about to spawn a future to be waited on here
2364    let (done_sender, done_receiver) = unbounded_channel();
2365    *done_chan = Some((done_sender.clone(), done_receiver));
2366
2367    let cancellation_listener = context.cancellation_listener.clone();
2368    if cancellation_listener.cancelled() {
2369        return Response::network_error(NetworkError::LoadCancelled);
2370    }
2371
2372    #[cfg(feature = "devtools")]
2373    let (devtools_request, status, headers, devtools_chan) = {
2374        if let Some(ref sender) = context.devtools_chan &&
2375            let Some(msg) = msg
2376        {
2377            send_request_to_devtools(msg, sender);
2378        }
2379        (
2380            request.clone(),
2381            response.status.clone(),
2382            response.headers.clone(),
2383            context.devtools_chan.clone(),
2384        )
2385    };
2386
2387    let done_sender2 = done_sender.clone();
2388    let done_sender3 = done_sender.clone();
2389    let timing_ptr2 = fetch_params.timing_info.clone();
2390    let timing_ptr3 = fetch_params.timing_info.clone();
2391    let url1 = request.url();
2392    let url2 = url1.clone();
2393
2394    let prealloc_size: usize = if let Some(possible_length) = response_stream
2395        .headers()
2396        .get(http::header::CONTENT_LENGTH)
2397        .and_then(|header_value| header_value.to_str().ok())
2398        .and_then(|s| s.parse::<usize>().ok())
2399    {
2400        // For compressed content, we pre-allocate a multiple of the
2401        // compressed size, assuming typical content will be highly compressed.
2402        let multiplier: usize = if response_stream.body().is_encoded() {
2403            5
2404        } else {
2405            1
2406        };
2407        possible_length.saturating_mul(multiplier)
2408    } else {
2409        // We don't know the length, so we fallback to something to still
2410        // avoid some reallocs.
2411        4096
2412    }
2413    .min(pref!(network_max_content_length) as usize);
2414    let _ = done_sender.send(Data::ContentLength(prealloc_size));
2415    *response_body.lock() = ResponseBody::Receiving(Vec::with_capacity(prealloc_size));
2416    let response_body2 = response_body.clone();
2417
2418    spawn_task(
2419        response_stream
2420            .into_body()
2421            .try_fold(response_body, move |response_body_accumulator, chunk| {
2422                if cancellation_listener.cancelled() {
2423                    *response_body_accumulator.lock() = ResponseBody::Done(vec![]);
2424                    let _ = done_sender.send(Data::Cancelled);
2425                    return future::ready(Err(std::io::Error::new(
2426                        std::io::ErrorKind::Interrupted,
2427                        "Fetch aborted",
2428                    )));
2429                }
2430                if let ResponseBody::Receiving(ref mut body) = *response_body_accumulator.lock() {
2431                    body.extend_from_slice(&chunk);
2432                    let _ = done_sender.send(Data::Payload(chunk));
2433                }
2434                future::ready(Ok(response_body_accumulator))
2435            })
2436            .and_then(move |complete_response_body| {
2437                debug!("successfully finished response for {:?}", url1);
2438                let mut body = complete_response_body.lock();
2439                let mut completed_body = match *body {
2440                    ResponseBody::Receiving(ref mut body) => std::mem::take(body),
2441                    _ => vec![],
2442                };
2443                // This allocation may be retained by the http-cache.
2444                completed_body.shrink_to_fit();
2445                // If devtools is disabled avoid cloning, since the result would
2446                // be unused anyway.
2447                #[cfg(feature = "devtools")]
2448                let devtools_response_body = if devtools_chan.is_some() {
2449                    let (data, truncated, content_size) = body_for_devtools(&completed_body);
2450                    Some(DevtoolsHttpResponseBody {
2451                        data: data.into(),
2452                        truncated,
2453                        content_size,
2454                    })
2455                } else {
2456                    None
2457                };
2458                *body = ResponseBody::Done(completed_body);
2459                #[cfg(feature = "devtools")]
2460                send_response_values_to_devtools(
2461                    Some(headers),
2462                    status,
2463                    devtools_response_body,
2464                    CacheState::None,
2465                    &devtools_request,
2466                    devtools_chan,
2467                );
2468                timing_ptr2.set_attribute(ResourceAttribute::ResponseEnd);
2469                let _ = done_sender2.send(Data::Done);
2470                future::ready(Ok(()))
2471            })
2472            .map_err(move |error| {
2473                if let std::io::ErrorKind::InvalidData = error.kind() {
2474                    debug!("Content decompression error for {:?}", url2);
2475                    let _ = done_sender3.send(Data::Error(NetworkError::DecompressionError));
2476                    let mut body = response_body2.lock();
2477
2478                    *body = ResponseBody::Done(vec![]);
2479                }
2480                debug!("finished response for {:?}", url2);
2481                let mut body = response_body2.lock();
2482                let completed_body = match *body {
2483                    ResponseBody::Receiving(ref mut body) => std::mem::take(body),
2484                    _ => vec![],
2485                };
2486                *body = ResponseBody::Done(completed_body);
2487                timing_ptr3.set_attribute(ResourceAttribute::ResponseEnd);
2488                let _ = done_sender3.send(Data::Done);
2489            }),
2490    );
2491
2492    // TODO these substeps aren't possible yet
2493    // Substep 1
2494
2495    // Substep 2
2496
2497    // TODO Read request
2498
2499    // Step 6-11
2500    // (needs stream bodies)
2501
2502    // Step 13
2503    // TODO this step isn't possible yet (CSP)
2504
2505    // Step 14, update the cached response, done via the shared response body.
2506
2507    // TODO this step isn't possible yet
2508    // Step 15
2509    if credentials_flag {
2510        set_cookies_from_headers(&url, &response.headers, &context.state.cookie_jar);
2511    }
2512    context
2513        .state
2514        .hsts_list
2515        .write()
2516        .update_hsts_list_from_response(&url, &response.headers);
2517
2518    // TODO these steps
2519    // Step 16
2520    // Substep 1
2521    // Substep 2
2522    // Sub-substep 1
2523    // Sub-substep 2
2524    // Sub-substep 3
2525    // Sub-substep 4
2526    // Substep 3
2527
2528    // Step 16
2529
2530    // Ensure we don't override "responseEnd" on successful return of this function
2531    response_end_timer.neuter();
2532    response
2533}
2534
2535/// [CORS preflight fetch](https://fetch.spec.whatwg.org#cors-preflight-fetch)
2536async fn cors_preflight_fetch(request: &Request, context: &FetchContext) -> Response {
2537    // Step 1. Let preflight be a new request whose method is `OPTIONS`, URL list is a clone
2538    // of request’s URL list, initiator is request’s initiator, destination is request’s destination,
2539    // origin is request’s origin, referrer is request’s referrer, referrer policy is request’s
2540    // referrer policy, mode is "cors", and response tainting is "cors".
2541    let mut preflight = RequestBuilder::new(
2542        request.target_webview_id,
2543        request.current_url_with_blob_claim(),
2544        request.referrer.clone(),
2545    )
2546    .method(Method::OPTIONS)
2547    .origin(match &request.origin {
2548        Origin::Client => {
2549            unreachable!("We shouldn't get Client origin in cors_preflight_fetch.")
2550        },
2551        Origin::Origin(origin) => origin.clone(),
2552    })
2553    .pipeline_id(request.pipeline_id)
2554    .initiator(request.initiator)
2555    .destination(request.destination)
2556    .referrer_policy(request.referrer_policy)
2557    .mode(RequestMode::CorsMode)
2558    .response_tainting(ResponseTainting::CorsTainting)
2559    .policy_container(match &request.policy_container {
2560        RequestPolicyContainer::Client => {
2561            unreachable!("We should have a policy container for request in cors_preflight_fetch")
2562        },
2563        RequestPolicyContainer::PolicyContainer(policy_container) => policy_container.clone(),
2564    })
2565    .url_list(request.url_list.clone())
2566    .build();
2567
2568    // Step 2. Append (`Accept`, `*/*`) to preflight’s header list.
2569    preflight
2570        .headers
2571        .insert(ACCEPT, HeaderValue::from_static("*/*"));
2572
2573    // Step 3. Append (`Access-Control-Request-Method`, request’s method) to preflight’s header list.
2574    preflight
2575        .headers
2576        .typed_insert::<AccessControlRequestMethod>(AccessControlRequestMethod::from(
2577            request.method.clone(),
2578        ));
2579
2580    // Step 4. Let headers be the CORS-unsafe request-header names with request’s header list.
2581    let headers = get_cors_unsafe_header_names(&request.headers);
2582
2583    // Step 5 If headers is not empty, then:
2584    if !headers.is_empty() {
2585        // 5.1 Let value be the items in headers separated from each other by `,`
2586        // TODO(36451): replace this with typed_insert when headers fixes headers#207
2587        preflight.headers.insert(
2588            ACCESS_CONTROL_REQUEST_HEADERS,
2589            HeaderValue::from_bytes(itertools::join(headers.iter(), ",").as_bytes())
2590                .unwrap_or(HeaderValue::from_static("")),
2591        );
2592    }
2593
2594    // Step 6. Let response be the result of running HTTP-network-or-cache fetch given a
2595    // new fetch params whose request is preflight.
2596    let mut fetch_params = FetchParams::new(
2597        preflight.clone(),
2598        ResourceFetchTiming::new(ResourceTimingType::None).into(),
2599    );
2600
2601    send_early_httprequest_to_devtools(&preflight, context);
2602
2603    let response =
2604        http_network_or_cache_fetch(&mut fetch_params, false, false, &mut None, context).await;
2605
2606    send_response_to_devtools(&preflight, context, &response, None);
2607    send_security_info_to_devtools(&preflight, context, &response);
2608
2609    // Step 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
2610    if cors_check(request, &response).is_ok() && response.status.code().is_success() {
2611        // Step 7.1 Let methods be the result of extracting header list values given
2612        // `Access-Control-Allow-Methods` and response’s header list.
2613        let mut methods = if response
2614            .headers
2615            .contains_key(header::ACCESS_CONTROL_ALLOW_METHODS)
2616        {
2617            match response.headers.typed_get::<AccessControlAllowMethods>() {
2618                Some(methods) => methods.iter().collect(),
2619                // Step 7.3 If either methods or headerNames is failure, return a network error.
2620                None => {
2621                    return Response::network_error(NetworkError::CorsAllowMethods);
2622                },
2623            }
2624        } else {
2625            vec![]
2626        };
2627
2628        // Step 7.2 Let headerNames be the result of extracting header list values given
2629        // `Access-Control-Allow-Headers` and response’s header list.
2630        let header_names = if response
2631            .headers
2632            .contains_key(header::ACCESS_CONTROL_ALLOW_HEADERS)
2633        {
2634            match response.headers.typed_get::<AccessControlAllowHeaders>() {
2635                Some(names) => names.iter().collect(),
2636                // Step 7.3 If either methods or headerNames is failure, return a network error.
2637                None => {
2638                    return Response::network_error(NetworkError::CorsAllowHeaders);
2639                },
2640            }
2641        } else {
2642            vec![]
2643        };
2644
2645        debug!(
2646            "CORS check: Allowed methods: {:?}, current method: {:?}",
2647            methods, request.method
2648        );
2649
2650        // Step 7.4 If methods is null and request’s use-CORS-preflight flag is set,
2651        // then set methods to a new list containing request’s method.
2652        if methods.is_empty() && request.use_cors_preflight {
2653            methods = vec![request.method.clone()];
2654        }
2655
2656        // Step 7.5 If request’s method is not in methods, request’s method is not a CORS-safelisted method,
2657        // and request’s credentials mode is "include" or methods does not contain `*`, then return a network error.
2658        if methods
2659            .iter()
2660            .all(|method| *method.as_str() != *request.method.as_ref()) &&
2661            !is_cors_safelisted_method(&request.method) &&
2662            (request.credentials_mode == CredentialsMode::Include ||
2663                methods.iter().all(|method| method.as_ref() != "*"))
2664        {
2665            return Response::network_error(NetworkError::CorsMethod);
2666        }
2667
2668        debug!(
2669            "CORS check: Allowed headers: {:?}, current headers: {:?}",
2670            header_names, request.headers
2671        );
2672
2673        // Step 7.6 If one of request’s header list’s names is a CORS non-wildcard request-header name
2674        // and is not a byte-case-insensitive match for an item in headerNames, then return a network error.
2675        //
2676        // Note: This check deviates from the spec. Other browsers (Chrome, Firefox, Safari) all treat a
2677        // `*` in headerNames as covering CORS non-wildcard request-header names.
2678        let header_names_set: HashSet<&HeaderName> = HashSet::from_iter(header_names.iter());
2679        if request.headers.iter().any(|(name, _)| {
2680            is_cors_non_wildcard_request_header_name(name) &&
2681                !header_names_set.contains(name) &&
2682                !header_names_set.contains(&HeaderName::from_static("*"))
2683        }) {
2684            return Response::network_error(NetworkError::CorsAuthorization);
2685        }
2686
2687        // Step 7.7 For each unsafeName of the CORS-unsafe request-header names with request’s header list,
2688        // if unsafeName is not a byte-case-insensitive match for an item in headerNames and request’s credentials
2689        // mode is "include" or headerNames does not contain `*`, return a network error.
2690        let unsafe_names = get_cors_unsafe_header_names(&request.headers);
2691        for unsafe_name in unsafe_names.iter() {
2692            if !header_names_set.contains(unsafe_name) &&
2693                (request.credentials_mode == CredentialsMode::Include ||
2694                    !header_names_set.contains(&HeaderName::from_static("*")))
2695            {
2696                return Response::network_error(NetworkError::CorsHeaders);
2697            }
2698        }
2699
2700        // Step 7.8 Let max-age be the result of extracting header list values given
2701        // `Access-Control-Max-Age` and response’s header list.
2702        let max_age: Option<Duration> = response
2703            .headers
2704            .typed_get::<AccessControlMaxAge>()
2705            .map(|acma| acma.into());
2706
2707        // Step 7.9 If max-age is failure or null, then set max-age to 5.
2708        let max_age = max_age.unwrap_or(Duration::from_secs(5));
2709
2710        // Step 7.10 If max-age is greater than an imposed limit on max-age, then set max-age to the imposed limit.
2711        // TODO: Need to define what an imposed limit on max-age is
2712
2713        // Step 7.11 If the user agent does not provide for a cache, then return response.
2714        // NOTE: This can be ignored, we do have a CORS cache
2715
2716        {
2717            let mut cors_cache = context.state.cors_cache.write();
2718            // Step 7.12 For each method in methods for which there is a method cache entry match using request,
2719            // set matching entry’s max-age to max-age.
2720            // Step 7.13 For each method in methods for which there is no method cache entry match using request,
2721            // create a new cache entry with request, max-age, method, and null.
2722            for method in &methods {
2723                cors_cache.match_method_and_update(request, method, max_age);
2724            }
2725
2726            // Step 7.14 For each headerName in headerNames for which there is a header-name cache entry match using request,
2727            // set matching entry’s max-age to max-age.
2728            // Step 7.15 For each headerName in headerNames for which there is no header-name cache entry match using request,
2729            // create a new cache entry with request, max-age, null, and headerName.
2730            for header_name in &header_names {
2731                cors_cache.match_header_and_update(request, header_name, max_age);
2732            }
2733        }
2734
2735        // Step 7.16 Return response.
2736        return response;
2737    }
2738
2739    // Step 8 Return a network error.
2740    Response::network_error(NetworkError::CorsGeneral)
2741}
2742
2743/// [CORS check](https://fetch.spec.whatwg.org#concept-cors-check)
2744fn cors_check(request: &Request, response: &Response) -> Result<(), ()> {
2745    // Step 1. Let origin be the result of getting `Access-Control-Allow-Origin` from response’s header list.
2746    let Some(origins) =
2747        get_value_from_header_list(ACCESS_CONTROL_ALLOW_ORIGIN.as_str(), &response.headers)
2748    else {
2749        // Step 2. If origin is null, then return failure.
2750        return Err(());
2751    };
2752    let origin = String::from_utf8(origins).map_err(|_| ())?;
2753
2754    // Step 3. If request’s credentials mode is not "include" and origin is `*`, then return success.
2755    if request.credentials_mode != CredentialsMode::Include && origin == "*" {
2756        return Ok(());
2757    }
2758
2759    // Step 4. If the result of byte-serializing a request origin with request is not origin, then return failure.
2760    if serialize_request_origin(request).to_string() != origin {
2761        return Err(());
2762    }
2763
2764    // Step 5. If request’s credentials mode is not "include", then return success.
2765    if request.credentials_mode != CredentialsMode::Include {
2766        return Ok(());
2767    }
2768
2769    // Step 6. Let credentials be the result of getting `Access-Control-Allow-Credentials` from response’s header list.
2770    let credentials = response
2771        .headers
2772        .typed_get::<AccessControlAllowCredentials>();
2773
2774    // Step 7. If credentials is `true`, then return success.
2775    if credentials.is_some() {
2776        return Ok(());
2777    }
2778
2779    // Step 8. Return failure.
2780    Err(())
2781}
2782
2783fn has_credentials(url: &ServoUrl) -> bool {
2784    !url.username().is_empty() || url.password().is_some()
2785}
2786
2787fn is_no_store_cache(headers: &HeaderMap) -> bool {
2788    headers.contains_key(header::IF_MODIFIED_SINCE) |
2789        headers.contains_key(header::IF_NONE_MATCH) |
2790        headers.contains_key(header::IF_UNMODIFIED_SINCE) |
2791        headers.contains_key(header::IF_MATCH) |
2792        headers.contains_key(header::IF_RANGE)
2793}
2794
2795/// <https://fetch.spec.whatwg.org/#redirect-status>
2796fn is_redirect_status(status: StatusCode) -> bool {
2797    matches!(
2798        status,
2799        StatusCode::MOVED_PERMANENTLY |
2800            StatusCode::FOUND |
2801            StatusCode::SEE_OTHER |
2802            StatusCode::TEMPORARY_REDIRECT |
2803            StatusCode::PERMANENT_REDIRECT
2804    )
2805}
2806
2807/// <https://fetch.spec.whatwg.org/#serializing-a-request-origin>
2808fn serialize_request_origin(request: &Request) -> headers::Origin {
2809    // Step 1. Assert: request’s origin is not "client".
2810    let Origin::Origin(origin) = &request.origin else {
2811        panic!("origin cannot be \"client\" at this point in time");
2812    };
2813
2814    // Step 2. If request’s redirect-taint is not "same-origin", then return "null".
2815    if request.redirect_taint_for_request() != RedirectTaint::SameOrigin {
2816        return headers::Origin::NULL;
2817    }
2818
2819    // Step 3. Return request’s origin, serialized.
2820    serialize_origin(origin)
2821}
2822
2823/// Step 3 of <https://fetch.spec.whatwg.org/#serializing-a-request-origin>.
2824pub fn serialize_origin(origin: &ImmutableOrigin) -> headers::Origin {
2825    match origin {
2826        ImmutableOrigin::Opaque(_) => headers::Origin::NULL,
2827        ImmutableOrigin::Tuple(scheme, host, port) => {
2828            // Note: This must be kept in sync with `Origin::ascii_serialization()`, which does not
2829            // use the port number when a default port is used.
2830            let port = match (scheme.as_ref(), port) {
2831                ("http" | "ws", 80) | ("https" | "wss", 443) | ("ftp", 21) => None,
2832                _ => Some(*port),
2833            };
2834
2835            // TODO: Ensure that hyper/servo don't disagree about valid origin headers
2836            headers::Origin::try_from_parts(scheme, &host.to_string(), port)
2837                .unwrap_or(headers::Origin::NULL)
2838        },
2839    }
2840}
2841
2842/// <https://fetch.spec.whatwg.org/#append-a-request-origin-header>
2843#[expect(
2844    clippy::collapsible_match,
2845    reason = "The current way follows the spec more closely"
2846)]
2847fn append_a_request_origin_header(request: &mut Request) {
2848    // Step 1. Assert: request’s origin is not "client".
2849    let Origin::Origin(request_origin) = &request.origin else {
2850        panic!("origin cannot be \"client\" at this point in time");
2851    };
2852
2853    // Step 2. Let serializedOrigin be the result of byte-serializing a request origin with request.
2854    let mut serialized_origin = serialize_request_origin(request);
2855
2856    // Step 3. If request’s response tainting is "cors" or request’s mode is "websocket",
2857    //         then append (`Origin`, serializedOrigin) to request’s header list.
2858    if request.response_tainting == ResponseTainting::CorsTainting ||
2859        matches!(request.mode, RequestMode::WebSocket { .. })
2860    {
2861        request.headers.typed_insert(serialized_origin);
2862    }
2863    // Step 4. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
2864    else if !matches!(request.method, Method::GET | Method::HEAD) {
2865        // Step 4.1 If request’s mode is not "cors", then switch on request’s referrer policy:
2866        if request.mode != RequestMode::CorsMode {
2867            match request.referrer_policy {
2868                ReferrerPolicy::NoReferrer => {
2869                    // Set serializedOrigin to `null`.
2870                    serialized_origin = headers::Origin::NULL;
2871                },
2872                ReferrerPolicy::NoReferrerWhenDowngrade |
2873                ReferrerPolicy::StrictOrigin |
2874                ReferrerPolicy::StrictOriginWhenCrossOrigin => {
2875                    // If request’s origin is a tuple origin, its scheme is "https", and
2876                    // request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
2877                    if let ImmutableOrigin::Tuple(scheme, _, _) = &request_origin &&
2878                        scheme == "https" &&
2879                        request.current_url().scheme() != "https"
2880                    {
2881                        serialized_origin = headers::Origin::NULL;
2882                    }
2883                },
2884                ReferrerPolicy::SameOrigin => {
2885                    // If request’s origin is not same origin with request’s current URL’s origin,
2886                    // then set serializedOrigin to `null`.
2887                    if *request_origin != request.current_url().origin() {
2888                        serialized_origin = headers::Origin::NULL;
2889                    }
2890                },
2891                _ => {
2892                    // Otherwise, do nothing.
2893                },
2894            };
2895        }
2896
2897        // Step 4.2. Append (`Origin`, serializedOrigin) to request’s header list.
2898        request.headers.typed_insert(serialized_origin);
2899    }
2900}
2901
2902/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-append-the-fetch-metadata-headers-for-a-request>
2903fn append_the_fetch_metadata_headers(r: &mut Request) {
2904    // Step 1. If r’s current url is not an potentially trustworthy URL, return.
2905    if !r.current_url().is_potentially_trustworthy() {
2906        return;
2907    }
2908
2909    // Step 2. Set the Sec-Fetch-Dest header for r.
2910    set_the_sec_fetch_dest_header(r);
2911
2912    // Step 3. Set the Sec-Fetch-Mode header for r.
2913    set_the_sec_fetch_mode_header(r);
2914
2915    // Step 4. Set the Sec-Fetch-Site header for r.
2916    set_the_sec_fetch_site_header(r);
2917
2918    // Step 5. Set the Sec-Fetch-User header for r.
2919    set_the_sec_fetch_user_header(r);
2920}
2921
2922/// Steps 8.16 to 8.18 in [HTTP network or cache fetch](https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch)
2923fn append_cache_data_to_headers(http_request: &mut Request) {
2924    match http_request.cache_mode {
2925        // Step 8.16: If httpRequest’s cache mode is "default" and httpRequest’s header list
2926        // contains `If-Modified-Since`, `If-None-Match`, `If-Unmodified-Since`, `If-Match`, or
2927        // `If-Range`, then set httpRequest’s cache mode to "no-store".
2928        CacheMode::Default if is_no_store_cache(&http_request.headers) => {
2929            http_request.cache_mode = CacheMode::NoStore;
2930        },
2931
2932        // Note that the following steps (8.17 and 8.18) are being considered for removal:
2933        // https://github.com/whatwg/fetch/issues/722#issuecomment-1420264615
2934
2935        // Step 8.17: If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache
2936        // cache-control header modification flag is unset, and httpRequest’s header list does not
2937        // contain `Cache-Control`, then append (`Cache-Control`, `max-age=0`) to httpRequest’s
2938        // header list.
2939        // TODO: Implement request's prevent no-cache cache-control header modification flag
2940        // https://fetch.spec.whatwg.org/#no-cache-prevent-cache-control
2941        CacheMode::NoCache if !http_request.headers.contains_key(header::CACHE_CONTROL) => {
2942            http_request
2943                .headers
2944                .typed_insert(CacheControl::new().with_max_age(Duration::from_secs(0)));
2945        },
2946
2947        // Step 8.18: If httpRequest’s cache mode is "no-store" or "reload", then:
2948        CacheMode::Reload | CacheMode::NoStore => {
2949            // Step 8.18.1: If httpRequest’s header list does not contain `Pragma`, then append
2950            // (`Pragma`, `no-cache`) to httpRequest’s header list.
2951            if !http_request.headers.contains_key(header::PRAGMA) {
2952                http_request.headers.typed_insert(Pragma::no_cache());
2953            }
2954
2955            // Step 8.18.2: If httpRequest’s header list does not contain `Cache-Control`, then
2956            // append (`Cache-Control`, `no-cache`) to httpRequest’s header list.
2957            if !http_request.headers.contains_key(header::CACHE_CONTROL) {
2958                http_request
2959                    .headers
2960                    .typed_insert(CacheControl::new().with_no_cache());
2961            }
2962        },
2963
2964        _ => {},
2965    }
2966}
2967
2968/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-dest>
2969fn set_the_sec_fetch_dest_header(r: &mut Request) {
2970    // Step 1. Assert: r’s current url is a potentially trustworthy URL.
2971    debug_assert!(r.current_url().is_potentially_trustworthy());
2972
2973    // Step 2. Let header be a Structured Header whose value is a token.
2974    // Step 3. If r’s destination is the empty string, set header’s value to the string "empty".
2975    // Otherwise, set header’s value to r’s destination.
2976    let header = r.destination;
2977
2978    // Step 4. Set a structured field value `Sec-Fetch-Dest`/header in r’s header list.
2979    r.headers.typed_insert(SecFetchDest(header));
2980}
2981
2982/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-mode>
2983fn set_the_sec_fetch_mode_header(r: &mut Request) {
2984    // Step 1. Assert: r’s current url is a potentially trustworthy URL.
2985    debug_assert!(r.current_url().is_potentially_trustworthy());
2986
2987    // Step 2. Let header be a Structured Header whose value is a token.
2988    // Step 3. Set header’s value to r’s mode.
2989    let header = &r.mode;
2990
2991    // Step 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
2992    r.headers.typed_insert(SecFetchMode::from(header));
2993}
2994
2995/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-site>
2996fn set_the_sec_fetch_site_header(r: &mut Request) {
2997    // The webappsec spec seems to have a similar issue as
2998    // https://github.com/whatwg/fetch/issues/1773
2999    let Origin::Origin(request_origin) = &r.origin else {
3000        panic!("request origin cannot be \"client\" at this point")
3001    };
3002
3003    // Step 1. Assert: r’s current url is a potentially trustworthy URL.
3004    debug_assert!(r.current_url().is_potentially_trustworthy());
3005
3006    // Step 2. Let header be a Structured Header whose value is a token.
3007    // Step 3. Set header’s value to same-origin.
3008    let mut header = SecFetchSite::SameOrigin;
3009
3010    // TODO: Step 3. If r is a navigation request that was explicitly caused by a
3011    // user’s interaction with the user agent, then set header’s value to none.
3012
3013    // Step 5. If header’s value is not none, then for each url in r’s url list:
3014    if header != SecFetchSite::None {
3015        for url in &r.url_list {
3016            // Step 5.1 If url is same origin with r’s origin, continue.
3017            if url.origin() == *request_origin {
3018                continue;
3019            }
3020
3021            // Step 5.2 Set header’s value to cross-site.
3022            header = SecFetchSite::CrossSite;
3023
3024            // Step 5.3 If r’s origin is not same site with url’s origin, then break.
3025            if !is_same_site(request_origin, &url.origin()) {
3026                break;
3027            }
3028
3029            // Step 5.4 Set header’s value to same-site.
3030            header = SecFetchSite::SameSite;
3031        }
3032    }
3033
3034    // Step 6. Set a structured field value `Sec-Fetch-Site`/header in r’s header list.
3035    r.headers.typed_insert(header);
3036}
3037
3038/// <https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-user>
3039fn set_the_sec_fetch_user_header(r: &mut Request) {
3040    // Step 1. Assert: r’s current url is a potentially trustworthy URL.
3041    debug_assert!(r.current_url().is_potentially_trustworthy());
3042
3043    // Step 2. If r is not a navigation request, or if r’s user-activation is false, return.
3044    if !r.is_navigation_request() || !r.user_activation {
3045        return;
3046    }
3047
3048    // Step 3. Let header be a Structured Header whose value is a token.
3049    // Step 4. Set header’s value to true.
3050    let header = SecFetchUser;
3051
3052    // Step 5. Set a structured field value `Sec-Fetch-User`/header in r’s header list.
3053    r.headers.typed_insert(header);
3054}
3055
3056/// <https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect>
3057fn set_requests_referrer_policy_on_redirect(request: &mut Request, response: &Response) {
3058    // Step 1: Let policy be the result of executing § 8.1 Parse a referrer policy from a
3059    // Referrer-Policy header on actualResponse.
3060    let referrer_policy: ReferrerPolicy = response
3061        .headers
3062        .typed_get::<headers::ReferrerPolicy>()
3063        .into();
3064
3065    // Step 2: If policy is not the empty string, then set request’s referrer policy to policy.
3066    if referrer_policy != ReferrerPolicy::EmptyString {
3067        request.referrer_policy = referrer_policy;
3068    }
3069}