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