Skip to main content

ts_runtime/
serve.rs

1//! Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
2//!
3//! Go `tsnet` stores an `ipn.ServeConfig` on the node and runs one accept loop per configured
4//! tailnet port, dispatching each accepted connection per its handler (proxy / text / raw TCP
5//! forward / hand-back). This module is the faithful equivalent on the **application** netstack: a
6//! [`ServeManager`](crate::serve::ServeManager) owns the current [`ServeState`](ts_control::ServeState), one accept-loop task
7//! per bound port, and tears every loop down on drop / on the next `set`.
8//!
9//! ## Storage + reconcile (full-replace)
10//!
11//! The manager holds the current [`ServeState`](ts_control::ServeState) plus one [`tokio::task::AbortHandle`] per bound
12//! port behind a single `Arc<Mutex<Inner>>` (mirroring [`crate::fallback_tcp::FallbackTcpManager`]).
13//! [`ServeManager::set`](crate::serve::ServeManager::set) uses **full-replace** semantics: it aborts *every* existing accept loop and
14//! respawns from the new config. Go reconciles incrementally (leaving unchanged ports running); we
15//! do full-replace because it is simpler and correct, and a `SetServeConfig` is a rare control-plane
16//! operation, not a hot path. The passed [`ServeState`](ts_control::ServeState) becomes the whole config (REPLACE, matching
17//! Go). `pure_reconcile` computes the add/remove port deltas for testing and documentation, even
18//! though the live path replaces wholesale.
19//!
20//! ## TLS termination
21//!
22//! TLS-terminating ports (`ServeTarget::terminates_tls`) need a `TlsAcceptor`; the caller
23//! (`Device::set_serve_config`) obtains it **once** via the cert path and hands it in per port. The
24//! manager never builds an acceptor and never touches the cert/ACME machinery — that keeps
25//! `ts_runtime` off the cert path and lets the device fail the whole `set` closed if a cert cannot
26//! be issued (no plaintext downgrade).
27//!
28//! ## Anti-leak
29//!
30//! Every accept loop binds the **overlay** netstack only (via `Channel::tcp_listen` on the
31//! device's own tailnet IPv4) — never a host socket. The `ServeTarget::Proxy` /
32//! `ServeTarget::TcpForward` backend dial is a **local host socket** to the embedder's own backend
33//! (exactly like Go's reverse-proxy to `127.0.0.1` and like [`crate::Runtime`]'s loopback proxy) —
34//! it is intentionally NOT routed through the `ts_forwarder` exit-egress path, so the exit-node
35//! anti-leak chokepoint is untouched. A backend dial failure drops the connection (fail-closed,
36//! logged); it never falls back to anything.
37
38use std::{
39    collections::{BTreeMap, BTreeSet},
40    net::{Ipv4Addr, SocketAddr},
41    sync::{Arc, Mutex},
42};
43
44use netstack::{CreateSocket, netcore::Channel, netsock::TcpStream as OverlayStream};
45use tokio::{
46    io::{AsyncRead, AsyncWrite, AsyncWriteExt},
47    sync::{Semaphore, mpsc},
48};
49use ts_control::{ServeState, ServeTarget, tls::TlsAcceptor};
50
51/// Max concurrent in-flight connections served per bound port. Bounds the per-port spawn fan-out so
52/// a flood of accepts on one serve port cannot grow tasks (and overlay sockets) without limit;
53/// saturated => the accept loop back-pressures (stops accepting) until an in-flight conn finishes.
54/// Mirrors the loopback proxy's `MAX_CONCURRENT_CONNS` rationale (each accepted conn pins an overlay
55/// TCP socket, ~512 KiB of rx+tx buffers — see `tcp_buffer_size` in AGENTS.md).
56const MAX_SERVE_CONNS_PER_PORT: usize = 256;
57
58/// A connection handed back to the embedder for a [`ServeTarget::Accept`] port (the in-process
59/// stand-in for Go `tsnet`'s `ListenTLS`-returned `net.Listener`).
60///
61/// `stream` is already TLS-terminated (the overlay stream wrapped in `tokio_rustls`'s server
62/// `TlsStream`), boxed so the channel is target-agnostic. `port` is the serve port it arrived on so
63/// an embedder serving `Accept` on several ports can demultiplex.
64pub struct ServeAccepted {
65    /// The tailnet (overlay) port this connection was accepted on.
66    pub port: u16,
67    /// The accepted, TLS-terminated stream, ready to read/write.
68    pub stream: Box<dyn AsyncReadWrite>,
69}
70
71/// Object-safe alias for the boxed accepted stream: an `AsyncRead + AsyncWrite` the embedder drives.
72pub trait AsyncReadWrite: AsyncRead + AsyncWrite + Send + Unpin {}
73impl<T: AsyncRead + AsyncWrite + Send + Unpin> AsyncReadWrite for T {}
74
75/// Receiver side of the [`ServeTarget::Accept`] hand-back channel (mirrors a `net.Listener`'s accept
76/// queue). [`ServeManager::set`] returns one; await [`recv`](mpsc::Receiver::recv) to take the next
77/// accepted, TLS-terminated connection. Dropped/replaced when the next `set` runs.
78pub type ServeAcceptedReceiver = mpsc::Receiver<ServeAccepted>;
79
80/// A fully-resolved per-port serve plan: the target plus, for TLS-terminating targets, the acceptor
81/// the device built up-front from the cert path. The caller guarantees `acceptor.is_some()` exactly
82/// when `target.terminates_tls()` — the manager asserts this is never violated by failing the bind.
83pub struct ResolvedPort {
84    /// What to serve on this port.
85    pub target: ServeTarget,
86    /// The TLS acceptor for this port, present iff `target.terminates_tls()`.
87    pub acceptor: Option<TlsAcceptor>,
88}
89
90/// Shared manager state behind a single lock.
91struct Inner {
92    /// The currently-stored config (what [`get`](ServeManager::get) returns). Empty default until
93    /// the first `set`.
94    state: ServeState,
95    /// One accept-loop abort handle per currently-bound port. Aborting a handle stops that port's
96    /// accept loop (and, transitively, drops its listener so the overlay port is released).
97    ports: BTreeMap<u16, tokio::task::AbortHandle>,
98}
99
100impl Drop for Inner {
101    fn drop(&mut self) {
102        for h in self.ports.values() {
103            h.abort();
104        }
105    }
106}
107
108/// Owns the stored Serve config and the live per-port accept loops (`tsnet` serving runtime).
109///
110/// Built once from the application netstack [`Channel`] and the device's overlay IPv4, held by the
111/// [`crate::Runtime`]. [`set`](Self::set) replaces the whole config (full-replace reconcile);
112/// dropping the manager (with the runtime / device) aborts every accept loop.
113pub struct ServeManager {
114    inner: Arc<Mutex<Inner>>,
115    channel: Channel,
116    self_ipv4: Ipv4Addr,
117}
118
119impl ServeManager {
120    /// Build a manager bound to the application netstack `channel` and the device's own tailnet
121    /// `self_ipv4` (the overlay address every serve listener binds on). No accept loop runs until the
122    /// first [`set`](Self::set).
123    pub fn new(channel: Channel, self_ipv4: Ipv4Addr) -> Self {
124        Self {
125            inner: Arc::new(Mutex::new(Inner {
126                state: ServeState::default(),
127                ports: BTreeMap::new(),
128            })),
129            channel,
130            self_ipv4,
131        }
132    }
133
134    /// The currently-stored config (Go `GetServeConfig`); empty default if none was ever set.
135    pub fn get(&self) -> ServeState {
136        self.inner
137            .lock()
138            .unwrap_or_else(|e| e.into_inner())
139            .state
140            .clone()
141    }
142
143    /// Replace the whole Serve config (Go `SetServeConfig`, REPLACE semantics), full-replace
144    /// reconcile.
145    ///
146    /// `state` is the new config; `resolved` carries the per-port target + (for TLS ports) the
147    /// pre-built acceptor, keyed identically to `state.ports`. Aborts every existing accept loop and
148    /// spawns one per port in `resolved`. Returns a fresh [`ServeAcceptedReceiver`] delivering
149    /// connections for every [`ServeTarget::Accept`] port (empty if there are none).
150    ///
151    /// The caller is responsible for `state.validate()` and for obtaining the acceptors (failing the
152    /// whole call closed if a cert can't be issued) before calling this; the manager only binds and
153    /// dispatches.
154    pub fn set(
155        &self,
156        state: ServeState,
157        resolved: BTreeMap<u16, ResolvedPort>,
158    ) -> ServeAcceptedReceiver {
159        // A bounded channel back-pressures a slow embedder rather than buffering unboundedly.
160        let (accept_tx, accept_rx) = mpsc::channel::<ServeAccepted>(MAX_SERVE_CONNS_PER_PORT);
161
162        let mut new_ports: BTreeMap<u16, tokio::task::AbortHandle> = BTreeMap::new();
163        for (port, rp) in resolved {
164            let channel = self.channel.clone();
165            let self_ipv4 = self.self_ipv4;
166            let accept_tx = accept_tx.clone();
167            let handle = tokio::spawn(async move {
168                if let Err(e) = run_port(channel, self_ipv4, port, rp, accept_tx).await {
169                    tracing::warn!(%port, error = %e, "serve listener exited");
170                }
171            })
172            .abort_handle();
173            new_ports.insert(port, handle);
174        }
175
176        // Swap in the new state + handles under the lock; aborting the OLD handles happens when the
177        // replaced map is dropped at end of scope (after the lock is released).
178        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
179        inner.state = state;
180        let old = std::mem::replace(&mut inner.ports, new_ports);
181        drop(inner);
182        for h in old.values() {
183            h.abort();
184        }
185
186        accept_rx
187    }
188}
189
190/// Compute which ports must be added and removed to go from `current` to `next` (pure; the diff Go
191/// reconciles incrementally). The live [`ServeManager::set`] uses full-replace, but this captures
192/// the delta for tests/documentation: a port is *changed* iff its target differs, which counts as
193/// both a remove and an add.
194#[cfg_attr(not(test), allow(dead_code))]
195fn pure_reconcile(
196    current: &BTreeMap<u16, ServeTarget>,
197    next: &BTreeMap<u16, ServeTarget>,
198) -> (BTreeSet<u16>, BTreeSet<u16>) {
199    let mut to_add = BTreeSet::new();
200    let mut to_remove = BTreeSet::new();
201    for (port, target) in next {
202        match current.get(port) {
203            Some(cur) if cur == target => {}
204            _ => {
205                to_add.insert(*port);
206            }
207        }
208    }
209    for port in current.keys() {
210        match next.get(port) {
211            Some(target) if current.get(port) == Some(target) => {}
212            _ => {
213                to_remove.insert(*port);
214            }
215        }
216    }
217    (to_add, to_remove)
218}
219
220/// Accept loop for one serve port: bind the overlay listener on `(self_ipv4, port)` and dispatch
221/// each accepted connection per `rp.target`, capped at [`MAX_SERVE_CONNS_PER_PORT`] in flight.
222async fn run_port(
223    channel: Channel,
224    self_ipv4: Ipv4Addr,
225    port: u16,
226    rp: ResolvedPort,
227    accept_tx: mpsc::Sender<ServeAccepted>,
228) -> Result<(), netstack::netcore::Error> {
229    // Anti-leak: bind the OVERLAY netstack on this node's own tailnet IPv4, never a host socket.
230    let listen_addr = SocketAddr::new(self_ipv4.into(), port);
231    let listener = channel.tcp_listen(listen_addr).await?;
232    tracing::debug!(%port, "serve listener accepting");
233
234    let rp = Arc::new(rp);
235    let inflight = Arc::new(Semaphore::new(MAX_SERVE_CONNS_PER_PORT));
236
237    loop {
238        // Acquire a permit BEFORE accepting so the loop back-pressures at the cap.
239        let Ok(permit) = inflight.clone().acquire_owned().await else {
240            return Ok(());
241        };
242        let overlay = listener.accept().await?;
243
244        let rp = rp.clone();
245        let accept_tx = accept_tx.clone();
246        tokio::spawn(async move {
247            let _permit = permit; // released when this connection finishes
248            dispatch_conn(port, overlay, rp, accept_tx).await;
249        });
250    }
251}
252
253/// Dispatch one accepted overlay connection per the port's target. TLS is terminated here (once per
254/// connection) for TLS-terminating targets; failures drop the connection (fail-closed, logged).
255async fn dispatch_conn(
256    port: u16,
257    overlay: OverlayStream,
258    rp: Arc<ResolvedPort>,
259    accept_tx: mpsc::Sender<ServeAccepted>,
260) {
261    match &rp.target {
262        // Raw passthrough: NO TLS. Splice the raw overlay stream to the local backend.
263        ServeTarget::TcpForward { to } => {
264            forward_to_backend(port, overlay, to).await;
265        }
266        // TLS-terminating targets: terminate TLS once, then act on the decrypted stream.
267        _ => {
268            let Some(acceptor) = rp.acceptor.as_ref() else {
269                // The caller's contract guarantees a TLS acceptor for every TLS-terminating port;
270                // a missing one means we must never serve plaintext — drop, fail-closed.
271                tracing::warn!(%port, "serve: missing TLS acceptor for TLS port; dropping conn");
272                return;
273            };
274            let tls = match acceptor.accept(overlay).await {
275                Ok(s) => s,
276                Err(e) => {
277                    tracing::debug!(%port, error = %e, "serve: TLS handshake failed; dropping conn");
278                    return;
279                }
280            };
281            match &rp.target {
282                ServeTarget::Accept => {
283                    // Hand the TLS-terminated stream back to the embedder over the channel.
284                    let accepted = ServeAccepted {
285                        port,
286                        stream: Box::new(tls),
287                    };
288                    if accept_tx.send(accepted).await.is_err() {
289                        tracing::debug!(%port, "serve: accept receiver dropped; closing conn");
290                    }
291                }
292                // Reached DIRECTLY (no request head consumed off `tls`): a plain splice with no
293                // prefix replay — the backend sees the client's bytes verbatim.
294                ServeTarget::Proxy { to } => {
295                    proxy_to_backend(port, tls, to).await;
296                }
297                ServeTarget::Text { body } => {
298                    write_text(port, tls, body).await;
299                }
300                ServeTarget::Redirect { to, status } => {
301                    serve_redirect(port, tls, to, *status).await;
302                }
303                ServeTarget::Path { handlers } => {
304                    serve_path(port, tls, handlers).await;
305                }
306                // `TcpForward` is handled in the non-TLS arm above; nothing else terminates TLS.
307                // The wildcard covers `#[non_exhaustive]` future raw (non-TLS) variants: if one is
308                // added it must NOT silently terminate TLS here — drop it fail-closed until this
309                // dispatch is taught how to serve it.
310                other => {
311                    debug_assert!(
312                        !other.terminates_tls(),
313                        "TLS-terminating ServeTarget reached fall-through arm"
314                    );
315                    tracing::warn!(%port, "serve: unhandled ServeTarget on TLS port; dropping conn");
316                }
317            }
318        }
319    }
320}
321
322/// Reverse-proxy a TLS-terminated stream to a local host backend (Go `Proxy` handler). The backend
323/// dial is a LOCAL host socket to the embedder's own backend — never the forwarder egress path.
324///
325/// Reached DIRECTLY from [`dispatch_conn`] (no request head has been consumed off `tls`), so no
326/// prefix replay is needed — the backend sees the client's bytes verbatim via the bidirectional
327/// splice. The `Path`-nested case (where a head WAS consumed) uses [`proxy_to_backend_with_prefix`]
328/// instead.
329async fn proxy_to_backend<S>(port: u16, tls: S, to: &str)
330where
331    S: AsyncRead + AsyncWrite + Unpin,
332{
333    proxy_to_backend_with_prefix(port, tls, to, &[]).await;
334}
335
336/// Reverse-proxy a TLS-terminated stream to a local host backend, writing `prefix` to the backend
337/// FIRST (before the bidirectional splice). This replays an HTTP request head already consumed off
338/// `tls` (e.g. by [`serve_path`]'s [`read_http_head`]) so the backend sees the complete request: the
339/// consumed request line + headers, then the rest of the body/stream via the splice. An empty
340/// `prefix` is equivalent to a plain splice ([`proxy_to_backend`]). The backend dial is a LOCAL host
341/// socket — never the forwarder egress path; any failure (dial or prefix write) drops the conn
342/// fail-closed.
343async fn proxy_to_backend_with_prefix<S>(port: u16, mut tls: S, to: &str, prefix: &[u8])
344where
345    S: AsyncRead + AsyncWrite + Unpin,
346{
347    let mut backend = match tokio::net::TcpStream::connect(to).await {
348        Ok(b) => b,
349        Err(e) => {
350            tracing::debug!(%port, %to, error = %e, "serve proxy: backend dial failed; dropping conn");
351            return;
352        }
353    };
354    if !prefix.is_empty()
355        && let Err(e) = backend.write_all(prefix).await
356    {
357        tracing::debug!(%port, %to, error = %e, "serve proxy: prefix replay failed; dropping conn");
358        return;
359    }
360    if let Err(e) = tokio::io::copy_bidirectional(&mut tls, &mut backend).await {
361        tracing::debug!(%port, %to, error = %e, "serve proxy: splice ended");
362    }
363}
364
365/// Forward a RAW (non-TLS) overlay stream to a local host backend (Go `TCPForward` handler). The
366/// backend dial is a LOCAL host socket — never the forwarder egress path.
367async fn forward_to_backend(port: u16, mut overlay: OverlayStream, to: &str) {
368    let mut backend = match tokio::net::TcpStream::connect(to).await {
369        Ok(b) => b,
370        Err(e) => {
371            tracing::debug!(%port, %to, error = %e, "serve forward: backend dial failed; dropping conn");
372            return;
373        }
374    };
375    if let Err(e) = tokio::io::copy_bidirectional(&mut overlay, &mut backend).await {
376        tracing::debug!(%port, %to, error = %e, "serve forward: splice ended");
377    }
378}
379
380/// Write a fixed body to the TLS-terminated stream, flush, and close (Go `Text` handler).
381async fn write_text<S>(port: u16, mut tls: S, body: &str)
382where
383    S: AsyncRead + AsyncWrite + Unpin,
384{
385    if let Err(e) = tls.write_all(body.as_bytes()).await {
386        tracing::debug!(%port, error = %e, "serve text: write failed");
387        return;
388    }
389    if let Err(e) = tls.flush().await {
390        tracing::debug!(%port, error = %e, "serve text: flush failed");
391    }
392    drop(tls.shutdown().await);
393}
394
395/// Max bytes of an HTTP request head (request line + headers) we will buffer before giving up. A
396/// peer that never sends `\r\n\r\n` within this exact bound is dropped fail-closed (no unbounded
397/// read); the buffer is bound-checked AFTER each read, so it never exceeds this cap.
398const MAX_HTTP_HEAD: usize = 8 * 1024;
399
400/// Read the HTTP request head (up to and including `\r\n\r\n`) from a TLS-terminated stream into a
401/// buffer. Returns `(buf, header_end)` where `header_end` is the offset just past the terminator, or
402/// `None` if the peer closed early or the head exceeded [`MAX_HTTP_HEAD`]. Hand-rolled (no
403/// axum/hyper); mirrors the peerAPI router's head-read style.
404async fn read_http_head<S>(stream: &mut S) -> Option<(Vec<u8>, usize)>
405where
406    S: AsyncRead + AsyncWrite + Unpin,
407{
408    use tokio::io::AsyncReadExt;
409
410    let mut buf = Vec::with_capacity(1024);
411    let mut tmp = [0u8; 1024];
412    loop {
413        if let Some(end) = crate::peerapi_doh::find_header_end(&buf) {
414            return Some((buf, end));
415        }
416        match stream.read(&mut tmp).await {
417            Ok(0) => return None,
418            Ok(n) => {
419                buf.extend_from_slice(&tmp[..n]);
420                // Bound-check AFTER extending so the buffer never exceeds MAX_HTTP_HEAD. The
421                // terminator is re-checked at the top of the loop, so a head whose terminator lands
422                // exactly at the bound still succeeds; only a head with no terminator within
423                // MAX_HTTP_HEAD is dropped fail-closed.
424                if crate::peerapi_doh::find_header_end(&buf).is_none() && buf.len() >= MAX_HTTP_HEAD
425                {
426                    return None;
427                }
428            }
429            Err(_) => return None,
430        }
431    }
432}
433
434/// Parse an HTTP head into the URL path the serve mux routes on: the request-line target, run
435/// through [`request_target_path`]. Returns `None` if the head is malformed, or if the target is
436/// one Go's HTTP server refuses outright — dispatch answers 400 for both, which is Go's answer
437/// too. Hand-rolled; no HTTP library framing assumptions beyond the request line.
438///
439/// The path that comes back is **not** the bytes off the wire: it is percent-decoded and stripped
440/// of scheme, authority and query, exactly as Go's `r.URL.Path` is, because that is what
441/// `getServeHandler` looks up and cleans. Normalizing it further — the cleaning, and the refusal
442/// of a path that is not absolute — is [`match_path_handler`]'s job.
443fn request_path(buf: &[u8]) -> Option<String> {
444    let mut headers = [httparse::EMPTY_HEADER; 32];
445    let mut req = httparse::Request::new(&mut headers);
446    match req.parse(buf) {
447        Ok(_) => {}
448        Err(_) => return None,
449    }
450    request_target_path(req.method.unwrap_or(""), req.path?)
451}
452
453/// The URL path Go's `net/http` hands `getServeHandler` as `r.URL.Path`, for a request with this
454/// `method` and this request-line `target`. `None` means Go's server never reaches a handler at
455/// all and answers `400 Bad Request`.
456///
457/// ## Go behaviour this mirrors
458///
459/// Go does not route on the bytes off the request line. `net/http`'s `readRequest` (Go stdlib
460/// `net/http/request.go`, go1.25.1) runs the target through `url.ParseRequestURI` — `net/url`'s
461/// `parse(rawURL, viaRequest: true)` plus `setPath`'s `unescape` (Go stdlib `net/url/url.go`) —
462/// and `getServeHandler` (`ipn/ipnlocal/serve.go` @
463/// `9ea7cba44591e0cd840c6c94d23274dd222059bf`) then looks up, cleans and walks `r.URL.Path`. That
464/// path differs from the raw target in three ways that decide where a request goes:
465///
466/// * It is **percent-decoded**. `/api/%2e%2e/secret` is the path `/api/../secret`, which
467///   [`clean_path`] resolves to `/secret` — served by `/`, never by `/api`. Route on the still
468///   encoded bytes and the cleaning sees no dot-dot segment to resolve, so the `/api` mount claims
469///   a request it was never mounted for: the exact outcome the cleaning exists to prevent, spelled
470///   with two escapes. `%2f` likewise decodes to a real `/` and becomes a segment boundary, as it
471///   does in Go.
472/// * It has **no scheme, authority or query**. For the absolute-form target every server must
473///   accept (RFC 7230 §5.3.2) — `GET http://host/api HTTP/1.1` — the path is `/api`, and the
474///   `/api` mount serves it. Cleaning the raw target instead gives `http:/host/api`, which is not
475///   absolute and would 404 a request Go serves.
476/// * It is **empty** for a target that carries no path: an authority-form `CONNECT host:443`, or a
477///   rootless opaque target like `host:443`. `path.Clean("")` is `"."`, so those still reach no
478///   mount.
479///
480/// The `None` cases are Go's own parse errors, each of which makes `readRequest` fail before any
481/// handler runs: an empty target, a control byte in it, a `%` not followed by two hex digits
482/// (`/api/%zz`), and a target that is neither rooted nor scheme-prefixed (`api/v2`).
483///
484/// **Not ported:** `parseAuthority`'s validation of the authority, which this function (like Go)
485/// then throws away. A malformed authority in an absolute-form target (`http://ho%zzst/api`) is a
486/// 400 in Go and routes on its path here. The authority reaches neither the mux nor a backend, so
487/// this can only accept a request Go rejects, never route one somewhere Go would not.
488fn request_target_path(method: &str, target: &str) -> Option<String> {
489    // `readRequest`: a CONNECT target is authority-form, so Go re-parses it as `http://<target>`
490    // and then drops the scheme it added. What comes out has an empty path unless the authority
491    // itself carries one.
492    let connect_form;
493    let raw = if method == "CONNECT" && !target.starts_with('/') {
494        connect_form = format!("http://{target}");
495        connect_form.as_str()
496    } else {
497        target
498    };
499
500    // `parse(raw, viaRequest: true)`, in its order.
501    if raw.is_empty() {
502        return None;
503    }
504    if raw.bytes().any(|b| b < b' ' || b == 0x7f) {
505        return None;
506    }
507    if raw == "*" {
508        // Go's own special case, ahead of everything else: `GET *` has the path `*`, which is not
509        // absolute and so matches no mount.
510        return Some("*".to_string());
511    }
512    let (scheme, rest) = split_scheme(raw)?;
513    // The query is cut off before the path is ever looked at.
514    let rest = rest.split_once('?').map(|(p, _)| p).unwrap_or(rest);
515    let rest = if !rest.starts_with('/') {
516        // Rootless. With a scheme this is an opaque URI, which has no path at all; without one,
517        // Go's server refuses the request.
518        if scheme.is_empty() {
519            return None;
520        }
521        ""
522    } else if !scheme.is_empty() {
523        // Absolute-form: `//authority` is consumed, and the path is whatever follows it. Go only
524        // splits an authority off a *request* target when a scheme is present, so a schemeless
525        // `//foo/bar` stays a path (and cleans to `/foo/bar`).
526        match rest.strip_prefix("//") {
527            Some(authority_and_path) => match authority_and_path.find('/') {
528                Some(i) => &authority_and_path[i..],
529                None => "",
530            },
531            None => rest,
532        }
533    } else {
534        rest
535    };
536    unescape_path(rest)
537}
538
539/// Go's `getScheme` (Go stdlib `net/url/url.go`): split a leading `scheme:` off a URL. Returns
540/// `("", raw)` when there is no scheme — an origin-form target starts with `/`, which is not a
541/// legal scheme byte — and `None` for Go's "missing protocol scheme" error, a target starting
542/// with `:`.
543fn split_scheme(raw: &str) -> Option<(&str, &str)> {
544    for (i, c) in raw.bytes().enumerate() {
545        match c {
546            b'a'..=b'z' | b'A'..=b'Z' => {}
547            // Legal inside a scheme but not as its first byte; leading one ⇒ there is no scheme.
548            b'0'..=b'9' | b'+' | b'-' | b'.' => {
549                if i == 0 {
550                    return Some(("", raw));
551                }
552            }
553            b':' => {
554                if i == 0 {
555                    return None;
556                }
557                // `i` indexes an ASCII byte, so both halves split on a char boundary.
558                return Some((&raw[..i], &raw[i + 1..]));
559            }
560            _ => return Some(("", raw)),
561        }
562    }
563    Some(("", raw))
564}
565
566/// Go's `unescape(s, encodePath)` (Go stdlib `net/url/url.go`), the decoding `setPath` applies
567/// before `r.URL.Path` is ever routed on: `%XX` becomes the byte it names, `+` stays a `+` (only a
568/// query *component* decodes it as a space), and a `%` not followed by two hex digits is Go's
569/// `EscapeError` — `None` here, a 400 there.
570///
571/// Go's decoded path is a Go string, which need not be UTF-8; a Rust `String` must be, so any
572/// undecodable byte becomes U+FFFD. Routing compares a mount only against runs of bytes delimited
573/// by `/`, and the substitution replaces no ASCII byte and introduces no `/`, so the segment
574/// structure — and with it every mount decision — is the one Go reaches on the raw bytes. (The
575/// single case it could differ in is a mount point spelled with a literal U+FFFD in it, which the
576/// decoded bytes could then equal without being it.)
577fn unescape_path(s: &str) -> Option<String> {
578    let b = s.as_bytes();
579    let mut out: Vec<u8> = Vec::with_capacity(b.len());
580    let mut i = 0usize;
581    while i < b.len() {
582        if b[i] == b'%' {
583            let hi = unhex(*b.get(i + 1)?)?;
584            let lo = unhex(*b.get(i + 2)?)?;
585            out.push(hi << 4 | lo);
586            i += 3;
587        } else {
588            out.push(b[i]);
589            i += 1;
590        }
591    }
592    // A decoded byte sequence that is not UTF-8 is kept lossily rather than refused: Go routes it,
593    // and see above for why the replacement cannot move the request to another mount.
594    Some(
595        String::from_utf8(out)
596            .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()),
597    )
598}
599
600/// Go's `unhex` (Go stdlib `net/url/url.go`): the value of one hex digit, or `None` if it is not one.
601fn unhex(c: u8) -> Option<u8> {
602    match c {
603        b'0'..=b'9' => Some(c - b'0'),
604        b'a'..=b'f' => Some(c - b'a' + 10),
605        b'A'..=b'F' => Some(c - b'A' + 10),
606        _ => None,
607    }
608}
609
610/// Reason phrase for a redirect status (best-effort; falls back to "Redirect").
611fn redirect_reason(status: u16) -> &'static str {
612    match status {
613        301 => "Moved Permanently",
614        302 => "Found",
615        303 => "See Other",
616        307 => "Temporary Redirect",
617        308 => "Permanent Redirect",
618        _ => "Redirect",
619    }
620}
621
622/// Write a bodyless HTTP redirect (Go `HTTPHandler` redirect) on a TLS-terminated stream, then close.
623/// Fail-closed: any write error drops the conn. No request parsing is needed — every request on a
624/// `Redirect` target gets the same response.
625async fn serve_redirect<S>(port: u16, mut tls: S, to: &str, status: u16)
626where
627    S: AsyncRead + AsyncWrite + Unpin,
628{
629    let head = format!(
630        "HTTP/1.1 {status} {reason}\r\nLocation: {to}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
631        reason = redirect_reason(status),
632    );
633    if let Err(e) = tls.write_all(head.as_bytes()).await {
634        tracing::debug!(%port, error = %e, "serve redirect: write failed");
635        return;
636    }
637    if let Err(e) = tls.flush().await {
638        tracing::debug!(%port, error = %e, "serve redirect: flush failed");
639    }
640    drop(tls.shutdown().await);
641}
642
643/// Write a bodyless HTTP status response (e.g. `404 Not Found`) on a TLS-terminated stream, then
644/// close. Local mirror of `peerapi_doh::write_status` (which takes the concrete peerAPI stream type).
645async fn write_http_status<S>(port: u16, mut tls: S, status: &str)
646where
647    S: AsyncRead + AsyncWrite + Unpin,
648{
649    let head = format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
650    if let Err(e) = tls.write_all(head.as_bytes()).await {
651        tracing::debug!(%port, error = %e, "serve path: status write failed");
652        return;
653    }
654    drop(tls.flush().await);
655    drop(tls.shutdown().await);
656}
657
658/// Go's `path.Clean` (Go stdlib `path/path.go`), transliterated. This is the lexical cleaning
659/// `getServeHandler` (`ipn/ipnlocal/serve.go` @ `49e148c4a30b4f8098f69468fd27a7021d85ea02`) applies
660/// to the request path *before* it walks the mounts, so it must be the same cleaning here: dot and
661/// dot-dot segments are resolved, repeated and trailing separators collapse, and a leading dot-dot
662/// on a rooted path is dropped (`/api/../secret` ⇒ `/secret`, `/../x` ⇒ `/x`, `//a//b/` ⇒ `/a/b`).
663///
664/// Purely lexical, exactly like Go's: it never touches a filesystem and never decodes percent
665/// escapes. Non-rooted inputs keep Go's answers too — `""` and `"."` clean to `"."`, and `"*"`
666/// cleans to `"*"` — which is what makes the "not absolute" refusal in [`match_path_handler`]
667/// catch the malformed request targets.
668fn clean_path(path: &str) -> String {
669    let s = path.as_bytes();
670    if s.is_empty() {
671        return ".".to_string();
672    }
673    let n = s.len();
674    let rooted = s[0] == b'/';
675
676    // `out` is Go's `lazybuf`: the cleaned bytes written so far. `dotdot` is the index past which
677    // a `..` may still eat an element (1 on a rooted path, so `..` can never eat the leading `/`).
678    let mut out: Vec<u8> = Vec::with_capacity(n);
679    let mut r = 0usize;
680    let mut dotdot = 0usize;
681    if rooted {
682        out.push(b'/');
683        r = 1;
684        dotdot = 1;
685    }
686
687    while r < n {
688        if s[r] == b'/' {
689            // Empty path element: drop it (this is what collapses `//` and a trailing `/`).
690            r += 1;
691        } else if s[r] == b'.' && (r + 1 == n || s[r + 1] == b'/') {
692            // `.` element: drop it.
693            r += 1;
694        } else if s[r] == b'.' && r + 1 < n && s[r + 1] == b'.' && (r + 2 == n || s[r + 2] == b'/')
695        {
696            // `..` element: back up over the previously written element, if there is one.
697            r += 2;
698            if out.len() > dotdot {
699                let mut w = out.len() - 1;
700                while w > dotdot && out[w] != b'/' {
701                    w -= 1;
702                }
703                out.truncate(w);
704            } else if !rooted {
705                // Nothing to back up over and no leading `/` to anchor to: the `..` is kept, as
706                // Go keeps it (`../..` cleans to itself). A rooted path drops it instead, which is
707                // why `/../secret` is `/secret` and can never escape above the root.
708                if !out.is_empty() {
709                    out.push(b'/');
710                }
711                out.extend_from_slice(b"..");
712                dotdot = out.len();
713            }
714        } else {
715            // A real path element: add the separator if one is needed, then copy the element.
716            if (rooted && out.len() != 1) || (!rooted && !out.is_empty()) {
717                out.push(b'/');
718            }
719            while r < n && s[r] != b'/' {
720                out.push(s[r]);
721                r += 1;
722            }
723        }
724    }
725
726    if out.is_empty() {
727        return ".".to_string();
728    }
729    // Every byte written is copied verbatim from `path` (valid UTF-8) and the buffer is only ever
730    // truncated at an ASCII `/`, so this cannot split a multi-byte character.
731    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
732}
733
734/// Whether a mount point in a [`ServeTarget::Path`] map claims `path`.
735///
736/// A mount at `P` claims exactly `P` itself and the paths **below** it — i.e. `path == P`, or `path`
737/// begins with `P` followed by `/`. It does **not** claim arbitrary strings that merely start with
738/// the same bytes: a `/api` mount does not claim `/apifoo`, `/apibar` or `/api-internal`, which fall
739/// through to whatever shorter mount (typically `/`) does claim them.
740///
741/// A mount written with a trailing slash means the same thing as one without: `/api/` is normalized
742/// to `/api`, so it claims `/api/v2` without needing the request to be `/api//v2`, and it also
743/// claims the bare `/api`. The root mount `/` normalizes to the empty prefix and therefore claims
744/// every path.
745///
746/// ## Go behaviour this mirrors
747///
748/// Go's `getServeHandler` (`ipn/ipnlocal/serve.go`) never does a raw byte-prefix test. It first
749/// looks the cleaned request path up in the handler map exactly, and only then walks *backwards*
750/// over the path's `/` separators, retrying the lookup on each successively shorter truncation of
751/// the path. Because every candidate it ever tries is the path cut at a `/`, a handler can only ever
752/// be reached at a path-segment boundary — `/apifoo` never reaches the `/api` handler there, and it
753/// must not here either.
754fn mount_claims_path(mount: &str, path: &str) -> bool {
755    // "/api/" and "/api" are the same mount; "/" becomes the empty prefix, which claims everything.
756    let base = mount.strip_suffix('/').unwrap_or(mount);
757    if base.is_empty() {
758        return true;
759    }
760    match path.strip_prefix(base) {
761        // Exactly the mount itself, or a path below it. Anything else (`/apifoo` for `/api`) is a
762        // different path that merely shares a byte prefix.
763        Some(rest) => rest.is_empty() || rest.starts_with('/'),
764        None => false,
765    }
766}
767
768/// Pick the [`ServeTarget`] a request `path` dispatches to in a [`ServeTarget::Path`] mux, given
769/// the request's URL path — what [`request_path`] returns, i.e. Go's `r.URL.Path`: percent-decoded,
770/// with any scheme, authority and query already stripped, and not yet cleaned.
771///
772/// Pure and total over `(handlers, path)` — the whole routing decision, with no I/O — so it is
773/// testable directly instead of only through a TLS-terminated socket. [`serve_path`] calls this; it
774/// is the single definition of the rule, and a test that re-implemented it would be testing its own
775/// copy rather than what dispatch does.
776///
777/// ## Go behaviour this mirrors
778///
779/// `getServeHandler` (`ipn/ipnlocal/serve.go` @ `49e148c4a30b4f8098f69468fd27a7021d85ea02`) resolves
780/// a request in three steps, and so does this:
781///
782/// 1. **Exact lookup of the path.** A mount spelled exactly as the request's path wins verbatim,
783///    before any cleaning (Go: `wsc.Handlers().GetOk(r.URL.Path)`).
784/// 2. **Clean, then match.** Otherwise the path is [`clean_path`]ed — Go's `path.Clean` — and only
785///    the *cleaned* path is offered to the mounts. Dot-dot is therefore resolved **before** any
786///    mount is consulted: with mounts at `/` and `/api`, `/api/../secret` is `/secret` and is served
787///    by `/`; it must never reach the `/api` backend, which was never mounted for it. Because the
788///    path arrives percent-decoded, `/api/%2e%2e/secret` is that same request and gets that same
789///    answer.
790/// 3. **Refuse a path that is not absolute.** A cleaned path not starting with `/` matches nothing.
791///    Go needs this guard because the malformed request targets — `*` (`GET *`) and the empty path
792///    of an authority-form target — clean to `*` and `.`, which are `path.Dir` fixed points that
793///    would spin its backwards walk forever. Here the walk cannot spin, but the guard still carries
794///    Go's *routing* answer: those targets match no mount. Without it a root mount claims them,
795///    because `/` normalizes to the empty prefix that claims every string. It fires on exactly what
796///    it fires on in Go — a parsed path, which can no longer carry a scheme — so an absolute-form
797///    `GET http://host/api` is routed on `/api` here as it is there, not refused.
798///
799/// Longest match wins among the mounts that claim the cleaned path (see [`mount_claims_path`]): the
800/// one with the most path bytes is chosen, so `/api/v2` beats `/api` beats `/`. This is the same
801/// answer as Go's backwards walk, which tries the path cut at each `/` from longest to shortest.
802/// Ties (only reachable between the same mount spelled with and without a trailing slash, e.g.
803/// `/api` and `/api/`) resolve to the last in `BTreeMap` order, deterministically. `None` means no
804/// mount claims the path, which dispatch turns into a fail-closed 404.
805fn match_path_handler<'h>(
806    handlers: &'h BTreeMap<String, ServeTarget>,
807    path: &str,
808) -> Option<&'h ServeTarget> {
809    // (1) The path, looked up exactly.
810    if let Some(target) = handlers.get(path) {
811        return Some(target);
812    }
813    // (2) Everything else routes on the cleaned path, never the uncleaned one.
814    let cleaned = clean_path(path);
815    // (3) Not an absolute path => no mount claims it.
816    if !cleaned.starts_with('/') {
817        return None;
818    }
819    handlers
820        .iter()
821        .filter(|(mount, _)| mount_claims_path(mount, &cleaned))
822        .max_by_key(|(mount, _)| mount.strip_suffix('/').unwrap_or(mount).len())
823        .map(|(_, target)| target)
824}
825
826/// Serve a [`ServeTarget::Path`] mux on a TLS-terminated stream: read the request head, pick the
827/// longest-matching mount in `handlers` (via [`match_path_handler`]), and dispatch the matched
828/// nested target on the already-decrypted stream. Fail-closed: a malformed head, no matching mount,
829/// or an un-dispatchable nested target ⇒ 404/drop. For a matched nested `Proxy`, the request head consumed
830/// here is replayed to the backend first (via [`proxy_to_backend_with_prefix`]) so the backend sees
831/// the complete request. Backend dial failures inside a nested `Proxy` drop the conn. Nested `Path`
832/// is rejected by `ServeState::validate`, so it is not expected here; it is dropped fail-closed if it
833/// ever reaches dispatch.
834async fn serve_path<S>(port: u16, mut tls: S, handlers: &BTreeMap<String, ServeTarget>)
835where
836    S: AsyncRead + AsyncWrite + Unpin,
837{
838    let Some((buf, _end)) = read_http_head(&mut tls).await else {
839        tracing::debug!(%port, "serve path: incomplete/oversized request head; dropping conn");
840        return;
841    };
842    let Some(path) = request_path(&buf) else {
843        write_http_status(port, tls, "400 Bad Request").await;
844        return;
845    };
846
847    let Some(target) = match_path_handler(handlers, &path) else {
848        write_http_status(port, tls, "404 Not Found").await;
849        return;
850    };
851
852    match target {
853        // The request head was already consumed off `tls` by `read_http_head`; replay it (`buf`) to
854        // the backend FIRST so the backend sees the complete request (head + remaining body/stream),
855        // not a request with its first request-line+headers missing.
856        ServeTarget::Proxy { to } => proxy_to_backend_with_prefix(port, tls, to, &buf).await,
857        ServeTarget::Text { body } => write_text(port, tls, body).await,
858        ServeTarget::Redirect { to, status } => serve_redirect(port, tls, to, *status).await,
859        // Accept (no hand-back channel here), TcpForward (raw, not on a TLS path), nested Path
860        // (rejected by validate), and any future `#[non_exhaustive]` variant are not servable as a
861        // Path leaf: drop fail-closed rather than guess.
862        _ => {
863            tracing::warn!(%port, "serve path: unsupported nested target; dropping conn");
864            write_http_status(port, tls, "404 Not Found").await;
865        }
866    }
867}
868
869#[cfg(test)]
870mod tests {
871    use super::*;
872
873    fn proxy(to: &str) -> ServeTarget {
874        ServeTarget::Proxy { to: to.into() }
875    }
876
877    #[test]
878    fn cap_is_bounded() {
879        assert_eq!(MAX_SERVE_CONNS_PER_PORT, 256);
880    }
881
882    #[test]
883    fn reconcile_adds_new_ports() {
884        let current = BTreeMap::new();
885        let mut next = BTreeMap::new();
886        next.insert(443u16, ServeTarget::Accept);
887        next.insert(8443u16, proxy("127.0.0.1:8080"));
888        let (add, remove) = pure_reconcile(&current, &next);
889        assert_eq!(add, BTreeSet::from([443, 8443]));
890        assert!(remove.is_empty());
891    }
892
893    #[test]
894    fn reconcile_removes_dropped_ports() {
895        let mut current = BTreeMap::new();
896        current.insert(443u16, ServeTarget::Accept);
897        current.insert(8443u16, proxy("127.0.0.1:8080"));
898        let mut next = BTreeMap::new();
899        next.insert(443u16, ServeTarget::Accept);
900        let (add, remove) = pure_reconcile(&current, &next);
901        assert!(add.is_empty());
902        assert_eq!(remove, BTreeSet::from([8443]));
903    }
904
905    #[test]
906    fn reconcile_changed_port_is_remove_and_add() {
907        // Same port, different target => counts as both (full-replace would respawn it anyway).
908        let mut current = BTreeMap::new();
909        current.insert(443u16, proxy("127.0.0.1:8080"));
910        let mut next = BTreeMap::new();
911        next.insert(443u16, proxy("127.0.0.1:9090"));
912        let (add, remove) = pure_reconcile(&current, &next);
913        assert_eq!(add, BTreeSet::from([443]));
914        assert_eq!(remove, BTreeSet::from([443]));
915    }
916
917    #[test]
918    fn reconcile_unchanged_port_is_noop() {
919        let mut current = BTreeMap::new();
920        current.insert(443u16, ServeTarget::Accept);
921        let next = current.clone();
922        let (add, remove) = pure_reconcile(&current, &next);
923        assert!(add.is_empty());
924        assert!(remove.is_empty());
925    }
926
927    #[test]
928    fn terminates_tls_matches_dispatch_arm() {
929        // The dispatch decision (TLS vs raw) must agree with the type's own `terminates_tls`: only
930        // TcpForward is raw; Accept/Proxy/Text/Path/Redirect all terminate TLS.
931        assert!(ServeTarget::Accept.terminates_tls());
932        assert!(proxy("127.0.0.1:8080").terminates_tls());
933        assert!(ServeTarget::Text { body: "ok".into() }.terminates_tls());
934        assert!(
935            ServeTarget::Redirect {
936                to: "/elsewhere".into(),
937                status: 302,
938            }
939            .terminates_tls()
940        );
941        let mut handlers = BTreeMap::new();
942        handlers.insert("/".to_string(), proxy("127.0.0.1:8080"));
943        assert!(ServeTarget::Path { handlers }.terminates_tls());
944        assert!(
945            !ServeTarget::TcpForward {
946                to: "127.0.0.1:5000".into()
947            }
948            .terminates_tls()
949        );
950    }
951
952    #[test]
953    fn find_header_end_shared_with_peerapi_doh() {
954        // The local mirror was removed; serve dispatch now uses the shared peerAPI helper. Keep one
955        // assertion that the shared fn behaves as serve dispatch relies on (peerapi_doh owns the
956        // exhaustive coverage).
957        assert_eq!(
958            crate::peerapi_doh::find_header_end(b"GET / HTTP/1.1\r\n\r\n"),
959            Some(18)
960        );
961        assert_eq!(
962            crate::peerapi_doh::find_header_end(b"GET / HTTP/1.1\r\n"),
963            None
964        );
965    }
966
967    #[test]
968    fn request_path_strips_query() {
969        assert_eq!(
970            request_path(b"GET /api/v1?x=1 HTTP/1.1\r\nHost: h\r\n\r\n").as_deref(),
971            Some("/api/v1")
972        );
973        assert_eq!(
974            request_path(b"GET / HTTP/1.1\r\n\r\n").as_deref(),
975            Some("/")
976        );
977        assert_eq!(request_path(b"not a request").as_deref(), None);
978    }
979
980    #[test]
981    fn request_path_none_on_malformed_request_line() {
982        // No method/version framing at all => httparse rejects => None.
983        assert_eq!(request_path(b"GARBAGE\r\n\r\n").as_deref(), None);
984        // Empty buffer => incomplete => None.
985        assert_eq!(request_path(b"").as_deref(), None);
986    }
987
988    #[test]
989    fn request_target_path_matches_go_url_path() {
990        // Each row is Go's `r.URL.Path` for that request line — the string `getServeHandler` looks
991        // up, cleans and walks. `None` is Go's parse error, which its server answers with a 400
992        // without ever reaching a handler.
993        for (method, target, want) in [
994            // Origin-form: the ordinary case, query cut off.
995            ("GET", "/", Some("/")),
996            ("GET", "/api/v1", Some("/api/v1")),
997            ("GET", "/api/v1?x=1", Some("/api/v1")),
998            ("GET", "/api?", Some("/api")),
999            // Percent-decoded, which is the whole point: an encoded dot-dot is a dot-dot, so
1000            // `clean_path` can resolve it before any mount is consulted.
1001            ("GET", "/api/%2e%2e/secret", Some("/api/../secret")),
1002            ("GET", "/api/%2E%2E/secret", Some("/api/../secret")),
1003            ("GET", "/api/..%2fsecret", Some("/api/../secret")),
1004            // `%2f` is a real separator once decoded, exactly as it is in Go.
1005            ("GET", "/api%2Fv2", Some("/api/v2")),
1006            ("GET", "/%41", Some("/A")),
1007            // `+` is only a space in a query *component*; in a path it stays a `+`.
1008            ("GET", "/a+b", Some("/a+b")),
1009            // Absolute-form (RFC 7230 §5.3.2): scheme and authority are stripped, leaving the path.
1010            ("GET", "http://host/api", Some("/api")),
1011            ("GET", "https://host/api/v2?x=1", Some("/api/v2")),
1012            ("GET", "http://user@host/api", Some("/api")),
1013            ("GET", "http://host", Some("")),
1014            ("GET", "http://host/", Some("/")),
1015            // No scheme means no authority to split: `//foo/bar` is a path (it cleans to /foo/bar).
1016            ("GET", "//foo/bar", Some("//foo/bar")),
1017            // Targets with no path at all. All of these clean to "." or "*", so no mount claims them.
1018            ("GET", "*", Some("*")),
1019            ("GET", "host:443", Some("")),
1020            ("CONNECT", "host:443", Some("")),
1021            ("CONNECT", "192.0.2.1:443", Some("")),
1022            ("CONNECT", "*", Some("")),
1023            // Go's parse errors => 400 before any handler.
1024            ("GET", "", None),
1025            ("GET", "api/v2", None),
1026            ("GET", ":80/x", None),
1027            ("GET", "/api/%zz", None),
1028            ("GET", "/api/%2", None),
1029            ("GET", "/api/%", None),
1030            ("GET", "/api/\u{1}", None),
1031        ] {
1032            assert_eq!(
1033                request_target_path(method, target).as_deref(),
1034                want,
1035                "request_target_path({method:?}, {target:?})"
1036            );
1037        }
1038    }
1039
1040    #[test]
1041    fn request_path_returns_the_decoded_url_path() {
1042        // Straight off the wire through the production parse: what dispatch routes on is Go's
1043        // `r.URL.Path`, not the bytes of the request target.
1044        assert_eq!(
1045            request_path(b"GET /api/%2e%2e/secret HTTP/1.1\r\nHost: h\r\n\r\n").as_deref(),
1046            Some("/api/../secret")
1047        );
1048        assert_eq!(
1049            request_path(b"GET http://host/api?x=1 HTTP/1.1\r\nHost: host\r\n\r\n").as_deref(),
1050            Some("/api")
1051        );
1052        // A bad escape is not a path: Go's server answers 400, and so does dispatch.
1053        assert_eq!(
1054            request_path(b"GET /api/%zz HTTP/1.1\r\nHost: h\r\n\r\n").as_deref(),
1055            None
1056        );
1057    }
1058
1059    /// Route one request head the way dispatch does: the production parse ([`request_path`])
1060    /// feeding the production selection ([`match_path_handler`]). Nothing here re-implements
1061    /// either.
1062    fn route<'h>(
1063        head: &[u8],
1064        handlers: &'h BTreeMap<String, ServeTarget>,
1065    ) -> Option<&'h ServeTarget> {
1066        match_path_handler(handlers, &request_path(head)?)
1067    }
1068
1069    #[test]
1070    fn percent_encoded_dot_dot_does_not_reach_the_mount_it_climbed_out_of() {
1071        // The bug: routing on the raw target leaves `%2e%2e` an ordinary path segment, so the
1072        // cleaning finds no dot-dot to resolve and the `/api` mount claims a request for
1073        // `/secret`. Go decodes first, cleans `/api/../secret` to `/secret`, and serves it from `/`.
1074        let handlers = mux();
1075        let root = proxy("127.0.0.1:1");
1076        let api = proxy("127.0.0.1:2");
1077        let api_v2 = proxy("127.0.0.1:3");
1078        for target in [
1079            "/api/%2e%2e/secret",
1080            "/api/%2E%2E/secret",
1081            "/api/..%2fsecret",
1082            "/api%2f..%2fsecret",
1083            "/api/v2/%2e%2e/%2e%2e/secret",
1084        ] {
1085            let head = format!("GET {target} HTTP/1.1\r\nHost: h\r\n\r\n");
1086            let picked = route(head.as_bytes(), &handlers);
1087            assert_ne!(
1088                picked,
1089                Some(&api),
1090                "{target} must not reach the /api backend"
1091            );
1092            assert_ne!(
1093                picked,
1094                Some(&api_v2),
1095                "{target} must not reach the /api/v2 backend"
1096            );
1097            assert_eq!(
1098                picked,
1099                Some(&root),
1100                "{target} decodes and cleans to /secret, which only / claims"
1101            );
1102        }
1103        // Decoding cuts both ways: an encoded separator that lands inside a mount routes there.
1104        let head = b"GET /api%2fv2/x HTTP/1.1\r\nHost: h\r\n\r\n";
1105        assert_eq!(
1106            route(head, &handlers),
1107            Some(&api_v2),
1108            "/api%2fv2/x decodes to /api/v2/x"
1109        );
1110    }
1111
1112    #[test]
1113    fn absolute_form_request_target_routes_on_its_path() {
1114        // RFC 7230 §5.3.2 requires every server to accept absolute-form. Go's `r.URL.Path` is
1115        // `/api`, so the `/api` mount serves it; cleaning the raw target gives `http:/host/api`,
1116        // which is not absolute and would 404.
1117        let handlers = mux();
1118        let api = proxy("127.0.0.1:2");
1119        for target in [
1120            "http://host/api",
1121            "https://host/api",
1122            "http://host/api?x=1",
1123            "http://user@host/api/v1",
1124        ] {
1125            let head = format!("GET {target} HTTP/1.1\r\nHost: host\r\n\r\n");
1126            assert_eq!(
1127                route(head.as_bytes(), &handlers),
1128                Some(&api),
1129                "{target} is a request for /api"
1130            );
1131        }
1132        // ...and the cleaning still applies to the path it carries.
1133        let head = b"GET http://host/api/../secret HTTP/1.1\r\nHost: host\r\n\r\n";
1134        assert_eq!(route(head, &handlers), Some(&proxy("127.0.0.1:1")));
1135    }
1136
1137    /// The mux `serve_path` dispatch tests below route against: root, `/api`, `/api/v2`, each with a
1138    /// distinguishable backend so a test can assert which one a path did *not* reach.
1139    fn mux() -> BTreeMap<String, ServeTarget> {
1140        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1141        handlers.insert("/".to_string(), proxy("127.0.0.1:1"));
1142        handlers.insert("/api".to_string(), proxy("127.0.0.1:2"));
1143        handlers.insert("/api/v2".to_string(), proxy("127.0.0.1:3"));
1144        handlers
1145    }
1146
1147    #[test]
1148    fn longest_matching_mount_wins() {
1149        // Calls the production selection (`serve_path` calls the same fn) — not a copy of it.
1150        let handlers = mux();
1151        assert_eq!(
1152            match_path_handler(&handlers, "/api/v2/x"),
1153            Some(&proxy("127.0.0.1:3")),
1154            "the longest mount claiming the path must win"
1155        );
1156        assert_eq!(
1157            match_path_handler(&handlers, "/api/v1"),
1158            Some(&proxy("127.0.0.1:2"))
1159        );
1160        assert_eq!(
1161            match_path_handler(&handlers, "/api"),
1162            Some(&proxy("127.0.0.1:2"))
1163        );
1164        assert_eq!(
1165            match_path_handler(&handlers, "/other"),
1166            Some(&proxy("127.0.0.1:1"))
1167        );
1168    }
1169
1170    #[test]
1171    fn mount_does_not_claim_a_longer_first_segment() {
1172        // The negative case, and the whole point: a `/api` mount must NOT swallow `/apifoo`. A raw
1173        // byte-prefix test routes these to the `/api` backend; Go's segment-boundary lookup does
1174        // not, and neither may we. Assert where they must *not* go, not only where they must.
1175        let handlers = mux();
1176        let api = proxy("127.0.0.1:2");
1177        let root = proxy("127.0.0.1:1");
1178        for path in ["/apifoo", "/apibar", "/api-internal", "/api_v2", "/apis/x"] {
1179            let picked = match_path_handler(&handlers, path);
1180            assert_ne!(picked, Some(&api), "{path} must not reach the /api backend");
1181            assert_eq!(
1182                picked,
1183                Some(&root),
1184                "{path} must fall through to the / mount"
1185            );
1186        }
1187        // Same shape one level down: `/api/v2` must not claim `/api/v20`.
1188        let picked = match_path_handler(&handlers, "/api/v20");
1189        assert_ne!(
1190            picked,
1191            Some(&proxy("127.0.0.1:3")),
1192            "/api/v20 must not reach the /api/v2 backend"
1193        );
1194        assert_eq!(picked, Some(&api));
1195    }
1196
1197    #[test]
1198    fn mount_claims_itself_and_paths_below_it() {
1199        assert!(mount_claims_path("/api", "/api"));
1200        assert!(mount_claims_path("/api", "/api/"));
1201        assert!(mount_claims_path("/api", "/api/v2/x"));
1202        assert!(!mount_claims_path("/api", "/apifoo"));
1203        assert!(!mount_claims_path("/api", "/ap"));
1204        assert!(!mount_claims_path("/api", "/"));
1205        // The root mount claims everything.
1206        assert!(mount_claims_path("/", "/"));
1207        assert!(mount_claims_path("/", "/anything/at/all"));
1208    }
1209
1210    #[test]
1211    fn trailing_slash_mount_needs_no_doubled_slash() {
1212        // `/api/` is the same mount as `/api`: it claims `/api/v2`, not only `/api//v2`.
1213        assert!(mount_claims_path("/api/", "/api/v2"));
1214        assert!(mount_claims_path("/api/", "/api/"));
1215        assert!(mount_claims_path("/api/", "/api"));
1216        assert!(!mount_claims_path("/api/", "/apifoo"));
1217
1218        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1219        handlers.insert("/".to_string(), proxy("127.0.0.1:1"));
1220        handlers.insert("/api/".to_string(), proxy("127.0.0.1:2"));
1221        assert_eq!(
1222            match_path_handler(&handlers, "/api/v2"),
1223            Some(&proxy("127.0.0.1:2"))
1224        );
1225        assert_eq!(
1226            match_path_handler(&handlers, "/apifoo"),
1227            Some(&proxy("127.0.0.1:1")),
1228            "/apifoo must fall through to / even when the mount is spelled /api/"
1229        );
1230    }
1231
1232    #[test]
1233    fn clean_path_matches_go_path_clean() {
1234        // The table is Go's own `path.Clean` test table (Go stdlib `path/path_test.go`), which is
1235        // the cleaning `getServeHandler` applies before it consults the mounts.
1236        for (input, want) in [
1237            ("", "."),
1238            ("abc", "abc"),
1239            ("abc/def", "abc/def"),
1240            ("a/b/c", "a/b/c"),
1241            (".", "."),
1242            ("..", ".."),
1243            ("../..", "../.."),
1244            ("/abc", "/abc"),
1245            ("/", "/"),
1246            ("abc/", "abc"),
1247            ("abc/def/", "abc/def"),
1248            ("a/b/c/", "a/b/c"),
1249            ("./", "."),
1250            ("../", ".."),
1251            ("../../", "../.."),
1252            ("/abc/", "/abc"),
1253            ("abc//def//ghi", "abc/def/ghi"),
1254            ("//abc", "/abc"),
1255            ("///abc", "/abc"),
1256            ("//abc//", "/abc"),
1257            ("abc//", "abc"),
1258            ("abc/./def", "abc/def"),
1259            ("/./abc/def", "/abc/def"),
1260            ("abc/..", "."),
1261            ("abc/def/..", "abc"),
1262            ("abc/def/../ghi", "abc/ghi"),
1263            ("abc/def/../../ghi", "ghi"),
1264            ("abc/def/../../..", ".."),
1265            ("/abc/def/../../..", "/"),
1266            ("abc/./../def", "def"),
1267            ("abc//./../def", "def"),
1268            ("abc/../../././../def", "../../def"),
1269            // A rooted path can never climb above the root: the leading `..` is dropped.
1270            ("/../abc", "/abc"),
1271            ("/api/../secret", "/secret"),
1272            // The malformed request targets. Neither becomes absolute, which is what the
1273            // "not absolute" refusal keys off.
1274            ("*", "*"),
1275            ("host:443", "host:443"),
1276        ] {
1277            assert_eq!(clean_path(input), want, "clean_path({input:?})");
1278        }
1279    }
1280
1281    #[test]
1282    fn dot_dot_segment_is_cleaned_before_the_mounts_are_consulted() {
1283        // The bug: matching the RAW target means `/api/../secret` starts with `/api/`, so the `/api`
1284        // mount claims it and the request reaches a backend it was never mounted for. Go cleans
1285        // first — the path is `/secret`, which only the `/` mount claims.
1286        let handlers = mux();
1287        let root = proxy("127.0.0.1:1");
1288        let api = proxy("127.0.0.1:2");
1289        let api_v2 = proxy("127.0.0.1:3");
1290
1291        for path in [
1292            "/api/../secret",
1293            "/api/v2/../../secret",
1294            "/api/./../secret",
1295            "/api/..//secret",
1296            // Climbing above the root is dropped, not an escape: still `/secret`.
1297            "/../api/../secret",
1298        ] {
1299            let picked = match_path_handler(&handlers, path);
1300            assert_ne!(picked, Some(&api), "{path} must not reach the /api backend");
1301            assert_ne!(
1302                picked,
1303                Some(&api_v2),
1304                "{path} must not reach the /api/v2 backend"
1305            );
1306            assert_eq!(
1307                picked,
1308                Some(&root),
1309                "{path} cleans to /secret, which only / claims"
1310            );
1311        }
1312
1313        // Cleaning cuts both ways: a dot-dot that lands back inside a mount still routes there.
1314        assert_eq!(
1315            match_path_handler(&handlers, "/api/v2/../v2/x"),
1316            Some(&api_v2),
1317            "/api/v2/../v2/x cleans to /api/v2/x"
1318        );
1319        assert_eq!(
1320            match_path_handler(&handlers, "/api/v2/.."),
1321            Some(&api),
1322            "/api/v2/.. cleans to /api"
1323        );
1324        // Redundant separators and dot segments normalize away too.
1325        assert_eq!(match_path_handler(&handlers, "//api//v2//x"), Some(&api_v2));
1326        assert_eq!(match_path_handler(&handlers, "/api/./v2"), Some(&api_v2));
1327    }
1328
1329    #[test]
1330    fn malformed_request_target_matches_no_mount() {
1331        // `GET * HTTP/1.1` yields the target `*`, and an authority-form target has no path at all.
1332        // Go refuses both (they do not clean to an absolute path). A root mount normalizes to the
1333        // empty prefix that claims every string, so without the refusal `*` would be served by `/`.
1334        let handlers = mux();
1335        for target in ["*", "host:443", "example.com:443", "", ".", "..", "api/v2"] {
1336            assert_eq!(
1337                match_path_handler(&handlers, target),
1338                None,
1339                "{target:?} is not an absolute path and must match no mount, not even /"
1340            );
1341        }
1342        // A mount spelled exactly as the raw target still wins: that is Go's first lookup, which
1343        // happens before the cleaning and the absolute-path refusal.
1344        let mut odd: BTreeMap<String, ServeTarget> = BTreeMap::new();
1345        odd.insert("*".to_string(), proxy("127.0.0.1:9"));
1346        assert_eq!(match_path_handler(&odd, "*"), Some(&proxy("127.0.0.1:9")));
1347    }
1348
1349    #[test]
1350    fn unmatched_path_selects_nothing() {
1351        // No root mount => a path no mount claims is `None`, which dispatch turns into a 404.
1352        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1353        handlers.insert("/api".to_string(), proxy("127.0.0.1:2"));
1354        assert_eq!(match_path_handler(&handlers, "/apifoo"), None);
1355        assert_eq!(match_path_handler(&handlers, "/other"), None);
1356        assert_eq!(
1357            match_path_handler(&handlers, "/api/v2"),
1358            Some(&proxy("127.0.0.1:2"))
1359        );
1360    }
1361
1362    #[test]
1363    fn redirect_reason_known_statuses() {
1364        assert_eq!(redirect_reason(301), "Moved Permanently");
1365        assert_eq!(redirect_reason(308), "Permanent Redirect");
1366        assert_eq!(redirect_reason(399), "Redirect");
1367    }
1368
1369    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1370
1371    /// Read everything the server side wrote to the `client` half of a duplex until the server task
1372    /// closes its end (drop/shutdown), returning it as a `String`.
1373    async fn drain_to_string(mut client: tokio::io::DuplexStream) -> String {
1374        let mut out = Vec::new();
1375        drop(client.read_to_end(&mut out).await);
1376        String::from_utf8(out).expect("server emitted valid utf8")
1377    }
1378
1379    #[tokio::test]
1380    async fn serve_redirect_emits_exact_response() {
1381        let (client, server) = tokio::io::duplex(4096);
1382        let t = tokio::spawn(async move {
1383            serve_redirect(443, server, "/elsewhere", 302).await;
1384        });
1385        let got = drain_to_string(client).await;
1386        t.await.unwrap();
1387        assert_eq!(
1388            got,
1389            "HTTP/1.1 302 Found\r\nLocation: /elsewhere\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1390        );
1391    }
1392
1393    #[tokio::test]
1394    async fn write_http_status_emits_status_line() {
1395        let (client, server) = tokio::io::duplex(4096);
1396        let t = tokio::spawn(async move {
1397            write_http_status(443, server, "404 Not Found").await;
1398        });
1399        let got = drain_to_string(client).await;
1400        t.await.unwrap();
1401        assert_eq!(
1402            got,
1403            "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1404        );
1405
1406        let (client, server) = tokio::io::duplex(4096);
1407        let t = tokio::spawn(async move {
1408            write_http_status(443, server, "400 Bad Request").await;
1409        });
1410        let got = drain_to_string(client).await;
1411        t.await.unwrap();
1412        assert_eq!(
1413            got,
1414            "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1415        );
1416    }
1417
1418    #[tokio::test]
1419    async fn read_http_head_reads_terminated_head() {
1420        let (mut client, mut server) = tokio::io::duplex(4096);
1421        client
1422            .write_all(b"GET /api HTTP/1.1\r\nHost: h\r\n\r\nBODY")
1423            .await
1424            .unwrap();
1425        drop(client);
1426        let (buf, end) = read_http_head(&mut server).await.expect("complete head");
1427        // `end` points just past the terminator; the head + trailing body are both buffered.
1428        assert_eq!(&buf[..end], b"GET /api HTTP/1.1\r\nHost: h\r\n\r\n");
1429        assert_eq!(&buf[end..], b"BODY");
1430    }
1431
1432    #[tokio::test]
1433    async fn read_http_head_none_on_early_eof() {
1434        let (mut client, mut server) = tokio::io::duplex(4096);
1435        client.write_all(b"GET / HTTP/1.1\r\n").await.unwrap();
1436        drop(client); // EOF before the terminator
1437        assert!(read_http_head(&mut server).await.is_none());
1438    }
1439
1440    #[tokio::test]
1441    async fn read_http_head_none_on_oversized_head() {
1442        let (mut client, mut server) = tokio::io::duplex(64 * 1024);
1443        // A head that never terminates and exceeds MAX_HTTP_HEAD must be dropped fail-closed.
1444        let oversized = vec![b'a'; MAX_HTTP_HEAD + 1024];
1445        client.write_all(&oversized).await.unwrap();
1446        drop(client);
1447        assert!(read_http_head(&mut server).await.is_none());
1448    }
1449
1450    #[tokio::test]
1451    async fn read_http_head_never_exceeds_max_head() {
1452        // A terminator landing exactly at the bound still succeeds (the buffer never overshoots).
1453        let (mut client, mut server) = tokio::io::duplex(MAX_HTTP_HEAD + 16);
1454        let mut head = vec![b'a'; MAX_HTTP_HEAD - 4];
1455        head.extend_from_slice(b"\r\n\r\n");
1456        assert_eq!(head.len(), MAX_HTTP_HEAD);
1457        client.write_all(&head).await.unwrap();
1458        drop(client);
1459        let (buf, end) = read_http_head(&mut server).await.expect("head at bound");
1460        assert_eq!(end, MAX_HTTP_HEAD);
1461        assert!(buf.len() <= MAX_HTTP_HEAD);
1462    }
1463
1464    #[tokio::test]
1465    async fn proxy_with_prefix_writes_prefix_before_bidi_copy() {
1466        // Fix 1 regression guard: the consumed request head MUST hit the backend FIRST, before the
1467        // bidirectional splice forwards the rest of the client stream. The backend is a real
1468        // loopback TcpListener (the helper dials `to` via tokio TcpStream).
1469        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1470        let backend_addr = listener.local_addr().unwrap();
1471
1472        let prefix = b"GET /api HTTP/1.1\r\nHost: h\r\n\r\n";
1473        let body = b"trailing-body-bytes";
1474        let backend = tokio::spawn(async move {
1475            let (mut sock, _) = listener.accept().await.unwrap();
1476            let mut head = vec![0u8; prefix.len()];
1477            sock.read_exact(&mut head).await.unwrap();
1478            let mut rest = vec![0u8; body.len()];
1479            sock.read_exact(&mut rest).await.unwrap();
1480            (head, rest)
1481        });
1482
1483        // Client side of the duplex stands in for the TLS-terminated stream the helper splices.
1484        let (mut client, server) = tokio::io::duplex(4096);
1485        let to = backend_addr.to_string();
1486        let proxy_task = tokio::spawn(async move {
1487            proxy_to_backend_with_prefix(443, server, &to, prefix).await;
1488        });
1489
1490        // Feed the rest of the request body through the splice, then close.
1491        client.write_all(body).await.unwrap();
1492        drop(client);
1493
1494        let (head, rest) = backend.await.unwrap();
1495        proxy_task.await.unwrap();
1496        assert_eq!(
1497            head, prefix,
1498            "prefix (consumed head) replayed to backend first"
1499        );
1500        assert_eq!(rest, body, "remaining stream spliced after the prefix");
1501    }
1502
1503    #[tokio::test]
1504    async fn serve_path_proxy_replays_consumed_head_to_backend() {
1505        // End-to-end longest-prefix selection routing to a nested Proxy: the head consumed by
1506        // `read_http_head` must reach the backend, proving the request is not dropped (the bug).
1507        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1508        let backend_addr = listener.local_addr().unwrap();
1509        let request = b"GET /api/v2/x HTTP/1.1\r\nHost: h\r\n\r\n";
1510        let backend = tokio::spawn(async move {
1511            let (mut sock, _) = listener.accept().await.unwrap();
1512            let mut head = vec![0u8; request.len()];
1513            sock.read_exact(&mut head).await.unwrap();
1514            head
1515        });
1516
1517        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1518        handlers.insert("/".to_string(), proxy("127.0.0.1:1")); // shorter prefix (not selected)
1519        handlers.insert("/api/v2".to_string(), proxy(&backend_addr.to_string())); // longest match
1520
1521        let (mut client, server) = tokio::io::duplex(4096);
1522        let path_task = tokio::spawn(async move {
1523            serve_path(443, server, &handlers).await;
1524        });
1525        client.write_all(request).await.unwrap();
1526        drop(client);
1527
1528        let head = backend.await.unwrap();
1529        path_task.await.unwrap();
1530        assert_eq!(
1531            head, request,
1532            "serve_path routed to the longest-prefix Proxy and replayed the consumed head"
1533        );
1534    }
1535
1536    #[tokio::test]
1537    async fn serve_path_text_target_emits_body() {
1538        // Longest-prefix selection routing to a nested Text target: the body is emitted verbatim.
1539        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1540        handlers.insert(
1541            "/".to_string(),
1542            ServeTarget::Text {
1543                body: "root".into(),
1544            },
1545        );
1546        handlers.insert(
1547            "/hello".to_string(),
1548            ServeTarget::Text {
1549                body: "hello-body".into(),
1550            },
1551        );
1552
1553        let (mut client, server) = tokio::io::duplex(4096);
1554        let t = tokio::spawn(async move {
1555            serve_path(443, server, &handlers).await;
1556        });
1557        client
1558            .write_all(b"GET /hello/world HTTP/1.1\r\nHost: h\r\n\r\n")
1559            .await
1560            .unwrap();
1561        // Keep the client half open: `read_http_head` already saw the full head, and the Text target
1562        // neither reads further nor needs EOF. Drain the body the server writes + shuts down.
1563        let got = drain_to_string(client).await;
1564        t.await.unwrap();
1565        assert_eq!(got, "hello-body");
1566    }
1567
1568    #[tokio::test]
1569    async fn serve_path_does_not_route_a_longer_first_segment_to_the_shorter_mount() {
1570        // End to end through the real dispatch: with `/` and `/hello` mounted, `/hellofoo` is a
1571        // different path, not a path below `/hello`, so it must be served by the `/` mount.
1572        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1573        handlers.insert(
1574            "/".to_string(),
1575            ServeTarget::Text {
1576                body: "root".into(),
1577            },
1578        );
1579        handlers.insert(
1580            "/hello".to_string(),
1581            ServeTarget::Text {
1582                body: "hello-body".into(),
1583            },
1584        );
1585
1586        let (mut client, server) = tokio::io::duplex(4096);
1587        let t = tokio::spawn(async move {
1588            serve_path(443, server, &handlers).await;
1589        });
1590        client
1591            .write_all(b"GET /hellofoo HTTP/1.1\r\nHost: h\r\n\r\n")
1592            .await
1593            .unwrap();
1594        let got = drain_to_string(client).await;
1595        t.await.unwrap();
1596        assert_ne!(
1597            got, "hello-body",
1598            "/hellofoo must not reach the /hello mount"
1599        );
1600        assert_eq!(got, "root");
1601    }
1602
1603    /// Text mux used by the dispatch tests below: `/` and `/api` with distinguishable bodies, so a
1604    /// test can assert which backend a request did *not* reach.
1605    fn text_mux() -> BTreeMap<String, ServeTarget> {
1606        let mut handlers: BTreeMap<String, ServeTarget> = BTreeMap::new();
1607        handlers.insert(
1608            "/".to_string(),
1609            ServeTarget::Text {
1610                body: "root".into(),
1611            },
1612        );
1613        handlers.insert(
1614            "/api".to_string(),
1615            ServeTarget::Text {
1616                body: "api-body".into(),
1617            },
1618        );
1619        handlers
1620    }
1621
1622    /// Run one raw request line through the real dispatch and return everything the server wrote.
1623    async fn serve_path_response(
1624        request: &[u8],
1625        handlers: BTreeMap<String, ServeTarget>,
1626    ) -> String {
1627        let (mut client, server) = tokio::io::duplex(4096);
1628        let t = tokio::spawn(async move {
1629            serve_path(443, server, &handlers).await;
1630        });
1631        client.write_all(request).await.unwrap();
1632        let got = drain_to_string(client).await;
1633        t.await.unwrap();
1634        got
1635    }
1636
1637    #[tokio::test]
1638    async fn serve_path_does_not_route_a_dot_dot_target_to_the_mount_it_climbed_out_of() {
1639        // End to end through the real dispatch: the request target names `/api`, but it climbs out
1640        // of it. Go cleans to `/secret` and serves it from `/`; the `/api` backend must never see
1641        // it — it was never mounted for `/secret`.
1642        let got = serve_path_response(
1643            b"GET /api/../secret HTTP/1.1\r\nHost: h\r\n\r\n",
1644            text_mux(),
1645        )
1646        .await;
1647        assert_ne!(
1648            got, "api-body",
1649            "/api/../secret must not reach the /api mount"
1650        );
1651        assert_eq!(got, "root", "/api/../secret cleans to /secret, served by /");
1652
1653        // The query string is stripped before cleaning, exactly as Go cleans `r.URL.Path`.
1654        let got = serve_path_response(
1655            b"GET /api/../secret?x=1 HTTP/1.1\r\nHost: h\r\n\r\n",
1656            text_mux(),
1657        )
1658        .await;
1659        assert_eq!(got, "root");
1660
1661        // And a target that stays inside the mount after cleaning still reaches it.
1662        let got =
1663            serve_path_response(b"GET /api/v2/../v2 HTTP/1.1\r\nHost: h\r\n\r\n", text_mux()).await;
1664        assert_eq!(got, "api-body");
1665    }
1666
1667    #[tokio::test]
1668    async fn serve_path_404s_a_malformed_request_target() {
1669        // `GET *` parses fine as a request line but is not an absolute path. Go matches no handler
1670        // for it; here the root mount would otherwise claim it, since `/` normalizes to the empty
1671        // prefix. Fail closed with a 404 instead of serving the root backend.
1672        let got = serve_path_response(b"GET * HTTP/1.1\r\nHost: h\r\n\r\n", text_mux()).await;
1673        assert_ne!(got, "root", "`GET *` must not be served by the / mount");
1674        assert!(
1675            got.starts_with("HTTP/1.1 404 Not Found\r\n"),
1676            "expected a 404, got {got:?}"
1677        );
1678
1679        // Authority-form (`CONNECT host:443`) likewise has no path to route on.
1680        let got =
1681            serve_path_response(b"CONNECT host:443 HTTP/1.1\r\nHost: h\r\n\r\n", text_mux()).await;
1682        assert!(
1683            got.starts_with("HTTP/1.1 404 Not Found\r\n"),
1684            "expected a 404, got {got:?}"
1685        );
1686    }
1687
1688    #[tokio::test]
1689    async fn serve_path_does_not_route_a_percent_encoded_dot_dot_to_the_mount_it_climbed_out_of() {
1690        // End to end through the real dispatch, with the two dots spelled as escapes: the request
1691        // target names `/api` but climbs out of it, and the `/api` backend must never see it.
1692        for target in [
1693            "/api/%2e%2e/secret",
1694            "/api/..%2fsecret",
1695            "/api%2f..%2fsecret",
1696        ] {
1697            let head = format!("GET {target} HTTP/1.1\r\nHost: h\r\n\r\n");
1698            let got = serve_path_response(head.as_bytes(), text_mux()).await;
1699            assert_ne!(got, "api-body", "{target} must not reach the /api mount");
1700            assert_eq!(
1701                got, "root",
1702                "{target} decodes and cleans to /secret, served by /"
1703            );
1704        }
1705    }
1706
1707    #[tokio::test]
1708    async fn serve_path_serves_an_absolute_form_request_target() {
1709        // `GET http://host/api HTTP/1.1` is a request for `/api` — absolute-form, which RFC 7230
1710        // §5.3.2 requires every server to accept. Routing on the raw target 404s it.
1711        let got = serve_path_response(
1712            b"GET http://host/api HTTP/1.1\r\nHost: host\r\n\r\n",
1713            text_mux(),
1714        )
1715        .await;
1716        assert_eq!(
1717            got, "api-body",
1718            "absolute-form /api must reach the /api mount"
1719        );
1720
1721        let got = serve_path_response(
1722            b"GET https://host/other?x=1 HTTP/1.1\r\nHost: host\r\n\r\n",
1723            text_mux(),
1724        )
1725        .await;
1726        assert_eq!(got, "root");
1727
1728        // The path it carries is cleaned like any other.
1729        let got = serve_path_response(
1730            b"GET http://host/api/../secret HTTP/1.1\r\nHost: host\r\n\r\n",
1731            text_mux(),
1732        )
1733        .await;
1734        assert_eq!(got, "root");
1735    }
1736
1737    #[tokio::test]
1738    async fn serve_path_400s_a_target_go_refuses_to_parse() {
1739        // Go's server fails these in `readRequest`, before any handler runs, and answers 400.
1740        for target in ["/api/%zz", "api/v2"] {
1741            let head = format!("GET {target} HTTP/1.1\r\nHost: h\r\n\r\n");
1742            let got = serve_path_response(head.as_bytes(), text_mux()).await;
1743            assert_ne!(got, "api-body", "{target} must reach no mount");
1744            assert_ne!(got, "root", "{target} must reach no mount");
1745            assert!(
1746                got.starts_with("HTTP/1.1 400 Bad Request\r\n"),
1747                "expected a 400 for {target}, got {got:?}"
1748            );
1749        }
1750    }
1751
1752    // NOTE: a live bind+accept test needs a running netstack channel + overlay; the existing
1753    // netstack-backed managers (fallback_tcp) likewise unit-test only the pure pieces (port diff,
1754    // dispatch decision) and leave the bind/accept path to integration coverage. The byte-emission
1755    // helpers above are exercised directly over `tokio::io::duplex` + loopback `TcpStream` backends;
1756    // the bind/accept/splice path is exercised via `Device::set_serve_config` against a real device.
1757}