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