Skip to main content

rust_web_server/proxy/
mod.rs

1//! Reverse proxy middleware with round-robin load balancing.
2//!
3//! `ReverseProxy` implements [`Middleware`] — wrap any application with it and
4//! all matching requests are forwarded to one of the configured backends over
5//! plain HTTP/1.1.  Failed backends are skipped and the next one is tried
6//! before returning `502 Bad Gateway`.
7//!
8//! # Example
9//!
10//! ```rust,no_run
11//! use rust_web_server::app::App;
12//! use rust_web_server::core::New;
13//! use rust_web_server::proxy::{LoadBalancing, ReverseProxy};
14//!
15//! // Proxy every request across two backends in round-robin order.
16//! let app = App::new()
17//!     .wrap(ReverseProxy::new(["http://backend-1:8080", "http://backend-2:8080"])
18//!         .strategy(LoadBalancing::RoundRobin));
19//!
20//! // Only proxy /api/* requests; everything else is handled locally.
21//! let app2 = App::new()
22//!     .wrap(ReverseProxy::new(["http://api-service:3000"])
23//!         .path_prefix("/api"));
24//! ```
25
26pub mod pool;
27pub mod status;
28#[cfg(feature = "http2")]
29pub(crate) mod async_upstream;
30#[cfg(not(target_arch = "wasm32"))]
31pub mod mirror;
32#[cfg(feature = "http2")]
33pub(crate) mod h2_upstream;
34#[cfg(feature = "http3")]
35pub(crate) mod h3_upstream;
36#[cfg(feature = "http2")]
37pub mod grpc_web;
38#[cfg(feature = "http2")]
39pub use grpc_web::GrpcWebLayer;
40
41#[cfg(test)]
42mod tests;
43
44use std::io::{Read, Write};
45use crate::ext::decimal::Decimal;
46use std::net::{TcpStream, ToSocketAddrs};
47use std::sync::atomic::{AtomicUsize, Ordering};
48use std::sync::Arc;
49use std::time::Duration;
50
51pub use pool::{ConnPool, Pool};
52
53use crate::application::Application;
54use crate::middleware::Middleware;
55use crate::request::Request;
56use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
57use crate::server::ConnectionInfo;
58
59// Hop-by-hop headers that must not be forwarded (RFC 9110 §7.6.1), plus
60// `proxy-connection` (legacy clients). Headers named in `Connection` are
61// dropped too (`connection_listed`).
62const HOP_BY_HOP: &[&str] = &[
63    "connection",
64    "keep-alive",
65    "proxy-authenticate",
66    "proxy-authorization",
67    "proxy-connection",
68    "te",
69    "trailer",
70    "transfer-encoding",
71    "upgrade",
72];
73
74/// Load balancing strategy used by [`ReverseProxy`].
75pub enum LoadBalancing {
76    /// Distribute requests across backends in a cyclic order.
77    RoundRobin,
78}
79
80/// Reverse proxy middleware.
81///
82/// Forwards incoming requests to one of the configured backends over HTTP/1.1.
83/// On connection failure the next backend in the list is tried; when all
84/// backends have failed the middleware returns `502 Bad Gateway`.
85///
86/// Hop-by-hop headers are stripped before forwarding.  `X-Forwarded-For` and
87/// `Via` are added to every forwarded request.
88///
89/// Idle connections are pooled and reused across requests (up to
90/// 64 idle per backend, 60-second timeout).
91/// This eliminates per-request TCP handshake overhead and ephemeral-port
92/// exhaustion.  Use [`ReverseProxy::with_pool`] to share a pool across
93/// multiple proxy instances or to tune pool parameters.
94pub struct ReverseProxy {
95    backends: Vec<Backend>,
96    path_prefix: Option<String>,
97    connect_timeout: Duration,
98    read_timeout: Duration,
99    counter: AtomicUsize,
100    pool: Arc<ConnPool>,
101    breaker: Option<Arc<dyn crate::circuit_breaker::Breaker>>,
102    trust: Option<Arc<UpstreamTls>>,
103    /// What `trust` was built from, so each TLS option adds to the others.
104    tls_ca: Option<String>,
105    tls_client: Option<(String, String)>,
106}
107
108impl ReverseProxy {
109    /// Create a proxy that distributes requests across `backends` in
110    /// round-robin order.  Each entry must be `"http://host:port"` or
111    /// `"host:port"` (port defaults to 80).
112    pub fn new<I, S>(backends: I) -> Self
113    where
114        I: IntoIterator<Item = S>,
115        S: AsRef<str>,
116    {
117        Self {
118            backends: backends
119                .into_iter()
120                .filter_map(|u| Backend::parse(u.as_ref()))
121                .collect(),
122            path_prefix: None,
123            connect_timeout: Duration::from_secs(5),
124            read_timeout: Duration::from_secs(30),
125            counter: AtomicUsize::new(0),
126            pool: Arc::new(ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60))),
127            breaker: None,
128            trust: None,
129            tls_ca: None,
130            tls_client: None,
131        }
132    }
133
134    /// Wire a [`crate::circuit_breaker::CircuitBreaker`] or
135    /// [`crate::circuit_breaker::RedisCircuitBreaker`] into this proxy:
136    /// before dialing a backend, its breaker state is checked (an `Open`
137    /// backend is skipped with no TCP attempt, exactly like a caller
138    /// manually checking `is_available` around each proxied call); after a
139    /// dial, `record_success`/`record_failure` is called automatically.
140    /// No breaker is wired by default — existing `ReverseProxy` callers see
141    /// no behavior change unless they opt in here.
142    ///
143    /// ```rust,no_run
144    /// use std::sync::Arc;
145    /// use rust_web_server::circuit_breaker::global as global_breaker;
146    /// use rust_web_server::proxy::ReverseProxy;
147    ///
148    /// let proxy = ReverseProxy::new(["http://backend-1:8080", "http://backend-2:8080"])
149    ///     .with_circuit_breaker(Arc::new(global_breaker()));
150    /// ```
151    pub fn with_circuit_breaker(mut self, breaker: Arc<dyn crate::circuit_breaker::Breaker>) -> Self {
152        self.breaker = Some(breaker);
153        self
154    }
155
156    /// Only proxy requests whose URI starts with `prefix`.
157    ///
158    /// Other requests are passed through to the next layer in the middleware
159    /// chain (or the inner application).
160    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
161        self.path_prefix = Some(prefix.into());
162        self
163    }
164
165    /// Override the load balancing strategy (currently only `RoundRobin`).
166    pub fn strategy(self, _strategy: LoadBalancing) -> Self {
167        self
168    }
169
170    /// Override the TCP connect timeout (default: 5 000 ms).
171    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
172        self.connect_timeout = Duration::from_millis(ms);
173        self
174    }
175
176    /// Override the response read timeout (default: 30 000 ms).
177    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
178        self.read_timeout = Duration::from_millis(ms);
179        self
180    }
181
182    /// Attach a shared connection pool.
183    ///
184    /// Useful for sharing one pool across multiple `ReverseProxy` instances
185    /// or for tuning pool parameters (capacity, idle timeout).
186    pub fn with_pool(mut self, pool: Arc<ConnPool>) -> Self {
187        self.pool = pool;
188        self
189    }
190
191    /// Trust the CA certificates in the PEM file `path` for `https://`
192    /// backends, **instead of** the public WebPKI roots — for internal
193    /// services behind a private CA or a self-signed certificate.
194    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
195        self.tls_ca = Some(path.to_string());
196        self.rebuild_trust()?;
197        Ok(self)
198    }
199
200    /// Present the client certificate in the PEM file `cert` (with its
201    /// private key in `key`) to `https://` backends that require one —
202    /// mutual TLS to the upstream. Since 18.3.0.
203    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
204        self.tls_client = Some((cert.to_string(), key.to_string()));
205        self.rebuild_trust()?;
206        Ok(self)
207    }
208
209    fn rebuild_trust(&mut self) -> Result<(), String> {
210        let client = self.tls_client.as_ref().map(|(c, k)| (c.as_str(), k.as_str()));
211        self.trust = Some(Arc::new(UpstreamTls::new(self.tls_ca.as_deref(), client)?));
212        Ok(())
213    }
214
215    /// Set the maximum number of idle connections per backend (default: 64).
216    pub fn max_idle_conns(mut self, n: usize) -> Self {
217        self.pool = Arc::new(ConnPool::new(n, Duration::from_secs(60)));
218        self
219    }
220
221    fn proxy(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
222        if self.backends.is_empty() {
223            return Err("no backends configured".to_string());
224        }
225        let n = self.backends.len();
226        let start = self.counter.fetch_add(1, Ordering::Relaxed);
227        let mut last_err = "all backends failed".to_string();
228        for attempt in 0..n {
229            let idx = (start + attempt) % n;
230            let backend = &self.backends[idx];
231            let key = format!("{}:{}", backend.host, backend.port);
232
233            if let Some(breaker) = &self.breaker {
234                if !breaker.is_available(&key) {
235                    last_err = format!("circuit open for {}", key);
236                    continue;
237                }
238            }
239
240            match self.try_backend(request, connection, backend) {
241                Ok(resp) => {
242                    if let Some(breaker) = &self.breaker {
243                        breaker.record_success(&key);
244                    }
245                    return Ok(resp);
246                }
247                Err(e) => {
248                    if let Some(breaker) = &self.breaker {
249                        breaker.record_failure(&key);
250                    }
251                    last_err = e;
252                }
253            }
254        }
255        Err(last_err)
256    }
257
258    fn try_backend(
259        &self,
260        request: &Request,
261        connection: &ConnectionInfo,
262        backend: &Backend,
263    ) -> Result<Response, String> {
264        forward_upstream_trusting(
265            &self.pool,
266            request,
267            crate::proxy::Peer::of(connection),
268            &backend.host,
269            backend.port,
270            backend.tls,
271            self.trust.as_deref(),
272            self.connect_timeout,
273            self.read_timeout,
274        )
275    }
276}
277
278impl Middleware for ReverseProxy {
279    fn handle(
280        &self,
281        request: &Request,
282        connection: &ConnectionInfo,
283        next: &dyn Application,
284    ) -> Result<Response, String> {
285        if let Some(prefix) = &self.path_prefix {
286            if !request.request_uri.starts_with(prefix.as_str()) {
287                return next.execute(request, connection);
288            }
289        }
290        match self.proxy(request, connection) {
291            Ok(mut resp) => {
292                status::received(&mut resp, None);
293                Ok(resp)
294            }
295            Err(e) => {
296                let mut resp = bad_gateway();
297                status::failed_with(&mut resp, &e, None);
298                Ok(resp)
299            }
300        }
301    }
302}
303
304// ── helpers ───────────────────────────────────────────────────────────────────
305
306/// The client as the forwarders need it: its address for `X-Forwarded-For`
307/// and whether it connected over TLS, for `X-Forwarded-Proto`.
308#[derive(Clone, Copy, Debug)]
309pub(crate) struct Peer<'a> {
310    pub ip: &'a str,
311    pub tls: bool,
312}
313
314impl<'a> Peer<'a> {
315    pub(crate) fn of(connection: &'a ConnectionInfo) -> Self {
316        Peer { ip: &connection.client.ip, tls: connection.tls }
317    }
318
319    /// A plain-HTTP client at `ip` (tests and callers without a connection).
320    pub(crate) fn plain(ip: &'a str) -> Self {
321        Peer { ip, tls: false }
322    }
323
324    pub(crate) fn proto(&self) -> &'static str {
325        if self.tls { "https" } else { "http" }
326    }
327}
328
329pub(crate) fn build_request(
330    request: &Request,
331    backend_host: &str,
332    client: Peer<'_>,
333    keep_alive: bool,
334) -> Vec<u8> {
335    // One buffer, sized up front and filled with extend_from_slice — no
336    // write!/format machinery, no lower-cased copy of each header name.
337    // `Content-Length` is regenerated from the (possibly de-chunked) body and
338    // `X-Forwarded-For` is extended below, so the client's copies are dropped:
339    // two `Content-Length` lines are a protocol error and a desync risk.
340    let connection = request.header(crate::header::Header::_CONNECTION).map(|h| h.value.as_ref());
341    // Inside a traced request the current span's `traceparent` (and the
342    // request's `baggage`) replace the client's.
343    #[cfg(not(target_arch = "wasm32"))]
344    let trace = crate::otel::propagation_headers();
345    #[cfg(target_arch = "wasm32")]
346    let trace: Option<(String, Option<String>)> = None;
347    let forwarded = |h: &&crate::header::Header| {
348        // An empty name would be sent as a malformed ": value" line.
349        !h.name.is_empty()
350            && !is_hop_by_hop_or_host(&h.name)
351            && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
352            && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
353            && !connection.is_some_and(|c| connection_listed(c, &h.name))
354            && !(trace.is_some() && (h.name.eq_ignore_ascii_case("traceparent") || h.name.eq_ignore_ascii_case("baggage")))
355    };
356    let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
357    // The Host the client asked for, unless an outer proxy already said
358    // (its X-Forwarded-Host passes through like any header).
359    // http or https, as the client connected, unless an outer proxy said.
360    let forwarded_proto = request.header("X-Forwarded-Proto").is_none().then(|| client.proto());
361    let forwarded_host = match request.header("X-Forwarded-Host") {
362        Some(_) => None,
363        None => request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()).filter(|v| !v.is_empty()),
364    };
365    let body_len = Decimal::new(request.body.len() as u128);
366    let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
367        + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
368        + client.ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
369        + forwarded_host.map_or(0, |v| v.len() + 20)
370        + forwarded_proto.map_or(0, |v| v.len() + 21)
371        + trace.as_ref().map_or(0, |(t, b)| t.len() + 15 + b.as_ref().map_or(0, |b| b.len() + 11))
372        + 13
373        + 24
374        + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
375        + 2
376        + request.body.len();
377    let mut out: Vec<u8> = Vec::with_capacity(capacity);
378    for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
379        out.extend_from_slice(part.as_bytes());
380    }
381    for h in request.headers.iter().filter(forwarded) {
382        for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
383            out.extend_from_slice(part.as_bytes());
384        }
385    }
386    out.extend_from_slice(b"X-Forwarded-For: ");
387    if let Some(prior) = prior_xff {
388        out.extend_from_slice(prior.as_bytes());
389        out.extend_from_slice(b", ");
390    }
391    for part in [client.ip, "\r\n", "Via: 1.1 rws\r\n"] {
392        out.extend_from_slice(part.as_bytes());
393    }
394    if let Some(host) = forwarded_host {
395        for part in ["X-Forwarded-Host: ", host, "\r\n"] {
396            out.extend_from_slice(part.as_bytes());
397        }
398    }
399    if let Some(proto) = forwarded_proto {
400        for part in ["X-Forwarded-Proto: ", proto, "\r\n"] {
401            out.extend_from_slice(part.as_bytes());
402        }
403    }
404    if let Some((traceparent, baggage)) = &trace {
405        for part in ["traceparent: ", traceparent, "\r\n"] {
406            out.extend_from_slice(part.as_bytes());
407        }
408        if let Some(baggage) = baggage {
409            for part in ["baggage: ", baggage, "\r\n"] {
410                out.extend_from_slice(part.as_bytes());
411            }
412        }
413    }
414    if keep_alive {
415        out.extend_from_slice(b"Connection: keep-alive\r\n");
416    } else {
417        out.extend_from_slice(b"Connection: close\r\n");
418    }
419    if !request.body.is_empty() {
420        out.extend_from_slice(b"Content-Length: ");
421        out.extend_from_slice(body_len.as_str().as_bytes());
422        out.extend_from_slice(b"\r\n");
423    }
424    out.extend_from_slice(b"\r\n");
425    out.extend_from_slice(&request.body);
426    out
427}
428
429/// Whether a request header is dropped on the way upstream: hop-by-hop
430/// headers and `Host` (rws sends its own). Matches `to_lowercase()` against
431/// the lower-case list — Unicode lower-casing, so a non-ASCII name (where
432/// e.g. the Kelvin sign lower-cases to `k`) still takes that path.
433fn is_hop_by_hop_or_host(name: &str) -> bool {
434    if name.is_ascii() {
435        name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
436    } else {
437        let lower = name.to_lowercase();
438        lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
439    }
440}
441
442/// Whether `name` is one of the comma-separated tokens of a `Connection`
443/// header value — those headers are hop-by-hop for this connection only.
444fn connection_listed(connection: &str, name: &str) -> bool {
445    connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
446}
447
448/// Decode HTTP/1.1 chunked transfer-encoding from `stream`.
449///
450/// `buf[header_end..]` may already contain some body bytes that arrived in
451/// the same read as the headers.  Returns the fully decoded body.
452fn decode_chunked<S: Read>(
453    stream: &mut S,
454    buf: &[u8],
455    header_end: usize,
456    tmp: &mut [u8],
457) -> Result<Vec<u8>, String> {
458    // Seed `raw` with any body bytes already buffered alongside the headers.
459    let mut raw: Vec<u8> = buf[header_end..].to_vec();
460    let mut decoded: Vec<u8> = Vec::new();
461
462    loop {
463        // Wait until we have at least one complete chunk-size line (ends with \r\n).
464        let crlf = loop {
465            if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
466                break p;
467            }
468            let n = stream.read(tmp).map_err(|e| e.to_string())?;
469            if n == 0 {
470                return Err("chunked: premature EOF reading chunk size".to_string());
471            }
472            raw.extend_from_slice(&tmp[..n]);
473        };
474
475        // Chunk size is hex, optionally followed by chunk-extensions (";…").
476        let size_line = std::str::from_utf8(&raw[..crlf])
477            .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
478        let size_str = size_line.split(';').next().unwrap_or("").trim();
479        let chunk_size = usize::from_str_radix(size_str, 16)
480            .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
481        raw.drain(..crlf + 2); // consume "<size>\r\n"
482
483        if chunk_size == 0 {
484            // Last chunk: skip trailer fields up to the empty line that ends
485            // the message. Leaving any of it unread would corrupt the next
486            // response on a pooled connection.
487            loop {
488                let line_end = loop {
489                    if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
490                        break p;
491                    }
492                    let n = stream.read(tmp).map_err(|e| e.to_string())?;
493                    if n == 0 {
494                        return Err("chunked: premature EOF in trailer".to_string());
495                    }
496                    raw.extend_from_slice(&tmp[..n]);
497                };
498                raw.drain(..line_end + 2);
499                if line_end == 0 {
500                    break;
501                }
502            }
503            break;
504        }
505
506        // Read chunk data + trailing CRLF.
507        while raw.len() < chunk_size + 2 {
508            let n = stream.read(tmp).map_err(|e| e.to_string())?;
509            if n == 0 {
510                return Err("chunked: premature EOF reading chunk body".to_string());
511            }
512            raw.extend_from_slice(&tmp[..n]);
513        }
514        decoded.extend_from_slice(&raw[..chunk_size]);
515        raw.drain(..chunk_size + 2); // consume "<data>\r\n"
516    }
517
518    Ok(decoded)
519}
520
521/// Rewrite `buf` in-place: strip `Transfer-Encoding`, add `Content-Length`,
522/// replace the old (undecoded) body with `decoded`.
523fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
524    let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
525    buf.clear();
526    for line in header_str.lines() {
527        if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
528            continue;
529        }
530        buf.extend_from_slice(line.as_bytes());
531        buf.extend_from_slice(b"\r\n");
532    }
533    let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
534    buf.extend_from_slice(decoded);
535}
536
537/// Headers rws regenerates for a buffered body, plus hop-by-hop headers
538/// (RFC 9110 §7.6.1) that must not be forwarded.
539pub(crate) const REGENERATED_OR_HOP_BY_HOP: &[&str] = &[
540    "content-length", "transfer-encoding", "connection", "keep-alive",
541    "proxy-connection", "te", "trailer", "upgrade",
542];
543
544/// Make a buffered upstream response safe to re-serialize. The body is
545/// already held in `content_range_list`, from which `Response::generate`
546/// (and the HTTP/2 / HTTP/3 writers) emit `Content-Type` and
547/// `Content-Length` themselves, so the upstream's own copies would be
548/// duplicated — and a duplicate `content-length` is a protocol error that
549/// HTTP/2 clients reject outright. The upstream's `Content-Type` is moved
550/// onto the body instead; the status line is re-emitted as HTTP/1.1
551/// regardless of the backend's version.
552#[cfg_attr(not(feature = "http2"), allow(dead_code))]
553pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
554    response.http_version.clear();
555    response.http_version.push_str(crate::http::VERSION.http_1_1);
556    let has_body = !response.content_range_list.is_empty();
557    if let [range] = response.content_range_list.as_mut_slice() {
558        if let Some(h) = response
559            .headers
560            .iter()
561            .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
562        {
563            range.content_type.clear();
564            range.content_type.push_str(&h.value);
565        }
566    }
567    // Compared in place (the list is lower-case ASCII), not lower-cased
568    // into a new String per header.
569    response.headers.retain(|h| {
570        if h.name.eq_ignore_ascii_case("content-type") {
571            // Keep it only when there's no body to carry it (e.g. HEAD, 304).
572            return !has_body;
573        }
574        !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
575    });
576    response
577}
578
579pub(crate) fn bad_gateway() -> Response {
580    crate::error::problem(STATUS_CODE_REASON_PHRASE.n502_bad_gateway, "")
581}
582
583// ── Streaming proxy helpers ───────────────────────────────────────────────────
584
585/// Responses larger than this threshold are streamed instead of buffered.
586const STREAM_THRESHOLD: usize = 1024 * 1024; // 1 MB
587
588/// A `Read` implementation that drains a prefix buffer before reading from the
589/// inner stream. Used to replay body bytes that arrived with the HTTP headers.
590pub(crate) struct ConcatReader<R: Read + Send> {
591    prefix: Vec<u8>,
592    prefix_pos: usize,
593    inner: R,
594}
595
596impl<R: Read + Send> ConcatReader<R> {
597    fn new(prefix: Vec<u8>, inner: R) -> Self {
598        ConcatReader { prefix, prefix_pos: 0, inner }
599    }
600}
601
602impl<R: Read + Send> Read for ConcatReader<R> {
603    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
604        if self.prefix_pos < self.prefix.len() {
605            let avail = &self.prefix[self.prefix_pos..];
606            let n = buf.len().min(avail.len());
607            buf[..n].copy_from_slice(&avail[..n]);
608            self.prefix_pos += n;
609            return Ok(n);
610        }
611        self.inner.read(buf)
612    }
613}
614
615
616/// Idle backend connections kept per `host:port`. 64 matches common nginx
617/// `keepalive` settings and the benchmark's concurrency; fewer meant most
618/// requests at 64-way concurrency still paid a TCP connect.
619pub(crate) const POOL_MAX_IDLE: usize = 64;
620
621/// The process-wide backend connection pool used by config-driven proxy
622/// routes (`proxy_config::DynamicProxy`), keyed by `host:port`.
623pub(crate) fn shared_pool() -> &'static ConnPool {
624    static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
625    POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
626}
627
628/// A backend connection the pooled forwarder drives: plain TCP, or TLS
629/// over TCP for `https://` backends.
630pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
631    fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
632}
633
634impl UpstreamIo for TcpStream {
635    fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
636        self.set_read_timeout(Some(read))?;
637        self.set_write_timeout(Some(write))
638    }
639}
640
641#[cfg(any(feature = "http-client", feature = "http2"))]
642pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
643
644#[cfg(any(feature = "http-client", feature = "http2"))]
645impl UpstreamIo for TlsStream {
646    fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
647        self.sock.set_io_timeouts(read, write)
648    }
649}
650
651/// Forward `request` to an HTTP or HTTPS backend at `host:port`, over a
652/// pooled keep-alive connection either way: plain backends use `plain_pool`,
653/// TLS backends the process-wide TLS pool (one handshake per connection, not
654/// per request). The single entry point for `ReverseProxy`, config-driven
655/// routes, `canary` and `ingress`.
656pub(crate) fn forward_upstream(
657    plain_pool: &ConnPool,
658    request: &Request,
659    client: Peer<'_>,
660    host: &str,
661    port: u16,
662    tls: bool,
663    connect_timeout: Duration,
664    read_timeout: Duration,
665) -> Result<Response, String> {
666    forward_upstream_trusting(plain_pool, request, client, host, port, tls, None, connect_timeout, read_timeout)
667}
668
669/// [`forward_upstream`] with the trust settings of one upstream: `trust`
670/// replaces the WebPKI roots for TLS backends (a private CA).
671#[allow(clippy::too_many_arguments)]
672pub(crate) fn forward_upstream_trusting(
673    plain_pool: &ConnPool,
674    request: &Request,
675    client: Peer<'_>,
676    host: &str,
677    port: u16,
678    tls: bool,
679    trust: Option<&UpstreamTls>,
680    connect_timeout: Duration,
681    read_timeout: Duration,
682) -> Result<Response, String> {
683    // Inside a traced request: a client span per forward, current while the
684    // request is built, so the upstream's `traceparent` names it.
685    #[cfg(not(target_arch = "wasm32"))]
686    let span = crate::otel::outbound_span(&request.method);
687    #[cfg(not(target_arch = "wasm32"))]
688    if let Some(span) = &span {
689        let scheme = if tls { "https" } else { "http" };
690        let path = request.request_uri.as_str();
691        for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
692            span.set_attribute(key, value);
693        }
694    }
695    let result = forward_upstream_untraced(plain_pool, request, client, host, port, tls, trust, connect_timeout, read_timeout);
696    #[cfg(not(target_arch = "wasm32"))]
697    if let Some(span) = &span {
698        span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
699    }
700    result
701}
702
703#[allow(clippy::too_many_arguments)]
704fn forward_upstream_untraced(
705    plain_pool: &ConnPool,
706    request: &Request,
707    client: Peer<'_>,
708    host: &str,
709    port: u16,
710    tls: bool,
711    trust: Option<&UpstreamTls>,
712    connect_timeout: Duration,
713    read_timeout: Duration,
714) -> Result<Response, String> {
715    if tls {
716        #[cfg(any(feature = "http-client", feature = "http2"))]
717        {
718            let (pool, config) = match trust {
719                Some(t) => (t.pool, Arc::clone(&t.config)),
720                None => (shared_tls_pool(), tls_client_config()),
721            };
722            return forward_via(pool, request, client, host, port, host, read_timeout, || {
723                connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
724            });
725        }
726        #[cfg(not(any(feature = "http-client", feature = "http2")))]
727        {
728            let _ = trust;
729            return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
730        }
731    }
732    forward_pooled(plain_pool, request, client, host, port, connect_timeout, read_timeout)
733}
734
735/// Trust settings for one upstream's TLS backends: the certificates in a CA
736/// file **instead of** the WebPKI roots — for internal services behind a
737/// private CA or a self-signed certificate (nginx's
738/// `proxy_ssl_trusted_certificate`) — and/or a client certificate rws
739/// presents to backends that require one (`proxy_ssl_certificate`, since
740/// 18.3.0). Connections are pooled per setting, so two upstreams at the same
741/// address with different trust never share one.
742pub struct UpstreamTls {
743    #[cfg(any(feature = "http-client", feature = "http2"))]
744    config: Arc<rustls::ClientConfig>,
745    #[cfg(any(feature = "http-client", feature = "http2"))]
746    pool: &'static Pool<TlsStream>,
747    /// Connections for the non-blocking forwarder, made with `config`.
748    #[cfg(feature = "http2")]
749    async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
750    /// `config` offering HTTP/2 by ALPN, for HTTP/2 and gRPC upstreams.
751    #[cfg(feature = "http2")]
752    h2_config: Arc<rustls::ClientConfig>,
753}
754
755impl UpstreamTls {
756    /// Load the PEM certificates in `path` as the only trusted roots.
757    pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
758        UpstreamTls::new(Some(path), None)
759    }
760
761    /// Trust the PEM certificates in `ca_file` (the WebPKI roots when `None`)
762    /// and, with `client_cert` = `(certificate chain PEM, private key PEM)`,
763    /// present that certificate to backends that ask for one.
764    pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
765        #[cfg(any(feature = "http-client", feature = "http2"))]
766        {
767            use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
768            let roots = match ca_file {
769                Some(path) => {
770                    let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
771                    let certs = CertificateDer::pem_slice_iter(&bytes)
772                        .collect::<Result<Vec<_>, _>>()
773                        .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
774                    if certs.is_empty() {
775                        return Err(format!("no certificates in CA file '{path}'"));
776                    }
777                    let mut roots = rustls::RootCertStore::empty();
778                    for cert in certs {
779                        roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
780                    }
781                    roots
782                }
783                None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
784            };
785            let builder = crate::tls_client_builder().with_root_certificates(roots);
786            let config = match client_cert {
787                None => builder.with_no_client_auth(),
788                Some((cert_path, key_path)) => {
789                    let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
790                    let chain = CertificateDer::pem_slice_iter(&bytes)
791                        .collect::<Result<Vec<_>, _>>()
792                        .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
793                    if chain.is_empty() {
794                        return Err(format!("no certificate in '{cert_path}'"));
795                    }
796                    let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
797                    let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
798                    builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
799                }
800            };
801            let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
802            Ok(UpstreamTls::with_config(config, &label))
803        }
804        #[cfg(not(any(feature = "http-client", feature = "http2")))]
805        {
806            let _ = client_cert;
807            Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
808        }
809    }
810
811    #[cfg(any(feature = "http-client", feature = "http2"))]
812    fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
813        #[cfg(feature = "http2")]
814        let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
815        UpstreamTls {
816            config: Arc::new(config),
817            pool: tls_pool_for_ca(label),
818            #[cfg(feature = "http2")]
819            async_pool: async_tls_pool_for_ca(label),
820            #[cfg(feature = "http2")]
821            h2_config,
822        }
823    }
824
825    /// The client configuration for HTTP/2 upstreams (ALPN `h2`).
826    #[cfg(feature = "http2")]
827    pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
828        &self.h2_config
829    }
830
831    /// Trust nothing: every TLS handshake fails, so the upstream answers 502.
832    /// Used when a configured CA file can't be loaded — failing closed rather
833    /// than falling back to the public roots.
834    pub(crate) fn reject_all(label: &str) -> UpstreamTls {
835        #[cfg(any(feature = "http-client", feature = "http2"))]
836        {
837            let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
838            UpstreamTls::with_config(config, &format!("reject-all:{label}"))
839        }
840        #[cfg(not(any(feature = "http-client", feature = "http2")))]
841        {
842            let _ = label;
843            UpstreamTls {}
844        }
845    }
846
847    /// How the non-blocking forwarder reaches these backends.
848    #[cfg(feature = "http2")]
849    pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
850        async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
851    }
852
853    /// The client configuration (for health checks).
854    #[cfg(any(feature = "http-client", feature = "http2"))]
855    pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
856        Arc::clone(&self.config)
857    }
858}
859
860/// One non-blocking connection pool per CA file, for the life of the process
861/// (a reload that keeps the same file keeps its warm connections).
862#[cfg(feature = "http2")]
863fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
864    static POOLS: std::sync::OnceLock<
865        std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
866    > = std::sync::OnceLock::new();
867    let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
868    pools
869        .entry(path.to_string())
870        .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
871}
872
873/// One pool per CA file, for the life of the process.
874#[cfg(any(feature = "http-client", feature = "http2"))]
875fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
876    static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
877        std::sync::OnceLock::new();
878    let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
879    pools
880        .entry(path.to_string())
881        .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
882}
883
884/// Forward `request` to `host:port` over plain HTTP/1.1, reusing an idle
885/// connection from `pool` when there is one and returning the connection to
886/// `pool` after a complete, reusable response.
887pub(crate) fn forward_pooled(
888    pool: &ConnPool,
889    request: &Request,
890    client: Peer<'_>,
891    host: &str,
892    port: u16,
893    connect_timeout: Duration,
894    read_timeout: Duration,
895) -> Result<Response, String> {
896    forward_via(pool, request, client, host, port, host, read_timeout, || connect_tcp(host, port, connect_timeout))
897}
898
899/// [`forward_pooled`], sending `host_header` as the `Host` (the client's, for
900/// a gateway that must preserve it) instead of the backend's address.
901#[cfg(feature = "gateway-api")]
902#[allow(clippy::too_many_arguments)]
903pub(crate) fn forward_pooled_with_host(
904    pool: &ConnPool,
905    request: &Request,
906    client: Peer<'_>,
907    host: &str,
908    port: u16,
909    host_header: &str,
910    connect_timeout: Duration,
911    read_timeout: Duration,
912) -> Result<Response, String> {
913    forward_via(pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
914}
915
916/// The pooled request/response cycle, for any connection type.
917///
918/// A backend may close an idle keep-alive connection at any moment, so a
919/// pooled connection that fails before *any* response byte arrives is
920/// retried once on a fresh connection — but only for idempotent methods
921/// (RFC 9110 §9.2.2): the request may already have reached the backend.
922#[allow(clippy::too_many_arguments)]
923fn forward_via<S: UpstreamIo>(
924    pool: &Pool<S>,
925    request: &Request,
926    client: Peer<'_>,
927    host: &str,
928    port: u16,
929    host_header: &str,
930    read_timeout: Duration,
931    connect: impl Fn() -> Result<S, String>,
932) -> Result<Response, String> {
933    let key = format!("{}:{}", host, port);
934    if let Some(stream) = pool.acquire(&key) {
935        match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
936            Exchange::Done(response) => return Ok(response),
937            Exchange::NoResponse(_) if is_idempotent(&request.method) => {} // stale: retry fresh
938            Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
939        }
940    }
941    let stream = connect()?;
942    match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
943        Exchange::Done(response) => Ok(response),
944        Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
945    }
946}
947
948/// Connect to the first address of `host:port` that accepts. `localhost`
949/// resolves to `::1` before `127.0.0.1` on many systems; a backend listening
950/// on IPv4 only must still be reachable by name.
951fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
952    let key = format!("{}:{}", host, port);
953    let addrs: Vec<_> = key
954        .to_socket_addrs()
955        .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
956        .collect();
957    let mut last_error = format!("no address resolved for {}", key);
958    for addr in addrs {
959        match TcpStream::connect_timeout(&addr, connect_timeout) {
960            Ok(stream) => {
961                let _ = stream.set_nodelay(true);
962                return Ok(stream);
963            }
964            Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
965        }
966    }
967    Err(last_error)
968}
969
970/// The process-wide pool of TLS connections to `https://` backends.
971#[cfg(any(feature = "http-client", feature = "http2"))]
972fn shared_tls_pool() -> &'static Pool<TlsStream> {
973    static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
974    POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
975}
976
977/// TLS client settings for backends: the Mozilla root store, no client
978/// certificate. Built once — parsing the root store per request was a large
979/// part of the per-request cost of HTTPS upstreams.
980#[cfg(any(feature = "http-client", feature = "http2"))]
981pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
982    static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
983    Arc::clone(CONFIG.get_or_init(|| {
984        let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
985        Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
986    }))
987}
988
989#[cfg(any(feature = "http-client", feature = "http2"))]
990fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
991    let tcp = connect_tcp(host, port, connect_timeout)?;
992    let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
993        .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
994    let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
995    Ok(rustls::StreamOwned::new(conn, tcp))
996}
997
998fn is_idempotent(method: &str) -> bool {
999    matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
1000}
1001
1002enum Exchange {
1003    Done(Response),
1004    /// Failed before any response byte (write error, or closed/errored on the first read).
1005    NoResponse(String),
1006    Failed(String),
1007}
1008
1009/// One request/response on `stream`. A fully read, keep-alive response puts
1010/// the connection back in `pool`; a streamed response keeps it until done.
1011fn exchange<S: UpstreamIo>(
1012    pool: &Pool<S>,
1013    key: &str,
1014    mut stream: S,
1015    request: &Request,
1016    host: &str,
1017    client: Peer<'_>,
1018    read_timeout: Duration,
1019) -> Exchange {
1020    if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
1021        return Exchange::Failed(e.to_string());
1022    }
1023    // keep_alive = true: ask the backend to hold the connection open.
1024    let req_bytes = build_request(request, host, client, true);
1025    if let Err(e) = stream.write_all(&req_bytes) {
1026        return Exchange::NoResponse(format!("write to backend failed: {}", e));
1027    }
1028
1029    let mut tmp = [0u8; 4096];
1030    let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
1031        Ok(head) => head,
1032        Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
1033        Err(HeadError::Partial(e)) => return Exchange::Failed(e),
1034    };
1035    let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
1036
1037    if response_has_no_body(&request.method, &header_lower) {
1038        if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
1039            pool.release(key, stream);
1040        }
1041        return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
1042            Ok(response) => Exchange::Done(response),
1043            Err(e) => Exchange::Failed(e),
1044        };
1045    }
1046
1047    if should_stream_response(&header_lower) {
1048        // Streaming path — pipe bytes straight to the client; the connection
1049        // can't be reused while the body is in flight.
1050        return match parse_status_and_headers(&header_bytes) {
1051            Ok(mut response) => {
1052                response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
1053                Exchange::Done(response)
1054            }
1055            Err(e) => Exchange::Failed(e),
1056        };
1057    }
1058    // Buffered path — read the full body, then return the connection to the pool.
1059    match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
1060        Ok((resp_bytes, reusable)) => {
1061            if reusable {
1062                pool.release(key, stream);
1063            }
1064            match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1065                Ok(response) => Exchange::Done(response),
1066                Err(e) => Exchange::Failed(e),
1067            }
1068        }
1069        Err(e) => Exchange::Failed(e),
1070    }
1071}
1072
1073/// Read exactly the HTTP response headers (up to and including `\r\n\r\n`).
1074///
1075/// Returns `(header_bytes, body_prefix)` where `body_prefix` contains any
1076/// body bytes that arrived in the same TCP segment as the headers.
1077#[cfg(test)]
1078fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1079    read_response_head(stream, tmp).map_err(|e| match e {
1080        HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1081    })
1082}
1083
1084/// Why reading a response head failed: before any byte arrived (the request
1085/// may never have been processed — e.g. a pooled connection the backend had
1086/// already closed) or part-way through.
1087enum HeadError {
1088    NothingReceived(String),
1089    Partial(String),
1090}
1091
1092fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1093    read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1094}
1095
1096/// The final response head: interim `1xx` heads (`100 Continue`,
1097/// `103 Early Hints`, …) are read past (RFC 9110 §15.2); a `103`'s `Link`
1098/// values are passed on to the client (`early_hints::forward_upstream`). Returning one as
1099/// the response left the real response in the connection, and once pooled
1100/// the next request — possibly another client's — received it.
1101fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1102    let (mut head, mut rest) = read_response_head(stream, tmp)?;
1103    let mut interim = 0;
1104    while is_interim_response(&head) {
1105        crate::early_hints::forward_upstream(&head);
1106        interim += 1;
1107        if interim > MAX_INTERIM_RESPONSES {
1108            return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1109        }
1110        (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1111    }
1112    Ok((head, rest))
1113}
1114
1115/// Read until a complete head is in `buf` (which may already hold bytes
1116/// that followed a previous head). `received` — bytes already came from this
1117/// response, so a failure is never "nothing received".
1118fn read_response_head_from<S: Read>(
1119    stream: &mut S,
1120    tmp: &mut [u8],
1121    mut buf: Vec<u8>,
1122    received: bool,
1123) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1124    loop {
1125        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1126            let body_prefix = buf[pos + 4..].to_vec();
1127            buf.truncate(pos + 4);
1128            return Ok((buf, body_prefix));
1129        }
1130        let nothing = buf.is_empty() && !received;
1131        let n = match stream.read(tmp) {
1132            Ok(n) => n,
1133            Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1134            Err(e) => return Err(HeadError::Partial(e.to_string())),
1135        };
1136        if n == 0 {
1137            let msg = "backend closed connection before headers were complete".to_string();
1138            return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1139        }
1140        buf.extend_from_slice(&tmp[..n]);
1141    }
1142}
1143
1144/// Interim responses tolerated before the final one.
1145pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1146
1147/// An interim (1xx) response head other than `101 Switching Protocols`
1148/// (which ends the HTTP exchange): the final response follows it.
1149pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1150    let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1151    let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1152    status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1153}
1154
1155/// RFC 9112 §6.3: a response to HEAD, and any 1xx, 204 or 304 response, ends
1156/// with its head — whatever `Content-Length` says (for HEAD it describes the
1157/// GET body). Waiting for that body hung until the read timeout (a 502).
1158pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1159    let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1160    method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1161}
1162
1163/// Returns `true` when the response should be streamed rather than buffered.
1164///
1165/// Streams when any of the following hold:
1166/// - `Content-Type: text/event-stream` — SSE
1167/// - `Transfer-Encoding: chunked` — AI token streams, etc.
1168/// - `Content-Length` exceeds 1 MB — large file downloads
1169pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1170    let is_sse = header_lower.lines().any(|l| {
1171        l.starts_with("content-type:") && l.contains("text/event-stream")
1172    });
1173    let is_chunked = header_lower.lines().any(|l| {
1174        l.starts_with("transfer-encoding:") && l.contains("chunked")
1175    });
1176    let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1177        l.strip_prefix("content-length:")?.trim().parse().ok()
1178    });
1179    let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1180    is_sse || is_chunked || is_large
1181}
1182
1183/// What the forwarders need from an upstream response head, found in one
1184/// case-insensitive pass over the raw bytes — the same answers as
1185/// [`response_has_no_body`], [`should_stream_response`] and the
1186/// `connection:` / `content-length:` scans over a lower-cased copy, without
1187/// making that copy.
1188#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1189pub(crate) struct HeadFacts {
1190    /// The second whitespace-separated token of the head (the status code).
1191    pub(crate) status_no_body: bool,
1192    pub(crate) sse: bool,
1193    pub(crate) chunked: bool,
1194    /// The first `content-length:` value that parses.
1195    pub(crate) content_length: Option<usize>,
1196    pub(crate) connection_close: bool,
1197}
1198
1199#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1200impl HeadFacts {
1201    pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1202        let text = std::str::from_utf8(head).unwrap_or("");
1203        let status = text.split_whitespace().nth(1).unwrap_or("");
1204        let mut facts = HeadFacts {
1205            status_no_body: status.starts_with('1') || status == "204" || status == "304",
1206            sse: false,
1207            chunked: false,
1208            content_length: None,
1209            connection_close: false,
1210        };
1211        for line in text.lines() {
1212            if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1213                facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1214            } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1215                facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1216            } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1217                if facts.content_length.is_none() {
1218                    facts.content_length = value.trim().parse().ok();
1219                }
1220            } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1221                facts.connection_close |= contains_ignore_ascii_case(value, "close");
1222            }
1223        }
1224        facts
1225    }
1226
1227    /// [`response_has_no_body`].
1228    pub(crate) fn no_body(&self, method: &str) -> bool {
1229        method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1230    }
1231
1232    /// [`should_stream_response`].
1233    pub(crate) fn should_stream(&self) -> bool {
1234        self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1235    }
1236}
1237
1238fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1239    let bytes = line.as_bytes();
1240    // `prefix` is ASCII, so a byte match ends on a char boundary.
1241    (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1242        .then(|| &line[prefix.len()..])
1243}
1244
1245fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1246    haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1247}
1248
1249/// Parse the status line and headers from raw header bytes (ending at `\r\n\r\n`).
1250fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1251    let s = std::str::from_utf8(header_bytes)
1252        .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1253    let mut lines = s.lines();
1254    let status_line = lines.next().ok_or("empty backend response")?;
1255    let mut parts = status_line.splitn(3, ' ');
1256    let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1257    let status_code: i16 = parts
1258        .next()
1259        .unwrap_or("502")
1260        .parse()
1261        .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1262    let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1263    let mut headers = Vec::new();
1264    for line in lines {
1265        let line = line.trim_end_matches('\r');
1266        if line.is_empty() { break; }
1267        if let Some(colon) = line.find(':') {
1268            headers.push(crate::header::Header {
1269                name: line[..colon].trim().to_string().into(),
1270                value: (line[colon + 1..].trim().to_string()).into(),
1271            });
1272        }
1273    }
1274    Ok(Response {
1275        http_version,
1276        status_code,
1277        reason_phrase,
1278        headers,
1279        content_range_list: vec![],
1280        stream_file: None,
1281        stream_pipe: None,
1282        trailers: None,
1283    })
1284}
1285
1286/// Read the remaining body after headers have already been read.
1287///
1288/// `header_bytes` ends with `\r\n\r\n`; `body_prefix` holds any body bytes
1289/// that arrived in the same TCP read.  Handles all three body mechanisms
1290/// (chunked, content-length, read-to-EOF).  Returns `(full_response_bytes, can_reuse)`.
1291fn read_response_from_partial<S: Read>(
1292    stream: &mut S,
1293    header_bytes: Vec<u8>,
1294    body_prefix: Vec<u8>,
1295    tmp: &mut [u8],
1296) -> Result<(Vec<u8>, bool), String> {
1297    let header_end = header_bytes.len();
1298    let mut buf = header_bytes;
1299    buf.extend_from_slice(&body_prefix);
1300
1301    let header_lower =
1302        std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1303    let connection_close =
1304        header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1305    let is_chunked = header_lower
1306        .lines()
1307        .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1308    let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1309        l.strip_prefix("content-length:")?.trim().parse().ok()
1310    });
1311
1312    if is_chunked {
1313        let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1314        rewrite_as_content_length(&mut buf, header_end, &decoded);
1315        Ok((buf, !connection_close))
1316    } else if let Some(len) = content_length {
1317        while buf.len() < header_end + len {
1318            let n = stream.read(tmp).map_err(|e| e.to_string())?;
1319            if n == 0 { break; }
1320            buf.extend_from_slice(&tmp[..n]);
1321        }
1322        Ok((buf, !connection_close))
1323    } else {
1324        loop {
1325            let n = stream.read(tmp).map_err(|e| e.to_string())?;
1326            if n == 0 { break; }
1327            buf.extend_from_slice(&tmp[..n]);
1328        }
1329        Ok((buf, false))
1330    }
1331}
1332
1333// ── Backend URL parsing ───────────────────────────────────────────────────────
1334
1335struct Backend {
1336    host: String,
1337    port: u16,
1338    /// Whether the upstream connection should use TLS.
1339    /// Set when the URL scheme is `https://`, `h2s://`, or `grpcs://`.
1340    tls: bool,
1341}
1342
1343impl Backend {
1344    fn parse(url: &str) -> Option<Self> {
1345        let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1346            (r, true, 443u16)
1347        } else if let Some(r) = url.strip_prefix("h2s://") {
1348            (r, true, 443u16)
1349        } else if let Some(r) = url.strip_prefix("grpcs://") {
1350            (r, true, 443u16)
1351        } else if let Some(r) = url.strip_prefix("http://") {
1352            (r, false, 80u16)
1353        } else if let Some(r) = url.strip_prefix("h2://") {
1354            (r, false, 80u16)
1355        } else if let Some(r) = url.strip_prefix("grpc://") {
1356            (r, false, 80u16)
1357        } else {
1358            (url, false, 80u16)
1359        };
1360        // Drop any path component.
1361        let host_port = rest.split('/').next().unwrap_or(rest);
1362        let (host, port) = if let Some(colon) = host_port.rfind(':') {
1363            let port_str = &host_port[colon + 1..];
1364            if let Ok(p) = port_str.parse::<u16>() {
1365                (host_port[..colon].to_string(), p)
1366            } else {
1367                (host_port.to_string(), default_port)
1368            }
1369        } else {
1370            (host_port.to_string(), default_port)
1371        };
1372        if host.is_empty() {
1373            return None;
1374        }
1375        Some(Backend { host, port, tls })
1376    }
1377}
1378
1379// ── HTTP/2 reverse proxy ──────────────────────────────────────────────────────
1380
1381/// Reverse proxy that forwards requests to HTTP/2 backends.
1382///
1383/// Wraps [`ReverseProxy`] and forces HTTP/2 (`h2`) for all upstream connections.
1384/// Requires the `http2` Cargo feature.
1385///
1386/// This proxy also transparently handles gRPC traffic
1387/// (`Content-Type: application/grpc*`) — gRPC DATA frames are forwarded
1388/// as-is because gRPC is layered directly on HTTP/2.
1389#[cfg(feature = "http2")]
1390pub struct H2ReverseProxy {
1391    inner: ReverseProxy,
1392}
1393
1394#[cfg(feature = "http2")]
1395impl H2ReverseProxy {
1396    /// Create a proxy distributing requests across `backends` in round-robin order.
1397    ///
1398    /// Each backend entry can be:
1399    /// - `"host:port"` — plain TCP (HTTP/2 cleartext)
1400    /// - `"h2://host:port"` — plain TCP (explicit scheme)
1401    /// - `"h2s://host:port"` — TLS (HTTP/2 over HTTPS; port defaults to 443)
1402    /// - `"https://host:port"` — TLS (same as `h2s://`)
1403    ///
1404    /// TLS backends require the `http2` Cargo feature (includes `rustls` +
1405    /// `webpki-roots`).  Certificate verification uses the WebPKI trust store.
1406    pub fn new<I, S>(backends: I) -> Self
1407    where
1408        I: IntoIterator<Item = S>,
1409        S: AsRef<str>,
1410    {
1411        H2ReverseProxy {
1412            inner: ReverseProxy::new(backends),
1413        }
1414    }
1415
1416    /// Only proxy requests whose URI starts with `prefix`; pass others through.
1417    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1418        self.inner = self.inner.path_prefix(prefix);
1419        self
1420    }
1421
1422    /// Override the TCP connect timeout (default: 5 s).
1423    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1424        self.inner = self.inner.connect_timeout_ms(ms);
1425        self
1426    }
1427
1428    /// Override the read timeout (default: 30 s). It bounds each wait for
1429    /// the upstream — the handshake, the response head, every body frame — so
1430    /// a streaming response (a gRPC server stream) ends only when it goes
1431    /// quiet for that long.
1432    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1433        self.inner = self.inner.read_timeout_ms(ms);
1434        self
1435    }
1436
1437    /// Trust the CA certificates in the PEM file `path` for `h2s://` /
1438    /// `https://` backends instead of the WebPKI roots. Since 18.3.0.
1439    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1440        self.inner = self.inner.tls_ca_file(path)?;
1441        Ok(self)
1442    }
1443
1444    /// Present a client certificate to TLS backends that require one (mutual
1445    /// TLS). Since 18.3.0.
1446    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1447        self.inner = self.inner.tls_client_cert(cert, key)?;
1448        Ok(self)
1449    }
1450
1451    fn matches(&self, request: &Request) -> bool {
1452        self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1453    }
1454}
1455
1456#[cfg(feature = "http2")]
1457impl crate::middleware::Middleware for H2ReverseProxy {
1458    fn handle(
1459        &self,
1460        request: &crate::request::Request,
1461        connection: &crate::server::ConnectionInfo,
1462        next: &dyn crate::application::Application,
1463    ) -> Result<crate::response::Response, String> {
1464        if !self.matches(request) {
1465            return next.execute(request, connection);
1466        }
1467        if self.inner.backends.is_empty() {
1468            let mut response = bad_gateway();
1469            status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1470            return Ok(response);
1471        }
1472        // A streamed request body can be sent once: no second backend then.
1473        let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1474        let n = self.inner.backends.len();
1475        let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1476        let mut last_error = String::new();
1477        for attempt in 0..attempts {
1478            let backend = &self.inner.backends[(start + attempt) % n];
1479            let tls = backend.tls.then(|| match &self.inner.trust {
1480                Some(trust) => trust.h2_config(),
1481                None => h2_upstream::default_tls(),
1482            });
1483            let target = h2_upstream::Target {
1484                backend,
1485                tls,
1486                connect_timeout: self.inner.connect_timeout,
1487                read_timeout: self.inner.read_timeout,
1488                authority: None,
1489            };
1490            match h2_upstream::forward(request, Peer::of(connection), &target) {
1491                Ok(mut response) => {
1492                    status::received(&mut response, None);
1493                    return Ok(response);
1494                }
1495                Err(e) => last_error = e,
1496            }
1497        }
1498        let mut response = bad_gateway();
1499        status::failed_with(&mut response, &last_error, None);
1500        Ok(response)
1501    }
1502
1503    /// Headers only: a request this proxy doesn't forward passes through
1504    /// untouched.
1505    fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1506        true
1507    }
1508
1509    /// Requests this proxy forwards are sent as their body arrives (gRPC
1510    /// client streaming and bidirectional calls).
1511    fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1512        self.matches(request)
1513    }
1514}
1515
1516// ── HTTP/3 reverse proxy ──────────────────────────────────────────────────────
1517
1518/// Reverse proxy that forwards requests to `https://` backends over HTTP/3
1519/// (QUIC). Since 18.13.0; requires the `http3` feature (default).
1520///
1521/// A backend QUIC can't reach (UDP blocked, no handshake within the connect
1522/// timeout, a TLS failure) is sent the request over HTTPS on TCP instead,
1523/// and stays on TCP for five minutes; `rws_upstream_h3_fallbacks_total`
1524/// counts it under the proxy's [`name`](Self::name).
1525///
1526/// ```rust,no_run
1527/// use rust_web_server::app::App;
1528/// use rust_web_server::core::New;
1529/// use rust_web_server::proxy::H3ReverseProxy;
1530///
1531/// let proxy = H3ReverseProxy::new(["https://edge1.internal:443", "https://edge2.internal:443"])
1532///     .path_prefix("/api")
1533///     .tls_ca_file("/etc/rws/internal-ca.pem")
1534///     .unwrap();
1535/// let app = App::new().wrap(proxy);
1536/// ```
1537#[cfg(feature = "http3")]
1538pub struct H3ReverseProxy {
1539    inner: ReverseProxy,
1540    name: String,
1541    /// Backends on TCP until the time kept here.
1542    tcp_until: std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>,
1543}
1544
1545#[cfg(feature = "http3")]
1546impl H3ReverseProxy {
1547    /// A proxy distributing requests across `backends` (`https://host:port`,
1548    /// port 443 by default) in round-robin order. Certificates are checked
1549    /// against the WebPKI roots unless [`tls_ca_file`](Self::tls_ca_file)
1550    /// says otherwise. A backend that isn't `https://` is reached over
1551    /// HTTP/1.1 on TCP.
1552    pub fn new<I, S>(backends: I) -> Self
1553    where
1554        I: IntoIterator<Item = S>,
1555        S: AsRef<str>,
1556    {
1557        H3ReverseProxy { inner: ReverseProxy::new(backends), name: "h3-reverse-proxy".to_string(), tcp_until: std::sync::Mutex::default() }
1558    }
1559
1560    /// The `upstream` label of this proxy's fallback metric.
1561    pub fn name(mut self, name: impl Into<String>) -> Self {
1562        self.name = name.into();
1563        self
1564    }
1565
1566    /// Only proxy requests whose URI starts with `prefix`; pass others through.
1567    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1568        self.inner = self.inner.path_prefix(prefix);
1569        self
1570    }
1571
1572    /// QUIC handshake (and TCP connect) timeout (default: 5 s).
1573    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1574        self.inner = self.inner.connect_timeout_ms(ms);
1575        self
1576    }
1577
1578    /// Longest wait for the backend — the response head and each body
1579    /// chunk (default: 30 s).
1580    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1581        self.inner = self.inner.read_timeout_ms(ms);
1582        self
1583    }
1584
1585    /// Trust the CA certificates in the PEM file `path` instead of the
1586    /// WebPKI roots.
1587    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1588        self.inner = self.inner.tls_ca_file(path)?;
1589        Ok(self)
1590    }
1591
1592    /// Present a client certificate to backends that require one.
1593    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1594        self.inner = self.inner.tls_client_cert(cert, key)?;
1595        Ok(self)
1596    }
1597
1598    fn matches(&self, request: &Request) -> bool {
1599        self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1600    }
1601
1602    fn on_tcp(&self, key: &str) -> bool {
1603        let mut tcp_until = self.tcp_until.lock().unwrap_or_else(|e| e.into_inner());
1604        match tcp_until.get(key) {
1605            Some(until) if std::time::Instant::now() < *until => true,
1606            Some(_) => {
1607                tcp_until.remove(key);
1608                false
1609            }
1610            None => false,
1611        }
1612    }
1613
1614    /// One attempt at `backend`: HTTP/3 unless it's on TCP, TCP when QUIC
1615    /// can't connect.
1616    fn attempt(&self, backend: &Backend, request: &Request, connection: &crate::server::ConnectionInfo) -> Result<Response, String> {
1617        let key = format!("{}:{}", backend.host, backend.port);
1618        if backend.tls && !self.on_tcp(&key) {
1619            let config = match &self.inner.trust {
1620                Some(trust) => trust.client_config(),
1621                None => tls_client_config(),
1622            };
1623            let target = h3_upstream::Target {
1624                host: &backend.host,
1625                port: backend.port,
1626                tls: &config,
1627                connect_timeout: self.inner.connect_timeout,
1628                read_timeout: self.inner.read_timeout,
1629            };
1630            match h3_upstream::forward(request, Peer::of(connection), &target) {
1631                Err(h3_upstream::H3Error::Connect(e)) => {
1632                    self.tcp_until.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone(), std::time::Instant::now() + crate::proxy_config::H3_FALLBACK);
1633                    crate::proxy_config::upstream::observe_h3_fallback(&self.name);
1634                    eprintln!("{}: HTTP/3 to {key} failed ({e}); using TCP for {} s", self.name, crate::proxy_config::H3_FALLBACK.as_secs());
1635                }
1636                result => return result.map_err(|e| e.to_string()),
1637            }
1638        }
1639        forward_upstream_trusting(
1640            &self.inner.pool,
1641            request,
1642            Peer::of(connection),
1643            &backend.host,
1644            backend.port,
1645            backend.tls,
1646            self.inner.trust.as_deref(),
1647            self.inner.connect_timeout,
1648            self.inner.read_timeout,
1649        )
1650    }
1651}
1652
1653#[cfg(feature = "http3")]
1654impl crate::middleware::Middleware for H3ReverseProxy {
1655    fn handle(
1656        &self,
1657        request: &crate::request::Request,
1658        connection: &crate::server::ConnectionInfo,
1659        next: &dyn crate::application::Application,
1660    ) -> Result<crate::response::Response, String> {
1661        if !self.matches(request) {
1662            return next.execute(request, connection);
1663        }
1664        if self.inner.backends.is_empty() {
1665            let mut response = bad_gateway();
1666            status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1667            return Ok(response);
1668        }
1669        // A streamed request body can be sent once: no second backend then.
1670        let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1671        let n = self.inner.backends.len();
1672        let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1673        let mut last_error = String::new();
1674        for attempt in 0..attempts {
1675            match self.attempt(&self.inner.backends[(start + attempt) % n], request, connection) {
1676                Ok(mut response) => {
1677                    status::received(&mut response, None);
1678                    return Ok(response);
1679                }
1680                Err(e) => last_error = e,
1681            }
1682        }
1683        let mut response = bad_gateway();
1684        status::failed_with(&mut response, &last_error, None);
1685        Ok(response)
1686    }
1687
1688    fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1689        true
1690    }
1691
1692    /// Requests this proxy forwards are sent as their body arrives.
1693    fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1694        self.matches(request)
1695    }
1696}
1697
1698/// Forward `request` over HTTP/2 to `url` (`h2://`, `grpc://`, `h2s://`,
1699/// `grpcs://`, `https://` or `host:port`) — the config file's `grpc` action.
1700/// `tls` forces TLS for a bare `host:port` (`[[upstream]] tls = true`).
1701#[cfg(feature = "http2")]
1702pub(crate) fn forward_h2(
1703    request: &Request,
1704    client: Peer<'_>,
1705    url: &str,
1706    tls: bool,
1707    trust: Option<&UpstreamTls>,
1708    connect_timeout: Duration,
1709    read_timeout: Duration,
1710) -> Result<Response, String> {
1711    let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1712    backend.tls |= tls;
1713    let tls = backend.tls.then(|| match trust {
1714        Some(t) => t.h2_config(),
1715        None => h2_upstream::default_tls(),
1716    });
1717    h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout, authority: None })
1718}
1719
1720/// Forward over TLS to `ip:port` with `config`, `server_name` as SNI (and
1721/// the name `config`'s verifier checks), `host_header` as the `Host` — the
1722/// Gateway API router's BackendTLSPolicy backends. Connections are pooled
1723/// per `label` (one per distinct policy content).
1724#[cfg(feature = "gateway-api")]
1725#[allow(clippy::too_many_arguments)]
1726pub(crate) fn forward_tls_with_host(
1727    config: &Arc<rustls::ClientConfig>,
1728    label: &str,
1729    request: &Request,
1730    client: Peer<'_>,
1731    ip: &str,
1732    port: u16,
1733    server_name: &str,
1734    host_header: &str,
1735    connect_timeout: Duration,
1736    read_timeout: Duration,
1737) -> Result<Response, String> {
1738    let pool = tls_pool_for_ca(label);
1739    forward_via(pool, request, client, ip, port, host_header, read_timeout, || {
1740        let tcp = connect_tcp(ip, port, connect_timeout)?;
1741        let name = rustls::pki_types::ServerName::try_from(server_name.to_string()).map_err(|e| format!("invalid TLS server name '{server_name}': {e}"))?;
1742        let conn = rustls::ClientConnection::new(Arc::clone(config), name).map_err(|e| e.to_string())?;
1743        Ok(rustls::StreamOwned::new(conn, tcp))
1744    })
1745}
1746
1747/// Forward over cleartext HTTP/2 with prior knowledge (h2c) to `host:port`,
1748/// sending `authority` as `:authority` — the Gateway API router's
1749/// `kubernetes.io/h2c` backends.
1750#[cfg(feature = "gateway-api")]
1751pub(crate) fn forward_h2c_with_host(
1752    request: &Request,
1753    client: Peer<'_>,
1754    host: &str,
1755    port: u16,
1756    authority: &str,
1757    connect_timeout: Duration,
1758    read_timeout: Duration,
1759) -> Result<Response, String> {
1760    let backend = Backend { host: host.to_string(), port, tls: false };
1761    h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls: None, connect_timeout, read_timeout, authority: Some(authority) })
1762}
1763
1764// ── gRPC proxy ────────────────────────────────────────────────────────────────
1765
1766/// gRPC reverse proxy middleware.
1767///
1768/// Recognises requests with `Content-Type: application/grpc*` and forwards them
1769/// to a backend over HTTP/2, leaving all other requests to the next layer.
1770///
1771/// Requires the `http2` Cargo feature.
1772///
1773/// # Example
1774///
1775/// ```rust,no_run
1776/// use rust_web_server::app::App;
1777/// use rust_web_server::core::New;
1778/// use rust_web_server::proxy::GrpcProxy;
1779///
1780/// let app = App::new()
1781///     .wrap(GrpcProxy::new(["grpc-service:50051"]));
1782/// ```
1783#[cfg(feature = "http2")]
1784pub struct GrpcProxy {
1785    inner: H2ReverseProxy,
1786}
1787
1788#[cfg(feature = "http2")]
1789impl GrpcProxy {
1790    /// Create a proxy distributing gRPC connections across `backends` in round-robin order.
1791    ///
1792    /// Each backend entry can be:
1793    /// - `"host:port"` — plain TCP (gRPC cleartext)
1794    /// - `"grpc://host:port"` — plain TCP (explicit scheme)
1795    /// - `"grpcs://host:port"` — TLS (gRPC over TLS; port defaults to 443)
1796    /// - `"https://host:port"` — TLS (same as `grpcs://`)
1797    ///
1798    /// TLS backends require the `http2` Cargo feature.
1799    pub fn new<I, S>(backends: I) -> Self
1800    where
1801        I: IntoIterator<Item = S>,
1802        S: AsRef<str>,
1803    {
1804        GrpcProxy { inner: H2ReverseProxy::new(backends) }
1805    }
1806
1807    /// Only proxy requests whose URI starts with `prefix`; pass others through.
1808    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1809        self.inner = self.inner.path_prefix(prefix);
1810        self
1811    }
1812
1813    /// See [`H2ReverseProxy::connect_timeout_ms`].
1814    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1815        self.inner = self.inner.connect_timeout_ms(ms);
1816        self
1817    }
1818
1819    /// See [`H2ReverseProxy::read_timeout_ms`]: a stream quiet for longer ends.
1820    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1821        self.inner = self.inner.read_timeout_ms(ms);
1822        self
1823    }
1824
1825    /// Trust this CA for `grpcs://` backends. Since 18.3.0.
1826    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1827        self.inner = self.inner.tls_ca_file(path)?;
1828        Ok(self)
1829    }
1830
1831    /// Present a client certificate to `grpcs://` backends (mutual TLS).
1832    /// Since 18.3.0.
1833    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1834        self.inner = self.inner.tls_client_cert(cert, key)?;
1835        Ok(self)
1836    }
1837}
1838
1839#[cfg(feature = "http2")]
1840impl crate::middleware::Middleware for GrpcProxy {
1841    fn handle(
1842        &self,
1843        request: &crate::request::Request,
1844        connection: &crate::server::ConnectionInfo,
1845        next: &dyn crate::application::Application,
1846    ) -> Result<crate::response::Response, String> {
1847        if is_grpc(request) {
1848            self.inner.handle(request, connection, next)
1849        } else {
1850            next.execute(request, connection)
1851        }
1852    }
1853
1854    fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1855        true
1856    }
1857
1858    fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1859        is_grpc(request) && self.inner.matches(request)
1860    }
1861}
1862
1863#[cfg(feature = "http2")]
1864fn is_grpc(request: &Request) -> bool {
1865    request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1866}
1867
1868// ── Backend::parse unit tests ─────────────────────────────────────────────────
1869
1870#[cfg(test)]
1871mod backend_parse_tests {
1872    use super::Backend;
1873
1874    fn parse(url: &str) -> Option<(String, u16, bool)> {
1875        Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1876    }
1877
1878    #[test]
1879    fn bare_host_port() {
1880        assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1881    }
1882
1883    #[test]
1884    fn http_scheme() {
1885        assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1886    }
1887
1888    #[test]
1889    fn h2_scheme_plain() {
1890        assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1891    }
1892
1893    #[test]
1894    fn grpc_scheme_plain() {
1895        assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1896    }
1897
1898    #[test]
1899    fn https_scheme_sets_tls_and_default_port() {
1900        assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1901    }
1902
1903    #[test]
1904    fn https_scheme_explicit_port() {
1905        assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1906    }
1907
1908    #[test]
1909    fn h2s_scheme_sets_tls() {
1910        assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1911    }
1912
1913    #[test]
1914    fn h2s_scheme_explicit_port() {
1915        assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1916    }
1917
1918    #[test]
1919    fn grpcs_scheme_sets_tls() {
1920        assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1921    }
1922
1923    #[test]
1924    fn grpcs_scheme_explicit_port() {
1925        assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1926    }
1927
1928    #[test]
1929    fn empty_host_returns_none() {
1930        assert_eq!(None, parse("https://"));
1931    }
1932
1933    #[test]
1934    fn bare_host_no_port_defaults_to_80() {
1935        assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1936    }
1937}