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