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