Skip to main content

strata_web_api/
fetch.rs

1//! Pure-Rust W3C fetch() Engine with Headers, AbortController, and HTTP Framing.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::io::{Cursor, Read, Write};
6use std::net::{TcpStream, ToSocketAddrs};
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::Arc;
9use std::time::Duration;
10
11use crate::tls::HttpTransportStream;
12
13/// Errors occurring during HTTP fetch requests.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum FetchError {
16    InvalidUrl(String),
17    NetworkError(String),
18    Timeout(String),
19    Aborted,
20    IoError(String),
21    SerializationError(String),
22    CorsError(String),
23}
24
25impl fmt::Display for FetchError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::InvalidUrl(s) => write!(f, "Invalid URL: {s}"),
29            Self::NetworkError(s) => write!(f, "Network error: {s}"),
30            Self::Timeout(s) => write!(f, "Request timed out: {s}"),
31            Self::Aborted => write!(f, "Request was aborted by AbortController"),
32            Self::IoError(s) => write!(f, "I/O error: {s}"),
33            Self::SerializationError(s) => write!(f, "Serialization error: {s}"),
34            Self::CorsError(s) => write!(f, "CORS error: {s}"),
35        }
36    }
37}
38
39impl std::error::Error for FetchError {}
40
41/// W3C AbortSignal signaling cancellation of asynchronous requests.
42#[derive(Clone, Default)]
43pub struct AbortSignal {
44    aborted: Arc<AtomicBool>,
45}
46
47impl AbortSignal {
48    pub fn is_aborted(&self) -> bool {
49        self.aborted.load(Ordering::SeqCst)
50    }
51}
52
53/// W3C AbortController used to cancel in-flight network requests.
54#[derive(Default)]
55pub struct AbortController {
56    signal: AbortSignal,
57}
58
59impl AbortController {
60    pub fn new() -> Self {
61        Self {
62            signal: AbortSignal::default(),
63        }
64    }
65
66    pub fn signal(&self) -> AbortSignal {
67        self.signal.clone()
68    }
69
70    pub fn abort(&self) {
71        self.signal.aborted.store(true, Ordering::SeqCst);
72    }
73}
74
75/// Case-insensitive HTTP Header map conforming to W3C Fetch spec.
76#[derive(Debug, Clone, PartialEq, Eq, Default)]
77pub struct Headers {
78    map: HashMap<String, String>,
79    all: HashMap<String, Vec<String>>,
80}
81
82impl Headers {
83    pub fn new() -> Self {
84        Self {
85            map: HashMap::new(),
86            all: HashMap::new(),
87        }
88    }
89
90    pub fn set(&mut self, key: &str, value: &str) {
91        let lower = key.to_ascii_lowercase();
92        self.map.insert(lower.clone(), value.to_string());
93        self.all.insert(lower, vec![value.to_string()]);
94    }
95
96    pub fn append(&mut self, key: &str, value: &str) {
97        let lower = key.to_ascii_lowercase();
98        if lower == "set-cookie" {
99            // Per RFC 6265 §3, Set-Cookie headers must NOT be joined with comma
100            self.map.insert(lower.clone(), value.to_string());
101        } else if let Some(existing) = self.map.get_mut(&lower) {
102            existing.push_str(", ");
103            existing.push_str(value);
104        } else {
105            self.map.insert(lower.clone(), value.to_string());
106        }
107        self.all.entry(lower).or_default().push(value.to_string());
108    }
109
110    pub fn get(&self, key: &str) -> Option<&str> {
111        self.map.get(&key.to_ascii_lowercase()).map(|s| s.as_str())
112    }
113
114    pub fn get_all(&self, key: &str) -> Vec<&str> {
115        self.all
116            .get(&key.to_ascii_lowercase())
117            .map(|vec| vec.iter().map(|s| s.as_str()).collect())
118            .unwrap_or_default()
119    }
120
121    pub fn has(&self, key: &str) -> bool {
122        self.map.contains_key(&key.to_ascii_lowercase())
123    }
124
125    pub fn delete(&mut self, key: &str) {
126        let lower = key.to_ascii_lowercase();
127        self.map.remove(&lower);
128        self.all.remove(&lower);
129    }
130
131    pub fn entries(&self) -> Vec<(&str, &str)> {
132        self.map
133            .iter()
134            .map(|(k, v)| (k.as_str(), v.as_str()))
135            .collect()
136    }
137
138    pub fn all_entries(&self) -> Vec<(&str, &str)> {
139        let mut out = Vec::new();
140        for (k, vals) in &self.all {
141            for v in vals {
142                out.push((k.as_str(), v.as_str()));
143            }
144        }
145        out
146    }
147}
148
149/// W3C Fetch request mode governing Cross-Origin Resource Sharing.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
151pub enum RequestMode {
152    #[default]
153    Cors,
154    NoCors,
155    SameOrigin,
156}
157
158/// W3C Fetch credentials mode governing cookie inclusion in cross-origin requests.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
160pub enum RequestCredentials {
161    #[default]
162    SameOrigin,
163    Include,
164    Omit,
165}
166
167/// Configuration options for an HTTP request.
168#[derive(Clone)]
169pub struct RequestInit {
170    pub method: String,
171    pub headers: Headers,
172    pub body: Option<Vec<u8>>,
173    pub timeout_ms: Option<u64>,
174    pub signal: Option<AbortSignal>,
175    pub cookie_jar: Option<Arc<std::sync::Mutex<crate::cookie::CookieJar>>>,
176    pub mode: RequestMode,
177    pub credentials: RequestCredentials,
178    pub origin: Option<String>,
179}
180
181impl Default for RequestInit {
182    fn default() -> Self {
183        Self {
184            method: "GET".to_string(),
185            headers: Headers::new(),
186            body: None,
187            timeout_ms: Some(15000),
188            signal: None,
189            cookie_jar: None,
190            mode: RequestMode::Cors,
191            credentials: RequestCredentials::SameOrigin,
192            origin: None,
193        }
194    }
195}
196
197impl RequestInit {
198    pub fn get() -> Self {
199        Self {
200            method: "GET".to_string(),
201            ..Default::default()
202        }
203    }
204
205    pub fn post() -> Self {
206        Self {
207            method: "POST".to_string(),
208            ..Default::default()
209        }
210    }
211
212    pub fn put() -> Self {
213        Self {
214            method: "PUT".to_string(),
215            ..Default::default()
216        }
217    }
218
219    pub fn delete() -> Self {
220        Self {
221            method: "DELETE".to_string(),
222            ..Default::default()
223        }
224    }
225
226    pub fn header(mut self, key: &str, val: &str) -> Self {
227        self.headers.set(key, val);
228        self
229    }
230
231    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
232        self.body = Some(body.into());
233        self
234    }
235
236    pub fn body_json_str(mut self, json_str: &str) -> Self {
237        self.headers.set("Content-Type", "application/json");
238        self.body = Some(json_str.as_bytes().to_vec());
239        self
240    }
241
242    pub fn signal(mut self, signal: AbortSignal) -> Self {
243        self.signal = Some(signal);
244        self
245    }
246
247    pub fn cookie_jar(mut self, jar: Arc<std::sync::Mutex<crate::cookie::CookieJar>>) -> Self {
248        self.cookie_jar = Some(jar);
249        self
250    }
251
252    pub fn mode(mut self, mode: RequestMode) -> Self {
253        self.mode = mode;
254        self
255    }
256
257    pub fn credentials(mut self, creds: RequestCredentials) -> Self {
258        self.credentials = creds;
259        self
260    }
261
262    pub fn origin(mut self, origin: impl Into<String>) -> Self {
263        self.origin = Some(origin.into());
264        self
265    }
266}
267
268/// HTTP Response representation.
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct Response {
271    pub status: u16,
272    pub status_text: String,
273    pub headers: Headers,
274    body: Vec<u8>,
275}
276
277impl Response {
278    pub fn new(status: u16, status_text: &str, headers: Headers, body: Vec<u8>) -> Self {
279        Self {
280            status,
281            status_text: status_text.to_string(),
282            headers,
283            body,
284        }
285    }
286
287    /// Whether HTTP status code is in the range 200..=299.
288    pub fn ok(&self) -> bool {
289        (200..=299).contains(&self.status)
290    }
291
292    /// Returns response body as UTF-8 string.
293    pub fn text(&self) -> Result<String, FetchError> {
294        String::from_utf8(self.body.clone()).map_err(|e| {
295            FetchError::SerializationError(format!("Response body is not valid UTF-8: {e}"))
296        })
297    }
298
299    /// Raw body bytes.
300    pub fn bytes(&self) -> &[u8] {
301        &self.body
302    }
303}
304
305/// Multipart form data builder.
306#[derive(Debug, Clone, Default)]
307pub struct FormData {
308    fields: Vec<(String, String)>,
309}
310
311impl FormData {
312    pub fn new() -> Self {
313        Self { fields: Vec::new() }
314    }
315
316    pub fn append(&mut self, name: &str, value: &str) {
317        self.fields.push((name.to_string(), value.to_string()));
318    }
319
320    pub fn get(&self, name: &str) -> Option<&str> {
321        self.fields
322            .iter()
323            .find(|(n, _)| n == name)
324            .map(|(_, v)| v.as_str())
325    }
326
327    /// Formats multipart form payload with boundary.
328    pub fn to_multipart_payload(&self, boundary: &str) -> Vec<u8> {
329        let mut out = Vec::new();
330        for (name, val) in &self.fields {
331            out.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
332            out.extend_from_slice(
333                format!("Content-Disposition: form-data; name=\"{name}\"\r\n\r\n").as_bytes(),
334            );
335            out.extend_from_slice(val.as_bytes());
336            out.extend_from_slice(b"\r\n");
337        }
338        out.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
339        out
340    }
341}
342
343/// Parsed URL components.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct ParsedUrl {
346    pub scheme: String,
347    pub host: String,
348    pub port: u16,
349    pub path_and_query: String,
350}
351
352impl ParsedUrl {
353    pub fn parse(url: &str) -> Result<Self, FetchError> {
354        let (scheme, rest) = if let Some(stripped) = url.strip_prefix("http://") {
355            ("http", stripped)
356        } else if let Some(stripped) = url.strip_prefix("https://") {
357            ("https", stripped)
358        } else {
359            return Err(FetchError::InvalidUrl(format!("Unsupported scheme: {url}")));
360        };
361
362        // Under RFC 3986, the authority segment terminates at the first '/', '?', or '#' (or end of string).
363        let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
364        let (host_port, path_query_frag) = rest.split_at(authority_end);
365
366        // Strip fragment (#...) from HTTP request path_and_query
367        let path_and_query_raw = match path_query_frag.split_once('#') {
368            Some((pq, _frag)) => pq,
369            None => path_query_frag,
370        };
371
372        let path = if path_and_query_raw.is_empty() {
373            "/".to_string()
374        } else if path_and_query_raw.starts_with('?') {
375            format!("/{path_and_query_raw}")
376        } else {
377            path_and_query_raw.to_string()
378        };
379
380        let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
381            let parsed_port = p
382                .parse::<u16>()
383                .map_err(|_| FetchError::InvalidUrl(format!("Invalid port: {p}")))?;
384            (h.to_string(), parsed_port)
385        } else {
386            let default_port = if scheme == "https" { 443 } else { 80 };
387            (host_port.to_string(), default_port)
388        };
389
390        if host.is_empty() {
391            return Err(FetchError::InvalidUrl(format!(
392                "Missing host in URL: {url}"
393            )));
394        }
395
396        // CWE-319 / Goal 27: Enforce strict TLS transport on HTTPS standard port 443.
397        // Cleartext transmission on port 443 is forbidden.
398        if scheme == "http" && port == 443 {
399            return Err(FetchError::InvalidUrl(format!(
400                "Cleartext transmission on HTTPS standard port 443 is forbidden (CWE-319): {url}"
401            )));
402        }
403
404        Ok(Self {
405            scheme: scheme.to_string(),
406            host,
407            port,
408            path_and_query: path,
409        })
410    }
411}
412
413/// Resolves a redirect location header against the base URL.
414pub fn resolve_redirect_url(base: &str, location: &str) -> Result<String, FetchError> {
415    let loc_trimmed = location.trim();
416    if loc_trimmed.starts_with("http://") || loc_trimmed.starts_with("https://") {
417        return Ok(loc_trimmed.to_string());
418    }
419
420    let parsed_base = ParsedUrl::parse(base)?;
421    let host_part = if (parsed_base.scheme == "http" && parsed_base.port == 80)
422        || (parsed_base.scheme == "https" && parsed_base.port == 443)
423    {
424        parsed_base.host
425    } else {
426        format!("{}:{}", parsed_base.host, parsed_base.port)
427    };
428
429    if let Some(stripped) = loc_trimmed.strip_prefix("//") {
430        return Ok(format!("{}://{stripped}", parsed_base.scheme));
431    }
432
433    if loc_trimmed.starts_with('/') {
434        return Ok(format!(
435            "{}://{}{}",
436            parsed_base.scheme, host_part, loc_trimmed
437        ));
438    }
439
440    let base_dir = match parsed_base.path_and_query.rfind('/') {
441        Some(idx) => &parsed_base.path_and_query[..=idx],
442        None => "/",
443    };
444    Ok(format!(
445        "{}://{}{}{}",
446        parsed_base.scheme, host_part, base_dir, loc_trimmed
447    ))
448}
449
450/// Computes the serialized origin (scheme + host + port) for an HTTP/HTTPS URL per RFC 6454 / W3C Fetch.
451pub fn compute_origin(url: &str) -> Result<String, FetchError> {
452    let parsed = ParsedUrl::parse(url)?;
453    let is_default_port = (parsed.scheme == "http" && parsed.port == 80)
454        || (parsed.scheme == "https" && parsed.port == 443);
455    if is_default_port {
456        Ok(format!("{}://{}", parsed.scheme, parsed.host))
457    } else {
458        Ok(format!(
459            "{}://{}:{}",
460            parsed.scheme, parsed.host, parsed.port
461        ))
462    }
463}
464
465/// Checks whether an HTTP request qualifies as a CORS-simple request under W3C Fetch spec.
466/// Returns (is_simple, list_of_custom_headers).
467pub fn is_cors_simple_request(req: &RequestInit) -> (bool, Vec<String>) {
468    let method = req.method.to_uppercase();
469    let method_simple = matches!(method.as_str(), "GET" | "HEAD" | "POST");
470    let mut custom_headers = Vec::new();
471
472    for (k, v) in req.headers.entries() {
473        let key_lower = k.to_ascii_lowercase();
474        match key_lower.as_str() {
475            "accept" | "accept-language" | "content-language" | "user-agent" | "host"
476            | "connection" | "accept-encoding" | "origin" | "content-length" => {}
477            "content-type" => {
478                let mime = v
479                    .split(';')
480                    .next()
481                    .unwrap_or("")
482                    .trim()
483                    .to_ascii_lowercase();
484                if !matches!(
485                    mime.as_str(),
486                    "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain"
487                ) {
488                    custom_headers.push(key_lower);
489                }
490            }
491            _ => {
492                custom_headers.push(key_lower);
493            }
494        }
495    }
496
497    let is_simple = method_simple && custom_headers.is_empty();
498    (is_simple, custom_headers)
499}
500
501/// Executes an HTTP or HTTPS fetch request, following standard HTTP redirects and enforcing W3C CORS rules.
502pub fn fetch(url: &str, init: Option<RequestInit>) -> Result<Response, FetchError> {
503    let req = init.unwrap_or_default();
504    let max_redirects = 5;
505    let mut current_url = url.to_string();
506    let mut current_req = req;
507
508    let client_origin = current_req
509        .origin
510        .clone()
511        .or_else(|| current_req.headers.get("origin").map(|s| s.to_string()));
512
513    let client_origin_norm = client_origin
514        .as_ref()
515        .map(|raw| compute_origin(raw).unwrap_or_else(|_| raw.trim().to_string()));
516
517    for _ in 0..max_redirects {
518        let target_origin = compute_origin(&current_url)?;
519        let is_same_origin = match &client_origin_norm {
520            Some(orig) => orig.eq_ignore_ascii_case(&target_origin),
521            None => true,
522        };
523
524        if !is_same_origin {
525            let origin_str = client_origin_norm.as_deref().unwrap_or("");
526
527            if current_req.mode == RequestMode::SameOrigin {
528                return Err(FetchError::CorsError(format!(
529                    "Cross-origin request to '{target_origin}' blocked by SameOrigin policy (origin: '{origin_str}')"
530                )));
531            }
532
533            // In NoCors mode, only simple methods and headers are permitted
534            let (is_simple, custom_headers) = is_cors_simple_request(&current_req);
535            if current_req.mode == RequestMode::NoCors && !is_simple {
536                return Err(FetchError::CorsError(
537                    "Invalid request in 'no-cors' mode: method or headers require CORS preflight"
538                        .into(),
539                ));
540            }
541
542            // Omit or SameOrigin credentials mode: strip cookie jar on cross-origin requests
543            if current_req.credentials != RequestCredentials::Include {
544                current_req.cookie_jar = None;
545                current_req.headers.delete("cookie");
546            }
547
548            // Under Cors mode, execute preflight OPTIONS check if request is not simple
549            if current_req.mode == RequestMode::Cors && !is_simple {
550                let mut preflight_headers = Headers::new();
551                preflight_headers.set("Origin", origin_str);
552                preflight_headers.set(
553                    "Access-Control-Request-Method",
554                    &current_req.method.to_uppercase(),
555                );
556                if !custom_headers.is_empty() {
557                    preflight_headers
558                        .set("Access-Control-Request-Headers", &custom_headers.join(", "));
559                }
560
561                let preflight_req = RequestInit {
562                    method: "OPTIONS".to_string(),
563                    headers: preflight_headers,
564                    body: None,
565                    timeout_ms: current_req.timeout_ms,
566                    signal: current_req.signal.clone(),
567                    cookie_jar: None,
568                    mode: RequestMode::Cors,
569                    credentials: RequestCredentials::Omit,
570                    origin: Some(origin_str.to_string()),
571                };
572
573                let preflight_resp = fetch_single(&current_url, &preflight_req)?;
574
575                if !(200..=299).contains(&preflight_resp.status) && preflight_resp.status != 204 {
576                    return Err(FetchError::CorsError(format!(
577                        "CORS preflight failed with HTTP status {}",
578                        preflight_resp.status
579                    )));
580                }
581
582                let allow_origin = preflight_resp
583                    .headers
584                    .get("access-control-allow-origin")
585                    .map(|s| s.trim())
586                    .ok_or_else(|| {
587                        FetchError::CorsError(
588                            "CORS preflight failed: missing 'Access-Control-Allow-Origin' header"
589                                .into(),
590                        )
591                    })?;
592
593                if allow_origin == "*" {
594                    if current_req.credentials == RequestCredentials::Include {
595                        return Err(FetchError::CorsError(
596                            "CORS preflight failed: 'Access-Control-Allow-Origin' cannot be wildcard '*' when credentials mode is 'Include'".into(),
597                        ));
598                    }
599                } else if !allow_origin.eq_ignore_ascii_case(origin_str) {
600                    return Err(FetchError::CorsError(format!(
601                        "CORS preflight failed: 'Access-Control-Allow-Origin' ('{allow_origin}') does not match origin '{origin_str}'"
602                    )));
603                }
604
605                if current_req.credentials == RequestCredentials::Include {
606                    let allow_creds = preflight_resp
607                        .headers
608                        .get("access-control-allow-credentials")
609                        .map(|s| s.trim());
610                    if allow_creds != Some("true") {
611                        return Err(FetchError::CorsError(
612                            "CORS preflight failed: 'Access-Control-Allow-Credentials' must be 'true'".into(),
613                        ));
614                    }
615                }
616
617                let allow_methods = preflight_resp
618                    .headers
619                    .get("access-control-allow-methods")
620                    .unwrap_or("");
621                let methods_list: Vec<&str> = allow_methods.split(',').map(|s| s.trim()).collect();
622                let req_method = current_req.method.to_uppercase();
623                if !methods_list
624                    .iter()
625                    .any(|&m| m == "*" || m.eq_ignore_ascii_case(&req_method))
626                {
627                    return Err(FetchError::CorsError(format!(
628                        "CORS preflight failed: method '{req_method}' not permitted by Access-Control-Allow-Methods ('{allow_methods}')"
629                    )));
630                }
631
632                if !custom_headers.is_empty() {
633                    let allow_headers = preflight_resp
634                        .headers
635                        .get("access-control-allow-headers")
636                        .unwrap_or("");
637                    let headers_list: Vec<&str> =
638                        allow_headers.split(',').map(|s| s.trim()).collect();
639                    let wildcard = headers_list.contains(&"*");
640                    if !wildcard {
641                        for header in &custom_headers {
642                            if !headers_list.iter().any(|&h| h.eq_ignore_ascii_case(header)) {
643                                return Err(FetchError::CorsError(format!(
644                                    "CORS preflight failed: header '{header}' not permitted by Access-Control-Allow-Headers ('{allow_headers}')"
645                                )));
646                            }
647                        }
648                    }
649                }
650            }
651
652            // Set Origin header on actual request
653            current_req.headers.set("Origin", origin_str);
654        }
655
656        let resp = fetch_single(&current_url, &current_req)?;
657
658        // If cross-origin in Cors mode, validate response CORS headers
659        if !is_same_origin && current_req.mode == RequestMode::Cors {
660            let origin_str = client_origin_norm.as_deref().unwrap_or("");
661            let allow_origin = resp
662                .headers
663                .get("access-control-allow-origin")
664                .map(|s| s.trim())
665                .ok_or_else(|| {
666                    FetchError::CorsError(format!(
667                        "CORS policy violation: missing 'Access-Control-Allow-Origin' header on response from {current_url}"
668                    ))
669                })?;
670
671            if allow_origin == "*" {
672                if current_req.credentials == RequestCredentials::Include {
673                    return Err(FetchError::CorsError(
674                        "CORS policy violation: 'Access-Control-Allow-Origin' cannot be wildcard '*' when credentials mode is 'Include'".into(),
675                    ));
676                }
677            } else if !allow_origin.eq_ignore_ascii_case(origin_str) {
678                return Err(FetchError::CorsError(format!(
679                    "CORS policy violation: Access-Control-Allow-Origin '{allow_origin}' does not match request origin '{origin_str}'"
680                )));
681            }
682
683            if current_req.credentials == RequestCredentials::Include {
684                let allow_creds = resp
685                    .headers
686                    .get("access-control-allow-credentials")
687                    .map(|s| s.trim());
688                if allow_creds != Some("true") {
689                    return Err(FetchError::CorsError(
690                        "CORS policy violation: 'Access-Control-Allow-Credentials' must be 'true' for credentialed requests".into(),
691                    ));
692                }
693            }
694        }
695
696        if (301..=303).contains(&resp.status) || resp.status == 307 || resp.status == 308 {
697            if let Some(loc) = resp.headers.get("location") {
698                let next_url = resolve_redirect_url(&current_url, loc)?;
699                let current_parsed = ParsedUrl::parse(&current_url)?;
700                let next_parsed = ParsedUrl::parse(&next_url)?;
701
702                // Disallow redirect downgrade from HTTPS to HTTP (CWE-319 / Goal 31)
703                if current_parsed.scheme == "https" && next_parsed.scheme == "http" {
704                    return Err(FetchError::NetworkError(format!(
705                        "Insecure redirect downgrade from HTTPS to HTTP rejected (CWE-319): {next_url}"
706                    )));
707                }
708
709                // Strip sensitive credentials on cross-origin redirects (RFC 9110 §15.4 / CWE-200)
710                let is_cross_origin = current_parsed.scheme != next_parsed.scheme
711                    || !current_parsed.host.eq_ignore_ascii_case(&next_parsed.host)
712                    || current_parsed.port != next_parsed.port;
713
714                if is_cross_origin {
715                    current_req.headers.delete("authorization");
716                    current_req.headers.delete("proxy-authorization");
717                    current_req.headers.delete("cookie");
718                }
719
720                current_url = next_url;
721                if resp.status == 303 || resp.status == 301 || resp.status == 302 {
722                    current_req.method = "GET".to_string();
723                    current_req.body = None;
724                }
725                continue;
726            }
727        }
728
729        return Ok(resp);
730    }
731
732    Err(FetchError::NetworkError(
733        "Too many redirects (exceeded 5 hops)".into(),
734    ))
735}
736
737/// Executes a single HTTP or HTTPS fetch request without following redirects.
738pub fn fetch_single(url: &str, req: &RequestInit) -> Result<Response, FetchError> {
739    // Check cancellation
740    if let Some(ref sig) = req.signal {
741        if sig.is_aborted() {
742            return Err(FetchError::Aborted);
743        }
744    }
745
746    let parsed = ParsedUrl::parse(url)?;
747    let timeout = Duration::from_millis(req.timeout_ms.unwrap_or(15000));
748
749    // Resolve DNS host and establish TCP connection
750    let addrs: Vec<std::net::SocketAddr> =
751        match (parsed.host.as_str(), parsed.port).to_socket_addrs() {
752            Ok(iter) => iter.collect(),
753            Err(e) => {
754                return Err(FetchError::NetworkError(format!(
755                    "DNS resolution failed for {}: {e}",
756                    parsed.host
757                )));
758            }
759        };
760
761    if addrs.is_empty() {
762        return Err(FetchError::NetworkError(format!(
763            "No IP addresses resolved for host {}",
764            parsed.host
765        )));
766    }
767
768    let mut tcp_stream_opt = None;
769    let mut last_err = None;
770
771    for addr in &addrs {
772        match TcpStream::connect_timeout(addr, timeout) {
773            Ok(s) => {
774                tcp_stream_opt = Some(s);
775                break;
776            }
777            Err(e) => {
778                last_err = Some(e);
779            }
780        }
781    }
782
783    let tcp_stream = tcp_stream_opt.ok_or_else(|| {
784        FetchError::NetworkError(format!(
785            "Connection to {}:{} failed: {}",
786            parsed.host,
787            parsed.port,
788            last_err
789                .map(|e| e.to_string())
790                .unwrap_or_else(|| "Network unreachable".into())
791        ))
792    })?;
793
794    tcp_stream
795        .set_read_timeout(Some(timeout))
796        .map_err(|e| FetchError::IoError(e.to_string()))?;
797    tcp_stream
798        .set_write_timeout(Some(timeout))
799        .map_err(|e| FetchError::IoError(e.to_string()))?;
800
801    // Transparently multiplex between Plain TCP and TLS 1.2/1.3
802    let mut transport: HttpTransportStream = if parsed.scheme == "https" {
803        crate::tls::create_tls_stream(tcp_stream, &parsed.host).map_err(FetchError::NetworkError)?
804    } else {
805        HttpTransportStream::Plain(tcp_stream)
806    };
807
808    let mut req_effective = req.clone();
809    if let Some(ref jar) = req_effective.cookie_jar {
810        if !req_effective.headers.has("cookie") {
811            if let Ok(mut jar_guard) = jar.lock() {
812                if let Some(cookie_val) = jar_guard.get_cookie_header_value(url) {
813                    req_effective.headers.set("Cookie", &cookie_val);
814                }
815            }
816        }
817    }
818
819    // If ALPN negotiated HTTP/2 ("h2"), dispatch to pure-Rust HTTP/2 client engine
820    if transport.alpn_protocol() == Some(b"h2") {
821        let resp = crate::http2::execute_http2_request(&mut transport, &req_effective, &parsed)?;
822        if let Some(ref jar) = req.cookie_jar {
823            if let Ok(mut jar_guard) = jar.lock() {
824                jar_guard.process_response_headers(&resp.headers, url);
825            }
826        }
827        return Ok(resp);
828    }
829
830    // Build HTTP/1.1 request
831    let mut request_bytes = Vec::new();
832    let method = req_effective.method.to_uppercase();
833    request_bytes
834        .extend_from_slice(format!("{method} {} HTTP/1.1\r\n", parsed.path_and_query).as_bytes());
835    request_bytes.extend_from_slice(format!("Host: {}\r\n", parsed.host).as_bytes());
836    request_bytes.extend_from_slice(b"Connection: close\r\n");
837
838    let body_len = req_effective.body.as_ref().map(|b| b.len()).unwrap_or(0);
839    if body_len > 0 {
840        request_bytes.extend_from_slice(format!("Content-Length: {body_len}\r\n").as_bytes());
841    }
842
843    if !req_effective.headers.has("Accept-Encoding") {
844        request_bytes.extend_from_slice(b"Accept-Encoding: gzip, deflate, br\r\n");
845    }
846
847    if !req_effective.headers.has("User-Agent") && !req_effective.headers.has("user-agent") {
848        request_bytes.extend_from_slice(
849            b"User-Agent: Mozilla/5.0 (compatible; Onyx/1.0; +https://strataui.org)\r\n",
850        );
851    }
852
853    for (k, v) in req_effective.headers.entries() {
854        request_bytes.extend_from_slice(format!("{k}: {v}\r\n").as_bytes());
855    }
856    request_bytes.extend_from_slice(b"\r\n");
857
858    if let Some(ref body) = req_effective.body {
859        request_bytes.extend_from_slice(body);
860    }
861
862    transport
863        .write_all(&request_bytes)
864        .map_err(|e| FetchError::NetworkError(e.to_string()))?;
865    transport
866        .flush()
867        .map_err(|e| FetchError::NetworkError(e.to_string()))?;
868
869    // Read response with RFC 7230 framing (terminates on Content-Length or chunked without waiting for EOF)
870    let resp = read_http_response(&mut transport)?;
871    if let Some(ref jar) = req.cookie_jar {
872        if let Ok(mut jar_guard) = jar.lock() {
873            jar_guard.process_response_headers(&resp.headers, url);
874        }
875    }
876    Ok(resp)
877}
878
879/// Decodes HTTP/1.1 chunked transfer encoded payloads.
880pub fn decode_chunked_body(raw_body: &[u8]) -> Result<Vec<u8>, FetchError> {
881    let mut decoded = Vec::new();
882    let mut cursor = 0;
883
884    while cursor < raw_body.len() {
885        let slice = &raw_body[cursor..];
886        let Some(newline_pos) = slice.windows(2).position(|w| w == b"\r\n") else {
887            break;
888        };
889
890        let size_str = std::str::from_utf8(&slice[..newline_pos])
891            .map_err(|e| FetchError::NetworkError(format!("Invalid chunk size encoding: {e}")))?
892            .trim();
893
894        let size_hex = size_str.split(';').next().unwrap_or(size_str).trim();
895        let chunk_size = usize::from_str_radix(size_hex, 16).map_err(|e| {
896            FetchError::NetworkError(format!("Invalid hex chunk size '{size_hex}': {e}"))
897        })?;
898
899        cursor += newline_pos + 2;
900
901        if chunk_size == 0 {
902            break;
903        }
904
905        if cursor + chunk_size > raw_body.len() {
906            return Err(FetchError::NetworkError(
907                "Truncated chunked HTTP payload".into(),
908            ));
909        }
910
911        decoded.extend_from_slice(&raw_body[cursor..cursor + chunk_size]);
912        cursor += chunk_size;
913
914        if cursor + 2 <= raw_body.len() && &raw_body[cursor..cursor + 2] == b"\r\n" {
915            cursor += 2;
916        }
917    }
918
919    Ok(decoded)
920}
921
922/// Maximum allowable HTTP header size in bytes (RFC 7230 / Slowloris DoS prevention).
923pub const MAX_HEADER_SIZE: usize = 64 * 1024; // 64 KB
924
925/// Maximum allowable HTTP response body size in bytes (128 MB).
926pub const MAX_RESPONSE_BODY_SIZE: usize = 128 * 1024 * 1024; // 128 MB
927
928/// Maximum allowable decompressed payload size in bytes (Decompression bomb protection).
929pub const MAX_DECOMPRESSED_SIZE: usize = 128 * 1024 * 1024; // 128 MB
930
931/// Decompresses body bytes based on HTTP Content-Encoding (gzip, deflate, br) with
932/// strict decompression bomb expansion limits.
933pub fn decompress_body(raw_body: &[u8], encoding: &str) -> Result<Vec<u8>, FetchError> {
934    let lower = encoding.trim().to_ascii_lowercase();
935    match lower.as_str() {
936        "gzip" => {
937            let mut decoder = flate2::read::GzDecoder::new(raw_body);
938            let mut decompressed = Vec::new();
939            let mut limited = (&mut decoder).take((MAX_DECOMPRESSED_SIZE + 1) as u64);
940            limited
941                .read_to_end(&mut decompressed)
942                .map_err(|e| FetchError::NetworkError(format!("Gzip decompression failed: {e}")))?;
943            if decompressed.len() > MAX_DECOMPRESSED_SIZE {
944                return Err(FetchError::NetworkError(format!(
945                    "Decompressed payload exceeded maximum limit of {MAX_DECOMPRESSED_SIZE} bytes (decompression bomb protection)"
946                )));
947            }
948            Ok(decompressed)
949        }
950        "deflate" => {
951            let mut decoder = flate2::read::ZlibDecoder::new(raw_body);
952            let mut decompressed = Vec::new();
953            let mut limited = (&mut decoder).take((MAX_DECOMPRESSED_SIZE + 1) as u64);
954            if limited.read_to_end(&mut decompressed).is_ok() {
955                if decompressed.len() > MAX_DECOMPRESSED_SIZE {
956                    return Err(FetchError::NetworkError(format!(
957                        "Decompressed payload exceeded maximum limit of {MAX_DECOMPRESSED_SIZE} bytes (decompression bomb protection)"
958                    )));
959                }
960                Ok(decompressed)
961            } else {
962                let mut raw_decoder = flate2::read::DeflateDecoder::new(raw_body);
963                let mut raw_decompressed = Vec::new();
964                let mut raw_limited = (&mut raw_decoder).take((MAX_DECOMPRESSED_SIZE + 1) as u64);
965                raw_limited
966                    .read_to_end(&mut raw_decompressed)
967                    .map_err(|e| {
968                        FetchError::NetworkError(format!("Deflate decompression failed: {e}"))
969                    })?;
970                if raw_decompressed.len() > MAX_DECOMPRESSED_SIZE {
971                    return Err(FetchError::NetworkError(format!(
972                        "Decompressed payload exceeded maximum limit of {MAX_DECOMPRESSED_SIZE} bytes (decompression bomb protection)"
973                    )));
974                }
975                Ok(raw_decompressed)
976            }
977        }
978        "br" | "brotli" => {
979            let mut decompressor = brotli::Decompressor::new(raw_body, 4096);
980            let mut decompressed = Vec::new();
981            let mut limited = (&mut decompressor).take((MAX_DECOMPRESSED_SIZE + 1) as u64);
982            limited.read_to_end(&mut decompressed).map_err(|e| {
983                FetchError::NetworkError(format!("Brotli decompression failed: {e:?}"))
984            })?;
985            if decompressed.len() > MAX_DECOMPRESSED_SIZE {
986                return Err(FetchError::NetworkError(format!(
987                    "Decompressed payload exceeded maximum limit of {MAX_DECOMPRESSED_SIZE} bytes (decompression bomb protection)"
988                )));
989            }
990            Ok(decompressed)
991        }
992        "identity" | "" => Ok(raw_body.to_vec()),
993        _ => Ok(raw_body.to_vec()),
994    }
995}
996
997/// Reads an HTTP/1.1 response from a synchronous byte stream, enforcing RFC 7230 framing.
998/// Terminates immediately upon reading `Content-Length` bytes or the terminal chunk `0\r\n\r\n`,
999/// preventing hangs on persistent keep-alive connections.
1000pub fn read_http_response<R: Read>(reader: &mut R) -> Result<Response, FetchError> {
1001    let mut buffer = Vec::with_capacity(4096);
1002    let mut header_end = None;
1003
1004    // 1. Read headers incrementally until \r\n\r\n with strict 64 KB limit
1005    let mut temp = [0u8; 1024];
1006    while header_end.is_none() {
1007        let n = reader
1008            .read(&mut temp)
1009            .map_err(|e| FetchError::NetworkError(e.to_string()))?;
1010        if n == 0 {
1011            break;
1012        }
1013        buffer.extend_from_slice(&temp[..n]);
1014        if buffer.len() > MAX_HEADER_SIZE {
1015            return Err(FetchError::NetworkError(format!(
1016                "HTTP header section exceeded {MAX_HEADER_SIZE} bytes limit (RFC 7230 DoS protection)"
1017            )));
1018        }
1019        header_end = buffer.windows(4).position(|w| w == b"\r\n\r\n");
1020    }
1021
1022    let Some(header_end_pos) = header_end else {
1023        return Err(FetchError::NetworkError(
1024            "Malformed HTTP response: no header delimiter".into(),
1025        ));
1026    };
1027
1028    let header_str = String::from_utf8_lossy(&buffer[..header_end_pos]);
1029    let mut lines = header_str.split("\r\n");
1030
1031    let status_line = lines
1032        .next()
1033        .ok_or_else(|| FetchError::NetworkError("Missing HTTP status line".into()))?;
1034
1035    let mut status_parts = status_line.splitn(3, ' ');
1036    let _version = status_parts.next();
1037    let status_code_str = status_parts.next().unwrap_or("0");
1038    let status_text = status_parts.next().unwrap_or("");
1039    let status_code = status_code_str.parse::<u16>().unwrap_or(0);
1040
1041    let mut headers = Headers::new();
1042    for line in lines {
1043        if let Some((k, v)) = line.split_once(':') {
1044            headers.append(k.trim(), v.trim());
1045        }
1046    }
1047
1048    // Residual bytes already read into buffer after the \r\n\r\n delimiter
1049    let initial_body = buffer[header_end_pos + 4..].to_vec();
1050
1051    // Responses to 1xx, 204 No Content, 304 Not Modified have no body per RFC 7230 §3.3.3
1052    if (100..200).contains(&status_code) || status_code == 204 || status_code == 304 {
1053        return Ok(Response::new(status_code, status_text, headers, Vec::new()));
1054    }
1055
1056    let is_chunked = headers
1057        .get("transfer-encoding")
1058        .map(|v| v.eq_ignore_ascii_case("chunked"))
1059        .unwrap_or(false);
1060
1061    let raw_body = if is_chunked {
1062        read_chunked_stream(reader, initial_body)?
1063    } else if let Some(cl_str) = headers.get("content-length") {
1064        let content_length = cl_str.trim().parse::<usize>().map_err(|e| {
1065            FetchError::NetworkError(format!("Invalid Content-Length '{cl_str}': {e}"))
1066        })?;
1067        read_fixed_length_body(reader, initial_body, content_length)?
1068    } else {
1069        // Delimited by connection closure (RFC 7230 Section 3.3.3 #7)
1070        let mut full_body = initial_body;
1071        let mut eof_buf = [0u8; 4096];
1072        loop {
1073            match reader.read(&mut eof_buf) {
1074                Ok(0) => break,
1075                Ok(n) => {
1076                    if full_body.len() + n > MAX_RESPONSE_BODY_SIZE {
1077                        return Err(FetchError::NetworkError(format!(
1078                            "Response body exceeded maximum allowable size ({MAX_RESPONSE_BODY_SIZE} bytes)"
1079                        )));
1080                    }
1081                    full_body.extend_from_slice(&eof_buf[..n]);
1082                }
1083                Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
1084                Err(e) => return Err(FetchError::NetworkError(e.to_string())),
1085            }
1086        }
1087        full_body
1088    };
1089
1090    let body = if let Some(encoding) = headers.get("content-encoding") {
1091        decompress_body(&raw_body, encoding)?
1092    } else {
1093        raw_body
1094    };
1095
1096    Ok(Response::new(status_code, status_text, headers, body))
1097}
1098
1099fn read_fixed_length_body<R: Read>(
1100    reader: &mut R,
1101    mut initial: Vec<u8>,
1102    content_length: usize,
1103) -> Result<Vec<u8>, FetchError> {
1104    if content_length > MAX_RESPONSE_BODY_SIZE {
1105        return Err(FetchError::NetworkError(format!(
1106            "Content-Length {content_length} exceeds maximum allowable body size ({MAX_RESPONSE_BODY_SIZE} bytes)"
1107        )));
1108    }
1109    if initial.len() >= content_length {
1110        initial.truncate(content_length);
1111        return Ok(initial);
1112    }
1113
1114    let remaining = content_length - initial.len();
1115    let mut temp = [0u8; 16384];
1116    let mut bytes_read = 0;
1117    while bytes_read < remaining {
1118        let to_read = (remaining - bytes_read).min(temp.len());
1119        let n = reader
1120            .read(&mut temp[..to_read])
1121            .map_err(|e| FetchError::NetworkError(format!("Error reading body: {e}")))?;
1122        if n == 0 {
1123            return Err(FetchError::NetworkError(format!(
1124                "Truncated HTTP body: expected {content_length} bytes, received {}",
1125                initial.len() + bytes_read
1126            )));
1127        }
1128        initial.extend_from_slice(&temp[..n]);
1129        bytes_read += n;
1130    }
1131    Ok(initial)
1132}
1133
1134fn read_chunked_stream<R: Read>(reader: &mut R, initial: Vec<u8>) -> Result<Vec<u8>, FetchError> {
1135    let mut decoded = Vec::new();
1136    let mut stream_buf = initial;
1137    let mut temp = [0u8; 4096];
1138
1139    loop {
1140        let newline_pos = loop {
1141            if let Some(pos) = stream_buf.windows(2).position(|w| w == b"\r\n") {
1142                break pos;
1143            }
1144            let n = reader
1145                .read(&mut temp)
1146                .map_err(|e| FetchError::NetworkError(e.to_string()))?;
1147            if n == 0 {
1148                return Err(FetchError::NetworkError(
1149                    "Unexpected EOF while reading chunk size".into(),
1150                ));
1151            }
1152            stream_buf.extend_from_slice(&temp[..n]);
1153        };
1154
1155        let size_str = std::str::from_utf8(&stream_buf[..newline_pos])
1156            .map_err(|e| FetchError::NetworkError(format!("Invalid chunk size UTF-8: {e}")))?
1157            .trim();
1158        let size_hex = size_str.split(';').next().unwrap_or(size_str).trim();
1159        let chunk_size = usize::from_str_radix(size_hex, 16).map_err(|e| {
1160            FetchError::NetworkError(format!("Invalid hex chunk size '{size_hex}': {e}"))
1161        })?;
1162
1163        stream_buf.drain(..newline_pos + 2);
1164
1165        if chunk_size == 0 {
1166            // Drain trailing CRLF / trailers
1167            while !stream_buf.starts_with(b"\r\n") {
1168                if stream_buf.is_empty() {
1169                    let n = reader
1170                        .read(&mut temp)
1171                        .map_err(|e| FetchError::NetworkError(e.to_string()))?;
1172                    if n == 0 {
1173                        break;
1174                    }
1175                    stream_buf.extend_from_slice(&temp[..n]);
1176                } else if let Some(end) = stream_buf.windows(2).position(|w| w == b"\r\n") {
1177                    stream_buf.drain(..end + 2);
1178                    break;
1179                } else {
1180                    break;
1181                }
1182            }
1183            if stream_buf.starts_with(b"\r\n") {
1184                stream_buf.drain(..2);
1185            }
1186            break;
1187        }
1188
1189        if chunk_size > MAX_RESPONSE_BODY_SIZE
1190            || decoded.len() + chunk_size > MAX_RESPONSE_BODY_SIZE
1191        {
1192            return Err(FetchError::NetworkError(format!(
1193                "Chunked response body exceeded maximum allowable size ({MAX_RESPONSE_BODY_SIZE} bytes)"
1194            )));
1195        }
1196
1197        let total_needed = chunk_size + 2;
1198        while stream_buf.len() < total_needed {
1199            let n = reader
1200                .read(&mut temp)
1201                .map_err(|e| FetchError::NetworkError(e.to_string()))?;
1202            if n == 0 {
1203                return Err(FetchError::NetworkError(
1204                    "Unexpected EOF while reading chunk payload".into(),
1205                ));
1206            }
1207            stream_buf.extend_from_slice(&temp[..n]);
1208        }
1209
1210        decoded.extend_from_slice(&stream_buf[..chunk_size]);
1211        stream_buf.drain(..total_needed);
1212    }
1213
1214    Ok(decoded)
1215}
1216
1217/// Parses raw HTTP/1.1 response bytes into a structured `Response`.
1218pub fn parse_http_response(raw: &[u8]) -> Result<Response, FetchError> {
1219    let mut cursor = Cursor::new(raw);
1220    read_http_response(&mut cursor)
1221}