Skip to main content

pitchfork_cli/proxy/
server.rs

1//! Reverse proxy server implementation.
2//!
3//! Listens on a configured port and routes requests to daemon processes based
4//! on the `Host` header subdomain pattern.
5//!
6//! When `proxy.https = true`, a local CA is auto-generated (via `rcgen`) and
7//! each incoming TLS connection is served with a per-domain certificate signed
8//! by that CA (SNI-based dynamic certificate issuance).
9
10use std::net::SocketAddr;
11use std::sync::Arc;
12
13use axum::Router;
14use axum::body::Body;
15use axum::extract::{Request, State};
16use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri};
17use axum::response::{IntoResponse, Response};
18use hyper::header::{COOKIE, HOST};
19
20/// Response header used to identify a pitchfork proxy (for health checks and debugging).
21const PITCHFORK_HEADER: &str = "x-pitchfork";
22
23/// Request header tracking how many times a request has passed through the proxy.
24/// Used to detect forwarding loops.
25const PROXY_HOPS_HEADER: &str = "x-pitchfork-hops";
26
27/// Maximum number of proxy hops before rejecting as a loop.
28const MAX_PROXY_HOPS: u64 = 5;
29
30/// How long a new connection has to reveal whether it is TLS and, if it is, to
31/// finish the handshake.
32///
33/// Both steps happen before the connection is a request the server is willing
34/// to spend time on, so a client that stalls there is holding a socket and a
35/// task for nothing.
36const HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
37
38/// Maximum number of minted host certificates kept at once.
39///
40/// Every distinct SNI name under the TLD costs a key generation and a file, and
41/// the set of names under a TLD is unbounded. A real machine serves a handful;
42/// this is generous for that and still refuses to grow without limit when
43/// something walks the namespace. The oldest entry is evicted, in memory and on
44/// disk, so a busy name simply gets minted again.
45const MAX_HOST_CERTS: usize = 256;
46
47/// How often a refusal may be logged. See [`crate::proxy::LogThrottle`].
48const REFUSAL_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
49
50/// Throttle for the "too many connections negotiating" warning.
51static REFUSED_HANDSHAKE: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
52
53/// Throttle for the "refusing to issue a certificate" warning.
54#[cfg(feature = "proxy-tls")]
55static REFUSED_SNI: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
56
57/// Total time shutdown spends letting connections and tunnels finish.
58///
59/// Shared by both drain phases and kept inside what the supervisor waits for,
60/// so neither phase is cut off by a caller that has stopped listening.
61pub(crate) const SHUTDOWN_DRAIN_BUDGET: std::time::Duration = std::time::Duration::from_secs(10);
62
63/// Maximum number of `CONNECT` tunnels open at once.
64///
65/// A tunnel holds two sockets for as long as the client keeps it, and nothing
66/// stops a client opening them in a loop — including through an existing
67/// tunnel, since the far end is this same listener. The handshake budget does
68/// not cover them, because a tunnel is established by then.
69const MAX_TUNNELS: usize = 256;
70
71/// Throttle for the "too many tunnels" warning.
72static REFUSED_TUNNEL: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
73
74/// Throttle for connections abandoned before they said anything.
75///
76/// Debug-level, so silent by default, but `mise run install-dev` turns debug
77/// logging on and these are triggered by exactly the behaviour their
78/// warn-level siblings are throttled for: a client opening connections and
79/// walking away. One line each would let it fill the disk of whoever is
80/// debugging.
81static ABANDONED_HANDSHAKE: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
82
83/// Throttle for `CONNECT` tunnels abandoned while being set up.
84static ABANDONED_TUNNEL: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
85
86/// Maximum number of connections negotiating at once.
87///
88/// This bounds only protocol detection and the TLS handshake, both of which are
89/// brief for a real client. A connection stops counting against it the moment
90/// its handshake finishes, so long-lived sessions — keep-alive, HTTP/2,
91/// WebSocket, CONNECT tunnels — do not consume the budget.
92const MAX_PENDING_HANDSHAKES: usize = 512;
93
94/// HTTP/1.1 hop-by-hop headers that are forbidden in HTTP/2 responses.
95/// These must be stripped when proxying an HTTP/1.1 backend response back to an HTTP/2 client.
96const HOP_BY_HOP_HEADERS: &[&str] = &[
97    "connection",
98    "keep-alive",
99    "proxy-connection",
100    "transfer-encoding",
101    "upgrade",
102];
103
104use hyper_util::client::legacy::Client;
105use hyper_util::client::legacy::connect::HttpConnector;
106use hyper_util::rt::TokioExecutor;
107use tokio::net::{TcpListener, TcpStream};
108
109use crate::daemon_id::DaemonId;
110use crate::pitchfork_toml::{ProxyProtocol, ProxyTlsMode};
111use crate::proxy::activity::{ACTIVITY, ActivityGuard, GuardedBody};
112use crate::settings::settings;
113use crate::supervisor::SUPERVISOR;
114
115// ─── Slug resolution cache ──────────────────────────────────────────────────
116//
117// `read_global_slugs()` reads ~/.config/pitchfork/config.toml from disk on every
118// call, and `namespace_for_dir()` traverses the filesystem upward to find the
119// nearest pitchfork.toml.  Both are called from `resolve_target_port()` which
120// sits in the hot path of every proxied HTTP request.
121//
122// This cache stores the resolved slug → (namespace, daemon_name) mapping
123// in memory with a short TTL so that the proxy does zero disk I/O for the vast
124// majority of requests while still picking up config changes within seconds.
125
126/// How long to cache the slug resolution table before re-reading from disk.
127const SLUG_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);
128
129/// How a hostname's TLS is handled, and which daemon port it maps to.
130///
131/// Read from the daemon's `pitchfork.toml` (`proxy_tls`, `proxy_tls_port`) when
132/// the slug table is refreshed, so the routing decision needs no disk I/O and
133/// is available whether or not the daemon is currently running.
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub struct ProxyTlsRoute {
136    /// `terminate` (default) or `passthrough`.
137    pub mode: ProxyTlsMode,
138    /// The HTTP version spoken to the daemon.
139    pub protocol: ProxyProtocol,
140    /// The daemon port this hostname maps to. `None` means the first port,
141    /// which is what a single-port daemon always wants.
142    pub port: Option<u16>,
143}
144
145/// Cached slug entry: pre-resolved namespace + daemon name for a slug.
146#[derive(Clone, Debug)]
147pub struct CachedSlugEntry {
148    /// The slug key as registered in config (needed for display in auto-start pages).
149    pub slug: String,
150    /// Expected namespace derived from `entry.resolve_dir()` (None if derivation failed).
151    pub namespace: Option<String>,
152    /// Daemon short name (defaults to slug name when not explicitly set).
153    pub daemon_name: String,
154    /// Project directory for this slug (needed for auto-start).
155    pub dir: std::path::PathBuf,
156    /// Worktrees (git) / workspaces (jj) discovered under this slug's project directory.
157    pub worktrees: Vec<crate::proxy::worktree::WorktreeEntry>,
158    /// Sanitized worktree prefixes (ASCII-lowercased) that were discovered but
159    /// are ambiguous, kept so a request naming one is refused rather than
160    /// falling through to the parent slug as an unknown wildcard prefix.
161    pub rejected_worktree_prefixes: std::collections::HashSet<String>,
162    /// TLS route for the slug's main checkout.
163    pub tls: ProxyTlsRoute,
164    /// TLS routes per worktree, keyed by ASCII-lowercased sanitized branch.
165    /// A worktree can configure its own `proxy_tls`, since each checkout has
166    /// its own `pitchfork.toml`.
167    pub worktree_tls: std::collections::HashMap<String, ProxyTlsRoute>,
168    /// The public URL requests for the slug itself are forwarded under.
169    /// Worktree subdomains of the slug are local names and keep their own.
170    pub public_url: Option<crate::proxy::public_url::PublicUrl>,
171}
172
173impl CachedSlugEntry {
174    /// The route this entry recorded for its main checkout, provided the slug
175    /// still names the same daemon in the same directory and namespace. A slug
176    /// repointed elsewhere must not carry the old daemon's mode and port over
177    /// to a new target whose config cannot be read.
178    fn known_route(
179        &self,
180        dir: &std::path::Path,
181        namespace: Option<&str>,
182        daemon_name: &str,
183    ) -> Option<ProxyTlsRoute> {
184        (self.dir == dir
185            && self.namespace.as_deref() == namespace
186            && self.daemon_name == daemon_name)
187            .then_some(self.tls)
188    }
189
190    /// The route this entry recorded for a worktree, provided the same daemon
191    /// was known there at the same path and namespace.
192    fn known_worktree_route(
193        &self,
194        wt: &crate::proxy::worktree::WorktreeEntry,
195        daemon_name: &str,
196    ) -> Option<ProxyTlsRoute> {
197        if self.daemon_name != daemon_name {
198            return None;
199        }
200        let branch = wt.sanitized_branch.to_ascii_lowercase();
201        self.worktrees
202            .iter()
203            .any(|known| {
204                known.sanitized_branch.eq_ignore_ascii_case(&branch)
205                    && known.path == wt.path
206                    && known.namespace == wt.namespace
207            })
208            .then(|| self.worktree_tls.get(&branch).copied())
209            .flatten()
210    }
211}
212
213/// In-memory cache for the global slug registry + derived namespaces.
214struct SlugCache {
215    entries: Arc<std::collections::HashMap<String, CachedSlugEntry>>,
216    expires_at: std::time::Instant,
217}
218
219/// The cached slug table.
220///
221/// A `std::sync::RwLock` rather than an async one on purpose: `rustls` calls
222/// its certificate resolver from a synchronous trait method, and that resolver
223/// has to know whether a hostname is passthrough before it issues a certificate
224/// for it. One lock means routing and the resolver read the same table by
225/// construction, so they cannot disagree about a hostname's mode. Every
226/// critical section is a clone of an `Arc` or a comparison of two `Instant`s,
227/// with the disk I/O deliberately outside, and nothing awaits while holding it.
228static SLUG_CACHE: once_cell::sync::Lazy<std::sync::RwLock<SlugCache>> =
229    once_cell::sync::Lazy::new(|| {
230        std::sync::RwLock::new(SlugCache {
231            entries: Arc::new(std::collections::HashMap::new()),
232            expires_at: std::time::Instant::now(), // expired → will be populated on first access
233        })
234    });
235
236/// Read the cached slug table without awaiting.
237///
238/// Empty until the table has been populated once, which every TLS connection
239/// does before reaching the certificate resolver. An empty table resolves every
240/// hostname to `terminate`, which is the behavior of a proxy with no slugs.
241fn slug_snapshot() -> Arc<std::collections::HashMap<String, CachedSlugEntry>> {
242    let guard = SLUG_CACHE
243        .read()
244        .unwrap_or_else(std::sync::PoisonError::into_inner);
245    Arc::clone(&guard.entries)
246}
247
248/// Serializes refreshes of [`SLUG_CACHE`], so at most one build is in flight.
249///
250/// Without it, every request arriving on an expired cache builds its own table
251/// and publishes it, which both duplicates the work — the build runs
252/// subprocesses to discover worktrees — and leaves each caller holding a
253/// different generation than the one the certificate resolver reads. With it,
254/// the first arrival builds and the rest wait and take that table, so one
255/// generation is live at a time.
256static SLUG_REFRESH: once_cell::sync::Lazy<tokio::sync::Mutex<()>> =
257    once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(()));
258
259/// The cached table if it has not expired.
260fn fresh_slugs() -> Option<Arc<std::collections::HashMap<String, CachedSlugEntry>>> {
261    let cache = SLUG_CACHE
262        .read()
263        .unwrap_or_else(std::sync::PoisonError::into_inner);
264    (std::time::Instant::now() < cache.expires_at).then(|| Arc::clone(&cache.entries))
265}
266
267/// Drop every worktree whose sanitized branch is ambiguous under
268/// case-insensitive host matching, keeping the unambiguous ones.
269///
270/// Both sides of a collision are dropped rather than one being picked: the
271/// alternative routes a request to a worktree the user did not name, which is
272/// worse than not routing it at all.
273fn reject_case_colliding_worktrees(
274    wts: Vec<crate::proxy::worktree::WorktreeEntry>,
275) -> (
276    Vec<crate::proxy::worktree::WorktreeEntry>,
277    std::collections::HashSet<String>,
278) {
279    let collisions =
280        crate::proxy::ascii_case_collisions(wts.iter().map(|w| w.sanitized_branch.as_str()));
281    if collisions.is_empty() {
282        return (wts, collisions);
283    }
284
285    let (dropped, kept): (Vec<_>, Vec<_>) = wts
286        .into_iter()
287        .partition(|w| collisions.contains(&w.sanitized_branch.to_ascii_lowercase()));
288
289    let mut folded: Vec<&String> = collisions.iter().collect();
290    folded.sort();
291    for key in folded {
292        let mut branches: Vec<&str> = dropped
293            .iter()
294            .filter(|w| w.sanitized_branch.eq_ignore_ascii_case(key))
295            .map(|w| w.branch.as_str())
296            .collect();
297        branches.sort();
298        log::warn!(
299            "Worktree slug collision: branches [{}] all route to '{key}' under \
300             case-insensitive host matching. None of them will be routed; \
301             rename a branch to disambiguate.",
302            branches.join(", "),
303        );
304    }
305
306    (kept, collisions)
307}
308
309/// Read a daemon's TLS route (`proxy_tls`, `proxy_tls_port`) from the config
310/// that applies in `dir`.
311///
312/// `Ok(None)` means that directory says nothing about the daemon: its config
313/// does not describe it. That is deliberately not the same as a route of
314/// `terminate`: a worktree the proxy knows nothing about inherits its slug's
315/// mode, where a synthesized `terminate` would silently stop splicing a
316/// passthrough daemon and answer with the proxy's certificate instead. A
317/// directory that *does* describe the daemon is authoritative, including when
318/// it leaves `proxy_tls` out and so terminates.
319///
320/// `Err` means the config could not be read at all, which says nothing about
321/// the daemon either way. The merged config fails as a whole, so an error in
322/// an unrelated daemon lands here too; callers that already know a route keep
323/// it rather than treat the error as `terminate`.
324///
325/// Any other way of resolving a hostname to a daemon can reuse this to get the
326/// same TLS decision, since the mode belongs to the daemon rather than to the
327/// hostname that reached it.
328///
329/// The config read goes through the merged-config cache, so a refresh that
330/// finds nothing changed costs a `stat` per config file rather than a reparse.
331pub(crate) fn read_proxy_tls_route(
332    dir: &std::path::Path,
333    namespace: Option<&str>,
334    daemon_name: &str,
335) -> miette::Result<Option<ProxyTlsRoute>> {
336    let Some(id) = namespace.and_then(|ns| DaemonId::try_new(ns, daemon_name).ok()) else {
337        return Ok(None);
338    };
339    let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(dir)?;
340    Ok(pt.daemons.get(&id).map(|cfg| ProxyTlsRoute {
341        mode: cfg.proxy_tls.unwrap_or_default(),
342        protocol: cfg.proxy_protocol.unwrap_or_default(),
343        port: cfg.effective_proxy_tls_port(),
344    }))
345}
346
347/// The result of [`read_proxy_tls_route`], falling back to `known` — the route
348/// recorded by the previous slug-table refresh — when the config is unreadable.
349///
350/// The warning is logged once per distinct error, since the table refreshes
351/// every couple of seconds and the error persists until the config is fixed.
352fn route_or_last_known(
353    read: miette::Result<Option<ProxyTlsRoute>>,
354    known: Option<ProxyTlsRoute>,
355    dir: &std::path::Path,
356    daemon_name: &str,
357) -> Option<ProxyTlsRoute> {
358    read.unwrap_or_else(|e| {
359        crate::proxy::hostname::warn_once(&format!(
360            "Proxy TLS route for daemon '{daemon_name}': could not read config in {}; \
361             keeping its last known TLS mode until the config is fixed: {e}",
362            dir.display()
363        ));
364        known
365    })
366}
367
368/// Build the slug lookup table from disk (expensive — involves file I/O + subprocesses).
369/// Called outside the cache lock via `spawn_blocking` to avoid blocking the Tokio runtime.
370///
371/// Keys are ASCII-lowercased, and slugs that collide once folded are left out
372/// entirely — see [`reject_case_colliding_worktrees`] for why ambiguity is
373/// rejected rather than resolved.
374///
375/// `previous` is the table being replaced. When a directory's config cannot be
376/// read, the route recorded there is kept, so a config error — even one in an
377/// unrelated daemon — cannot quietly turn a running passthrough daemon into a
378/// terminated one that answers with the proxy's certificate.
379fn build_slug_entries(
380    previous: &std::collections::HashMap<String, CachedSlugEntry>,
381) -> std::collections::HashMap<String, CachedSlugEntry> {
382    let global_slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
383    let collisions = crate::proxy::ascii_case_collisions(global_slugs.keys().map(String::as_str));
384    let mut folded: Vec<&String> = collisions.iter().collect();
385    folded.sort();
386    for key in folded {
387        let mut spellings: Vec<&str> = global_slugs
388            .keys()
389            .filter(|s| s.eq_ignore_ascii_case(key))
390            .map(String::as_str)
391            .collect();
392        spellings.sort();
393        log::warn!(
394            "Slug collision: [{}] differ only by case and host names are case-insensitive. \
395             None of them will be routed; remove or rename all but one.",
396            spellings.join(", "),
397        );
398    }
399
400    let mut entries: std::collections::HashMap<String, CachedSlugEntry> =
401        std::collections::HashMap::with_capacity(global_slugs.len());
402    let worktree_enabled = crate::settings::settings().general.worktree;
403    for (slug, entry) in &global_slugs {
404        let key = slug.to_ascii_lowercase();
405        if collisions.contains(&key) {
406            continue;
407        }
408        let ns = entry.resolve_namespace();
409        let daemon_name = entry.daemon.as_deref().unwrap_or(slug).to_string();
410        let (worktrees, rejected_worktree_prefixes) = if worktree_enabled {
411            let wts = match entry.resolve_dir() {
412                Some(dir) => crate::proxy::worktree::discover_worktrees(&dir),
413                None => vec![],
414            };
415            let wts = wts
416                .into_iter()
417                .map(|mut wt| {
418                    wt.namespace =
419                        crate::pitchfork_toml::PitchforkToml::namespace_for_dir(&wt.path).ok();
420                    wt
421                })
422                .collect();
423            reject_case_colliding_worktrees(wts)
424        } else {
425            (vec![], std::collections::HashSet::new())
426        };
427        let dir = entry.resolve_dir().unwrap_or_default();
428        let public_url = entry.public_url.as_deref().and_then(|value| {
429            crate::proxy::public_url::PublicUrl::parse(value)
430                .map_err(|e| {
431                    crate::proxy::hostname::warn_once(&format!(
432                        "Slug '{slug}' has an invalid public_url, so it is forwarded \
433                         under its local name: {e}"
434                    ))
435                })
436                .ok()
437        });
438        let prev = previous.get(&key);
439        // The slug's own directory has nothing to inherit from, so silence
440        // there is the default route. An unreadable config keeps the last
441        // known route; with none known yet, there is nothing else to go on.
442        let tls = route_or_last_known(
443            read_proxy_tls_route(&dir, ns.as_deref(), &daemon_name),
444            prev.and_then(|p| p.known_route(&dir, ns.as_deref(), &daemon_name)),
445            &dir,
446            &daemon_name,
447        )
448        .unwrap_or_default();
449        // A worktree only gets an entry when its own config describes the
450        // daemon, or when it did last time and cannot be read now; the rest
451        // inherit the slug's route at lookup time.
452        let worktree_tls = worktrees
453            .iter()
454            .filter_map(|wt| {
455                let branch = wt.sanitized_branch.to_ascii_lowercase();
456                route_or_last_known(
457                    read_proxy_tls_route(&wt.path, wt.namespace.as_deref(), &daemon_name),
458                    prev.and_then(|p| p.known_worktree_route(wt, &daemon_name)),
459                    &wt.path,
460                    &daemon_name,
461                )
462                .map(|route| (branch, route))
463            })
464            .collect();
465        entries.insert(
466            key,
467            CachedSlugEntry {
468                slug: slug.clone(),
469                namespace: ns,
470                daemon_name,
471                dir,
472                worktrees,
473                rejected_worktree_prefixes,
474                tls,
475                worktree_tls,
476                public_url,
477            },
478        );
479    }
480    entries
481}
482
483/// Return the cached slug table, refreshing from disk if expired.
484///
485/// The disk I/O happens *outside* the cache lock so a refresh does not block
486/// readers, and refreshes are serialized against each other so only one build
487/// runs at a time. Every caller therefore returns the one table that is
488/// published, which is what keeps routing and the certificate resolver from
489/// disagreeing about a hostname: a caller holding its own build could route a
490/// hostname as terminating while the resolver, reading the published table,
491/// refuses to issue for it and the handshake is dropped rather than spliced.
492pub async fn get_cached_slugs() -> Arc<std::collections::HashMap<String, CachedSlugEntry>> {
493    // Fast path: cache still valid — just clone the Arc.
494    if let Some(entries) = fresh_slugs() {
495        return entries;
496    }
497
498    // Slow path: one refresh at a time.
499    let _refreshing = SLUG_REFRESH.lock().await;
500
501    // Another caller may have refreshed while this one waited for the lock.
502    if let Some(entries) = fresh_slugs() {
503        return entries;
504    }
505
506    // Build from disk on a blocking thread (involves subprocess calls).
507    let previous = slug_snapshot();
508    let new_entries = Arc::new(
509        tokio::task::spawn_blocking(move || build_slug_entries(&previous))
510            .await
511            .unwrap_or_else(|e| {
512                log::warn!("Failed to refresh slug cache: {e}");
513                std::collections::HashMap::new()
514            }),
515    );
516
517    let mut cache = SLUG_CACHE
518        .write()
519        .unwrap_or_else(std::sync::PoisonError::into_inner);
520    cache.entries = Arc::clone(&new_entries);
521    cache.expires_at = std::time::Instant::now() + SLUG_CACHE_TTL;
522    new_entries
523}
524
525// ─── Hostname registry cache ────────────────────────────────────────────────
526//
527// The automatic `<daemon>.<worktree>.<project>` hostnames are resolved against
528// a registry built from every project pitchfork knows about.  Building it reads
529// configuration files and enumerates git worktrees, so the result is cached
530// with the same short TTL as the slug table.
531
532struct RegistryCache {
533    registry: Arc<crate::proxy::hostname::HostRegistry>,
534    expires_at: std::time::Instant,
535}
536
537/// The cached hostname registry.
538///
539/// A `std::sync::RwLock` for the same reason as [`SLUG_CACHE`]: the certificate
540/// resolver runs in a synchronous trait method and has to know whether a
541/// hostname is passthrough before it issues a certificate for it. Both readers
542/// share one registry, so routing and the resolver cannot disagree.
543static HOST_REGISTRY: once_cell::sync::Lazy<std::sync::RwLock<RegistryCache>> =
544    once_cell::sync::Lazy::new(|| {
545        std::sync::RwLock::new(RegistryCache {
546            registry: Arc::new(crate::proxy::hostname::HostRegistry::default()),
547            expires_at: std::time::Instant::now(), // expired -> built on first access
548        })
549    });
550
551/// Serializes registry refreshes, so one build runs at a time and every caller
552/// returns the table that was published. See [`SLUG_REFRESH`].
553static REGISTRY_REFRESH: once_cell::sync::Lazy<tokio::sync::Mutex<()>> =
554    once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(()));
555
556/// The cached registry if it has not expired.
557fn fresh_registry() -> Option<Arc<crate::proxy::hostname::HostRegistry>> {
558    let cache = HOST_REGISTRY
559        .read()
560        .unwrap_or_else(std::sync::PoisonError::into_inner);
561    (std::time::Instant::now() < cache.expires_at).then(|| Arc::clone(&cache.registry))
562}
563
564/// Read the cached hostname registry without awaiting.
565///
566/// Empty until it has been built once, which every TLS connection does before
567/// reaching the certificate resolver. An empty registry resolves every hostname
568/// to `terminate`, the behavior of a proxy that knows no projects.
569fn registry_snapshot() -> Arc<crate::proxy::hostname::HostRegistry> {
570    let cache = HOST_REGISTRY
571        .read()
572        .unwrap_or_else(std::sync::PoisonError::into_inner);
573    Arc::clone(&cache.registry)
574}
575
576/// Return a snapshot of the cached hostname registry, rebuilding if expired.
577pub async fn get_cached_host_registry() -> Arc<crate::proxy::hostname::HostRegistry> {
578    if let Some(registry) = fresh_registry() {
579        return registry;
580    }
581
582    // One refresh at a time; the rest wait and take its result.
583    let _refreshing = REGISTRY_REFRESH.lock().await;
584    if let Some(registry) = fresh_registry() {
585        return registry;
586    }
587
588    let registry = Arc::new(
589        tokio::task::spawn_blocking(crate::proxy::hostname::HostRegistry::build)
590            .await
591            .unwrap_or_else(|e| {
592                log::warn!("Failed to refresh hostname registry: {e}");
593                crate::proxy::hostname::HostRegistry::default()
594            }),
595    );
596    for err in &registry.errors {
597        crate::proxy::hostname::warn_once(err);
598    }
599
600    let mut cache = HOST_REGISTRY
601        .write()
602        .unwrap_or_else(std::sync::PoisonError::into_inner);
603    cache.registry = Arc::clone(&registry);
604    cache.expires_at = std::time::Instant::now() + SLUG_CACHE_TTL;
605    registry
606}
607
608/// Try to match a subdomain against a slug table, with optional wildcard fallback.
609///
610/// When `wildcard` is true and no exact match is found, progressively strips
611/// subdomain prefixes from the left until a match is found or no dots remain.
612/// For example, with slug "myapp" registered, `tenant.myapp` matches "myapp".
613///
614/// `entries` must be keyed by the ASCII-lowercased slug, as
615/// [`build_slug_entries`] produces: host names are case-insensitive (RFC 4343),
616/// so the subdomain is lowercased before every lookup.
617fn wildcard_slug_lookup<'a>(
618    subdomain: &str,
619    entries: &'a std::collections::HashMap<String, CachedSlugEntry>,
620    wildcard: bool,
621) -> Option<&'a CachedSlugEntry> {
622    let subdomain = subdomain.to_ascii_lowercase();
623
624    entries.get(&subdomain).or_else(|| {
625        if !wildcard {
626            return None;
627        }
628        // "a.b.myapp" has dots at 1,3 → "b.myapp", "myapp"
629        subdomain
630            .match_indices('.')
631            .map(|(i, _)| &subdomain[i + 1..])
632            .find_map(|candidate| entries.get(candidate))
633    })
634}
635
636/// What a wildcard subdomain prefix resolves to within a slug's worktrees.
637#[derive(Debug)]
638enum PrefixMatch<'a> {
639    /// The prefix names exactly one discovered worktree.
640    Worktree(&'a crate::proxy::worktree::WorktreeEntry),
641    /// The prefix names no worktree — an ordinary wildcard subdomain, served
642    /// by the slug's main checkout.
643    Unknown,
644    /// The prefix names worktrees that were rejected as ambiguous.  Serving the
645    /// main checkout here would answer successfully with the wrong content, so
646    /// the request is refused instead.
647    Ambiguous,
648}
649
650/// Resolve a wildcard subdomain prefix against a slug's cached worktrees.
651fn match_worktree_prefix<'a>(cached: &'a CachedSlugEntry, prefix: &str) -> PrefixMatch<'a> {
652    if let Some(wt) = cached
653        .worktrees
654        .iter()
655        .find(|w| w.sanitized_branch.eq_ignore_ascii_case(prefix))
656    {
657        return PrefixMatch::Worktree(wt);
658    }
659    if cached
660        .rejected_worktree_prefixes
661        .contains(&prefix.to_ascii_lowercase())
662    {
663        return PrefixMatch::Ambiguous;
664    }
665    PrefixMatch::Unknown
666}
667
668/// The TLS route for a worktree of `cached`.
669///
670/// A worktree whose own config describes the daemon is authoritative. One the
671/// proxy knows nothing about — an unreadable or momentarily invalid config, a
672/// checkout that predates the daemon — inherits the slug's *mode* but not its
673/// port.
674///
675/// Inheriting the mode is what keeps a passthrough slug from quietly being
676/// terminated with the proxy's certificate while its config is unreadable. The
677/// port is deliberately not inherited: `proxy_tls_port` names a position in one
678/// daemon's port list, and the daemon behind a worktree hostname is a different
679/// process with its own ports, so the hostname falls back to that daemon's own
680/// first port rather than to a number chosen for another checkout.
681fn worktree_route(cached: &CachedSlugEntry, sanitized_branch: &str) -> ProxyTlsRoute {
682    cached
683        .worktree_tls
684        .get(&sanitized_branch.to_ascii_lowercase())
685        .copied()
686        .unwrap_or(ProxyTlsRoute {
687            mode: cached.tls.mode,
688            protocol: cached.tls.protocol,
689            port: None,
690        })
691}
692
693/// Strip a trailing `.{suffix}` from `s`, ignoring ASCII case.
694///
695/// Returns the remaining prefix, or `None` when `s` does not end that way.
696fn strip_dot_suffix_ignore_case(s: &str, suffix: &str) -> Option<String> {
697    let needle_len = suffix.len() + 1;
698    if s.len() <= needle_len {
699        return None;
700    }
701    let split = s.len() - needle_len;
702    if !s.is_char_boundary(split) {
703        return None;
704    }
705    let (head, tail) = s.split_at(split);
706    if tail.starts_with('.') && tail[1..].eq_ignore_ascii_case(suffix) {
707        Some(head.to_string())
708    } else {
709        None
710    }
711}
712
713/// Look up a slug in the cached table.
714///
715/// With wildcard enabled (default), falls back to progressively shorter
716/// subdomain suffixes when an exact match is not found.  For example,
717/// `tenant.myapp` will match slug `myapp` if no slug named `tenant.myapp`
718/// exists.
719async fn cached_slug_lookup(subdomain: &str) -> Option<CachedSlugEntry> {
720    let entries = get_cached_slugs().await;
721    wildcard_slug_lookup(subdomain, &entries, settings().proxy.wildcard).cloned()
722}
723
724// ─── Auto-start deduplication ───────────────────────────────────────────────
725//
726// When auto_start is enabled, concurrent proxy requests for the same stopped
727// daemon must not trigger multiple start operations.  This set tracks daemon
728// IDs that are currently being auto-started.
729
730static AUTO_START_IN_PROGRESS: once_cell::sync::Lazy<
731    tokio::sync::Mutex<std::collections::HashSet<DaemonId>>,
732> = once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
733
734/// Result of resolving a proxy target for a given host.
735enum ResolveResult {
736    /// Daemon is running and ready — forward to this port.
737    /// Covers both already-running daemons and freshly auto-started ones.
738    ///
739    /// The guard records the forwarded work as the daemon's activity, and has
740    /// to be held for as long as that work lasts.
741    Ready(u16, Option<ActivityGuard>, ProxyProtocol),
742    /// Daemon is currently starting (auto-start in progress or just triggered).
743    Starting { slug: String },
744    /// No matching slug or daemon found.
745    NotFound,
746    /// The hostname is reserved for a project or stack page, which a later
747    /// change will serve.  It must never fall through to a daemon.
748    Page {
749        project: String,
750        worktree: Option<String>,
751        daemons: Vec<String>,
752        /// The checkout the hostname resolved to, which is what maps the page
753        /// back to its URL in the web UI: hostname labels are sanitized and can
754        /// be overridden, so they are not the names those URLs use.
755        dir: Option<std::path::PathBuf>,
756    },
757    /// The hostname named a project or daemon that does not exist.
758    Unknown { heading: String, known: Vec<String> },
759    /// Routing refused with a descriptive reason.
760    Error(String),
761}
762
763/// Shared proxy state passed to each request handler.
764/// Callback type invoked on proxy errors (e.g. for logging/alerting).
765type OnErrorFn = Arc<dyn Fn(&str) + Send + Sync>;
766
767#[derive(Clone)]
768struct ProxyState {
769    /// HTTP client used to forward requests to daemon backends.
770    client: Arc<Client<HttpConnector, Body>>,
771    /// Client for daemons with `proxy_protocol = "h2c"`: cleartext HTTP/2 with
772    /// prior knowledge, since there is no ALPN to negotiate it over plain TCP.
773    h2c_client: Arc<Client<HttpConnector, Body>>,
774    /// The configured TLD (e.g. "localhost").
775    tld: String,
776    /// Whether the proxy is serving HTTPS.
777    is_tls: bool,
778    /// Address a `CONNECT` tunnel is spliced to: this proxy's own listener.
779    connect_target: Option<SocketAddr>,
780    /// Address a client on this machine uses to reach the listener, which the
781    /// PAC file names.
782    contact_ip: std::net::IpAddr,
783    /// Cancelled when the proxy is shutting down.
784    cancel: tokio_util::sync::CancellationToken,
785    /// Budget for concurrent `CONNECT` tunnels.
786    tunnel_slots: Arc<tokio::sync::Semaphore>,
787    /// Live `CONNECT` tunnels.
788    ///
789    /// A tunnel outlives the request that created it, so it cannot live in the
790    /// connection `JoinSet`. Tracking it here lets shutdown cancel the tunnels
791    /// and then wait for them, rather than returning while one still owns both
792    /// of its sockets.
793    tunnels: tokio_util::task::TaskTracker,
794    /// Optional error callback invoked on proxy errors (e.g. for logging/alerting).
795    on_error: Option<OnErrorFn>,
796}
797
798/// Start the reverse proxy server.
799///
800/// Binds to the configured port and serves until the process exits.
801/// When `proxy.https = true`, TLS is terminated here using a self-signed
802/// certificate (auto-generated if not present).
803///
804/// This function is intended to be spawned as a background task.
805pub async fn serve(
806    bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
807    cancel: tokio_util::sync::CancellationToken,
808) -> crate::Result<()> {
809    let s = settings();
810    let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
811
812    let effective_tld = crate::proxy::effective_tld(&s).to_string();
813
814    let Some(effective_port) = u16::try_from(s.proxy.port).ok().filter(|&p| p > 0) else {
815        let msg = format!(
816            "proxy.port {} is out of valid port range (1-65535), proxy server cannot start",
817            s.proxy.port
818        );
819        let _ = bind_tx.send(Err(msg.clone()));
820        miette::bail!("{msg}");
821    };
822
823    let mut connector = HttpConnector::new();
824    // Limit how long the proxy waits to establish a TCP connection to a backend.
825    // Without this, a daemon that accepts the SYN but never completes the handshake
826    // would stall the proxy indefinitely.
827    connector.set_connect_timeout(Some(std::time::Duration::from_secs(10)));
828
829    let client = Client::builder(TokioExecutor::new())
830        // Reclaim idle keep-alive connections after 30 s so that file descriptors
831        // are not held open forever when a backend goes quiet.
832        .pool_idle_timeout(std::time::Duration::from_secs(30))
833        .build(connector.clone());
834
835    let h2c_client = Client::builder(TokioExecutor::new())
836        .pool_idle_timeout(std::time::Duration::from_secs(30))
837        .http2_only(true)
838        .build(connector);
839
840    // Resolve bind address from settings.
841    // In LAN mode, default to 0.0.0.0 so the proxy is reachable from other
842    // devices on the network.  Users can still override with proxy.host.
843    let bind_ip: std::net::IpAddr = if lan_enabled && s.proxy.host == "127.0.0.1" {
844        std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)
845    } else {
846        match s.proxy.host.parse() {
847            Ok(ip) => ip,
848            Err(_) => {
849                log::warn!(
850                    "proxy.host {:?} is not a valid IP address — falling back to 127.0.0.1. \
851                     The proxy will only be reachable on the loopback interface.",
852                    s.proxy.host
853                );
854                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
855            }
856        }
857    };
858    let addr = SocketAddr::from((bind_ip, effective_port));
859    // The address a local client should use to reach this listener. Derived
860    // from the bind address rather than assumed to be 127.0.0.1: with
861    // `proxy.host = "::1"` nothing is listening on IPv4 at all, so both the PAC
862    // file and the CONNECT tunnel have to name the IPv6 loopback instead.
863    let contact_ip = local_contact_ip(bind_ip);
864    let tunnels = tokio_util::task::TaskTracker::new();
865
866    let state = ProxyState {
867        client: Arc::new(client),
868        h2c_client: Arc::new(h2c_client),
869        tld: effective_tld.clone(),
870        is_tls: s.proxy.https,
871        // CONNECT tunnels loop back into this same listener, so the TLS
872        // handshake inside the tunnel reaches the SNI resolver.
873        connect_target: Some(SocketAddr::from((contact_ip, effective_port))),
874        contact_ip,
875        cancel: cancel.clone(),
876        tunnel_slots: Arc::new(tokio::sync::Semaphore::new(MAX_TUNNELS)),
877        tunnels: tunnels.clone(),
878        on_error: None,
879    };
880
881    // `/proxy.pac` is served from the proxy's own listener because that is the
882    // one HTTP endpoint that always exists while the proxy runs. The handler
883    // falls through to normal proxying when the request is addressed to a
884    // hostname under the TLD, so a daemon can still own that path.
885    let plain_state = state.clone();
886    let app = Router::new()
887        // `any`, not `get`: axum answers a path match with no method match at
888        // the router, before `fallback` runs. Registering GET alone would turn
889        // a POST to `/proxy.pac` on *any* proxied hostname into a 405 that the
890        // backend daemon never sees, which is exactly the fall-through the
891        // comment above promises. The handler decides the method instead.
892        .route(crate::proxy::pac::PAC_PATH, axum::routing::any(pac_handler))
893        .fallback(proxy_handler)
894        .with_state(state);
895
896    if s.proxy.https {
897        serve_https_with_http_fallback(
898            app,
899            addr,
900            &s,
901            effective_port,
902            effective_tld,
903            plain_state,
904            bind_tx,
905            cancel,
906        )
907        .await
908    } else {
909        // `plain_state` carries the tunnel tracker, which this path has to
910        // drain too: `proxy.https = false` still serves CONNECT through the
911        // PAC file, for `http://` and `ws://` URLs.
912        serve_http(app, addr, effective_port, plain_state, bind_tx, cancel).await
913    }
914}
915
916/// Serve one accepted connection until it ends, asking it to close gracefully
917/// once `cancel` fires.
918///
919/// Shared by every listener path. Without the graceful request an idle
920/// keep-alive connection or an HTTP/2 session never ends on its own, so each
921/// one would run out the whole shutdown drain budget and then be aborted.
922macro_rules! serve_conn_until_cancelled {
923    ($io:expr, $svc:expr, $cancel:expr) => {{
924        let builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
925        let conn = builder.serve_connection_with_upgrades($io, $svc);
926        tokio::pin!(conn);
927        tokio::select! {
928            r = conn.as_mut() => r,
929            _ = $cancel.cancelled() => {
930                conn.as_mut().graceful_shutdown();
931                conn.await
932            }
933        }
934    }};
935}
936
937/// Serve plain HTTP.
938async fn serve_http(
939    app: Router,
940    addr: SocketAddr,
941    effective_port: u16,
942    proxy_state: ProxyState,
943    bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
944    cancel: tokio_util::sync::CancellationToken,
945) -> crate::Result<()> {
946    let listener = match TcpListener::bind(addr).await {
947        Ok(l) => {
948            if settings().proxy.sync_hosts {
949                crate::proxy::hosts::sync_hosts_from_settings();
950            }
951            let _ = bind_tx.send(Ok(()));
952            l
953        }
954        Err(e) => {
955            let msg = bind_error_message(effective_port, &e);
956            let _ = bind_tx.send(Err(msg.clone()));
957            return Err(miette::miette!("{msg}"));
958        }
959    };
960
961    log::info!("Proxy server listening on http://{addr}");
962    if effective_port < 1024 {
963        log::info!(
964            "Note: port {effective_port} is a privileged port. \
965             The supervisor must be started with sudo to bind to this port."
966        );
967    }
968    // Served by hand rather than through `axum::serve`, for the same reason as
969    // the HTTPS path: axum spawns each connection as a free task, so once its
970    // shutdown wait is cut short the connections keep running — a `ws://`
971    // stream or a long response splicing on while the supervisor stops the
972    // daemons behind it. Here they live in a `JoinSet`, which aborts whatever
973    // is left when the drain budget runs out.
974    let mut conn_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
975    loop {
976        while conn_tasks.try_join_next().is_some() {}
977        tokio::select! {
978            accept_result = listener.accept() => {
979                let (stream, peer_addr) = match accept_result {
980                    Ok(conn) => conn,
981                    Err(e) => {
982                        log::warn!("Accept error (will retry): {e}");
983                        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
984                        continue;
985                    }
986                };
987                // Handlers read the peer address to decide how much of this
988                // machine's configuration a response may describe.
989                let app = app
990                    .clone()
991                    .layer(axum::Extension(axum::extract::ConnectInfo(peer_addr)));
992                let cancel = cancel.clone();
993                conn_tasks.spawn(async move {
994                    let io = hyper_util::rt::TokioIo::new(stream);
995                    let svc = hyper_util::service::TowerToHyperService::new(app);
996                    if let Err(e) = serve_conn_until_cancelled!(io, svc, cancel) {
997                        log::debug!("Connection error: {e}");
998                    }
999                });
1000            }
1001            _ = cancel.cancelled() => break,
1002        }
1003    }
1004
1005    // One deadline for both drains, as the HTTPS path has: in-flight
1006    // connections first, then the CONNECT tunnels.
1007    let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_BUDGET;
1008    if tokio::time::timeout_at(deadline, async {
1009        while conn_tasks.join_next().await.is_some() {}
1010    })
1011    .await
1012    .is_err()
1013    {
1014        log::debug!("Proxy connections still open after {SHUTDOWN_DRAIN_BUDGET:?}; aborting them");
1015    }
1016    // Aborts whatever did not finish in time.
1017    drop(conn_tasks);
1018
1019    // A CONNECT request's connection completes the moment it is upgraded; the
1020    // tunnel it spawned outlives it, so without this the supervisor would go
1021    // on to stop daemons while tunnels were still splicing bytes.
1022    proxy_state.tunnels.close();
1023    let _ = tokio::time::timeout_at(deadline, proxy_state.tunnels.wait()).await;
1024    Ok(())
1025}
1026
1027/// Serve HTTPS with automatic HTTP detection on the same port.
1028///
1029/// Peeks at the first byte of each incoming TCP connection:
1030/// - `0x16` (TLS ClientHello) → hand off to the TLS acceptor (HTTP/2 + HTTP/1.1 via ALPN)
1031/// - anything else → 302 redirect to HTTPS
1032#[cfg(feature = "proxy-tls")]
1033#[allow(clippy::too_many_arguments)]
1034async fn serve_https_with_http_fallback(
1035    app: Router,
1036    addr: SocketAddr,
1037    s: &crate::settings::Settings,
1038    effective_port: u16,
1039    effective_tld: String,
1040    plain_proxy_state: ProxyState,
1041    bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
1042    cancel: tokio_util::sync::CancellationToken,
1043) -> crate::Result<()> {
1044    use rustls::ServerConfig;
1045    use tokio_rustls::TlsAcceptor;
1046
1047    let (cert_path, key_path) = resolve_tls_paths(s)?;
1048
1049    // Install ring as the default CryptoProvider if none has been set yet.
1050    let _ = rustls::crypto::ring::default_provider().install_default();
1051
1052    // A configured `tls_cert` is served as-is: the user supplied a certificate
1053    // for these host names, so pitchfork has no CA to mint from and no business
1054    // replacing what they chose.  Otherwise the local CA signs a leaf per SNI
1055    // host on demand, which is what makes names of any depth work.
1056    let resolver: Arc<dyn rustls::server::ResolvesServerCert> = if s.proxy.tls_cert.is_empty() {
1057        if ensure_ca(&cert_path, &key_path, || {
1058            cert_path.exists() && key_path.exists()
1059        })? {
1060            log::info!("Generated local CA certificate at {}", cert_path.display());
1061            log::info!("To trust the CA in your browser, run: pitchfork proxy trust");
1062        }
1063        Arc::new(SniCertResolver::new(
1064            &cert_path,
1065            &key_path,
1066            effective_tld.clone(),
1067        )?)
1068    } else {
1069        log::info!(
1070            "Serving the configured certificate {} (no certificates are minted)",
1071            cert_path.display()
1072        );
1073        Arc::new(StaticCertResolver::new(
1074            &cert_path,
1075            &key_path,
1076            effective_tld.clone(),
1077        )?)
1078    };
1079
1080    let mut tls_config = ServerConfig::builder()
1081        .with_no_client_auth()
1082        .with_cert_resolver(resolver);
1083    // Advertise HTTP/2 and HTTP/1.1 via ALPN so browsers negotiate HTTP/2
1084    // for multiplexed requests (eliminates the 6-connection-per-host limit).
1085    tls_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
1086
1087    let acceptor = TlsAcceptor::from(Arc::new(tls_config));
1088
1089    let listener = match TcpListener::bind(addr).await {
1090        Ok(l) => {
1091            if settings().proxy.sync_hosts {
1092                crate::proxy::hosts::sync_hosts_from_settings();
1093            }
1094            let _ = bind_tx.send(Ok(()));
1095            l
1096        }
1097        Err(e) => {
1098            let msg = bind_error_message(effective_port, &e);
1099            let _ = bind_tx.send(Err(msg.clone()));
1100            return Err(miette::miette!("{msg}"));
1101        }
1102    };
1103
1104    log::info!("Proxy server listening on https://{addr} (HTTP also accepted)");
1105    if effective_port < 1024 {
1106        log::info!(
1107            "Note: port {effective_port} is a privileged port. \
1108             The supervisor must be started with sudo to bind to this port."
1109        );
1110    }
1111
1112    // Build a lightweight app for plain-HTTP requests arriving on the TLS port.
1113    // Two things are exempt from the redirect to HTTPS:
1114    //
1115    //   * `/proxy.pac`, because the browser reads the PAC file before it has
1116    //     any way to trust this listener's certificate.
1117    //   * `CONNECT`, which is how a PAC-configured browser opens an `https://`
1118    //     URL. Redirecting it would break the PAC path entirely.
1119    let redirect_app = Router::new()
1120        .route(
1121            // `any` for the same reason as the TLS side: the method check
1122            // belongs in the handler, so a proxied host keeps this path.
1123            crate::proxy::pac::PAC_PATH,
1124            axum::routing::any(plain_pac_handler),
1125        )
1126        .fallback(plain_fallback_handler)
1127        .with_state(PlainState {
1128            tld: effective_tld.clone(),
1129            port: effective_port,
1130            proxy: plain_proxy_state.clone(),
1131        });
1132
1133    // Accept connections and sniff the first byte to decide TLS vs plain HTTP.
1134    let mut conn_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1135    let handshake_slots = Arc::new(tokio::sync::Semaphore::new(MAX_PENDING_HANDSHAKES));
1136    loop {
1137        // Reap finished connection tasks during normal operation so the JoinSet
1138        // does not retain one entry per historical connection.
1139        while conn_tasks.try_join_next().is_some() {}
1140
1141        tokio::select! {
1142            accept_result = listener.accept() => {
1143                let (stream, peer_addr) = match accept_result {
1144                    Ok(conn) => conn,
1145                    Err(e) => {
1146                        log::warn!("Accept error (will retry): {e}");
1147                        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1148                        continue;
1149                    }
1150                };
1151
1152                // Refuse rather than queue without bound. A client can hold a
1153                // connection in protocol detection or mid-handshake by simply
1154                // not sending, and each one costs a task and a descriptor.
1155                //
1156                // The permit covers the handshake only and is released before
1157                // the connection is served, so established sessions never
1158                // occupy the budget.
1159                let Ok(handshake_permit) = Arc::clone(&handshake_slots).try_acquire_owned() else {
1160                    // Throttled: whoever is saturating the handshake budget can
1161                    // provoke this line as fast as it can open sockets.
1162                    if let Some(suppressed) = REFUSED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL) {
1163                        log::warn!(
1164                            "Proxy refused a connection: {MAX_PENDING_HANDSHAKES} \
1165                             still negotiating \
1166                             ({suppressed} similar refusals since the last message)"
1167                        );
1168                    }
1169                    drop(stream);
1170                    continue;
1171                };
1172
1173                let acceptor = acceptor.clone();
1174                // This loop serves the router itself rather than going through
1175                // `into_make_service_with_connect_info`, so the peer address is
1176                // attached here. Handlers use it to decide how much of this
1177                // machine's configuration a response may describe.
1178                let app = app
1179                    .clone()
1180                    .layer(axum::Extension(axum::extract::ConnectInfo(peer_addr)));
1181                let redirect_app = redirect_app.clone();
1182                let tld = effective_tld.clone();
1183                let cancel = cancel.clone();
1184
1185                conn_tasks.spawn(async move {
1186                    // Peek at the first byte without consuming it.
1187                    // TLS ClientHello always starts with 0x16 (content type "handshake").
1188                    //
1189                    // One deadline covers the peek and the handshake together,
1190                    // so a client that trickles its first byte in just in time
1191                    // does not start a second full budget.
1192                    let handshake_deadline = tokio::time::Instant::now() + HANDSHAKE_TIMEOUT;
1193                    let mut peek_buf = [0u8; 1];
1194                    match tokio::time::timeout_at(handshake_deadline, stream.peek(&mut peek_buf)).await {
1195                        Ok(Ok(0)) | Ok(Err(_)) => return,
1196                        Err(_) => {
1197                            if let Some(suppressed) =
1198                                ABANDONED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL)
1199                            {
1200                                log::debug!(
1201                                    "Connection sent nothing within the handshake timeout \
1202                                     ({suppressed} similar since the last message)"
1203                                );
1204                            }
1205                            return;
1206                        }
1207                        Ok(Ok(_)) => {}
1208                    }
1209
1210                    if peek_buf[0] == 0x16 {
1211                        // A TLS connection whose SNI names a `proxy_tls = "passthrough"`
1212                        // daemon is spliced through untouched, so the daemon's own
1213                        // certificate, ALPN and client-certificate request reach the
1214                        // client. Everything else is terminated here as before.
1215                        //
1216                        // The peek counts against the same handshake deadline:
1217                        // it is still negotiation, not a session.
1218                        let sni_budget = SNI_PEEK_TIMEOUT.min(
1219                            handshake_deadline.saturating_duration_since(tokio::time::Instant::now()),
1220                        );
1221                        match peek_sni_host(&stream, sni_budget).await {
1222                            SniProbe::Host(host) => {
1223                                // Also under the handshake deadline: on a cache
1224                                // miss this rebuilds the slug and host
1225                                // registries, which can be slow, and the
1226                                // connection still holds a negotiation slot.
1227                                let Ok(mode) = tokio::time::timeout_at(
1228                                    handshake_deadline,
1229                                    resolve_tls_mode(&host, &tld),
1230                                )
1231                                .await
1232                                else {
1233                                    if let Some(suppressed) =
1234                                        ABANDONED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL)
1235                                    {
1236                                        log::debug!(
1237                                            "Routing lookup for '{host}' did not finish within the \
1238                                             handshake timeout ({suppressed} similar since the \
1239                                             last message)"
1240                                        );
1241                                    }
1242                                    return;
1243                                };
1244                                if mode.is_passthrough() {
1245                                    // The splice is the session, however long
1246                                    // it lasts; it must not keep a slot meant
1247                                    // for connections still negotiating.
1248                                    drop(handshake_permit);
1249                                    // Ended by shutdown like any other
1250                                    // connection, rather than by the drain
1251                                    // budget running out.
1252                                    tokio::select! {
1253                                        _ = serve_passthrough(stream, &host, &tld) => {}
1254                                        _ = cancel.cancelled() => {}
1255                                    }
1256                                    return;
1257                                }
1258                            }
1259                            SniProbe::NoHost => {}
1260                            // The hostname could not be read here, so this
1261                            // connection is handed to the TLS acceptor like any
1262                            // other: rustls defragments the handshake itself
1263                            // and hands the real host name to the certificate
1264                            // resolver, which refuses to issue for a
1265                            // passthrough hostname rather than answering with
1266                            // the proxy's certificate. Unrelated terminating
1267                            // hostnames are served normally.
1268                            SniProbe::Undetermined => {
1269                                log::debug!(
1270                                    "Could not read the ClientHello of a TLS connection; \
1271                                     handing it to the TLS acceptor, which refuses to terminate \
1272                                     a passthrough hostname."
1273                                );
1274                                // Make sure the resolver's synchronous snapshots
1275                                // have been populated before it has to decide.
1276                                // Bounded like the rest of negotiation; if it
1277                                // runs out, the accept below does too.
1278                                let _ = tokio::time::timeout_at(handshake_deadline, async {
1279                                    let _ = get_cached_slugs().await;
1280                                    let _ = get_cached_host_registry().await;
1281                                })
1282                                .await;
1283                            }
1284                        }
1285
1286                        // TLS handshake → HTTP/2 or HTTP/1.1 (negotiated via ALPN)
1287                        let accepted = match tokio::time::timeout_at(
1288                            handshake_deadline,
1289                            acceptor.accept(stream),
1290                        )
1291                        .await
1292                        {
1293                            Ok(r) => r,
1294                            Err(_) => {
1295                                if let Some(suppressed) =
1296                                    ABANDONED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL)
1297                                {
1298                                    log::debug!(
1299                                        "TLS handshake did not complete in time \
1300                                         ({suppressed} similar since the last message)"
1301                                    );
1302                                }
1303                                return;
1304                            }
1305                        };
1306                        // Negotiation is over either way; the session that
1307                        // follows can last as long as it likes.
1308                        drop(handshake_permit);
1309                        match accepted {
1310                            Ok(tls_stream) => {
1311                                let io = hyper_util::rt::TokioIo::new(tls_stream);
1312                                let svc = hyper_util::service::TowerToHyperService::new(app);
1313                                if let Err(e) = serve_conn_until_cancelled!(io, svc, cancel) {
1314                                    // HTTP/2 RST_STREAM errors from cancelled browser requests
1315                                    // (navigation, HMR) are normal — log at debug to avoid noise.
1316                                    log::debug!("Connection error: {e}");
1317                                }
1318                            }
1319                            Err(e) => {
1320                                log::debug!("TLS handshake error: {e}");
1321                            }
1322                        }
1323                    } else {
1324                        // Plain HTTP on the TLS port → 302 redirect to HTTPS.
1325                        // Nothing left to negotiate.
1326                        drop(handshake_permit);
1327                        let io = hyper_util::rt::TokioIo::new(stream);
1328                        let svc = hyper_util::service::TowerToHyperService::new(redirect_app);
1329                        let _ = serve_conn_until_cancelled!(io, svc, cancel);
1330                    }
1331                });
1332
1333                while conn_tasks.try_join_next().is_some() {}
1334            }
1335            _ = cancel.cancelled() => {
1336                log::info!("Proxy server shutting down (cancel signal received)");
1337                break;
1338            }
1339        }
1340    }
1341
1342    // One budget for both drains, not one each. The supervisor waits a fixed
1343    // time for this task; two independent timeouts could together outlast it,
1344    // so the second phase would be cut off rather than bounded.
1345    let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_BUDGET;
1346
1347    // In-flight connections first.
1348    let _ = tokio::time::timeout_at(deadline, async {
1349        while conn_tasks.join_next().await.is_some() {}
1350    })
1351    .await;
1352
1353    // Then the CONNECT tunnels. They were cancelled along with everything else
1354    // when the token fired, so this is waiting for them to let go of their
1355    // sockets rather than waiting for their peers to finish.
1356    plain_proxy_state.tunnels.close();
1357    let _ = tokio::time::timeout_at(deadline, plain_proxy_state.tunnels.wait()).await;
1358
1359    Ok(())
1360}
1361
1362/// How long to wait for a complete ClientHello before giving up on reading SNI.
1363///
1364/// A client sends its ClientHello immediately after the TCP handshake, so this
1365/// only ever expires on a stalled or malicious connection.
1366#[cfg(feature = "proxy-tls")]
1367const SNI_PEEK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
1368
1369/// How much of the connection's opening bytes to examine while looking for SNI.
1370///
1371/// A ClientHello with a realistic extension set is well under 2 KiB; the cap
1372/// bounds the work done for a connection that never sends a parseable one.
1373#[cfg(feature = "proxy-tls")]
1374const SNI_PEEK_MAX_BYTES: usize = 16 * 1024;
1375
1376/// What peeking at a connection's opening bytes established about its hostname.
1377///
1378/// The third case is the one that matters: "no hostname" and "hostname unknown"
1379/// must not be treated alike, because a connection whose hostname could not be
1380/// read may well belong to a passthrough daemon.
1381#[cfg(feature = "proxy-tls")]
1382#[derive(Debug, PartialEq, Eq)]
1383enum SniProbe {
1384    /// The ClientHello named this host.
1385    Host(String),
1386    /// A complete ClientHello carried no SNI, or the connection is not a TLS
1387    /// handshake at all. Either way it cannot name a passthrough daemon.
1388    NoHost,
1389    /// No verdict: the hello stalled, exceeded the inspection window, or never
1390    /// reconciled its own length fields. Passthrough cannot be ruled out.
1391    Undetermined,
1392}
1393
1394/// Read the SNI hostname from a connection's ClientHello *without consuming
1395/// it*, so the same bytes are still available to whichever path handles the
1396/// connection.
1397///
1398/// `timeout` bounds the whole probe, including a read that never completes:
1399/// a peer that opens a connection and then sends nothing more is given up on
1400/// rather than holding the connection task open. A client that sends part of
1401/// a hello and then closes is noticed as soon as its close arrives, even
1402/// though `peek` keeps returning the buffered bytes rather than end of file,
1403/// and is reported as [`SniProbe::Undetermined`] without waiting out the
1404/// timeout.
1405#[cfg(feature = "proxy-tls")]
1406async fn peek_sni_host(stream: &TcpStream, timeout: std::time::Duration) -> SniProbe {
1407    use crate::proxy::sni::{SniPeek, parse_sni};
1408
1409    const MIN_PAUSE: std::time::Duration = std::time::Duration::from_millis(10);
1410    const MAX_PAUSE: std::time::Duration = std::time::Duration::from_millis(200);
1411
1412    let deadline = tokio::time::Instant::now() + timeout;
1413    let mut buf = vec![0u8; 2048];
1414    let mut last_n = 0;
1415    let mut pause = MIN_PAUSE;
1416
1417    loop {
1418        // The deadline has to bound the read itself: a peer that opens a
1419        // connection and then stops sending leaves `peek` waiting forever, and
1420        // the check further down never runs to end it.
1421        let n = match tokio::time::timeout_at(deadline, stream.peek(&mut buf)).await {
1422            // End of file with nothing buffered: the client hung up before
1423            // saying anything, so there is nothing to route and nothing to
1424            // downgrade.
1425            Ok(Ok(0)) => return SniProbe::NoHost,
1426            Ok(Ok(n)) => n,
1427            Ok(Err(e)) => {
1428                log::debug!("Failed to peek at a TLS connection: {e}");
1429                return SniProbe::Undetermined;
1430            }
1431            Err(_elapsed) => {
1432                log::debug!("Timed out waiting for a client that sent no ClientHello");
1433                return SniProbe::Undetermined;
1434            }
1435        };
1436        match parse_sni(&buf[..n]) {
1437            SniPeek::Found(host) => return SniProbe::Host(host),
1438            SniPeek::Absent | SniPeek::NotTls => return SniProbe::NoHost,
1439            SniPeek::Incomplete => {}
1440        }
1441
1442        // The hello may simply be longer than the window we looked at.
1443        if n == buf.len() && buf.len() < SNI_PEEK_MAX_BYTES {
1444            buf.resize((buf.len() * 2).min(SNI_PEEK_MAX_BYTES), 0);
1445            continue;
1446        }
1447        if n >= SNI_PEEK_MAX_BYTES {
1448            log::debug!("Giving up on SNI after {n} bytes without a complete ClientHello");
1449            return SniProbe::Undetermined;
1450        }
1451        if tokio::time::Instant::now() >= deadline {
1452            log::debug!("Timed out waiting for a complete ClientHello ({n} bytes read)");
1453            return SniProbe::Undetermined;
1454        }
1455        // Peeked data stays in the socket buffer, so the socket always reads as
1456        // readable and waiting on that would spin. Its readiness does record
1457        // the peer's close, though, which `peek` cannot report while bytes are
1458        // still buffered: a client that sent part of a hello and hung up will
1459        // never finish it.
1460        match stream.ready(tokio::io::Interest::READABLE).await {
1461            Ok(ready) if ready.is_read_closed() => {
1462                log::debug!("Client closed after {n} bytes of an incomplete ClientHello");
1463                return SniProbe::Undetermined;
1464            }
1465            Ok(_) => {}
1466            Err(e) => {
1467                log::debug!("Failed to poll a TLS connection: {e}");
1468                return SniProbe::Undetermined;
1469            }
1470        }
1471        // Re-peek soon while the hello is still arriving, and back off while
1472        // it has stalled, so a slow client is not polled hundreds of times.
1473        pause = if n > last_n {
1474            MIN_PAUSE
1475        } else {
1476            (pause * 2).min(MAX_PAUSE)
1477        };
1478        last_n = n;
1479        tokio::time::sleep_until((tokio::time::Instant::now() + pause).min(deadline)).await;
1480    }
1481}
1482
1483/// Splice a TLS connection straight through to its daemon.
1484///
1485/// Neither direction is inspected or rewritten, so the daemon terminates TLS
1486/// with its own certificate, negotiates its own ALPN (HTTP/2 and gRPC included)
1487/// and can require client certificates — none of which survive termination at
1488/// the proxy.
1489///
1490/// A stopped daemon is auto-started first and the connection is held until it
1491/// is ready, bounded by `proxy.auto_start_timeout`: a raw TLS stream has no
1492/// equivalent of the HTML "Starting…" page. When routing fails there is
1493/// likewise nothing to reply with, so the connection is closed and the reason
1494/// is logged.
1495#[cfg(feature = "proxy-tls")]
1496async fn serve_passthrough(mut stream: TcpStream, host: &str, tld: &str) {
1497    // Held until the splice ends: an open passthrough connection is activity
1498    // for as long as it is open, since the proxy cannot see the requests
1499    // inside it.
1500    let (port, _activity) = match resolve_passthrough_port(host, tld).await {
1501        Ok(ready) => ready,
1502        Err(msg) => {
1503            log::warn!("TLS passthrough for '{host}' failed: {msg}");
1504            return;
1505        }
1506    };
1507
1508    let addr = SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port));
1509    let mut backend = match connect_backend(addr).await {
1510        Ok(b) => b,
1511        Err(e) => {
1512            log::warn!("TLS passthrough for '{host}': failed to connect to {addr}: {e}");
1513            return;
1514        }
1515    };
1516
1517    log::debug!("TLS passthrough: splicing '{host}' to {addr}");
1518    if let Err(e) = tokio::io::copy_bidirectional(&mut stream, &mut backend).await {
1519        // A client or daemon closing one half mid-stream is ordinary.
1520        log::debug!("TLS passthrough for '{host}' ended: {e}");
1521    }
1522}
1523
1524/// How long to keep retrying a refused connection to a daemon that has just
1525/// been reported ready.
1526///
1527/// A daemon can be recorded as running and holding a port a moment before its
1528/// listener actually accepts. This window covers that gap without making a
1529/// genuinely dead port hang the client for the full auto-start budget.
1530#[cfg(feature = "proxy-tls")]
1531const PASSTHROUGH_CONNECT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1532
1533/// Connect to a daemon's port, retrying a refused connection briefly.
1534#[cfg(feature = "proxy-tls")]
1535async fn connect_backend(addr: SocketAddr) -> std::io::Result<TcpStream> {
1536    let deadline = tokio::time::Instant::now() + PASSTHROUGH_CONNECT_GRACE;
1537    loop {
1538        match TcpStream::connect(addr).await {
1539            Ok(stream) => return Ok(stream),
1540            Err(e) => {
1541                let retryable = e.kind() == std::io::ErrorKind::ConnectionRefused;
1542                if !retryable || tokio::time::Instant::now() >= deadline {
1543                    return Err(e);
1544                }
1545                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1546            }
1547        }
1548    }
1549}
1550
1551/// Resolve the daemon port a passthrough hostname splices to, starting the
1552/// daemon if it is not running.
1553///
1554/// Waiting replaces the "Starting…" page that the HTTP path shows, and the
1555/// whole resolution — waiting behind another connection's start *and* running
1556/// one of its own — is bounded by a single `proxy.auto_start_timeout` budget,
1557/// which is what the documentation promises.
1558#[cfg(feature = "proxy-tls")]
1559async fn resolve_passthrough_port(
1560    host: &str,
1561    tld: &str,
1562) -> std::result::Result<(u16, Option<ActivityGuard>), String> {
1563    let budget = settings().proxy_auto_start_timeout();
1564    match tokio::time::timeout(budget, resolve_passthrough_port_inner(host, tld)).await {
1565        Ok(result) => result,
1566        Err(_elapsed) => Err(format!(
1567            "no daemon was ready for '{host}' within proxy.auto_start_timeout ({budget:?})"
1568        )),
1569    }
1570}
1571
1572/// Inner loop of [`resolve_passthrough_port`], wrapped by the caller so that
1573/// waiting and starting share one deadline.
1574#[cfg(feature = "proxy-tls")]
1575async fn resolve_passthrough_port_inner(
1576    host: &str,
1577    tld: &str,
1578) -> std::result::Result<(u16, Option<ActivityGuard>), String> {
1579    loop {
1580        match resolve_target(host, tld).await {
1581            ResolveResult::Ready(port, activity, _) => return Ok((port, activity)),
1582            // Another connection is already auto-starting this daemon, or it
1583            // is being stopped for inactivity; wait for that to finish rather
1584            // than starting a second copy. The caller's timeout ends this
1585            // wait.
1586            ResolveResult::Starting { slug: _ } => {
1587                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
1588            }
1589            ResolveResult::NotFound => {
1590                return Err(
1591                    "no running daemon with a port matched this hostname, and it could not \
1592                     be auto-started"
1593                        .to_string(),
1594                );
1595            }
1596            // A project or stack page is HTML the proxy serves itself, and an
1597            // unknown name has a page listing what does exist. Neither is
1598            // something a spliced TLS stream can carry, so the connection is
1599            // closed with the reason logged.
1600            ResolveResult::Page {
1601                project, worktree, ..
1602            } => {
1603                return Err(match worktree {
1604                    Some(worktree) => {
1605                        format!("'{worktree}' of project '{project}' is a stack page, not a daemon")
1606                    }
1607                    None => format!("'{project}' is a project page, not a daemon"),
1608                });
1609            }
1610            ResolveResult::Unknown { heading, .. } => return Err(heading),
1611            ResolveResult::Error(msg) => return Err(msg),
1612        }
1613    }
1614}
1615
1616/// Fallback when proxy-tls feature is not enabled.
1617#[cfg(not(feature = "proxy-tls"))]
1618#[allow(clippy::too_many_arguments)]
1619async fn serve_https_with_http_fallback(
1620    _app: Router,
1621    _addr: SocketAddr,
1622    _s: &crate::settings::Settings,
1623    _effective_port: u16,
1624    _effective_tld: String,
1625    _plain_proxy_state: ProxyState,
1626    bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
1627    _cancel: tokio_util::sync::CancellationToken,
1628) -> crate::Result<()> {
1629    let msg = "HTTPS proxy support requires the `proxy-tls` feature.\n\
1630         Rebuild pitchfork with: cargo build --features proxy-tls"
1631        .to_string();
1632    let _ = bind_tx.send(Err(msg.clone()));
1633    miette::bail!("{msg}");
1634}
1635
1636/// Resolve the CA certificate and key paths from settings.
1637///
1638/// If `tls_cert` / `tls_key` are empty, falls back to the auto-generated
1639/// CA paths in `$PITCHFORK_STATE_DIR/proxy/`.
1640///
1641/// Setting only one of the two is refused. Filling the other half from the
1642/// generated CA would pair a user's key with pitchfork's certificate, or the
1643/// reverse, and when the CA does not exist yet, generating it would write a
1644/// new CA key over the user's file.
1645#[cfg(feature = "proxy-tls")]
1646fn resolve_tls_paths(
1647    s: &crate::settings::Settings,
1648) -> crate::Result<(std::path::PathBuf, std::path::PathBuf)> {
1649    if let Some(problem) = tls_pair_problem(&s.proxy.tls_cert, &s.proxy.tls_key) {
1650        miette::bail!("{problem}");
1651    }
1652    let proxy_dir = crate::env::PITCHFORK_STATE_DIR.join("proxy");
1653    let resolve = |configured: &str, default: &str| {
1654        if configured.is_empty() {
1655            proxy_dir.join(default)
1656        } else {
1657            std::path::PathBuf::from(configured)
1658        }
1659    };
1660    Ok((
1661        resolve(&s.proxy.tls_cert, "ca.pem"),
1662        resolve(&s.proxy.tls_key, "ca-key.pem"),
1663    ))
1664}
1665
1666/// Why `proxy.tls_cert` and `proxy.tls_key` cannot be used as configured:
1667/// they are a pair, so both are set or neither is.
1668pub(crate) fn tls_pair_problem(cert: &str, key: &str) -> Option<String> {
1669    match (cert.is_empty(), key.is_empty()) {
1670        (false, true) => Some(
1671            "proxy.tls_cert is set but proxy.tls_key is empty; set both, or neither to use \
1672             the generated CA"
1673                .to_string(),
1674        ),
1675        (true, false) => Some(
1676            "proxy.tls_key is set but proxy.tls_cert is empty; set both, or neither to use \
1677             the generated CA"
1678                .to_string(),
1679        ),
1680        _ => None,
1681    }
1682}
1683
1684/// Generate the CA pair unless `usable` says the one on disk will do.
1685///
1686/// `proxy setup` and a starting supervisor can both find the CA missing and
1687/// generate one at once. The cert and key are separate files, so two writers
1688/// interleaving can leave one's certificate beside the other's key: a pair
1689/// that trusts fine and then signs nothing that verifies. The check and the
1690/// write happen under one lock so only the first generation happens.
1691///
1692/// Returns whether a new pair was written.
1693#[cfg(feature = "proxy-tls")]
1694pub fn ensure_ca(
1695    cert_path: &std::path::Path,
1696    key_path: &std::path::Path,
1697    usable: impl FnOnce() -> bool,
1698) -> crate::Result<bool> {
1699    let _lock = xx::fslock::get(cert_path, false)
1700        .map_err(|e| miette::miette!("Failed to lock {}: {e}", cert_path.display()))?;
1701    if usable() {
1702        return Ok(false);
1703    }
1704    generate_ca(cert_path, key_path)?;
1705    // Leaves cached from a previous CA would still load — they are only
1706    // checked for expiry — and be served for names the new CA never signed.
1707    // They are all stale now, so they go.
1708    clear_host_certs(&host_certs_dir_for(cert_path), None);
1709    Ok(true)
1710}
1711
1712/// Where leaves signed by the CA at `ca_cert_path` are cached.
1713#[cfg(feature = "proxy-tls")]
1714fn host_certs_dir_for(ca_cert_path: &std::path::Path) -> std::path::PathBuf {
1715    ca_cert_path
1716        .parent()
1717        .unwrap_or(std::path::Path::new("."))
1718        .join("host-certs")
1719}
1720
1721/// Name of the cache subdirectory for leaves signed by the CA `ca_cert_pem`.
1722///
1723/// Leaves are kept per CA so that one signed by a replaced CA is never looked
1724/// up again, even if a running supervisor writes it after the cache was
1725/// cleared: loading only checks expiry, not the issuer. FNV-1a rather than
1726/// `DefaultHasher`, whose output may change between Rust releases and would
1727/// orphan the cache on every upgrade.
1728#[cfg(feature = "proxy-tls")]
1729fn ca_cache_id(ca_cert_pem: &str) -> String {
1730    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
1731    for b in ca_cert_pem.bytes() {
1732        hash ^= u64::from(b);
1733        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1734    }
1735    format!("ca-{hash:016x}")
1736}
1737
1738/// Remove cached leaves under `root` that do not belong to the CA `keep`
1739/// names: loose `*.pem` files from the older flat layout, and every other
1740/// CA's subdirectory. Other files are left alone.
1741#[cfg(feature = "proxy-tls")]
1742fn clear_host_certs(root: &std::path::Path, keep: Option<&str>) {
1743    let Ok(entries) = std::fs::read_dir(root) else {
1744        return;
1745    };
1746    for entry in entries.filter_map(|e| e.ok()) {
1747        let path = entry.path();
1748        let name = entry.file_name();
1749        let result = if path.is_dir() {
1750            let is_ca_dir = name.to_str().is_some_and(|n| n.starts_with("ca-"));
1751            if !is_ca_dir || keep.is_some_and(|k| name == k) {
1752                continue;
1753            }
1754            std::fs::remove_dir_all(&path)
1755        } else if path.extension().is_some_and(|x| x == "pem") {
1756            std::fs::remove_file(&path)
1757        } else {
1758            continue;
1759        };
1760        if let Err(e) = result {
1761            log::debug!(
1762                "Could not remove stale cached certs {}: {e}",
1763                path.display()
1764            );
1765        }
1766    }
1767}
1768
1769/// Generate a local root CA certificate and private key using `rcgen`.
1770///
1771/// The CA is used to sign per-domain certificates on demand (SNI).
1772/// Files are written in PEM format to `cert_path` and `key_path`. Callers go
1773/// through [`ensure_ca`], which holds the CA lock around the check and this
1774/// write.
1775#[cfg(feature = "proxy-tls")]
1776fn generate_ca(cert_path: &std::path::Path, key_path: &std::path::Path) -> crate::Result<()> {
1777    use rcgen::{
1778        BasicConstraints, CertificateParams, DistinguishedName, DnType, IsCa, KeyUsagePurpose,
1779    };
1780
1781    // Create parent directory if needed
1782    if let Some(parent) = cert_path.parent() {
1783        std::fs::create_dir_all(parent)
1784            .map_err(|e| miette::miette!("Failed to create proxy cert directory: {e}"))?;
1785    }
1786
1787    let mut params = CertificateParams::default();
1788    let mut dn = DistinguishedName::new();
1789    dn.push(DnType::CommonName, "Pitchfork Local CA");
1790    dn.push(DnType::OrganizationName, "Pitchfork");
1791    params.distinguished_name = dn;
1792    params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1793    params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
1794
1795    let key_pair = rcgen::KeyPair::generate()
1796        .map_err(|e| miette::miette!("Failed to generate CA key pair: {e}"))?;
1797    let ca_cert = params
1798        .self_signed(&key_pair)
1799        .map_err(|e| miette::miette!("Failed to self-sign CA certificate: {e}"))?;
1800
1801    // Write the CA certificate (public — 0644 is fine)
1802    std::fs::write(cert_path, ca_cert.pem()).map_err(|e| {
1803        miette::miette!(
1804            "Failed to write CA certificate to {}: {e}",
1805            cert_path.display()
1806        )
1807    })?;
1808
1809    // Write the CA private key with restrictive permissions (0600).
1810    // Using OpenOptions + mode() so the file is never world-readable,
1811    // even briefly before a chmod call.
1812    {
1813        #[cfg(unix)]
1814        {
1815            use std::io::Write;
1816            use std::os::unix::fs::OpenOptionsExt;
1817            std::fs::OpenOptions::new()
1818                .write(true)
1819                .create(true)
1820                .truncate(true)
1821                .mode(0o600)
1822                .open(key_path)
1823                .and_then(|mut f| f.write_all(key_pair.serialize_pem().as_bytes()))
1824                .map_err(|e| {
1825                    miette::miette!("Failed to write CA key to {}: {e}", key_path.display())
1826                })?;
1827        }
1828        #[cfg(not(unix))]
1829        {
1830            std::fs::write(key_path, key_pair.serialize_pem()).map_err(|e| {
1831                miette::miette!("Failed to write CA key to {}: {e}", key_path.display())
1832            })?;
1833            log::debug!(
1834                "CA private key written to {} (file permissions are not restricted \
1835                 on non-Unix platforms — consider restricting access manually)",
1836                key_path.display()
1837            );
1838        }
1839    }
1840
1841    Ok(())
1842}
1843
1844/// Resolver that serves one configured certificate for every connection.
1845///
1846/// Used when `proxy.tls_cert` / `proxy.tls_key` are set. No certificate is
1847/// minted: whatever the user configured is what clients see, for every SNI
1848/// name.
1849#[cfg(feature = "proxy-tls")]
1850struct StaticCertResolver {
1851    certified: Arc<rustls::sign::CertifiedKey>,
1852    /// TLD hostnames are resolved against, so a passthrough hostname is
1853    /// refused here too rather than answered with the configured certificate.
1854    tld: String,
1855}
1856
1857#[cfg(feature = "proxy-tls")]
1858impl std::fmt::Debug for StaticCertResolver {
1859    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1860        f.debug_struct("StaticCertResolver").finish_non_exhaustive()
1861    }
1862}
1863
1864#[cfg(feature = "proxy-tls")]
1865impl StaticCertResolver {
1866    fn new(
1867        cert_path: &std::path::Path,
1868        key_path: &std::path::Path,
1869        tld: String,
1870    ) -> crate::Result<Self> {
1871        use rustls::pki_types::CertificateDer;
1872        use rustls_pemfile::{certs, private_key};
1873
1874        let cert_pem = std::fs::read(cert_path).map_err(|e| {
1875            miette::miette!("Failed to read proxy.tls_cert {}: {e}", cert_path.display())
1876        })?;
1877        let key_pem = std::fs::read(key_path).map_err(|e| {
1878            miette::miette!("Failed to read proxy.tls_key {}: {e}", key_path.display())
1879        })?;
1880
1881        let cert_ders: Vec<CertificateDer<'static>> = certs(&mut cert_pem.as_slice())
1882            .collect::<Result<Vec<_>, _>>()
1883            .map_err(|e| miette::miette!("Failed to parse {}: {e}", cert_path.display()))?;
1884        if cert_ders.is_empty() {
1885            miette::bail!("No certificates found in {}", cert_path.display());
1886        }
1887
1888        let key_der = private_key(&mut key_pem.as_slice())
1889            .map_err(|e| miette::miette!("Failed to parse {}: {e}", key_path.display()))?
1890            .ok_or_else(|| miette::miette!("No private key found in {}", key_path.display()))?;
1891        let signing_key = rustls::crypto::ring::sign::any_supported_type(&key_der)
1892            .map_err(|e| miette::miette!("Failed to use the configured private key: {e}"))?;
1893
1894        let certified = rustls::sign::CertifiedKey::new(cert_ders, signing_key);
1895        // `CertifiedKey::new` only packages the two; it does not check that the
1896        // key belongs to the certificate. Without this the listener would start
1897        // cleanly and then fail every single handshake.
1898        certified.keys_match().map_err(|e| {
1899            miette::miette!(
1900                "proxy.tls_key {} does not match proxy.tls_cert {}: {e}",
1901                key_path.display(),
1902                cert_path.display()
1903            )
1904        })?;
1905
1906        Ok(Self {
1907            certified: Arc::new(certified),
1908            tld,
1909        })
1910    }
1911}
1912
1913#[cfg(feature = "proxy-tls")]
1914impl rustls::server::ResolvesServerCert for StaticCertResolver {
1915    fn resolve(
1916        &self,
1917        client_hello: rustls::server::ClientHello<'_>,
1918    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
1919        // As in `SniCertResolver::resolve`: a passthrough hostname whose hello
1920        // could not be read before the handshake must fail rather than be
1921        // answered with a certificate that is not the daemon's.
1922        if let Some(domain) = client_hello.server_name()
1923            && resolve_tls_mode_in(domain, &self.tld, &slug_snapshot(), &registry_snapshot())
1924                .is_passthrough()
1925        {
1926            log::warn!(
1927                "Refusing to terminate TLS for '{domain}', which is configured for \
1928                 proxy_tls = \"passthrough\": its ClientHello could not be inspected before the \
1929                 handshake, so the stream could not be spliced to the daemon."
1930            );
1931            return None;
1932        }
1933        Some(Arc::clone(&self.certified))
1934    }
1935}
1936
1937/// SNI-based certificate resolver.
1938///
1939/// Holds the local CA and a two-level cache of per-domain certificates:
1940/// - L1: in-memory `HashMap` (fastest, process-lifetime)
1941/// - L2: on-disk `host-certs/<safe_name>.pem` (survives restarts)
1942///
1943/// A `pending` set prevents concurrent requests for the same domain from
1944/// triggering multiple simultaneous cert-generation operations.
1945///
1946/// On each new TLS connection, `resolve()` is called with the SNI hostname;
1947/// if no cached cert exists for that domain, one is signed by the CA on the fly.
1948///
1949/// # Locking strategy
1950/// Both `cache` and `pending` use `std::sync::Mutex` paired with a
1951/// `std::sync::Condvar`.  The critical sections are intentionally short
1952/// (hash-map lookups / inserts), so the blocking time is negligible.
1953/// `get_or_create` is only called from the synchronous `ResolvesServerCert`
1954/// trait method (not from an async context), so blocking a thread here is
1955/// acceptable.
1956#[cfg(feature = "proxy-tls")]
1957struct SniCertResolver {
1958    /// The CA issuer (key + parsed cert params, used to sign leaf certs).
1959    issuer: rcgen::Issuer<'static, rcgen::KeyPair>,
1960    /// TLD this CA is willing to sign for; anything else is refused. Also the
1961    /// TLD hostnames are resolved against, so a passthrough hostname can be
1962    /// recognized before a certificate is issued for it.
1963    tld: String,
1964    /// Directory where per-domain PEM files are cached on disk.
1965    host_certs_dir: std::path::PathBuf,
1966    /// L1 cache: domain → certified key (in-memory), with insertion order kept
1967    /// alongside so the oldest can be evicted once the cache is full.
1968    cache: std::sync::Mutex<CertCache>,
1969    /// Pending set: domains currently being generated (dedup concurrent requests).
1970    /// Using a `Condvar` so waiting threads are parked instead of spin-sleeping,
1971    /// which avoids blocking tokio worker threads.
1972    pending: std::sync::Mutex<std::collections::HashSet<String>>,
1973    /// Condvar paired with `pending` — notified when a domain is removed from the set.
1974    pending_cv: std::sync::Condvar,
1975}
1976
1977/// Delete the oldest cached certificates until at most [`MAX_HOST_CERTS`] remain.
1978///
1979/// Called at startup, because eviction during a run only knows about names that
1980/// run has seen. Oldest is by modification time, which is when the certificate
1981/// was minted, so the ones most recently useful survive.
1982#[cfg(feature = "proxy-tls")]
1983fn prune_host_certs(dir: &std::path::Path) {
1984    let Ok(entries) = std::fs::read_dir(dir) else {
1985        return;
1986    };
1987    let mut files: Vec<(std::time::SystemTime, std::path::PathBuf)> = entries
1988        .filter_map(|e| e.ok())
1989        .filter(|e| e.path().extension().is_some_and(|x| x == "pem"))
1990        .filter_map(|e| {
1991            let modified = e.metadata().and_then(|m| m.modified()).ok()?;
1992            Some((modified, e.path()))
1993        })
1994        .collect();
1995    if files.len() <= MAX_HOST_CERTS {
1996        return;
1997    }
1998    files.sort_by_key(|(t, _)| *t);
1999    let excess = files.len() - MAX_HOST_CERTS;
2000    for (_, path) in files.into_iter().take(excess) {
2001        if let Err(e) = std::fs::remove_file(&path) {
2002            log::debug!("Could not prune cached cert {}: {e}", path.display());
2003        }
2004    }
2005}
2006
2007/// Minted certificates, bounded and evicted oldest-first.
2008#[cfg(feature = "proxy-tls")]
2009#[derive(Default)]
2010struct CertCache {
2011    by_domain: std::collections::HashMap<String, Arc<rustls::sign::CertifiedKey>>,
2012    /// Insertion order, oldest first.
2013    order: std::collections::VecDeque<String>,
2014}
2015
2016#[cfg(feature = "proxy-tls")]
2017impl CertCache {
2018    fn get(&self, domain: &str) -> Option<&Arc<rustls::sign::CertifiedKey>> {
2019        self.by_domain.get(domain)
2020    }
2021
2022    /// Insert `key`, evicting the oldest entry when full.
2023    ///
2024    /// Returns the evicted domain, whose on-disk copy the caller removes.
2025    fn insert(&mut self, domain: String, key: Arc<rustls::sign::CertifiedKey>) -> Option<String> {
2026        if self.by_domain.insert(domain.clone(), key).is_none() {
2027            self.order.push_back(domain);
2028        }
2029        if self.by_domain.len() <= MAX_HOST_CERTS {
2030            return None;
2031        }
2032        let evicted = self.order.pop_front()?;
2033        self.by_domain.remove(&evicted);
2034        Some(evicted)
2035    }
2036}
2037
2038#[cfg(feature = "proxy-tls")]
2039impl std::fmt::Debug for SniCertResolver {
2040    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2041        f.debug_struct("SniCertResolver").finish_non_exhaustive()
2042    }
2043}
2044
2045#[cfg(feature = "proxy-tls")]
2046impl SniCertResolver {
2047    /// Load the CA from disk and prepare the resolver.
2048    fn new(
2049        ca_cert_path: &std::path::Path,
2050        ca_key_path: &std::path::Path,
2051        tld: String,
2052    ) -> crate::Result<Self> {
2053        let ca_key_pem = std::fs::read_to_string(ca_key_path)
2054            .map_err(|e| miette::miette!("Failed to read CA key {}: {e}", ca_key_path.display()))?;
2055        let ca_cert_pem = std::fs::read_to_string(ca_cert_path).map_err(|e| {
2056            miette::miette!("Failed to read CA cert {}: {e}", ca_cert_path.display())
2057        })?;
2058
2059        // Verify the PEM is readable (sanity check)
2060        if !ca_cert_pem.contains("BEGIN CERTIFICATE") {
2061            miette::bail!("CA cert file does not contain a valid PEM certificate");
2062        }
2063
2064        let ca_key = rcgen::KeyPair::from_pem(&ca_key_pem)
2065            .map_err(|e| miette::miette!("Failed to parse CA key: {e}"))?;
2066
2067        // Parse the CA cert + key into an Issuer for signing leaf certs.
2068        let issuer = rcgen::Issuer::from_ca_cert_pem(&ca_cert_pem, ca_key)
2069            .map_err(|e| miette::miette!("Failed to parse CA cert: {e}"))?;
2070
2071        // Leaves live in a subdirectory for this CA, and those of any other CA
2072        // are cleared, so a leaf from a replaced CA can never be served.
2073        let host_certs_root = host_certs_dir_for(ca_cert_path);
2074        let cache_id = ca_cache_id(&ca_cert_pem);
2075        clear_host_certs(&host_certs_root, Some(&cache_id));
2076        let host_certs_dir = host_certs_root.join(&cache_id);
2077        std::fs::create_dir_all(&host_certs_dir)
2078            .map_err(|e| miette::miette!("Failed to create host-certs dir: {e}"))?;
2079        // The in-memory cache starts empty on every run, so without this the
2080        // directory would keep files from previous processes for ever and grow
2081        // across restarts however well eviction works within one.
2082        prune_host_certs(&host_certs_dir);
2083
2084        Ok(Self {
2085            issuer,
2086            tld,
2087            host_certs_dir,
2088            cache: std::sync::Mutex::new(CertCache::default()),
2089            pending: std::sync::Mutex::new(std::collections::HashSet::new()),
2090            pending_cv: std::sync::Condvar::new(),
2091        })
2092    }
2093
2094    /// `get_or_create`, but only for names this CA is allowed to sign.
2095    ///
2096    /// The CA is installed in the machine's trust store and the proxy answers on
2097    /// 127.0.0.1, so without this check any name that resolves to loopback — an
2098    /// /etc/hosts line, a rebinding answer, a poisoned resolver — could obtain a
2099    /// browser-trusted certificate for itself and its parent wildcard just by
2100    /// sending it as SNI. Returning `None` fails the handshake and writes
2101    /// nothing to the on-disk cache.
2102    fn get_or_create_checked(&self, domain: &str) -> Option<Arc<rustls::sign::CertifiedKey>> {
2103        if !crate::proxy::owns_name(&self.tld, domain) {
2104            // Throttled for the same reason the refusal exists: anything that
2105            // can reach the listener can ask for any name, repeatedly.
2106            if let Some(suppressed) = REFUSED_SNI.allow(REFUSAL_LOG_INTERVAL) {
2107                log::warn!(
2108                    "Refusing to issue a certificate for {domain:?}: \
2109                     the pitchfork CA only signs names under .{} \
2110                     ({suppressed} similar refusals since the last message)",
2111                    self.tld
2112                );
2113            }
2114            return None;
2115        }
2116        self.get_or_create(domain)
2117    }
2118
2119    /// Get or create a `CertifiedKey` for the given domain.
2120    ///
2121    /// Resolution order:
2122    /// 1. L1 in-memory cache
2123    /// 2. L2 on-disk cache (`host-certs/<safe_name>.pem`)
2124    /// 3. Generate fresh cert, persist to disk, populate both caches
2125    ///
2126    /// Concurrent requests for the same domain are deduplicated: the second
2127    /// thread waits on a `Condvar` until the first thread finishes, then reads
2128    /// from the cache.  This avoids both duplicate cert generation and the
2129    /// spin-sleep anti-pattern that would block tokio worker threads.
2130    ///
2131    /// # Locking discipline
2132    /// `cache` and `pending` are **never held simultaneously**.  The protocol is:
2133    /// 1. Check `cache` (lock, read, unlock).
2134    /// 2. Acquire `pending`; wait if domain is in-progress; re-check `cache`
2135    ///    after waking (unlock `cache` before re-acquiring `pending` is not
2136    ///    needed because we release `cache` before entering the `pending` block).
2137    /// 3. Insert domain into `pending`; release `pending` lock.
2138    /// 4. Generate cert (no locks held).
2139    /// 5. Insert into `cache` (lock, write, unlock).
2140    /// 6. Remove from `pending` and notify (lock, write, unlock).
2141    fn get_or_create(&self, domain: &str) -> Option<Arc<rustls::sign::CertifiedKey>> {
2142        // L1: memory cache (fast path — no pending lock needed)
2143        {
2144            let cache = self.cache.lock().ok()?;
2145            if let Some(ck) = cache.get(domain) {
2146                return Some(Arc::clone(ck));
2147            }
2148        } // cache lock released here
2149
2150        // Dedup: acquire the pending lock, wait if another thread is generating
2151        // this domain, then re-check the cache (without holding pending) before
2152        // deciding to generate.
2153        //
2154        // We deliberately release the pending lock before re-checking the cache
2155        // to avoid holding both locks simultaneously.  The re-check is safe
2156        // because: if the generating thread inserted into the cache and then
2157        // removed from pending, we will see the cert in the cache.  If we miss
2158        // the window (extremely unlikely), we will generate a duplicate cert,
2159        // which is harmless — the last writer wins in the cache.
2160        loop {
2161            {
2162                let mut pending = self.pending.lock().ok()?;
2163                if pending.contains(domain) {
2164                    // Another thread is generating; wait until it finishes.
2165                    pending = self.pending_cv.wait(pending).ok()?;
2166                    // pending lock re-acquired; loop to re-check cache below.
2167                    drop(pending);
2168                } else {
2169                    // No one else is generating; claim the slot and proceed.
2170                    pending.insert(domain.to_string());
2171                    break;
2172                }
2173            } // pending lock released
2174
2175            // Re-check cache after being woken (the generating thread may have
2176            // already populated it).  Cache lock is acquired independently of
2177            // pending lock here — no nesting.
2178            {
2179                let cache = self.cache.lock().ok()?;
2180                if let Some(ck) = cache.get(domain) {
2181                    return Some(Arc::clone(ck));
2182                }
2183            } // cache lock released
2184        } // pending lock released at break
2185
2186        let result = self.get_or_create_inner(domain);
2187
2188        // Always clear the pending flag and wake waiting threads.
2189        // notify_all() is called *inside* the lock scope so that the domain is
2190        // guaranteed to be removed before any waiting thread is woken up.
2191        // If the lock is poisoned we recover it (the data is still valid) so
2192        // that the domain is always removed and waiters are always notified.
2193        {
2194            let mut pending = match self.pending.lock() {
2195                Ok(g) => g,
2196                Err(e) => e.into_inner(),
2197            };
2198            pending.remove(domain);
2199            self.pending_cv.notify_all();
2200        }
2201
2202        result
2203    }
2204
2205    /// Inner implementation: check disk cache, then generate.
2206    fn get_or_create_inner(&self, domain: &str) -> Option<Arc<rustls::sign::CertifiedKey>> {
2207        let disk_path = self.disk_path(domain);
2208
2209        // L2: disk cache — try to load existing cert+key PEM
2210        if disk_path.exists() {
2211            if let Ok(ck) = self.load_from_disk(&disk_path) {
2212                let ck = Arc::new(ck);
2213                self.remember(domain, &ck);
2214                return Some(ck);
2215            }
2216            // Disk cache corrupt/expired — fall through to regenerate
2217            let _ = std::fs::remove_file(&disk_path);
2218        }
2219
2220        // L3: generate fresh cert
2221        let ck = self.sign_for_domain(domain).ok()?;
2222
2223        let ck = Arc::new(ck);
2224        self.remember(domain, &ck);
2225        Some(ck)
2226    }
2227
2228    /// Cache `ck` for `domain`, dropping the oldest entry when full.
2229    ///
2230    /// The evicted certificate's file is removed too, so the on-disk cache
2231    /// stays bounded alongside the in-memory one.
2232    fn remember(&self, domain: &str, ck: &Arc<rustls::sign::CertifiedKey>) {
2233        let evicted = match self.cache.lock() {
2234            Ok(mut cache) => cache.insert(domain.to_string(), Arc::clone(ck)),
2235            Err(_) => return,
2236        };
2237        if let Some(evicted) = evicted {
2238            let path = self.disk_path(&evicted);
2239            if let Err(e) = std::fs::remove_file(&path)
2240                && e.kind() != std::io::ErrorKind::NotFound
2241            {
2242                log::debug!("Could not evict cached cert {}: {e}", path.display());
2243            }
2244        }
2245    }
2246
2247    /// Where the cached certificate for `domain` lives.
2248    fn disk_path(&self, domain: &str) -> std::path::PathBuf {
2249        self.host_certs_dir
2250            .join(format!("{}.pem", cert_cache_file_stem(domain)))
2251    }
2252
2253    /// Load a `CertifiedKey` from a combined cert+key PEM file on disk.
2254    ///
2255    /// Returns an error if the certificate has already expired, so the caller
2256    /// can fall through to regeneration rather than serving a stale cert.
2257    fn load_from_disk(&self, path: &std::path::Path) -> crate::Result<rustls::sign::CertifiedKey> {
2258        use rustls::pki_types::CertificateDer;
2259        use rustls_pemfile::{certs, private_key};
2260
2261        let pem = std::fs::read_to_string(path)
2262            .map_err(|e| miette::miette!("Failed to read disk cert {}: {e}", path.display()))?;
2263
2264        let cert_ders: Vec<CertificateDer<'static>> = certs(&mut pem.as_bytes())
2265            .collect::<Result<Vec<_>, _>>()
2266            .map_err(|e| miette::miette!("Failed to parse certs from {}: {e}", path.display()))?;
2267
2268        if cert_ders.is_empty() {
2269            miette::bail!("No certificates found in {}", path.display());
2270        }
2271
2272        // Check that the first certificate has not expired using x509-parser.
2273        {
2274            let (_, cert) = x509_parser::parse_x509_certificate(&cert_ders[0]).map_err(|e| {
2275                miette::miette!("Failed to parse certificate from {}: {e}", path.display())
2276            })?;
2277            use chrono::Utc;
2278            let now_ts = Utc::now().timestamp();
2279            let not_after_ts = cert.validity().not_after.timestamp();
2280            if not_after_ts < now_ts {
2281                miette::bail!(
2282                    "Cached certificate at {} has expired — will regenerate",
2283                    path.display()
2284                );
2285            }
2286        }
2287
2288        let key_der = private_key(&mut pem.as_bytes())
2289            .map_err(|e| miette::miette!("Failed to parse key from {}: {e}", path.display()))?
2290            .ok_or_else(|| miette::miette!("No private key found in {}", path.display()))?;
2291
2292        let signing_key = rustls::crypto::ring::sign::any_supported_type(&key_der)
2293            .map_err(|e| miette::miette!("Failed to create signing key from disk: {e}"))?;
2294
2295        Ok(rustls::sign::CertifiedKey::new(cert_ders, signing_key))
2296    }
2297
2298    /// Sign a leaf certificate for `domain` using the CA.
2299    ///
2300    /// SANs include:
2301    /// - `DNS:<domain>` (exact match)
2302    /// - `DNS:*.<parent>` (sibling wildcard, e.g. `*.pf.localhost` for `docs.pf.localhost`)
2303    ///
2304    /// Returns both the `CertifiedKey` and the combined PEM for disk caching.
2305    fn sign_for_domain(&self, domain: &str) -> crate::Result<rustls::sign::CertifiedKey> {
2306        use rcgen::date_time_ymd;
2307        use rcgen::{CertificateParams, DistinguishedName, DnType, SanType};
2308        use rustls::pki_types::CertificateDer;
2309        use rustls_pemfile::private_key;
2310
2311        let mut params = CertificateParams::default();
2312        let mut dn = DistinguishedName::new();
2313        dn.push(DnType::CommonName, domain);
2314        params.distinguished_name = dn;
2315
2316        // Set validity dynamically: from yesterday to 10 years from now.
2317        {
2318            use chrono::{Datelike, Duration, Utc};
2319            let yesterday = Utc::now() - Duration::days(1);
2320            // 397 days: stays within Chrome/Safari's 398-day maximum validity limit
2321            // for TLS certificates (including locally-trusted CA leaf certs).
2322            let expiry = Utc::now() + Duration::days(397);
2323            params.not_before = date_time_ymd(
2324                yesterday.year(),
2325                yesterday.month() as u8,
2326                yesterday.day() as u8,
2327            );
2328            params.not_after =
2329                date_time_ymd(expiry.year(), expiry.month() as u8, expiry.day() as u8);
2330        }
2331
2332        // Build SANs: exact domain + sibling wildcard (e.g. *.pf.localhost)
2333        let mut sans =
2334            vec![SanType::DnsName(domain.to_string().try_into().map_err(
2335                |e| miette::miette!("Invalid domain name '{domain}': {e}"),
2336            )?)];
2337        // Sibling wildcard for the parent domain, one level up.
2338        //
2339        // Only when the parent is strictly inside the TLD. `*.<tld>` would cover
2340        // every name the proxy serves, which is far broader than the one host
2341        // this certificate is for, and a parent outside the TLD is not ours to
2342        // claim at all.
2343        if let Some(dot_pos) = domain.find('.') {
2344            let parent = &domain[dot_pos + 1..];
2345            if crate::proxy::is_strictly_under_tld(&self.tld, parent) {
2346                let wildcard = format!("*.{parent}");
2347                if let Ok(wc) = wildcard.try_into() {
2348                    sans.push(SanType::DnsName(wc));
2349                }
2350            }
2351        }
2352        params.subject_alt_names = sans;
2353
2354        let leaf_key = rcgen::KeyPair::generate()
2355            .map_err(|e| miette::miette!("Failed to generate leaf key: {e}"))?;
2356        let leaf_cert = params
2357            .signed_by(&leaf_key, &self.issuer)
2358            .map_err(|e| miette::miette!("Failed to sign leaf cert for '{domain}': {e}"))?;
2359
2360        // Convert to rustls types
2361        let cert_der = CertificateDer::from(leaf_cert.der().to_vec());
2362        let key_pem = leaf_key.serialize_pem();
2363        let key_der = private_key(&mut key_pem.as_bytes())
2364            .map_err(|e| miette::miette!("Failed to parse leaf key PEM: {e}"))?
2365            .ok_or_else(|| miette::miette!("No private key found in generated PEM"))?;
2366
2367        let signing_key = rustls::crypto::ring::sign::any_supported_type(&key_der)
2368            .map_err(|e| miette::miette!("Failed to create signing key: {e}"))?;
2369
2370        // Persist cert + key to disk cache as combined PEM.
2371        // Use 0600 so the private key is not world-readable.
2372        let disk_path = self.disk_path(domain);
2373        let combined_pem = format!("{}{}", leaf_cert.pem(), key_pem);
2374        {
2375            #[cfg(unix)]
2376            {
2377                use std::io::Write;
2378                use std::os::unix::fs::OpenOptionsExt;
2379                if let Err(e) = std::fs::OpenOptions::new()
2380                    .write(true)
2381                    .create(true)
2382                    .truncate(true)
2383                    .mode(0o600)
2384                    .open(&disk_path)
2385                    .and_then(|mut f| f.write_all(combined_pem.as_bytes()))
2386                {
2387                    log::warn!(
2388                        "Failed to persist cert for '{domain}' to {}: {e}",
2389                        disk_path.display()
2390                    );
2391                }
2392            }
2393            #[cfg(not(unix))]
2394            {
2395                if let Err(e) = std::fs::write(&disk_path, combined_pem) {
2396                    log::warn!(
2397                        "Failed to persist cert for '{domain}' to {}: {e}",
2398                        disk_path.display()
2399                    );
2400                } else {
2401                    log::debug!(
2402                        "Leaf cert for '{domain}' written to {} (file permissions are not \
2403                         restricted on non-Unix platforms — consider restricting access manually)",
2404                        disk_path.display()
2405                    );
2406                }
2407            }
2408        }
2409
2410        Ok(rustls::sign::CertifiedKey::new(vec![cert_der], signing_key))
2411    }
2412}
2413
2414#[cfg(feature = "proxy-tls")]
2415impl rustls::server::ResolvesServerCert for SniCertResolver {
2416    fn resolve(
2417        &self,
2418        client_hello: rustls::server::ClientHello<'_>,
2419    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
2420        let domain = client_hello.server_name()?;
2421        // This is the last point where a passthrough hostname can still be
2422        // caught, and the first where the host name is authoritative: rustls
2423        // has reassembled the handshake itself. Issuing here would answer with
2424        // the proxy's certificate in place of the daemon's and drop the
2425        // client-certificate request, so the handshake is failed instead.
2426        // Reached only when the pre-handshake peek could not read the hello.
2427        if resolve_tls_mode_in(domain, &self.tld, &slug_snapshot(), &registry_snapshot())
2428            .is_passthrough()
2429        {
2430            log::warn!(
2431                "Refusing to terminate TLS for '{domain}', which is configured for \
2432                 proxy_tls = \"passthrough\": its ClientHello could not be inspected before the \
2433                 handshake, so the stream could not be spliced to the daemon."
2434            );
2435            return None;
2436        }
2437
2438        // Refuse to sign for a name outside the proxy's own TLD.
2439        //
2440        // The CA is installed in the machine's trust store and the proxy answers
2441        // on 127.0.0.1, so without this check any name that resolves to loopback
2442        // — an /etc/hosts line, a rebinding answer, a poisoned resolver — could
2443        // obtain a browser-trusted certificate for itself and its parent
2444        // wildcard just by sending it as SNI. Returning `None` fails the
2445        // handshake and writes nothing to the on-disk cache.
2446        self.get_or_create_checked(domain)
2447    }
2448}
2449
2450/// Why the CA pair at `cert` and `key` cannot sign certificates, if it cannot.
2451///
2452/// Existence is not enough: a truncated file or a key that belongs to another
2453/// certificate stops the HTTPS listener from starting, and trusting such a
2454/// certificate would install something the proxy never serves from.
2455#[cfg(feature = "proxy-tls")]
2456pub(crate) fn ca_pair_problem(cert: &std::path::Path, key: &std::path::Path) -> Option<String> {
2457    use rcgen::PublicKeyData;
2458
2459    let cert_pem = match std::fs::read_to_string(cert) {
2460        Ok(p) => p,
2461        Err(e) => return Some(format!("cannot read {}: {e}", cert.display())),
2462    };
2463    let key_pem = match std::fs::read_to_string(key) {
2464        Ok(p) => p,
2465        Err(e) => return Some(format!("cannot read {}: {e}", key.display())),
2466    };
2467    let key_pair = match rcgen::KeyPair::from_pem(&key_pem) {
2468        Ok(k) => k,
2469        Err(e) => return Some(format!("cannot parse {}: {e}", key.display())),
2470    };
2471    let Some(Ok(der)) = rustls_pemfile::certs(&mut cert_pem.as_bytes()).next() else {
2472        return Some(format!("no certificate in {}", cert.display()));
2473    };
2474    let parsed = match x509_parser::parse_x509_certificate(&der) {
2475        Ok((_, c)) => c,
2476        Err(e) => return Some(format!("cannot parse {}: {e}", cert.display())),
2477    };
2478    if parsed.public_key().subject_public_key.data.as_ref() != key_pair.der_bytes() {
2479        return Some(format!(
2480            "{} is not the key for {}",
2481            key.display(),
2482            cert.display()
2483        ));
2484    }
2485    if let Err(e) = rcgen::Issuer::from_ca_cert_pem(&cert_pem, key_pair) {
2486        return Some(format!("{} cannot sign certificates: {e}", cert.display()));
2487    }
2488    None
2489}
2490
2491/// A file name for `domain`'s cached certificate, distinct for distinct names.
2492///
2493/// Letters, digits, `-` and `.` are kept, since they are safe in a file name
2494/// and make the cache readable; every other byte is percent-encoded. Mapping
2495/// `.` to `_`, as this once did, sent `a_b.localhost` and `a.b.localhost` to
2496/// the same file, so one name's certificate could be served for the other.
2497#[cfg(feature = "proxy-tls")]
2498fn cert_cache_file_stem(domain: &str) -> String {
2499    let mut out = String::with_capacity(domain.len());
2500    for b in domain.bytes() {
2501        if b.is_ascii_alphanumeric() || b == b'-' || b == b'.' {
2502            out.push(char::from(b));
2503        } else {
2504            out.push_str(&format!("%{b:02X}"));
2505        }
2506    }
2507    out
2508}
2509
2510/// State for the plain-HTTP side of the TLS listener.
2511#[derive(Clone)]
2512struct PlainState {
2513    tld: String,
2514    port: u16,
2515    /// Carried so `CONNECT` can be tunnelled without re-deriving the routing
2516    /// configuration.
2517    proxy: ProxyState,
2518}
2519
2520/// Plain HTTP arriving on the HTTPS port.
2521///
2522/// `CONNECT` is tunnelled, because that is how a PAC-configured browser opens
2523/// an `https://` URL. Everything else is redirected to HTTPS.
2524async fn plain_fallback_handler(State(state): State<PlainState>, req: Request) -> Response {
2525    if req.method() == axum::http::Method::CONNECT {
2526        let raw_host = get_request_host(&req).unwrap_or_default();
2527        return connect_handler(&state.proxy, req, &raw_host).await;
2528    }
2529    redirect_to_https_handler(req).await
2530}
2531
2532/// Render the PAC script, or an error page explaining why it could not be.
2533/// Refuse a write method aimed at the PAC file.
2534///
2535/// A PAC file is fetched, never written, so anything but `GET` or `HEAD` is a
2536/// mistake. Returning `Some` here rather than restricting the route keeps the
2537/// path available to proxied hostnames under every method.
2538fn reject_non_read(method: &axum::http::Method) -> Option<Response> {
2539    if matches!(*method, axum::http::Method::GET | axum::http::Method::HEAD) {
2540        return None;
2541    }
2542    let mut res = error_response(
2543        StatusCode::METHOD_NOT_ALLOWED,
2544        "the proxy auto-config file is read-only\n",
2545    );
2546    res.headers_mut().insert(
2547        axum::http::header::ALLOW,
2548        HeaderValue::from_static("GET, HEAD"),
2549    );
2550    Some(res)
2551}
2552
2553fn pac_response(tld: &str, host: &str, port: u16) -> Response {
2554    match crate::proxy::pac::generate(tld, host, port) {
2555        Ok(body) => (
2556            StatusCode::OK,
2557            [(
2558                axum::http::header::CONTENT_TYPE,
2559                "application/x-ns-proxy-autoconfig",
2560            )],
2561            body,
2562        )
2563            .into_response(),
2564        Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
2565    }
2566}
2567
2568/// Serve `/proxy.pac` on the proxy listener.
2569///
2570/// A request addressed to a name *beneath* the TLD is a normal proxied request
2571/// that happens to use this path, so it is forwarded to the backend instead.
2572/// The TLD apex is not: no slug can route it, so `http://localhost/proxy.pac`
2573/// with `proxy.tld = "localhost"` is a request for the PAC file.
2574async fn pac_handler(State(state): State<ProxyState>, req: Request) -> Response {
2575    let host = get_request_host(&req).unwrap_or_default();
2576    let bare = host.split(':').next().unwrap_or("");
2577    if !bare.is_empty() && crate::proxy::is_strictly_under_tld(&state.tld, bare) {
2578        return proxy_handler(State(state), req).await;
2579    }
2580    // Only now is this known to be a request for the PAC file itself, so the
2581    // method check belongs here rather than on the route.
2582    if let Some(deny) = reject_non_read(req.method()) {
2583        return deny;
2584    }
2585    let port = req
2586        .uri()
2587        .authority()
2588        .and_then(|a| a.port_u16())
2589        .or_else(|| host.rsplit(':').next().and_then(|p| p.parse().ok()))
2590        .unwrap_or(if state.is_tls { 443 } else { 80 });
2591    pac_response(&state.tld, &url_host(state.contact_ip), port)
2592}
2593
2594/// Serve `/proxy.pac` over plain HTTP on the HTTPS listener.
2595async fn plain_pac_handler(State(state): State<PlainState>, req: Request) -> Response {
2596    // Same rule as the TLS side: a name beneath the TLD is a proxied request
2597    // that happens to use this path, so it is redirected to HTTPS like any
2598    // other. The apex is not routable, so it gets the PAC file.
2599    let host = get_request_host(&req).unwrap_or_default();
2600    let bare = host.split(':').next().unwrap_or("");
2601    if !bare.is_empty() && crate::proxy::is_strictly_under_tld(&state.tld, bare) {
2602        return redirect_to_https_handler(req).await;
2603    }
2604    if let Some(deny) = reject_non_read(req.method()) {
2605        return deny;
2606    }
2607    pac_response(&state.tld, &url_host(state.proxy.contact_ip), state.port)
2608}
2609
2610/// The address a client on this machine uses to reach a listener bound to
2611/// `bind_ip`.
2612///
2613/// A wildcard bind is reachable over the loopback address of its own family; a
2614/// specific address is reachable at exactly that address.
2615fn local_contact_ip(bind_ip: std::net::IpAddr) -> std::net::IpAddr {
2616    match bind_ip {
2617        std::net::IpAddr::V4(ip) if ip.is_unspecified() => {
2618            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
2619        }
2620        std::net::IpAddr::V6(ip) if ip.is_unspecified() => {
2621            std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)
2622        }
2623        ip => ip,
2624    }
2625}
2626
2627/// Format an address for a URL or PAC directive, bracketing IPv6 literals.
2628fn url_host(ip: std::net::IpAddr) -> String {
2629    match ip {
2630        std::net::IpAddr::V6(ip) => format!("[{ip}]"),
2631        std::net::IpAddr::V4(ip) => ip.to_string(),
2632    }
2633}
2634
2635/// The port in a CONNECT authority (`host:port`, `[v6]:port`), if it names one.
2636fn connect_port(authority: &str) -> Option<u16> {
2637    let (host, port) = authority.rsplit_once(':')?;
2638    // A bare IPv6 literal's last colon is inside the address, not before a port.
2639    if host.contains(':') && !host.ends_with(']') {
2640        return None;
2641    }
2642    port.parse().ok()
2643}
2644
2645/// Handle a `CONNECT` request from a client using the PAC file.
2646///
2647/// A proxy auto-config file routes `*.<tld>` through this listener, and a
2648/// browser opening an `https://` URL asks the proxy to tunnel with `CONNECT
2649/// host:port`. Without this the PAC path would only ever work for plain HTTP.
2650///
2651/// The tunnel's far end is this same listener: the target host is a name only
2652/// pitchfork resolves, and the TLS handshake inside the tunnel carries the SNI
2653/// the certificate resolver needs in order to mint a certificate for it. So the
2654/// connection is spliced back to the proxy's own address, where it arrives as an
2655/// ordinary TLS connection and is routed by `Host` as usual.
2656///
2657/// Only names under the configured TLD are tunnelled. An open CONNECT proxy
2658/// would let anything on the machine reach any host through pitchfork.
2659async fn connect_handler(state: &ProxyState, req: Request, raw_host: &str) -> Response {
2660    let authority = req
2661        .uri()
2662        .authority()
2663        .map(|a| a.as_str().to_string())
2664        .unwrap_or_else(|| raw_host.to_string());
2665    let host = authority
2666        .rsplit_once(':')
2667        .map(|(h, _)| h)
2668        .unwrap_or(&authority)
2669        .trim_start_matches('[')
2670        .trim_end_matches(']')
2671        .to_string();
2672
2673    // The shared rule rather than a hand-rolled pair of conditions; keeping a
2674    // second copy of "is this name ours" is how several of these drifted apart.
2675    if !crate::proxy::owns_name(&state.tld, &host) {
2676        return error_response(
2677            StatusCode::FORBIDDEN,
2678            &format!(
2679                "pitchfork only tunnels CONNECT for names under .{} — refusing {host}",
2680                state.tld
2681            ),
2682        );
2683    }
2684
2685    // With `proxy.https = false` the tunnel lands on a plain HTTP listener.
2686    // That still carries `ws://` and `http://` traffic, which browsers send
2687    // through CONNECT too, but a TLS handshake for an `https://` URL could
2688    // only fail there, and with an error that names neither cause nor fix.
2689    if !state.is_tls && connect_port(&authority) == Some(443) {
2690        return error_response(
2691            StatusCode::BAD_GATEWAY,
2692            &format!(
2693                "proxy.https is false, so pitchfork cannot serve https://{host}; \
2694                 use http:// or enable proxy.https"
2695            ),
2696        );
2697    }
2698
2699    let Some(target) = state.connect_target else {
2700        return error_response(
2701            StatusCode::SERVICE_UNAVAILABLE,
2702            "The proxy listener address is unknown, so CONNECT cannot be tunnelled",
2703        );
2704    };
2705
2706    // Refuse once shutdown has begun, so no tunnel is created after the drain
2707    // has started looking for stragglers.
2708    if state.cancel.is_cancelled() {
2709        return error_response(
2710            StatusCode::SERVICE_UNAVAILABLE,
2711            "The proxy is shutting down",
2712        );
2713    }
2714
2715    // Bounded like the handshake phase and the DNS listener. The permit is
2716    // held for the life of the tunnel, which is the resource being limited.
2717    let Ok(permit) = Arc::clone(&state.tunnel_slots).try_acquire_owned() else {
2718        if let Some(suppressed) = REFUSED_TUNNEL.allow(REFUSAL_LOG_INTERVAL) {
2719            log::warn!(
2720                "Proxy refused a CONNECT tunnel: {MAX_TUNNELS} already open \
2721                 ({suppressed} similar refusals since the last message)"
2722            );
2723        }
2724        return error_response(
2725            StatusCode::SERVICE_UNAVAILABLE,
2726            "Too many CONNECT tunnels are open",
2727        );
2728    };
2729    let cancel = state.cancel.clone();
2730
2731    // Reply 200 first, then take over the upgraded stream. hyper only hands the
2732    // socket over once the response has been sent.
2733    //
2734    // Tracked so shutdown can wait for the splice to stop rather than leaving
2735    // it holding two sockets.
2736    state.tunnels.spawn(async move {
2737        // Dropped with the task, releasing the slot when the tunnel closes.
2738        let _permit = permit;
2739
2740        // Both of these happen before there is a tunnel to speak of, and
2741        // neither is bounded by anything on its own. A client that never
2742        // finishes reading the 200 leaves `upgrade::on` pending forever, and a
2743        // target that accepts nothing leaves `connect` the same way — in each
2744        // case holding one of the tunnel slots for good, so enough stalls
2745        // permanently shrink the proxy's CONNECT capacity. Shutdown does not
2746        // rescue them either: the drain gives up when its own timeout elapses
2747        // and the tracker never aborts what is left.
2748        //
2749        // Racing the cancellation token as well as the clock means shutdown
2750        // reaches a tunnel that is still being set up, not only one that is
2751        // already running.
2752        macro_rules! setup_step {
2753            ($what:literal, $fut:expr) => {
2754                tokio::select! {
2755                    r = tokio::time::timeout(HANDSHAKE_TIMEOUT, $fut) => match r {
2756                        Ok(Ok(v)) => v,
2757                        Ok(Err(e)) => {
2758                            if let Some(n) = ABANDONED_TUNNEL.allow(REFUSAL_LOG_INTERVAL) {
2759                                log::debug!(
2760                                    concat!(
2761                                        "CONNECT {} for {target} failed: {e}",
2762                                        " ({n} similar since the last message)"
2763                                    ),
2764                                    $what,
2765                                    target = target,
2766                                    e = e,
2767                                    n = n
2768                                );
2769                            }
2770                            return;
2771                        }
2772                        Err(_) => {
2773                            if let Some(n) = ABANDONED_TUNNEL.allow(REFUSAL_LOG_INTERVAL) {
2774                                log::debug!(
2775                                    concat!(
2776                                        "CONNECT {} for {target} did not finish within",
2777                                        " {timeout:?}",
2778                                        " ({n} similar since the last message)"
2779                                    ),
2780                                    $what,
2781                                    target = target,
2782                                    timeout = HANDSHAKE_TIMEOUT,
2783                                    n = n
2784                                );
2785                            }
2786                            return;
2787                        }
2788                    },
2789                    // Not throttled: shutdown happens once, so the count is
2790                    // bounded by the tunnels open at that moment.
2791                    _ = cancel.cancelled() => {
2792                        log::debug!("CONNECT {} for {target} abandoned by shutdown", $what);
2793                        return;
2794                    }
2795                }
2796            };
2797        }
2798
2799        let upgraded = setup_step!("upgrade", hyper::upgrade::on(req));
2800        let mut client = hyper_util::rt::TokioIo::new(upgraded);
2801        let mut server = setup_step!("connect", tokio::net::TcpStream::connect(target));
2802
2803        // Straight byte splice: the payload is TLS pitchfork must not and
2804        // cannot read here. Shutdown drops both sockets rather than waiting
2805        // for the peers to finish, since a tunnel can legitimately stay open
2806        // for hours.
2807        tokio::select! {
2808            r = tokio::io::copy_bidirectional(&mut client, &mut server) => {
2809                // Throttled like the setup steps: a client can end tunnels
2810                // with errors as fast as it can open them.
2811                if let Err(e) = r
2812                    && let Some(n) = ABANDONED_TUNNEL.allow(REFUSAL_LOG_INTERVAL)
2813                {
2814                    log::debug!(
2815                        "CONNECT tunnel to {target} ended: {e} ({n} similar since the last message)"
2816                    );
2817                }
2818            }
2819            _ = cancel.cancelled() => {
2820                log::debug!("CONNECT tunnel to {target} closed by shutdown");
2821            }
2822        }
2823    });
2824
2825    Response::builder()
2826        .status(StatusCode::OK)
2827        .header(PITCHFORK_HEADER, "1")
2828        .body(Body::empty())
2829        .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
2830}
2831
2832/// Get the effective host from a request.
2833///
2834/// HTTP/2 uses the `:authority` pseudo-header, which hyper exposes via
2835/// `req.uri().authority()` rather than in the `HeaderMap`.
2836/// HTTP/1.1 uses the `Host` header.
2837fn get_request_host(req: &Request) -> Option<String> {
2838    // HTTP/2: :authority is available via the request URI, not the HeaderMap.
2839    let authority = req
2840        .uri()
2841        .authority()
2842        .map(|a| a.as_str().to_string())
2843        .filter(|s| !s.is_empty());
2844
2845    authority.or_else(|| {
2846        req.headers()
2847            .get(HOST)
2848            .and_then(|h| h.to_str().ok())
2849            .map(str::to_string)
2850    })
2851}
2852
2853/// Rejoin a `cookie` header that arrived split across several fields.
2854///
2855/// An HTTP/2 client may send each cookie as its own header field (RFC 9113
2856/// §8.2.3). An HTTP/1.1 backend joins repeated fields with `", "`, which
2857/// corrupts every cookie value, so they must be joined with `"; "` first.
2858fn join_cookie_fields(headers: &mut HeaderMap) {
2859    let fields: Vec<&[u8]> = headers
2860        .get_all(COOKIE)
2861        .iter()
2862        .map(HeaderValue::as_bytes)
2863        .collect();
2864    if fields.len() < 2 {
2865        return;
2866    }
2867
2868    let joined = HeaderValue::from_bytes(&fields.join(b"; ".as_slice()))
2869        .expect("valid header values joined with \"; \" form a valid header value");
2870    headers.insert(COOKIE, joined);
2871}
2872
2873/// Inject `X-Forwarded-*` headers into a proxied request.
2874///
2875/// Because the proxy is a **first-hop** dev tool (not a mid-tier forwarder),
2876/// all four headers are **unconditionally overwritten** with values derived
2877/// from the actual incoming connection.  Any values supplied by the connecting
2878/// client are discarded.
2879///
2880/// Trusting client-supplied `x-forwarded-for` / `x-forwarded-proto` would
2881/// allow a local process to spoof a remote IP or trick a backend's
2882/// HTTPS-detection logic (CSRF checks, secure-cookie flags, redirect rules).
2883///
2884/// A slug with a public URL takes its host, scheme and port from that URL
2885/// instead, which comes from the user's own config rather than the client.
2886fn inject_forwarded_headers(
2887    req: &mut Request,
2888    is_tls: bool,
2889    host_header: &str,
2890    public_url: Option<&crate::proxy::public_url::PublicUrl>,
2891) {
2892    let remote_addr = req
2893        .extensions()
2894        .get::<axum::extract::ConnectInfo<SocketAddr>>()
2895        .map(|ci| ci.0.ip().to_string())
2896        .unwrap_or_else(|| "127.0.0.1".to_string());
2897
2898    let proto = if is_tls { "https" } else { "http" };
2899    let default_port = if is_tls { "443" } else { "80" };
2900
2901    // Always set fresh values — we are the edge, never a mid-tier forwarder.
2902    // Discard any x-forwarded-* headers supplied by the connecting client.
2903    let forwarded_for = remote_addr.clone();
2904    let (forwarded_proto, forwarded_host, forwarded_port) = match public_url {
2905        Some(public) => (
2906            public.proto.to_string(),
2907            public.authority.clone(),
2908            public.port.to_string(),
2909        ),
2910        None => (
2911            proto.to_string(),
2912            host_header.to_string(),
2913            host_header
2914                .rsplit_once(':')
2915                .map(|(_, port)| port.to_string())
2916                .unwrap_or_else(|| default_port.to_string()),
2917        ),
2918    };
2919
2920    // Strip any client-supplied x-forwarded-* and RFC 7239 Forwarded headers
2921    // before inserting ours, so that no trace of the original values reaches
2922    // the backend.  The RFC 7239 `Forwarded` header is stripped alongside the
2923    // legacy `x-forwarded-*` set because backends that read it (Django, Rails,
2924    // Spring) would otherwise see client-injected spoofed IPs or protocols.
2925    for name in [
2926        "x-forwarded-for",
2927        "x-forwarded-proto",
2928        "x-forwarded-host",
2929        "x-forwarded-port",
2930        "forwarded",
2931    ] {
2932        if let Ok(header_name) = axum::http::HeaderName::from_bytes(name.as_bytes()) {
2933            req.headers_mut().remove(&header_name);
2934        }
2935    }
2936
2937    let headers = [
2938        ("x-forwarded-for", forwarded_for),
2939        ("x-forwarded-proto", forwarded_proto),
2940        ("x-forwarded-host", forwarded_host),
2941        ("x-forwarded-port", forwarded_port),
2942    ];
2943
2944    for (name, value) in headers {
2945        if let Ok(v) = HeaderValue::from_str(&value) {
2946            let header_name = axum::http::HeaderName::from_static(name);
2947            req.headers_mut().insert(header_name, v);
2948        }
2949    }
2950}
2951
2952/// The public URL of the slug `host` names exactly, if it has one.
2953///
2954/// Only the slug's own hostname qualifies: `<branch>.<slug>.<tld>` names a
2955/// worktree, which is browsed locally and keeps its local host.
2956fn entry_public_url(
2957    host: &str,
2958    tld: &str,
2959    cached: &CachedSlugEntry,
2960) -> Option<crate::proxy::public_url::PublicUrl> {
2961    let subdomain = strip_tld(host, tld)?;
2962    cached
2963        .slug
2964        .eq_ignore_ascii_case(&subdomain)
2965        .then(|| cached.public_url.clone())
2966        .flatten()
2967}
2968
2969/// Main proxy request handler.
2970///
2971/// Parses the `Host` header, resolves the target daemon, and forwards the request.
2972/// WebSocket / HTTP upgrade requests are forwarded transparently via hyper's upgrade mechanism.
2973async fn proxy_handler(State(state): State<ProxyState>, mut req: Request) -> Response {
2974    // Extract the host (supports both HTTP/2 :authority and HTTP/1.1 Host)
2975    let Some(raw_host) = get_request_host(&req) else {
2976        return error_response(StatusCode::BAD_REQUEST, "Missing Host header");
2977    };
2978
2979    // A browser configured through the PAC file sends CONNECT for every
2980    // `https://` URL, so this is the entry point for the whole PAC path under
2981    // the default HTTPS configuration.
2982    if req.method() == axum::http::Method::CONNECT {
2983        return connect_handler(&state, req, &raw_host).await;
2984    }
2985    // Strip port from host for routing.
2986    // IPv6 addresses in Host headers are bracketed per RFC 2732: `[::1]:port`.
2987    // Splitting naïvely on ':' would break on the colons inside the address.
2988    let host = if raw_host.starts_with('[') {
2989        // IPv6: "[::1]:port" or "[::1]"
2990        raw_host
2991            .split("]:")
2992            .next()
2993            .unwrap_or(&raw_host)
2994            .trim_start_matches('[')
2995            .trim_end_matches(']')
2996            .to_string()
2997    } else {
2998        // IPv4 / hostname: "host:port" or "host"
2999        raw_host.split(':').next().unwrap_or(&raw_host).to_string()
3000    };
3001    // A fully qualified name may end in the root dot (`api.localhost.`). The
3002    // resolver and the certificate issuer already accept it through
3003    // `owns_name`, so routing has to as well, or the name resolves and
3004    // handshakes only to be answered "not found".
3005    let host = host.trim_end_matches('.').to_string();
3006
3007    // Loop detection: check hop count.
3008    //
3009    // Security: strip (zero out) the hop counter on the very first hop to
3010    // prevent external clients from forging a high value and triggering a
3011    // 508 Loop Detected response (denial-of-service).  A request is
3012    // considered "first hop" when it does not carry the `x-pitchfork-hops`
3013    // request header that pitchfork injects when forwarding — i.e. it did
3014    // not come from another pitchfork proxy instance.
3015    // Note: `x-pitchfork` is a *response* header added by pitchfork and is
3016    // never present on incoming requests, so it cannot be used here.
3017    let is_from_pitchfork = req.headers().contains_key(PROXY_HOPS_HEADER);
3018    let hops: u64 = if is_from_pitchfork {
3019        req.headers()
3020            .get(PROXY_HOPS_HEADER)
3021            .and_then(|v| v.to_str().ok())
3022            .and_then(|s| s.parse().ok())
3023            .unwrap_or(0)
3024    } else {
3025        // External request: ignore any forged hop counter.
3026        0
3027    };
3028    if hops >= MAX_PROXY_HOPS {
3029        return error_response(
3030            StatusCode::LOOP_DETECTED,
3031            &format!(
3032                "Loop detected for '{host}': request has passed through the proxy {hops} times.\n\
3033                 This usually means a backend is proxying back through pitchfork without rewriting \n\
3034                 the Host header. If you use Vite/webpack proxy, set changeOrigin: true."
3035            ),
3036        );
3037    }
3038
3039    let local_client = is_local_client(&req);
3040
3041    // Intercept "pitchfork.<tld>" — route to the built-in web UI
3042    let target_port = if let Some(subdomain) = strip_tld(&host, &state.tld) {
3043        if subdomain.eq_ignore_ascii_case("pitchfork") {
3044            // With `web.tls_cert` set the web UI listener terminates TLS
3045            // itself, and the proxy only speaks plain HTTP to backends. Send
3046            // the browser to the HTTPS URL rather than fail the handshake.
3047            if let Some(origin) = crate::web::https_origin() {
3048                let path = req
3049                    .uri()
3050                    .path_and_query()
3051                    .map(|pq| pq.as_str())
3052                    .unwrap_or("/");
3053                return page_redirect_response(&origin, path);
3054            }
3055            crate::web::port()
3056        } else {
3057            None
3058        }
3059    } else {
3060        None
3061    };
3062
3063    let (target_port, activity, protocol, public_url) = if let Some(port) = target_port {
3064        (port, None, ProxyProtocol::Http1, None)
3065    } else {
3066        // A passthrough hostname must never be forwarded as plain HTTP: the
3067        // daemon expects a TLS handshake on that port, so the request would
3068        // fail deep inside the daemon with nothing to point at the cause.
3069        if resolve_tls_mode(&host, &state.tld).await.is_passthrough() {
3070            return error_response(
3071                StatusCode::BAD_GATEWAY,
3072                &passthrough_unroutable_message(&host, state.is_tls),
3073            );
3074        }
3075        let (resolved, public_url) = resolve_target_with_public_url(&host, &state.tld).await;
3076        match resolved {
3077            ResolveResult::Ready(port, activity, protocol) => {
3078                (port, activity, protocol, public_url)
3079            }
3080            ResolveResult::Starting { slug } => {
3081                return starting_html_response(&slug, &raw_host);
3082            }
3083            ResolveResult::Page {
3084                project,
3085                worktree,
3086                daemons,
3087                dir,
3088            } => {
3089                // A reserved name answers 200 while an unknown one answers 404,
3090                // which tells anything on the network which projects exist. Off
3091                // this machine the two look the same.
3092                if !local_client {
3093                    return unknown_host_response(&host, "Not found", &[]);
3094                }
3095                // The project and stack pages live in the web UI, which is
3096                // their canonical location, so this hostname redirects there.
3097                // The page is found by the checkout the hostname resolved
3098                // to, because its URL is built from the registered project
3099                // name and the worktree's own name, neither of which has to
3100                // match the sanitized, overridable labels in the hostname.
3101                if let Some(base) = crate::web::url()
3102                    && let Some(resolved) = dir.clone()
3103                    && let Some(path) = tokio::task::spawn_blocking(move || {
3104                        crate::web::routes::api::projects::page_path_for_dir(&resolved)
3105                    })
3106                    .await
3107                    .ok()
3108                    .flatten()
3109                {
3110                    return page_redirect_response(&base, &path);
3111                }
3112                return page_placeholder_response(
3113                    &project,
3114                    worktree.as_deref(),
3115                    &daemons,
3116                    &state.tld,
3117                    &host_port_suffix(&raw_host),
3118                    crate::web::url().as_deref(),
3119                );
3120            }
3121            ResolveResult::Unknown { heading, known } => {
3122                // The heading says which project was recognised, which is one
3123                // more thing than a remote client needs to learn.
3124                return unknown_host_response(
3125                    &host,
3126                    if local_client { &heading } else { "Not found" },
3127                    if local_client { &known } else { &[] },
3128                );
3129            }
3130            ResolveResult::NotFound => {
3131                return error_response(
3132                    StatusCode::BAD_GATEWAY,
3133                    &format!(
3134                        "No daemon found for host '{host}'.\n\
3135                         A daemon is reachable once it configures a `port` and its project is \
3136                         known to pitchfork; run `pitchfork proxy status` to see the hostnames \
3137                         it serves.\n\
3138                         Expected format: <daemon>.<project>.{tld}",
3139                        tld = state.tld
3140                    ),
3141                );
3142            }
3143            ResolveResult::Error(msg) => {
3144                if local_client {
3145                    return error_response(StatusCode::BAD_GATEWAY, &msg);
3146                }
3147                // The message names directories on this machine.
3148                log::warn!("Refused '{host}' for a non-local client: {msg}");
3149                return error_response(
3150                    StatusCode::BAD_GATEWAY,
3151                    &format!("'{host}' is not available."),
3152                );
3153            }
3154        }
3155    };
3156    // Build the forwarding URI
3157    let path_and_query = req
3158        .uri()
3159        .path_and_query()
3160        .map(|pq| pq.as_str())
3161        .unwrap_or("/");
3162
3163    let forward_uri = match Uri::builder()
3164        .scheme("http")
3165        .authority(format!("localhost:{target_port}"))
3166        .path_and_query(path_and_query)
3167        .build()
3168    {
3169        Ok(uri) => uri,
3170        Err(e) => {
3171            return error_response(
3172                StatusCode::INTERNAL_SERVER_ERROR,
3173                &format!("Failed to build forward URI: {e}"),
3174            );
3175        }
3176    };
3177
3178    let h2c = protocol.is_h2c();
3179    if h2c && req.headers().contains_key(axum::http::header::UPGRADE) {
3180        return error_response(
3181            StatusCode::NOT_IMPLEMENTED,
3182            &format!(
3183                "'{host}' uses proxy_protocol = \"h2c\", which cannot carry protocol upgrades \
3184                 such as WebSocket. Remove proxy_protocol, or connect without an Upgrade header."
3185            ),
3186        );
3187    }
3188    if h2c {
3189        // HTTP/2 forbids connection-specific headers, so drop them along with
3190        // every header `Connection` nominates, before the proxy adds its own.
3191        // `TE: trailers` is the one exception, and gRPC requires it.
3192        let nominated: Vec<axum::http::HeaderName> = req
3193            .headers()
3194            .get_all(axum::http::header::CONNECTION)
3195            .iter()
3196            .filter_map(|v| v.to_str().ok())
3197            .flat_map(|v| v.split(','))
3198            .filter_map(|t| axum::http::HeaderName::from_bytes(t.trim().as_bytes()).ok())
3199            .collect();
3200        for name in nominated {
3201            if name != axum::http::header::TE {
3202                req.headers_mut().remove(&name);
3203            }
3204        }
3205        for h in HOP_BY_HOP_HEADERS {
3206            if let Ok(name) = axum::http::HeaderName::from_bytes(h.as_bytes()) {
3207                req.headers_mut().remove(&name);
3208            }
3209        }
3210    }
3211
3212    // Update the request URI and Host header. A slug with a public URL keeps
3213    // that URL's host, so the backend sees the address the user browses. An
3214    // h2c backend is the exception for `Host`: HTTP/2 carries `:authority` in
3215    // the request URI, which the client also dials, so it stays local there.
3216    *req.uri_mut() = forward_uri;
3217    let host_value = match &public_url {
3218        Some(public) if !h2c => HeaderValue::from_str(&public.authority).ok(),
3219        _ => None,
3220    }
3221    .unwrap_or_else(|| {
3222        HeaderValue::from_str(&format!("localhost:{target_port}"))
3223            .unwrap_or_else(|_| HeaderValue::from_static("localhost"))
3224    });
3225    req.headers_mut().insert(HOST, host_value);
3226
3227    // Inject X-Forwarded-* headers
3228    inject_forwarded_headers(&mut req, state.is_tls, &raw_host, public_url.as_ref());
3229
3230    // Increment hop counter
3231    if let Ok(v) = HeaderValue::from_str(&(hops + 1).to_string()) {
3232        req.headers_mut()
3233            .insert(axum::http::HeaderName::from_static(PROXY_HOPS_HEADER), v);
3234    }
3235
3236    // Explicitly strip HTTP/2 pseudo-headers (":authority", ":method", etc.)
3237    // before forwarding to an HTTP/1.1 backend. Although hyper typically does
3238    // not store pseudo-headers in the HeaderMap, some middleware layers or
3239    // future hyper versions might; stripping them here is a defensive measure.
3240    let pseudo_headers: Vec<_> = req
3241        .headers()
3242        .keys()
3243        .filter(|k| k.as_str().starts_with(':'))
3244        .cloned()
3245        .collect();
3246    for key in pseudo_headers {
3247        req.headers_mut().remove(&key);
3248    }
3249
3250    join_cookie_fields(req.headers_mut());
3251
3252    // Downgrade the forwarded request to HTTP/1.1. TLS connections negotiate
3253    // HTTP/2 inbound via ALPN, but the upstream forward client speaks HTTP/1 to
3254    // the daemon. Without this, the still-h2-tagged request is rejected by the
3255    // client with `UserUnsupportedVersion`, surfacing as a 502 to the browser.
3256    *req.version_mut() = if h2c {
3257        axum::http::Version::HTTP_2
3258    } else {
3259        axum::http::Version::HTTP_11
3260    };
3261
3262    // Extract the client-side OnUpgrade handle *before* consuming req
3263    let client_upgrade = hyper::upgrade::on(&mut req);
3264
3265    // Forward the request with a per-request timeout so that a backend that
3266    // accepts the TCP connection but then stalls (deadlock, blocking I/O, etc.)
3267    // cannot hold the proxy connection open forever and exhaust file descriptors.
3268    //
3269    // 120 s is intentionally generous for a local dev proxy — it covers slow
3270    // test suites, large file uploads, and SSE streams while still bounding
3271    // the worst-case resource leak.
3272    let result = match tokio::time::timeout(std::time::Duration::from_secs(120), async {
3273        if h2c {
3274            state.h2c_client.request(req).await
3275        } else {
3276            state.client.request(req).await
3277        }
3278    })
3279    .await
3280    {
3281        Ok(r) => r,
3282        Err(_elapsed) => {
3283            let msg = format!(
3284                "Request to daemon on port {target_port} timed out after 120 s.\n\
3285                 The daemon accepted the connection but did not respond in time."
3286            );
3287            log::warn!("{msg}");
3288            if let Some(ref on_error) = state.on_error {
3289                on_error(&msg);
3290            }
3291            return error_response(StatusCode::GATEWAY_TIMEOUT, &msg);
3292        }
3293    };
3294    match result {
3295        Ok(mut resp) => {
3296            // Extract backend upgrade handle *before* consuming resp
3297            let backend_upgrade = hyper::upgrade::on(&mut resp);
3298            let (mut parts, body) = resp.into_parts();
3299
3300            // Add pitchfork identification header
3301            parts.headers.insert(
3302                axum::http::HeaderName::from_static(PITCHFORK_HEADER),
3303                HeaderValue::from_static("1"),
3304            );
3305
3306            // Strip the internal hop-counter so it is never leaked to external clients.
3307            parts.headers.remove(PROXY_HOPS_HEADER);
3308
3309            // Strip hop-by-hop headers when serving HTTPS (HTTP/2 forbids them).
3310            // Skip 101 Switching Protocols — that response is always HTTP/1.1 and
3311            // the client needs the `Upgrade` header to complete the WS handshake
3312            // (RFC 6455 §4.1 requires `Upgrade: websocket` in the 101 response).
3313            if state.is_tls && parts.status != StatusCode::SWITCHING_PROTOCOLS {
3314                for h in HOP_BY_HOP_HEADERS {
3315                    if let Ok(name) = axum::http::HeaderName::from_bytes(h.as_bytes()) {
3316                        parts.headers.remove(&name);
3317                    }
3318                }
3319            }
3320
3321            // If the backend returned 101 Switching Protocols, pipe the upgraded streams.
3322            if parts.status == StatusCode::SWITCHING_PROTOCOLS {
3323                // Note: loop detection for WebSocket upgrades is already handled at the
3324                // top of proxy_handler (hops >= MAX_PROXY_HOPS check) before the request
3325                // is forwarded.  A 101 response here means the backend accepted the
3326                // upgrade, so the hop count was already within limits.
3327                // Tracked with the CONNECT tunnels and raced against the
3328                // cancellation token, so shutdown drains it instead of leaving
3329                // it splicing to a daemon that is about to be stopped.
3330                let cancel = state.cancel.clone();
3331                state.tunnels.spawn(async move {
3332                    // An open WebSocket is activity until either side closes
3333                    // it, however quiet it is.
3334                    let _activity = activity;
3335                    let splice = async move {
3336                        if let (Ok(client_upgraded), Ok(backend_upgraded)) =
3337                            (client_upgrade.await, backend_upgrade.await)
3338                        {
3339                            let mut client_io = hyper_util::rt::TokioIo::new(client_upgraded);
3340                            let mut backend_io = hyper_util::rt::TokioIo::new(backend_upgraded);
3341                            // No application-level timeout here: tokio::time::timeout would be a
3342                            // hard wall-clock deadline for the entire tunnel, not an idle timeout.
3343                            // Long-lived connections (Vite/webpack HMR, SSE-over-WS) would be
3344                            // silently terminated after the deadline even if data is actively
3345                            // flowing.  The OS TCP keepalive is sufficient to reap truly dead
3346                            // connections; a proper idle timeout would require a custom
3347                            // AsyncRead/AsyncWrite wrapper that resets the timer on each I/O op.
3348                            let _ = tokio::io::copy_bidirectional(&mut client_io, &mut backend_io)
3349                                .await;
3350                        }
3351                    };
3352                    // The whole splice, upgrade waits included: an abandoned
3353                    // handshake leaves those pending, and the tracker never
3354                    // aborts, so only the token ends it at shutdown.
3355                    tokio::select! {
3356                        _ = splice => {}
3357                        _ = cancel.cancelled() => {}
3358                    }
3359                });
3360                return Response::from_parts(parts, Body::empty());
3361            }
3362
3363            // Backend refused the upgrade (returned a non-101 response) — forward it as-is.
3364            // This can happen when the backend rejects a WebSocket handshake with e.g. 400.
3365            //
3366            // The body carries the activity guard, so a streamed response
3367            // (server-sent events, a long download) counts until it ends.
3368            Response::from_parts(parts, Body::new(GuardedBody::new(body, activity)))
3369        }
3370        Err(e) => {
3371            let msg = format!(
3372                "Failed to connect to daemon on port {target_port}: {e}\n\
3373                 The daemon may have stopped or is not yet ready."
3374            );
3375            if let Some(ref on_error) = state.on_error {
3376                on_error(&msg);
3377            } else {
3378                log::warn!("{msg}");
3379            }
3380            error_response(StatusCode::BAD_GATEWAY, &msg)
3381        }
3382    }
3383}
3384
3385/// Explain why a request for a `proxy_tls = "passthrough"` hostname arrived on
3386/// the HTTP path, where it cannot be served.
3387///
3388/// Passthrough routes on the hostname in the TLS ClientHello, so there are two
3389/// ways to end up here: the proxy is not serving TLS at all, or the TLS
3390/// connection named one host and the request inside it named another.
3391///
3392/// A connection with no SNI at all never reaches this point: the certificate
3393/// resolver has no name to issue for, so the handshake fails outright.
3394fn passthrough_unroutable_message(host: &str, is_tls: bool) -> String {
3395    if is_tls {
3396        format!(
3397            "'{host}' uses proxy_tls = \"passthrough\", which routes on the host name \
3398             in the TLS ClientHello.\n\
3399             This connection's TLS handshake named a different host, so it was \
3400             terminated here and the request inside it cannot be spliced to the \
3401             daemon.\n\
3402             Make the connection itself name '{host}' rather than overriding the Host \
3403             header of a connection opened to something else."
3404        )
3405    } else {
3406        format!(
3407            "'{host}' uses proxy_tls = \"passthrough\", but the proxy is serving \
3408             plain HTTP.\n\
3409             Passthrough splices a TLS stream to the daemon, so it requires \
3410             settings.proxy.https = true.\n\
3411             Enable HTTPS on the proxy, or set proxy_tls = \"terminate\" on the daemon."
3412        )
3413    }
3414}
3415
3416/// Resolve the target for a given hostname.
3417///
3418/// Slug-based routing using the global config's `[slugs]` section:
3419/// 1. Strip TLD to get subdomain (the slug)
3420/// 2. Look up slug in global config → find project dir + daemon name
3421/// 3. Check state file for a running daemon with that name → get its port
3422/// 4. If `proxy.auto_start` is enabled and the daemon is not running,
3423///    trigger an automatic start and wait for it to become ready.
3424///
3425/// # Returns
3426/// - `ResolveResult::Ready(port, _)`    — daemon running (or just auto-started), forward to this port
3427/// - `ResolveResult::Starting { slug }` — daemon start in progress (show waiting page)
3428/// - `ResolveResult::NotFound`          — no daemon matched
3429/// - `ResolveResult::Error(msg)`        — routing refused with a descriptive reason
3430///
3431/// # Locking
3432/// The state file lock is held only for the duration of the snapshot copy,
3433/// then released immediately to avoid serialising all proxy requests.
3434async fn resolve_target(host: &str, tld: &str) -> ResolveResult {
3435    resolve_target_with_public_url(host, tld).await.0
3436}
3437
3438/// [`resolve_target`], also returning the public URL of the slug entry the
3439/// route was resolved from.
3440///
3441/// The public URL comes from the same entry that picks the daemon, so a slug
3442/// reload while the request waits for a daemon start cannot pair that daemon
3443/// with another registration's public address.
3444async fn resolve_target_with_public_url(
3445    host: &str,
3446    tld: &str,
3447) -> (ResolveResult, Option<crate::proxy::public_url::PublicUrl>) {
3448    let ctx = match resolve_route_context(host, tld).await {
3449        Ok(ctx) => ctx,
3450        Err(result) => return (result, None),
3451    };
3452    let public_url = entry_public_url(host, tld, &ctx.cached);
3453    (resolve_with_context(ctx).await, public_url)
3454}
3455
3456async fn resolve_with_context(ctx: RouteContext) -> ResolveResult {
3457    // One budget for everything this request may wait on: an idle stop under
3458    // way and then the start after it.
3459    let deadline = auto_start_deadline();
3460
3461    let daemons = {
3462        let state_file = SUPERVISOR.state_file.lock().await;
3463        state_file.daemons.clone()
3464    };
3465
3466    let daemon_name = &ctx.cached.daemon_name;
3467    let running_matches: Vec<(&DaemonId, &crate::daemon::Daemon)> = daemons
3468        .iter()
3469        .filter(|(id, d)| {
3470            id.name() == daemon_name
3471                && d.status.is_running()
3472                && match &ctx.expected_namespace {
3473                    Some(ns) => id.namespace() == ns,
3474                    None => true,
3475                }
3476        })
3477        .collect();
3478
3479    match running_matches.as_slice() {
3480        [] => {
3481            try_auto_start(
3482                &ctx.cached.slug,
3483                &ctx.cached,
3484                ctx.worktree_dir.as_deref(),
3485                ctx.expected_namespace.as_deref(),
3486                &ctx.route,
3487                deadline,
3488            )
3489            .await
3490        }
3491        // With more than one namespace running a daemon of this name and no
3492        // namespace to narrow by, the first match is used — as before.
3493        [(id, d), ..] => match select_daemon_port(&ctx.route, d) {
3494            Some(port) => match begin_running(id, deadline).await {
3495                Running::Yes(activity) => {
3496                    ResolveResult::Ready(port, Some(activity), ctx.route.protocol)
3497                }
3498                Running::Stopping => ResolveResult::Starting {
3499                    slug: ctx.cached.slug.clone(),
3500                },
3501                Running::No => {
3502                    try_auto_start(
3503                        &ctx.cached.slug,
3504                        &ctx.cached,
3505                        ctx.worktree_dir.as_deref(),
3506                        ctx.expected_namespace.as_deref(),
3507                        &ctx.route,
3508                        deadline,
3509                    )
3510                    .await
3511                }
3512            },
3513            None => ResolveResult::NotFound,
3514        },
3515    }
3516}
3517
3518/// Whether a daemon found running is still running once its request has
3519/// been recorded as activity.
3520enum Running {
3521    /// Still running; forward while holding this.
3522    Yes(ActivityGuard),
3523    /// Still being stopped for inactivity when the request's time ran out.
3524    Stopping,
3525    /// Stopped since the state was read, including by an idle stop the
3526    /// request waited out: start it again.
3527    No,
3528}
3529
3530/// When a request that may auto-start a daemon has to give up:
3531/// `proxy.auto_start_timeout` from now.
3532fn auto_start_deadline() -> tokio::time::Instant {
3533    tokio::time::Instant::now() + settings().proxy_auto_start_timeout()
3534}
3535
3536/// Wait until `deadline` for any stop for inactivity of `ids` to finish.
3537/// Returns whether none is under way any more.
3538///
3539/// A request that arrives while its daemon is being stopped waits here and
3540/// then starts it again, rather than reaching a daemon that is going away or
3541/// being turned away while it goes.
3542async fn wait_out_idle_stops(ids: &[DaemonId], deadline: tokio::time::Instant) -> bool {
3543    while ids.iter().any(|id| ACTIVITY.is_idle_stopping(id)) {
3544        if tokio::time::Instant::now() >= deadline {
3545            return false;
3546        }
3547        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3548    }
3549    true
3550}
3551
3552/// Record a request for a daemon that the state showed running, then check
3553/// that it still is.
3554///
3555/// Recording comes first: once it has, a stop for inactivity can no longer be
3556/// claimed, so a daemon that is still running at the check stays running for
3557/// as long as the request holds the guard.
3558///
3559/// A stop for inactivity under way is waited out until `deadline`. It may have
3560/// been called off rather than carried out, so the daemon is then looked at
3561/// again instead of assumed stopped.
3562async fn begin_running(id: &DaemonId, deadline: tokio::time::Instant) -> Running {
3563    let activity = match ACTIVITY.begin(id) {
3564        Some(activity) => activity,
3565        None => {
3566            if !wait_out_idle_stops(std::slice::from_ref(id), deadline).await {
3567                return Running::Stopping;
3568            }
3569            match ACTIVITY.begin(id) {
3570                Some(activity) => activity,
3571                // Claimed again straight away.
3572                None => return Running::Stopping,
3573            }
3574        }
3575    };
3576    let running = {
3577        let state_file = SUPERVISOR.state_file.lock().await;
3578        state_file
3579            .daemons
3580            .get(id)
3581            .is_some_and(|d| d.status.is_running())
3582    };
3583    if running {
3584        Running::Yes(activity)
3585    } else {
3586        Running::No
3587    }
3588}
3589
3590/// What a hostname resolves to before the daemon's running state is consulted:
3591/// the slug it matched, the namespace and worktree it names, and how its TLS
3592/// is handled.
3593struct RouteContext {
3594    cached: CachedSlugEntry,
3595    expected_namespace: Option<String>,
3596    worktree_dir: Option<std::path::PathBuf>,
3597    route: ProxyTlsRoute,
3598}
3599
3600/// Resolve a hostname to its slug, worktree and TLS route.
3601///
3602/// This is the part of routing that does not depend on whether the daemon is
3603/// running, which is what lets the 443 listener decide between terminating TLS
3604/// and splicing the raw stream before anything is started.
3605///
3606/// Returns `Err(ResolveResult)` when the host does not route at all, carrying
3607/// the response the caller should produce.
3608async fn resolve_route_context(host: &str, tld: &str) -> Result<RouteContext, ResolveResult> {
3609    let Some(subdomain) = strip_tld(host, tld) else {
3610        return Err(ResolveResult::NotFound);
3611    };
3612
3613    let cached = cached_slug_lookup(&subdomain).await.filter(|cached| {
3614        // A slug too long for the configured TLD is not advertised as a URL, so
3615        // it does not take precedence over the daemon's automatic hostname
3616        // here either.
3617        if crate::proxy::hostname::hostname_fits(&cached.slug) {
3618            return true;
3619        }
3620        crate::proxy::hostname::warn_once(&format!(
3621            "Slug '{}' plus the configured proxy.tld is over the DNS length limit, \
3622             so it is not routed.",
3623            cached.slug
3624        ));
3625        false
3626    });
3627    let Some(cached) = cached else {
3628        // No legacy slug matched; fall through to the automatic
3629        // `<daemon>.<worktree>.<project>` hostnames.
3630        return Err(resolve_registry_target(&subdomain).await);
3631    };
3632
3633    // ─── Worktree prefix extraction ──────────────────────────────────────
3634    // When a wildcard subdomain like "feature-a.myapp" matched slug "myapp",
3635    // the prefix "feature-a" may correspond to a git worktree or jj workspace.
3636    let (expected_namespace, worktree_dir, route) = if !subdomain.eq_ignore_ascii_case(&cached.slug)
3637    {
3638        let prefix = strip_dot_suffix_ignore_case(&subdomain, &cached.slug);
3639        match prefix {
3640            Some(ref p) => match match_worktree_prefix(&cached, p) {
3641                PrefixMatch::Worktree(wt) => {
3642                    let ns = wt.namespace.clone().or_else(|| {
3643                        log::warn!(
3644                            "Worktree '{}' has no cached namespace; \
3645                             falling back to parent slug namespace.",
3646                            wt.path.display()
3647                        );
3648                        cached.namespace.clone()
3649                    });
3650                    let route = worktree_route(&cached, &wt.sanitized_branch);
3651                    (ns, Some(wt.path.clone()), route)
3652                }
3653                PrefixMatch::Ambiguous => {
3654                    return Err(ResolveResult::Error(format!(
3655                        "'{host}' is ambiguous: more than one branch or workspace of '{slug}' \
3656                         sanitizes to the prefix '{p}', and host names are case-insensitive.\n\
3657                         Rename one of them so the prefixes differ by more than case, then \
3658                         reload.\n\
3659                         The supervisor log lists the colliding branches.",
3660                        slug = cached.slug,
3661                    )));
3662                }
3663                PrefixMatch::Unknown => (cached.namespace.clone(), None, cached.tls),
3664            },
3665            None => (cached.namespace.clone(), None, cached.tls),
3666        }
3667    } else {
3668        (cached.namespace.clone(), None, cached.tls)
3669    };
3670
3671    Ok(RouteContext {
3672        cached,
3673        expected_namespace,
3674        worktree_dir,
3675        route,
3676    })
3677}
3678
3679/// How the proxy should handle TLS for `host`.
3680///
3681/// Answered from the slug cache alone, so it is cheap enough to call on every
3682/// TLS connection. Anything that does not resolve to a daemon — an unknown
3683/// host, the built-in web UI, a bare IP — keeps today's behavior and
3684/// terminates.
3685pub(crate) async fn resolve_tls_mode(host: &str, tld: &str) -> ProxyTlsMode {
3686    let entries = get_cached_slugs().await;
3687    let registry = get_cached_host_registry().await;
3688    resolve_tls_mode_in(host, tld, &entries, &registry)
3689}
3690
3691/// [`resolve_tls_mode`] against a given slug table, without awaiting.
3692///
3693/// Used by the certificate resolver, which runs in a synchronous trait method
3694/// and reads [`slug_snapshot`].
3695fn resolve_tls_mode_in(
3696    host: &str,
3697    tld: &str,
3698    entries: &std::collections::HashMap<String, CachedSlugEntry>,
3699    registry: &crate::proxy::hostname::HostRegistry,
3700) -> ProxyTlsMode {
3701    let Some(subdomain) = strip_tld(host, tld) else {
3702        return ProxyTlsMode::Terminate;
3703    };
3704    let wildcard = settings().proxy.wildcard;
3705
3706    // Legacy slugs resolve first, exactly as routing resolves them.
3707    if let Some(cached) = wildcard_slug_lookup(&subdomain, entries, wildcard)
3708        && crate::proxy::hostname::hostname_fits(&cached.slug)
3709    {
3710        // A wildcard match may name a worktree, which carries its own setting.
3711        if !subdomain.eq_ignore_ascii_case(&cached.slug)
3712            && let Some(prefix) = strip_dot_suffix_ignore_case(&subdomain, &cached.slug)
3713            && let PrefixMatch::Worktree(wt) = match_worktree_prefix(cached, &prefix)
3714        {
3715            return worktree_route(cached, &wt.sanitized_branch).mode;
3716        }
3717        return cached.tls.mode;
3718    }
3719
3720    // Otherwise the automatic `<daemon>.<worktree>.<project>` hostnames, whose
3721    // mode lives in the config of the checkout the name points at.
3722    match registry.resolve(&subdomain, wildcard) {
3723        crate::proxy::hostname::HostTarget::Daemon { proxy_tls, .. } => {
3724            proxy_tls.unwrap_or_default()
3725        }
3726        // A project or stack page, an unknown name: the proxy answers those
3727        // itself over its own certificate.
3728        _ => ProxyTlsMode::Terminate,
3729    }
3730}
3731
3732/// Pick which of a running daemon's ports a hostname forwards to.
3733///
3734/// Without `proxy_tls_port`, a terminating hostname uses the port the process
3735/// was detected listening on, falling back to the first resolved port — the
3736/// historical behavior, and the right answer for a single-port daemon. A
3737/// passthrough hostname reverses that order, because the first detected
3738/// listener of a multi-port daemon need not be the one speaking TLS.
3739///
3740/// With `proxy_tls_port` set, the configured port is matched by *position* in
3741/// the daemon's `port` list, so the mapping survives auto-bump: a daemon
3742/// configured for `[8443, 9443]` whose ports bumped to `[8444, 9444]` still
3743/// routes `proxy_tls_port = 9443` to 9444. Config validation rejects a
3744/// `proxy_tls_port` the daemon does not declare, so the only way the position
3745/// lookup can miss is a state record that predates the current config; the
3746/// port is then used as written only while the daemon has no resolved ports to
3747/// contradict it.
3748fn select_daemon_port(route: &ProxyTlsRoute, daemon: &crate::daemon::Daemon) -> Option<u16> {
3749    let Some(want) = route.port else {
3750        // A passthrough hostname has to reach the daemon's *TLS* listener.
3751        // `active_port` is whichever port was detected first, which on a
3752        // multi-port daemon can be a secondary plain-HTTP or status listener
3753        // that came up earlier, so the declared first port wins there — as
3754        // documented. A terminating hostname keeps preferring the detected
3755        // port, which is what routes daemons that declare no ports at all.
3756        // Port 0 is what a daemon carries when it asked the operating system
3757        // to choose and nothing has been detected yet; it is not connectable.
3758        let detected = daemon.active_port.filter(|&p| p != 0);
3759        let first_declared = daemon.resolved_port.iter().copied().find(|&p| p != 0);
3760        return if route.mode.is_passthrough() {
3761            first_declared.or(detected)
3762        } else {
3763            detected.or(first_declared)
3764        };
3765    };
3766
3767    let configured = daemon
3768        .port
3769        .as_ref()
3770        .map(|p| p.expect.as_slice())
3771        .unwrap_or(&[]);
3772    if let Some(idx) = configured.iter().position(|&p| p == want)
3773        && let Some(&resolved) = daemon.resolved_port.get(idx)
3774    {
3775        // A recorded 0 is a port the daemon asked the operating system to
3776        // choose and nothing has detected yet, so it is no more connectable
3777        // here than on the path that takes the daemon's first port. That is a
3778        // daemon still starting, not a mismatch, so it is not warned about:
3779        // auto-start polls through this state several times a second.
3780        return (resolved != 0).then_some(resolved);
3781    }
3782    if daemon.resolved_port.contains(&want) {
3783        return Some(want);
3784    }
3785    if daemon.resolved_port.is_empty() {
3786        // Nothing recorded to place the port against — the config is the only
3787        // information there is, so use it.
3788        return Some(want);
3789    }
3790    // Every request to the hostname lands here until the daemon restarts, so
3791    // the warning is logged once per daemon and port set, not per request.
3792    crate::proxy::hostname::warn_once(&format!(
3793        "Daemon {} has proxy_tls_port {want}, which is not among its resolved ports {:?}; \
3794         refusing to route rather than forwarding to a port it never bound. \
3795         Restart the daemon if its ports changed.",
3796        daemon.id, daemon.resolved_port,
3797    ));
3798    None
3799}
3800
3801/// RAII guard that removes a `DaemonId` from `AUTO_START_IN_PROGRESS` on drop.
3802///
3803/// This ensures the in-progress flag is cleared even if the auto-start future
3804/// panics (e.g. an unexpected `unwrap` inside a dependency).  Without this,
3805/// the daemon ID would stay in the set permanently and every subsequent proxy
3806/// request would return "Starting …" forever.
3807struct AutoStartGuard {
3808    daemon_id: DaemonId,
3809}
3810
3811impl Drop for AutoStartGuard {
3812    fn drop(&mut self) {
3813        let daemon_id = self.daemon_id.clone();
3814        // Spawn a cleanup task because `Drop` is synchronous and the mutex is
3815        // async.  If the runtime is shutting down this may not execute, but in
3816        // that case the entire set is being dropped anyway.
3817        tokio::spawn(async move {
3818            AUTO_START_IN_PROGRESS.lock().await.remove(&daemon_id);
3819        });
3820    }
3821}
3822
3823/// Per-daemon locks held while a proxy request starts a dependency graph.
3824///
3825/// `AUTO_START_IN_PROGRESS` only deduplicates requests for the same hostname.
3826/// Two hostnames whose daemons share a dependency would otherwise start it
3827/// concurrently, and the supervisor answers the second start with "already
3828/// running" while the first is still waiting for it to become ready — letting
3829/// the second daemon start against a dependency that is not ready yet. A graph
3830/// holds the lock of every daemon in it until it has finished starting, so an
3831/// overlapping graph waits and then finds its shared dependencies ready.
3832///
3833/// Entries are weak: a lock lives only while a startup holds or awaits it, and
3834/// dead entries are pruned on the next call, so daemons of worktrees that come
3835/// and go do not accumulate for the life of the supervisor.
3836static STARTUP_LOCKS: once_cell::sync::Lazy<
3837    std::sync::Mutex<std::collections::HashMap<DaemonId, std::sync::Weak<tokio::sync::Mutex<()>>>>,
3838> = once_cell::sync::Lazy::new(Default::default);
3839
3840/// Lock every daemon in `ids`, in sorted order so that overlapping graphs
3841/// cannot deadlock.
3842async fn lock_startup_graph(mut ids: Vec<DaemonId>) -> Vec<tokio::sync::OwnedMutexGuard<()>> {
3843    ids.sort();
3844    ids.dedup();
3845    let locks: Vec<Arc<tokio::sync::Mutex<()>>> = {
3846        let mut map = STARTUP_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
3847        map.retain(|_, lock| lock.strong_count() > 0);
3848        ids.into_iter()
3849            .map(|id| {
3850                let entry = map.entry(id).or_default();
3851                entry.upgrade().unwrap_or_else(|| {
3852                    let lock = Arc::new(tokio::sync::Mutex::new(()));
3853                    *entry = Arc::downgrade(&lock);
3854                    lock
3855                })
3856            })
3857            .collect()
3858    };
3859    let mut guards = Vec::with_capacity(locks.len());
3860    for lock in locks {
3861        guards.push(lock.lock_owned().await);
3862    }
3863    guards
3864}
3865
3866/// Attempt to auto-start a daemon for the given slug.
3867///
3868/// If `proxy.auto_start` is disabled, returns `NotFound`.
3869/// Uses a dedup set to prevent concurrent starts for the same daemon.
3870/// Starts the daemon together with its `depends` graph exactly as
3871/// `pitchfork start` does — dependencies first, level by level, each waited on
3872/// until ready — then polls for the daemon's active port.
3873///
3874/// The request's wait — for the whole graph and then for the port — is bounded
3875/// by `proxy_auto_start_timeout`. The start itself runs as its own task and is
3876/// not cancelled when the request gives up: abandoning a graph between levels
3877/// would leave dependencies starting with nothing waiting on them, and the
3878/// next request would then start the daemon before they were ready.
3879async fn try_auto_start(
3880    slug: &str,
3881    cached: &CachedSlugEntry,
3882    worktree_dir: Option<&std::path::Path>,
3883    expected_namespace: Option<&str>,
3884    route: &ProxyTlsRoute,
3885    deadline: tokio::time::Instant,
3886) -> ResolveResult {
3887    let s = settings();
3888    if !s.proxy.auto_start {
3889        return ResolveResult::NotFound;
3890    }
3891
3892    let ns = expected_namespace
3893        .map(|s| s.to_string())
3894        .or_else(|| cached.namespace.clone())
3895        .unwrap_or_else(|| "global".to_string());
3896    let daemon_id = match DaemonId::try_new(&ns, &cached.daemon_name) {
3897        Ok(id) => id,
3898        Err(_) => return ResolveResult::NotFound,
3899    };
3900
3901    {
3902        let mut in_progress = AUTO_START_IN_PROGRESS.lock().await;
3903        if !in_progress.insert(daemon_id.clone()) {
3904            return ResolveResult::Starting {
3905                slug: slug.to_string(),
3906            };
3907        }
3908    }
3909
3910    // Shared by the start task and this request, so the daemon stays marked
3911    // as starting until both the graph and this request's port wait are done.
3912    let guard = Arc::new(AutoStartGuard {
3913        daemon_id: daemon_id.clone(),
3914    });
3915
3916    // The request's deadline, which may already be partly spent waiting out
3917    // an idle stop, so the whole request stays within one timeout.
3918    let timeout = s.proxy_auto_start_timeout();
3919    let timed_out = || {
3920        log::warn!("Auto-start: total timeout ({timeout:?}) exceeded for daemon {daemon_id}");
3921        ResolveResult::Error(format!(
3922            "Auto-start for '{daemon_id}' timed out after {timeout:?}.\n\
3923             The daemon and its dependencies did not all become ready, with the daemon \
3924             bound to a port, within the configured proxy_auto_start_timeout.\n\
3925             Startup continues in the background; reload to check again.\n\
3926             Increase the timeout or check the logs of the daemon and its dependencies \
3927             for slow startup."
3928        ))
3929    };
3930
3931    log::info!("Auto-start: starting daemon {daemon_id} for slug '{slug}'");
3932    let start = tokio::spawn({
3933        let guard = guard.clone();
3934        let daemon_id = daemon_id.clone();
3935        let config_dir = worktree_dir.unwrap_or(&cached.dir).to_path_buf();
3936        async move {
3937            let _guard = guard;
3938            start_with_dependencies(&daemon_id, &config_dir).await
3939        }
3940    });
3941    match tokio::time::timeout_at(deadline, start).await {
3942        Ok(Ok(Ok(()))) => {}
3943        Ok(Ok(Err(result))) => return result,
3944        Ok(Err(e)) => {
3945            log::warn!("Auto-start: start task for {daemon_id} failed: {e}");
3946            return ResolveResult::Error(format!("Failed to start daemon '{daemon_id}': {e}"));
3947        }
3948        Err(_elapsed) => return timed_out(),
3949    }
3950
3951    let result =
3952        tokio::time::timeout_at(deadline, wait_for_active_port(slug, &daemon_id, route)).await;
3953    drop(guard);
3954    result.unwrap_or_else(|_elapsed| timed_out())
3955}
3956
3957/// Start `daemon_id` and everything it depends on, through the same batch
3958/// start `pitchfork start` uses.
3959///
3960/// Configuration is loaded from `config_dir` — the checkout the hostname named
3961/// — together with every registered namespace, so a dependency on a daemon of
3962/// another registered project resolves just as it does from that directory on
3963/// the command line.
3964///
3965/// Returns the response to give the request when the daemon cannot be started.
3966async fn start_with_dependencies(
3967    daemon_id: &DaemonId,
3968    config_dir: &std::path::Path,
3969) -> std::result::Result<(), ResolveResult> {
3970    let loaded =
3971        crate::pitchfork_toml::PitchforkToml::all_merged_all_namespaces_from(config_dir).await;
3972    let pt = match loaded {
3973        Ok(pt) => pt,
3974        Err(e) => {
3975            log::warn!(
3976                "Auto-start: failed to load config from {}: {e}",
3977                config_dir.display()
3978            );
3979            return Err(ResolveResult::NotFound);
3980        }
3981    };
3982
3983    if !pt.daemons.contains_key(daemon_id) {
3984        log::debug!(
3985            "Auto-start: daemon {daemon_id} not found in config at {}",
3986            config_dir.display()
3987        );
3988        return Err(ResolveResult::NotFound);
3989    }
3990
3991    // `pitchfork start` refuses a disabled daemon, and so does the proxy.
3992    if SUPERVISOR
3993        .state_file
3994        .lock()
3995        .await
3996        .disabled
3997        .contains(daemon_id)
3998    {
3999        return Err(ResolveResult::Error(format!(
4000            "Daemon '{daemon_id}' is disabled, so it is not started.\n\
4001             Enable it with: pitchfork enable {daemon_id}"
4002        )));
4003    }
4004
4005    let graph: Vec<DaemonId> =
4006        match crate::deps::resolve_dependencies(std::slice::from_ref(daemon_id), &pt.daemons) {
4007            Ok(order) => order.levels.into_iter().flatten().collect(),
4008            Err(e) => {
4009                log::warn!("Auto-start: cannot resolve dependencies of {daemon_id}: {e}");
4010                return Err(ResolveResult::Error(format!(
4011                    "Cannot start '{daemon_id}': {e}"
4012                )));
4013            }
4014        };
4015    // Record the start as activity for every daemon in the graph, for as long
4016    // as the start runs — past the request's own wait, if it gives up. A
4017    // dependency that is already running is skipped by the start, so it must
4018    // not be stopped for inactivity meanwhile; one whose stop is already under
4019    // way is waited out first, and then started again. Taken before waiting
4020    // on the startup locks, so a dependency cannot go while this start queues
4021    // behind another.
4022    let _activity = match ACTIVITY.begin_all(&graph) {
4023        Some(activity) => activity,
4024        None => {
4025            wait_out_idle_stops(&graph, auto_start_deadline()).await;
4026            match ACTIVITY.begin_all(&graph) {
4027                Some(activity) => activity,
4028                None => {
4029                    return Err(ResolveResult::Error(format!(
4030                        "A dependency of '{daemon_id}' is still being stopped for inactivity.\n\
4031                         Reload to start it again."
4032                    )));
4033                }
4034            }
4035        }
4036    };
4037    let proxy_idle = proxy_idle_timeouts(daemon_id, &graph, &pt).await;
4038    let _locks = lock_startup_graph(graph).await;
4039
4040    // The same entry point as `pitchfork start`, over this supervisor's own
4041    // socket as the web UI's controls use it.
4042    let ipc = match crate::ipc::client::IpcClient::connect(false).await {
4043        Ok(ipc) => Arc::new(ipc),
4044        Err(e) => {
4045            log::warn!("Auto-start: failed to connect to the supervisor: {e}");
4046            return Err(ResolveResult::Error(format!(
4047                "Failed to start daemon '{daemon_id}': {e}"
4048            )));
4049        }
4050    };
4051    let opts = crate::ipc::batch::StartOptions {
4052        quiet: true,
4053        proxy_idle: Some(proxy_idle),
4054        ..Default::default()
4055    };
4056    let result = match ipc
4057        .start_daemons_with_config(std::slice::from_ref(daemon_id), opts, pt)
4058        .await
4059    {
4060        Ok(result) => result,
4061        Err(e) => {
4062            log::warn!("Auto-start: failed to start {daemon_id}: {e}");
4063            return Err(ResolveResult::Error(format!(
4064                "Failed to start daemon '{daemon_id}': {e}"
4065            )));
4066        }
4067    };
4068    if !result.any_failed {
4069        return Ok(());
4070    }
4071
4072    let message = match result.failed.first() {
4073        Some((id, reason)) if id == daemon_id => {
4074            format!("Daemon '{daemon_id}' failed to start: {reason}\nCheck its logs for errors.")
4075        }
4076        Some((dep, reason)) => format!(
4077            "Daemon '{daemon_id}' was not started because its dependency '{dep}' failed: \
4078             {reason}\n\
4079             Check the logs of '{dep}' for errors."
4080        ),
4081        None => format!(
4082            "Daemon '{daemon_id}' or one of its dependencies failed to start.\n\
4083             Check the supervisor log for errors."
4084        ),
4085    };
4086    log::warn!("Auto-start: {message}");
4087    Err(ResolveResult::Error(message))
4088}
4089
4090/// Poll the state file until a started daemon reports a port to forward to.
4091async fn wait_for_active_port(
4092    slug: &str,
4093    daemon_id: &DaemonId,
4094    route: &ProxyTlsRoute,
4095) -> ResolveResult {
4096    let poll_interval = std::time::Duration::from_millis(250);
4097
4098    loop {
4099        let daemons = {
4100            let sf = SUPERVISOR.state_file.lock().await;
4101            sf.daemons.clone()
4102        };
4103
4104        if let Some(d) = daemons.get(daemon_id) {
4105            if d.status.is_running() {
4106                // Selected through the same route as an already-running daemon,
4107                // so a hostname with `proxy_tls_port` lands on its configured
4108                // port on the request that started the daemon, not only on
4109                // later ones.
4110                if let Some(port) = select_daemon_port(route, d) {
4111                    // Recorded as the request's activity. Its start held the
4112                    // daemon's activity until it finished, so a stop for
4113                    // inactivity can only have been claimed since if the grace
4114                    // period is shorter than this poll. Then it is on its way
4115                    // down, and the request is answered as for a daemon still
4116                    // starting: the page reloads, and a passthrough connection
4117                    // resolves again, and either starts it once more.
4118                    return match ACTIVITY.begin(daemon_id) {
4119                        Some(activity) => {
4120                            log::info!("Auto-start: daemon {daemon_id} is ready on port {port}");
4121                            ResolveResult::Ready(port, Some(activity), route.protocol)
4122                        }
4123                        None => ResolveResult::Starting {
4124                            slug: slug.to_string(),
4125                        },
4126                    };
4127                }
4128            } else {
4129                log::warn!(
4130                    "Auto-start: daemon {daemon_id} is no longer running (status: {})",
4131                    d.status
4132                );
4133                return ResolveResult::Error(format!(
4134                    "Daemon '{daemon_id}' started but exited unexpectedly.\n\
4135                     Check its logs for errors."
4136                ));
4137            }
4138        } else {
4139            log::warn!("Auto-start: daemon {daemon_id} not found in state file after start");
4140            return ResolveResult::Error(format!(
4141                "Daemon '{daemon_id}' started but disappeared from the state file.\n\
4142                 Check its logs for errors."
4143            ));
4144        }
4145
4146        tokio::time::sleep(poll_interval).await;
4147    }
4148}
4149
4150/// Which daemons of a proxy auto-start may later be stopped for inactivity,
4151/// with their grace periods in milliseconds.
4152///
4153/// The daemon behind the hostname uses its own `proxy_idle_timeout`, or else
4154/// `proxy.idle_timeout` as its project resolves it. A dependency uses its own
4155/// `proxy_idle_timeout` when it sets one, and otherwise inherits the daemon's:
4156/// it was started only because that daemon needed it. Daemons with idle
4157/// shutdown off are left out, and are started as explicit.
4158///
4159/// Only daemons this start actually launches are affected; one that is
4160/// already running keeps whatever ownership it had.
4161async fn proxy_idle_timeouts(
4162    daemon_id: &DaemonId,
4163    closure: &[DaemonId],
4164    pt: &crate::pitchfork_toml::PitchforkToml,
4165) -> std::collections::HashMap<DaemonId, u64> {
4166    let own = |id: &DaemonId| pt.daemons.get(id).and_then(|d| d.proxy_idle_timeout);
4167    let target = match own(daemon_id) {
4168        Some(configured) => configured.duration(),
4169        None => {
4170            // Project settings are read from files, so off the request thread.
4171            let project_dir = crate::ipc::batch::resolve_config_base_dir(
4172                pt.daemons.get(daemon_id).and_then(|d| d.path.as_deref()),
4173            );
4174            tokio::task::spawn_blocking(move || {
4175                crate::settings::Settings::load_from_dir(&project_dir).proxy_idle_timeout()
4176            })
4177            .await
4178            .ok()
4179            .flatten()
4180        }
4181    };
4182    let millis = |d: std::time::Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
4183    closure
4184        .iter()
4185        .filter_map(|id| {
4186            let grace = if id == daemon_id {
4187                target
4188            } else {
4189                own(id).map_or(target, |configured| configured.duration())
4190            };
4191            grace.map(|g| (id.clone(), millis(g)))
4192        })
4193        .collect()
4194}
4195
4196/// Resolve a hostname against the automatic hostname registry.
4197///
4198/// Runs only after the legacy `[slugs]` registry found no match, so a slug
4199/// keeps precedence over an automatic hostname that spells the same thing.
4200async fn resolve_registry_target(subdomain: &str) -> ResolveResult {
4201    let registry = get_cached_host_registry().await;
4202    if !crate::proxy::hostname::hostname_fits(subdomain) {
4203        // Nothing advertises a name this long, so nothing answers to one.
4204        return ResolveResult::Unknown {
4205            heading: "Host name too long".to_string(),
4206            known: registry.project_labels(),
4207        };
4208    }
4209    match registry.resolve(subdomain, settings().proxy.wildcard) {
4210        crate::proxy::hostname::HostTarget::Daemon {
4211            ref dir,
4212            ref namespace,
4213            ref daemon,
4214            proxy_tls,
4215            proxy_protocol,
4216            proxy_tls_port,
4217            ..
4218        } => {
4219            // The mode and port were captured with the hostname, from one read
4220            // of the checkout's config, so a config that has since become
4221            // unreadable cannot turn a passthrough daemon into a terminated
4222            // one.
4223            let route = ProxyTlsRoute {
4224                mode: proxy_tls.unwrap_or_default(),
4225                protocol: proxy_protocol.unwrap_or_default(),
4226                port: proxy_tls_port,
4227            };
4228            // When several checkouts share this daemon's namespace — in this
4229            // project or in another one, since namespaces come from directory
4230            // names — the ID no longer says which checkout is running, so the
4231            // request has to be matched to the directory it named.
4232            let per_checkout = registry.shares_daemon_id(namespace, daemon);
4233            resolve_registry_daemon(subdomain, dir, namespace, daemon, per_checkout, &route).await
4234        }
4235        crate::proxy::hostname::HostTarget::ProjectPage { project } => {
4236            let entry = registry.projects.get(&project);
4237            ResolveResult::Page {
4238                daemons: entry.map(|p| p.primary.labels()).unwrap_or_default(),
4239                dir: entry.map(|p| p.primary.dir.clone()),
4240                project,
4241                worktree: None,
4242            }
4243        }
4244        crate::proxy::hostname::HostTarget::WorktreePage { project, worktree } => {
4245            let checkout = registry
4246                .projects
4247                .get(&project)
4248                .and_then(|p| p.worktrees.get(&worktree));
4249            ResolveResult::Page {
4250                daemons: checkout.map(|c| c.labels()).unwrap_or_default(),
4251                dir: checkout.map(|c| c.dir.clone()),
4252                project,
4253                worktree: Some(worktree),
4254            }
4255        }
4256        crate::proxy::hostname::HostTarget::UnknownProject { known } => ResolveResult::Unknown {
4257            heading: "Unknown project".to_string(),
4258            known,
4259        },
4260        crate::proxy::hostname::HostTarget::UnknownDaemon {
4261            project,
4262            worktree,
4263            known,
4264        } => ResolveResult::Unknown {
4265            heading: match worktree {
4266                Some(wt) => format!("Unknown daemon in '{wt}' of project '{project}'"),
4267                None => format!("Unknown daemon in project '{project}'"),
4268            },
4269            known,
4270        },
4271    }
4272}
4273
4274/// Find the running daemon behind an automatic hostname, auto-starting it when
4275/// it is not running.
4276///
4277/// Several checkouts of one project can share a namespace when the project
4278/// declares one explicitly, so a daemon running in the matching directory is
4279/// preferred over one that merely shares the name.
4280async fn resolve_registry_daemon(
4281    host: &str,
4282    dir: &std::path::Path,
4283    namespace: &str,
4284    daemon: &str,
4285    per_checkout: bool,
4286    route: &ProxyTlsRoute,
4287) -> ResolveResult {
4288    // One budget for waiting out an idle stop and the start after it.
4289    let deadline = auto_start_deadline();
4290    let daemons = {
4291        let state_file = SUPERVISOR.state_file.lock().await;
4292        state_file.daemons.clone()
4293    };
4294
4295    let mut matches: Vec<crate::daemon::Daemon> = daemons
4296        .iter()
4297        .filter(|(id, d)| {
4298            id.name() == daemon && id.namespace() == namespace && d.status.is_running()
4299        })
4300        .map(|(_, d)| d.clone())
4301        .collect();
4302    // Attributing a daemon to a checkout walks the filesystem, so it happens off
4303    // the request's worker thread.
4304    matches = sort_by_checkout(matches, dir).await;
4305
4306    if let Some(d) = matches.first() {
4307        // A running daemon from another checkout would serve that checkout's
4308        // content under this one's hostname, so say what is wrong instead.
4309        if per_checkout && !runs_in_checkout(d.clone(), dir).await {
4310            return ResolveResult::Error(format!(
4311                "'{host}' belongs to the checkout at {}, but daemon '{namespace}/{daemon}' is \
4312                 running from {}.\n\
4313                 These checkouts share the namespace '{namespace}', so pitchfork cannot run \
4314                 both copies at once.\n\
4315                 Give each checkout its own top-level `namespace`, or stop the other one first.",
4316                dir.display(),
4317                d.dir
4318                    .as_deref()
4319                    .map(|p| p.display().to_string())
4320                    .unwrap_or_else(|| "an unknown directory".to_string()),
4321            ));
4322        }
4323        let Some(port) = select_daemon_port(route, d) else {
4324            return ResolveResult::NotFound;
4325        };
4326        match begin_running(&d.id, deadline).await {
4327            Running::Yes(activity) => {
4328                return ResolveResult::Ready(port, Some(activity), route.protocol);
4329            }
4330            Running::Stopping => {
4331                return ResolveResult::Starting {
4332                    slug: host.to_string(),
4333                };
4334            }
4335            // Stopped since the state was read: start it again below.
4336            Running::No => {}
4337        }
4338    }
4339
4340    let cached = CachedSlugEntry {
4341        slug: host.to_string(),
4342        namespace: Some(namespace.to_string()),
4343        daemon_name: daemon.to_string(),
4344        dir: dir.to_path_buf(),
4345        worktrees: vec![],
4346        rejected_worktree_prefixes: std::collections::HashSet::new(),
4347        tls: *route,
4348        worktree_tls: std::collections::HashMap::new(),
4349        public_url: None,
4350    };
4351    let result = try_auto_start(host, &cached, None, Some(namespace), route, deadline).await;
4352
4353    // The start can land on a record another checkout already owns, because the
4354    // supervisor refuses to run a second daemon under the same ID. Serving that
4355    // port would hand this hostname the other checkout's content.
4356    if per_checkout && let ResolveResult::Ready(..) = result {
4357        let started = {
4358            let state_file = SUPERVISOR.state_file.lock().await;
4359            state_file
4360                .daemons
4361                .iter()
4362                .find(|(id, _)| id.name() == daemon && id.namespace() == namespace)
4363                .map(|(_, d)| d.clone())
4364        };
4365        if let Some(d) = started
4366            && !runs_in_checkout(d.clone(), dir).await
4367        {
4368            return ResolveResult::Error(format!(
4369                "'{host}' belongs to the checkout at {}, but daemon '{namespace}/{daemon}' is \
4370                 running from {}.\n\
4371                 These checkouts share the namespace '{namespace}', so pitchfork cannot run \
4372                 both copies at once.\n\
4373                 Give each checkout its own top-level `namespace`, or stop the other one first.",
4374                dir.display(),
4375                d.dir
4376                    .as_deref()
4377                    .map(|p| p.display().to_string())
4378                    .unwrap_or_else(|| "an unknown directory".to_string()),
4379            ));
4380        }
4381    }
4382
4383    result
4384}
4385
4386/// Whether the request came from this machine.
4387///
4388/// Names of other people's projects, daemon labels and absolute paths are
4389/// details of the developer's machine. They help whoever is sitting at it and
4390/// tell a device on the LAN things it has no business knowing, so pages spell
4391/// them out for loopback clients only.
4392fn is_local_client(req: &Request) -> bool {
4393    // A request whose peer is unknown is treated as remote: withholding detail
4394    // from a local client is a small loss, and the reverse is a leak.
4395    req.extensions()
4396        .get::<axum::extract::ConnectInfo<SocketAddr>>()
4397        .is_some_and(|ci| ci.0.ip().is_loopback())
4398}
4399
4400/// Whether a daemon is running from this checkout.
4401///
4402/// The daemon's directory is resolved to the checkout that contains it rather
4403/// than compared as a path prefix, so a worktree nested inside its primary
4404/// checkout is attributed to the worktree, and a symlinked or non-canonical
4405/// directory still matches. A daemon whose explicit `dir` lies outside every
4406/// checkout belongs to none of them, which keeps it reachable as long as its
4407/// hostname is unambiguous.
4408fn daemon_runs_in(daemon: &crate::daemon::Daemon, checkout: &std::path::Path) -> bool {
4409    daemon
4410        .dir
4411        .as_deref()
4412        .is_some_and(|d| crate::proxy::hostname::checkout_root_of(d) == checkout)
4413}
4414
4415/// [`daemon_runs_in`] off the async worker, since it walks the filesystem.
4416async fn runs_in_checkout(daemon: crate::daemon::Daemon, checkout: &std::path::Path) -> bool {
4417    let checkout = checkout.to_path_buf();
4418    tokio::task::spawn_blocking(move || daemon_runs_in(&daemon, &checkout))
4419        .await
4420        .unwrap_or(false)
4421}
4422
4423/// Order the candidates so that daemons running in this checkout come first.
4424///
4425/// Only the attribution runs off-thread, and the candidates stay here, so a
4426/// failure in that task costs the ordering rather than the candidates
4427/// themselves.
4428async fn sort_by_checkout(
4429    daemons: Vec<crate::daemon::Daemon>,
4430    checkout: &std::path::Path,
4431) -> Vec<crate::daemon::Daemon> {
4432    if daemons.len() < 2 {
4433        return daemons;
4434    }
4435    let dirs: Vec<Option<std::path::PathBuf>> = daemons.iter().map(|d| d.dir.clone()).collect();
4436    let checkout = checkout.to_path_buf();
4437    let here = tokio::task::spawn_blocking(move || {
4438        dirs.iter()
4439            .map(|dir| {
4440                dir.as_deref()
4441                    .is_some_and(|d| crate::proxy::hostname::checkout_root_of(d) == checkout)
4442            })
4443            .collect::<Vec<bool>>()
4444    })
4445    .await;
4446
4447    match here {
4448        Ok(here) => {
4449            let mut ordered: Vec<(bool, crate::daemon::Daemon)> =
4450                here.into_iter().zip(daemons).collect();
4451            ordered.sort_by_key(|(here, _)| !here);
4452            ordered.into_iter().map(|(_, d)| d).collect()
4453        }
4454        Err(e) => {
4455            log::warn!("Checkout attribution task failed: {e}");
4456            daemons
4457        }
4458    }
4459}
4460
4461/// Escape the five characters that change the meaning of HTML text.
4462fn escape_html(s: &str) -> String {
4463    s.replace('&', "&amp;")
4464        .replace('<', "&lt;")
4465        .replace('>', "&gt;")
4466        .replace('"', "&quot;")
4467        .replace('\'', "&#x27;")
4468}
4469
4470/// Wrap body markup in the shared pitchfork page chrome.
4471fn html_page(status: StatusCode, title: &str, body: String) -> Response {
4472    let html = format!(
4473        r##"<!DOCTYPE html>
4474<html lang="en">
4475<head>
4476    <meta charset="UTF-8">
4477    <meta name="viewport" content="width=device-width, initial-scale=1">
4478    <title>{title} — pitchfork</title>
4479    <style>
4480        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
4481        body {{
4482            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
4483            background: #0f1117;
4484            color: #e1e4e8;
4485            display: flex;
4486            align-items: center;
4487            justify-content: center;
4488            min-height: 100vh;
4489        }}
4490        .container {{ max-width: 640px; padding: 2rem; }}
4491        h1 {{ font-size: 1.5rem; font-weight: 600; margin-bottom: 0.75rem; }}
4492        p {{ color: #8b949e; font-size: 0.9rem; margin-bottom: 0.75rem; }}
4493        ul {{ list-style: none; margin: 0.5rem 0 1rem; }}
4494        li {{ margin: 0.25rem 0; }}
4495        code, a {{
4496            color: #58a6ff;
4497            font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
4498            text-decoration: none;
4499        }}
4500    </style>
4501</head>
4502<body>
4503    <div class="container">{body}</div>
4504</body>
4505</html>"##
4506    );
4507    Response::builder()
4508        .status(status)
4509        .header("content-type", "text/html; charset=utf-8")
4510        .body(Body::from(html))
4511        .unwrap_or_else(|_| (status, title.to_string()).into_response())
4512}
4513
4514/// The `:port` part of a Host header, or an empty string when it carries none.
4515///
4516/// Links on pitchfork's own pages keep the port the request arrived on, so they
4517/// still work when the proxy listens somewhere other than 80 or 443.
4518fn host_port_suffix(raw_host: &str) -> String {
4519    let port = if raw_host.starts_with('[') {
4520        raw_host.split_once("]:").map(|(_, port)| port)
4521    } else {
4522        raw_host.rsplit_once(':').map(|(_, port)| port)
4523    };
4524    port.filter(|p| p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty())
4525        .map(|p| format!(":{p}"))
4526        .unwrap_or_default()
4527}
4528
4529/// Redirect a reserved project or stack hostname to its page in the web UI.
4530///
4531/// The page lives at `/projects/<project>[/<worktree>]`, which is its canonical
4532/// location. Both labels come from hostname labels, so they are already limited
4533/// to characters that need no escaping in a path.
4534fn page_redirect_response(base: &str, path: &str) -> Response {
4535    let target = format!("{base}{path}");
4536    Response::builder()
4537        .status(StatusCode::FOUND)
4538        .header(axum::http::header::LOCATION, &target)
4539        .header(axum::http::header::CACHE_CONTROL, "no-store")
4540        .body(axum::body::Body::from(format!(
4541            "This page is at {target}\n"
4542        )))
4543        .unwrap_or_else(|_| {
4544            html_page(
4545                StatusCode::INTERNAL_SERVER_ERROR,
4546                "pitchfork",
4547                String::new(),
4548            )
4549        })
4550}
4551
4552/// Serve the placeholder for a reserved project or stack hostname.
4553///
4554/// `<project>.<tld>` and `<worktree>.<project>.<tld>` belong to the project and
4555/// stack pages, which the web UI serves. This stands in when the web UI is not
4556/// running, so the hostname never resolves to whichever daemon shares its
4557/// name.
4558fn page_placeholder_response(
4559    project: &str,
4560    worktree: Option<&str>,
4561    daemons: &[String],
4562    tld: &str,
4563    port_suffix: &str,
4564    web_url: Option<&str>,
4565) -> Response {
4566    let heading = match worktree {
4567        Some(wt) => format!("{} · {}", escape_html(project), escape_html(wt)),
4568        None => escape_html(project),
4569    };
4570    let suffix = match worktree {
4571        Some(wt) => format!(
4572            "{}.{}.{}",
4573            escape_html(wt),
4574            escape_html(project),
4575            escape_html(tld)
4576        ),
4577        None => format!("{}.{}", escape_html(project), escape_html(tld)),
4578    };
4579    let list = if daemons.is_empty() {
4580        "<p>No daemon in this checkout has a port configured.</p>".to_string()
4581    } else {
4582        let items: String = daemons
4583            .iter()
4584            .map(|d| {
4585                let d = escape_html(d);
4586                format!("<li><a href=\"//{d}.{suffix}{port_suffix}\">{d}.{suffix}</a></li>")
4587            })
4588            .collect();
4589        format!("<p>Daemons here:</p><ul>{items}</ul>")
4590    };
4591    let page = if worktree.is_some() {
4592        "stack"
4593    } else {
4594        "project"
4595    };
4596    // The web UI has a page for a checkout only when a registered namespace
4597    // covers its directory, while a hostname is reserved for any checkout the
4598    // proxy knows, including ones known only from a slug or the state file. The
4599    // two cases need different advice.
4600    let explanation = match web_url {
4601        Some(url) => format!(
4602            "<p>This address is reserved for the {page} page, which the web UI serves.              No registered project covers this checkout, so it has no page yet: add its              directory under <code>[namespaces]</code> in your user config, or run              <code>pitchfork proxy add</code> from it.              <a href=\"{url}/projects\">Open the project list</a>.</p>",
4603            url = escape_html(url),
4604        ),
4605        None => format!(
4606            "<p>This address is reserved for the {page} page, which the web UI serves.              Enable it with <code>[settings.web] auto_start = true</code> to open this              address.</p>"
4607        ),
4608    };
4609    let body = format!("<h1>{heading}</h1>{explanation}{list}");
4610    html_page(StatusCode::OK, "pitchfork", body)
4611}
4612
4613/// Serve the 404 page for a hostname whose project or daemon does not exist.
4614fn unknown_host_response(host: &str, heading: &str, known: &[String]) -> Response {
4615    let list = if known.is_empty() {
4616        "<p>Nothing is registered under this name yet.</p>".to_string()
4617    } else {
4618        let items: String = known
4619            .iter()
4620            .map(|k| format!("<li><code>{}</code></li>", escape_html(k)))
4621            .collect();
4622        format!("<p>Known names:</p><ul>{items}</ul>")
4623    };
4624    let body = format!(
4625        "<h1>{heading}</h1><p>No route for <code>{host}</code>.</p>{list}",
4626        heading = escape_html(heading),
4627        host = escape_html(host),
4628    );
4629    html_page(StatusCode::NOT_FOUND, "Not found", body)
4630}
4631
4632/// Strip the TLD suffix from a hostname, returning the subdomain part.
4633///
4634/// Host names are case-insensitive (RFC 4343) and a browser passes on whatever
4635/// the user typed, so `API.MyProject.LOCALHOST` has to lose its TLD like any
4636/// other spelling. A trailing root dot names the same host and is accepted too:
4637/// this is the one place every routing path passes a host name through, whether
4638/// it came from a `Host` header, an HTTP/2 `:authority`, a peeked ClientHello,
4639/// or rustls handing over the SNI name it parsed, and only some of those are
4640/// normalized by the time they arrive.
4641///
4642/// Examples:
4643/// - `api.myproject.localhost` with tld `localhost` → `api.myproject`
4644/// - `API.LocalHost.` with tld `localhost` → `API`
4645/// - `localhost` with tld `localhost` → `None` (no subdomain)
4646fn strip_tld(host: &str, tld: &str) -> Option<String> {
4647    strip_dot_suffix_ignore_case(host.trim_end_matches('.'), tld)
4648}
4649
4650/// Build a human-friendly error message for port binding failures.
4651fn bind_error_message(port: u16, err: &std::io::Error) -> String {
4652    if port < 1024 {
4653        format!(
4654            "Failed to bind proxy server to port {port}: {err}\n\
4655             Hint: ports below 1024 require elevated privileges. Run \
4656             `pitchfork proxy setup`, which grants the bind capability on Linux, \
4657             or set an unprivileged proxy.port and let setup redirect {port} to it."
4658        )
4659    } else {
4660        format!(
4661            "Failed to bind proxy server to port {port}: {err}\n\
4662             Hint: another process may already be using this port."
4663        )
4664    }
4665}
4666
4667/// Build an HTML "Starting…" response that auto-refreshes every 2 seconds.
4668///
4669/// Displayed when a proxy request triggers an auto-start for a stopped daemon.
4670/// Once the daemon is ready, the next refresh will proxy normally to the backend.
4671fn starting_html_response(slug: &str, raw_host: &str) -> Response {
4672    let escaped_slug = slug
4673        .replace('&', "&amp;")
4674        .replace('<', "&lt;")
4675        .replace('>', "&gt;")
4676        .replace('"', "&quot;")
4677        .replace('\'', "&#x27;");
4678    let escaped_host = raw_host
4679        .replace('&', "&amp;")
4680        .replace('<', "&lt;")
4681        .replace('>', "&gt;")
4682        .replace('"', "&quot;")
4683        .replace('\'', "&#x27;");
4684
4685    let html = format!(
4686        r##"<!DOCTYPE html>
4687<html lang="en">
4688<head>
4689    <meta charset="UTF-8">
4690    <meta name="viewport" content="width=device-width, initial-scale=1">
4691    <meta http-equiv="refresh" content="2">
4692    <title>Starting {escaped_slug}… — pitchfork</title>
4693    <style>
4694        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
4695        body {{
4696            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
4697            background: #0f1117;
4698            color: #e1e4e8;
4699            display: flex;
4700            align-items: center;
4701            justify-content: center;
4702            min-height: 100vh;
4703        }}
4704        .container {{
4705            text-align: center;
4706            max-width: 480px;
4707            padding: 2rem;
4708        }}
4709        .spinner {{
4710            width: 48px;
4711            height: 48px;
4712            border: 4px solid rgba(255, 255, 255, 0.1);
4713            border-top-color: #58a6ff;
4714            border-radius: 50%;
4715            animation: spin 0.8s linear infinite;
4716            margin: 0 auto 1.5rem;
4717        }}
4718        @keyframes spin {{
4719            to {{ transform: rotate(360deg); }}
4720        }}
4721        h1 {{
4722            font-size: 1.5rem;
4723            font-weight: 600;
4724            margin-bottom: 0.5rem;
4725        }}
4726        .slug {{
4727            color: #58a6ff;
4728            font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
4729        }}
4730        .host {{
4731            color: #8b949e;
4732            font-size: 0.875rem;
4733            margin-top: 0.25rem;
4734        }}
4735        .hint {{
4736            color: #8b949e;
4737            font-size: 0.8rem;
4738            margin-top: 1.5rem;
4739        }}
4740    </style>
4741</head>
4742<body>
4743    <div class="container">
4744        <div class="spinner"></div>
4745        <h1>Starting <span class="slug">{escaped_slug}</span>…</h1>
4746        <p class="host">{escaped_host}</p>
4747        <p class="hint">This page will refresh automatically when the daemon is ready.</p>
4748    </div>
4749</body>
4750</html>"##
4751    );
4752
4753    Response::builder()
4754        .status(StatusCode::SERVICE_UNAVAILABLE)
4755        .header("content-type", "text/html; charset=utf-8")
4756        .header("retry-after", "2")
4757        .body(Body::from(html))
4758        .unwrap_or_else(|_| (StatusCode::SERVICE_UNAVAILABLE, "Starting…").into_response())
4759}
4760
4761/// Handler that redirects plain-HTTP requests to HTTPS.
4762///
4763/// Used when the proxy is configured for HTTPS but receives a plain-HTTP
4764/// request on the same port (after the first-byte peek determines it is
4765/// not a TLS ClientHello).  Returns a 302 redirect to the HTTPS equivalent.
4766///
4767/// WebSocket upgrade attempts over plain HTTP are rejected with 400
4768/// because WS-over-plain-HTTP to a TLS port is inherently broken.
4769async fn redirect_to_https_handler(req: Request) -> Response {
4770    // Reject WebSocket upgrades over plain HTTP
4771    if req.headers().contains_key("upgrade") {
4772        log::warn!("Dropping plain-HTTP WebSocket upgrade attempt — use wss:// instead of ws://");
4773        return (
4774            StatusCode::BAD_REQUEST,
4775            "WebSocket over plain HTTP is not supported on the HTTPS port. Use wss:// instead.",
4776        )
4777            .into_response();
4778    }
4779
4780    let raw_host = get_request_host(&req);
4781    let Some(raw_host) = raw_host else {
4782        return (StatusCode::BAD_REQUEST, "Missing Host header").into_response();
4783    };
4784
4785    // Strip any incoming port from Host and use the configured HTTPS port.
4786    let hostname = if raw_host.starts_with('[') {
4787        // IPv6: "[::1]:port" or "[::1]"
4788        raw_host
4789            .split_once("]:")
4790            .map(|(host, _)| host)
4791            .unwrap_or(&raw_host)
4792            .trim_start_matches('[')
4793            .trim_end_matches(']')
4794    } else {
4795        // IPv4/hostname: "host:port" or "host"
4796        let mut parts = raw_host.rsplitn(2, ':');
4797        let last = parts.next().unwrap_or(&raw_host);
4798        parts.next().unwrap_or(last)
4799    };
4800
4801    let path = req
4802        .uri()
4803        .path_and_query()
4804        .map(|pq| pq.as_str())
4805        .unwrap_or("/");
4806
4807    let https_port = match u16::try_from(settings().proxy.port).ok().filter(|&p| p > 0) {
4808        Some(443) | None => String::new(),
4809        Some(port) => format!(":{port}"),
4810    };
4811
4812    let host_for_url = if raw_host.starts_with('[') {
4813        format!("[{hostname}]")
4814    } else {
4815        hostname.to_string()
4816    };
4817
4818    let location = format!("https://{host_for_url}{https_port}{path}");
4819    (
4820        StatusCode::FOUND,
4821        [
4822            (axum::http::header::LOCATION, location),
4823            // Identifies the redirect as pitchfork's, so a probe on the port
4824            // can tell this listener apart from an unrelated service.
4825            (
4826                axum::http::HeaderName::from_static(PITCHFORK_HEADER),
4827                "1".to_string(),
4828            ),
4829        ],
4830    )
4831        .into_response()
4832}
4833
4834/// Build a plain-text error response.
4835fn error_response(status: StatusCode, message: &str) -> Response {
4836    // Carries the identification header like any other proxy response: a
4837    // client — `pitchfork proxy doctor` included — should be able to tell that
4838    // pitchfork answered even when the answer is an error.
4839    (
4840        status,
4841        [(
4842            axum::http::HeaderName::from_static(PITCHFORK_HEADER),
4843            HeaderValue::from_static("1"),
4844        )],
4845        message.to_string(),
4846    )
4847        .into_response()
4848}
4849
4850#[cfg(test)]
4851mod tests {
4852    use super::*;
4853
4854    /// An idle stop can be called off rather than carried out. A request
4855    /// that waited it out then finds the daemon still running and forwards to
4856    /// it, instead of starting it all over again.
4857    #[tokio::test]
4858    async fn a_request_forwards_after_an_idle_stop_is_called_off() {
4859        let id = DaemonId::new("calledoff", "api");
4860        SUPERVISOR.state_file.lock().await.daemons.insert(
4861            id.clone(),
4862            crate::daemon::Daemon {
4863                id: id.clone(),
4864                status: crate::daemon_status::DaemonStatus::Running,
4865                ..Default::default()
4866            },
4867        );
4868        assert!(ACTIVITY.claim_idle_stop(&id, std::time::Duration::ZERO));
4869        let releaser = {
4870            let id = id.clone();
4871            tokio::spawn(async move {
4872                tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4873                ACTIVITY.release_idle_stop(&id);
4874            })
4875        };
4876        assert!(matches!(
4877            begin_running(&id, auto_start_deadline()).await,
4878            Running::Yes(_)
4879        ));
4880        releaser.await.unwrap();
4881        SUPERVISOR.state_file.lock().await.daemons.remove(&id);
4882    }
4883
4884    /// A request for a daemon mid idle-stop waits the stop out, so it can
4885    /// start the daemon again, instead of being answered "Starting…".
4886    #[tokio::test]
4887    async fn a_request_waits_out_an_idle_stop() {
4888        let id = DaemonId::new("waitproj", "api");
4889        assert!(ACTIVITY.claim_idle_stop(&id, std::time::Duration::ZERO));
4890        let releaser = {
4891            let id = id.clone();
4892            tokio::spawn(async move {
4893                tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4894                ACTIVITY.release_idle_stop(&id);
4895            })
4896        };
4897        assert!(matches!(
4898            begin_running(&id, auto_start_deadline()).await,
4899            Running::No
4900        ));
4901        releaser.await.unwrap();
4902        assert!(ACTIVITY.begin(&id).is_some());
4903    }
4904
4905    /// Axum answers a path match with no method match itself, so a route
4906    /// registered for `GET` alone takes that path away from `fallback` for
4907    /// every other method. `/proxy.pac` has to stay reachable on a proxied
4908    /// hostname under any method, so it is registered with `any` and the
4909    /// handler decides. This pins the router behaviour that choice rests on.
4910    #[tokio::test]
4911    async fn a_get_only_route_never_reaches_the_fallback() {
4912        async fn routed() -> &'static str {
4913            "routed"
4914        }
4915        async fn fell_through() -> &'static str {
4916            "fell-through"
4917        }
4918
4919        // A hand-written request over a plain socket: no HTTP client, so no
4920        // TLS provider to install for a test that never uses TLS.
4921        async fn post_to(app: Router) -> String {
4922            use tokio::io::{AsyncReadExt, AsyncWriteExt};
4923
4924            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4925            let addr = listener.local_addr().unwrap();
4926            let server = tokio::spawn(async move {
4927                let _ = axum::serve(listener, app).await;
4928            });
4929
4930            let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
4931            sock.write_all(
4932                b"POST /proxy.pac HTTP/1.1\r\nHost: example\r\nConnection: close\r\n\r\n",
4933            )
4934            .await
4935            .unwrap();
4936            let mut raw = Vec::new();
4937            sock.read_to_end(&mut raw).await.unwrap();
4938            server.abort();
4939
4940            let text = String::from_utf8_lossy(&raw).into_owned();
4941            let status = text.split_whitespace().nth(1).unwrap_or("").to_string();
4942            if status == "405" {
4943                return status;
4944            }
4945            text.rsplit("\r\n").next().unwrap_or("").to_string()
4946        }
4947
4948        let get_only = Router::new()
4949            .route("/proxy.pac", axum::routing::get(routed))
4950            .fallback(fell_through);
4951        assert_eq!(
4952            post_to(get_only).await,
4953            "405",
4954            "axum reached the fallback on a method mismatch, so `any` is unnecessary"
4955        );
4956
4957        let any_method = Router::new()
4958            .route("/proxy.pac", axum::routing::any(routed))
4959            .fallback(fell_through);
4960        assert_eq!(
4961            post_to(any_method).await,
4962            "routed",
4963            "`any` did not deliver the POST to the handler"
4964        );
4965    }
4966
4967    #[cfg(feature = "proxy-tls")]
4968    #[test]
4969    fn a_ca_pair_is_checked_not_just_found() {
4970        let dir = tempfile::tempdir().unwrap();
4971        let (cert, key) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem"));
4972        generate_ca(&cert, &key).unwrap();
4973        assert_eq!(ca_pair_problem(&cert, &key), None);
4974
4975        // A key from a different CA.
4976        let (other_cert, other_key) = (dir.path().join("b.pem"), dir.path().join("b-key.pem"));
4977        generate_ca(&other_cert, &other_key).unwrap();
4978        assert!(ca_pair_problem(&cert, &other_key).is_some());
4979
4980        // A truncated certificate.
4981        std::fs::write(&cert, "-----BEGIN CERTIFICATE-----\nAAAA\n").unwrap();
4982        assert!(ca_pair_problem(&cert, &key).is_some());
4983    }
4984
4985    #[cfg(feature = "proxy-tls")]
4986    #[test]
4987    fn a_new_ca_clears_leaves_signed_by_the_old_one() {
4988        // Cached leaves are checked only for expiry when loaded, so after a
4989        // regeneration they would be served for names the new CA never signed.
4990        let dir = tempfile::tempdir().unwrap();
4991        let (cert, key) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem"));
4992        let host_certs = host_certs_dir_for(&cert);
4993        std::fs::create_dir_all(&host_certs).unwrap();
4994        std::fs::write(host_certs.join("api.localhost.pem"), "old leaf").unwrap();
4995        std::fs::write(host_certs.join("notes.txt"), "keep me").unwrap();
4996
4997        // Kept while the pair is usable.
4998        assert!(!ensure_ca(&cert, &key, || true).unwrap());
4999        assert!(host_certs.join("api.localhost.pem").exists());
5000
5001        // Gone once a new pair is written; unrelated files stay.
5002        assert!(ensure_ca(&cert, &key, || false).unwrap());
5003        assert!(!host_certs.join("api.localhost.pem").exists());
5004        assert!(host_certs.join("notes.txt").exists());
5005    }
5006
5007    #[cfg(feature = "proxy-tls")]
5008    #[test]
5009    fn leaves_are_cached_per_ca_so_a_replaced_ca_is_never_served() {
5010        // A running supervisor can write a leaf after a new CA cleared the
5011        // cache. Loading only checks expiry, so the leaf has to live where the
5012        // new CA never looks.
5013        let dir = tempfile::tempdir().unwrap();
5014        let (cert, key) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem"));
5015        let _ = rustls::crypto::ring::default_provider().install_default();
5016        ensure_ca(&cert, &key, || false).unwrap();
5017        let first = SniCertResolver::new(&cert, &key, "localhost".into()).unwrap();
5018        assert!(first.get_or_create_checked("api.localhost").is_some());
5019        let old_dir = first.host_certs_dir.clone();
5020        assert!(std::fs::read_dir(&old_dir).unwrap().count() > 0);
5021
5022        ensure_ca(&cert, &key, || false).unwrap();
5023        // The old CA's resolver writes after the rotation.
5024        std::fs::create_dir_all(&old_dir).unwrap();
5025        std::fs::write(old_dir.join("late.localhost.pem"), "old leaf").unwrap();
5026
5027        let second = SniCertResolver::new(&cert, &key, "localhost".into()).unwrap();
5028        assert_ne!(second.host_certs_dir, old_dir);
5029        // Starting under the new CA clears the other CA's leaves outright.
5030        assert!(!old_dir.exists());
5031    }
5032
5033    #[cfg(feature = "proxy-tls")]
5034    #[test]
5035    fn cert_cache_file_names_do_not_collide() {
5036        // `.` used to become `_`, so these two shared a file.
5037        assert_ne!(
5038            cert_cache_file_stem("a_b.localhost"),
5039            cert_cache_file_stem("a.b.localhost")
5040        );
5041        assert_eq!(cert_cache_file_stem("api.localhost"), "api.localhost");
5042        assert_eq!(cert_cache_file_stem("a_b.localhost"), "a%5Fb.localhost");
5043        assert_eq!(
5044            cert_cache_file_stem("*.proj.localhost"),
5045            "%2A.proj.localhost"
5046        );
5047        // No path separators survive.
5048        assert!(!cert_cache_file_stem("../x").contains('/'));
5049    }
5050
5051    #[test]
5052    fn connect_port_reads_the_authority() {
5053        assert_eq!(connect_port("api.localhost:443"), Some(443));
5054        assert_eq!(connect_port("api.localhost:80"), Some(80));
5055        assert_eq!(connect_port("[::1]:443"), Some(443));
5056        assert_eq!(connect_port("api.localhost"), None);
5057        assert_eq!(connect_port("::1"), None);
5058    }
5059
5060    #[test]
5061    fn a_half_configured_certificate_pair_is_refused() {
5062        // Either half alone would be filled in from the generated CA: the
5063        // user's key signing with pitchfork's certificate, or a new CA key
5064        // written over the user's file.
5065        assert!(tls_pair_problem("", "/k.pem").is_some());
5066        assert!(tls_pair_problem("/c.pem", "").is_some());
5067        assert!(tls_pair_problem("", "").is_none());
5068        assert!(tls_pair_problem("/c.pem", "/k.pem").is_none());
5069    }
5070
5071    /// A resolver backed by a freshly generated CA in a temporary directory.
5072    #[cfg(feature = "proxy-tls")]
5073    fn test_resolver(tld: &str) -> (SniCertResolver, tempfile::TempDir) {
5074        let dir = tempfile::tempdir().unwrap();
5075        let cert = dir.path().join("ca.pem");
5076        let key = dir.path().join("ca-key.pem");
5077        generate_ca(&cert, &key).unwrap();
5078        let _ = rustls::crypto::ring::default_provider().install_default();
5079        (
5080            SniCertResolver::new(&cert, &key, tld.to_string()).unwrap(),
5081            dir,
5082        )
5083    }
5084
5085    /// SANs on a certificate the resolver minted for `domain`.
5086    #[cfg(feature = "proxy-tls")]
5087    fn sans_for(resolver: &SniCertResolver, domain: &str) -> Vec<String> {
5088        let ck = resolver.get_or_create(domain).expect("a certificate");
5089        let (_, cert) = x509_parser::parse_x509_certificate(&ck.cert[0]).unwrap();
5090        cert.subject_alternative_name()
5091            .unwrap()
5092            .map(|ext| {
5093                ext.value
5094                    .general_names
5095                    .iter()
5096                    .filter_map(|n| match n {
5097                        x509_parser::extensions::GeneralName::DNSName(d) => Some(d.to_string()),
5098                        _ => None,
5099                    })
5100                    .collect()
5101            })
5102            .unwrap_or_default()
5103    }
5104
5105    #[cfg(feature = "proxy-tls")]
5106    #[test]
5107    fn the_ca_refuses_to_sign_for_a_name_outside_the_tld() {
5108        use rustls::server::ResolvesServerCert;
5109
5110        let (resolver, _dir) = test_resolver("localhost");
5111        let cache = resolver.host_certs_dir.clone();
5112
5113        // The CA is installed in the machine's trust store and the proxy
5114        // answers on loopback, so minting for an arbitrary SNI would hand out a
5115        // browser-trusted certificate for somebody else's name.
5116        for foreign in [
5117            "login.microsoftonline.com",
5118            "example.com",
5119            "notlocalhost",
5120            "localhost.evil.com",
5121        ] {
5122            assert!(
5123                resolver.get_or_create_checked(foreign).is_none(),
5124                "expected {foreign:?} to be refused"
5125            );
5126        }
5127
5128        // And nothing was written to the on-disk cache for them.
5129        let cached: Vec<String> = std::fs::read_dir(&cache)
5130            .map(|rd| {
5131                rd.filter_map(|e| e.ok())
5132                    .map(|e| e.file_name().to_string_lossy().into_owned())
5133                    .collect()
5134            })
5135            .unwrap_or_default();
5136        assert!(
5137            cached.is_empty(),
5138            "unexpected cached certificates: {cached:?}"
5139        );
5140
5141        // Names under the TLD are still served, at any depth.
5142        for ours in ["localhost", "api.localhost", "core.wt.proj.localhost"] {
5143            assert!(
5144                resolver.get_or_create_checked(ours).is_some(),
5145                "expected {ours:?} to be issued"
5146            );
5147        }
5148        // `resolve` is the trait entry point and applies the same rule.
5149        let _ = &resolver as &dyn ResolvesServerCert;
5150    }
5151
5152    #[cfg(feature = "proxy-tls")]
5153    #[test]
5154    fn the_certificate_cache_is_bounded_and_evicts_the_oldest() {
5155        // The set of names under a TLD is unbounded, and each one costs a key
5156        // generation and a file, so the cache must not grow with it.
5157        let (resolver, _dir) = test_resolver("localhost");
5158        let host_certs = resolver.host_certs_dir.clone();
5159
5160        for i in 0..MAX_HOST_CERTS + 8 {
5161            assert!(
5162                resolver
5163                    .get_or_create_checked(&format!("h{i}.localhost"))
5164                    .is_some()
5165            );
5166        }
5167
5168        let cached = resolver.cache.lock().unwrap();
5169        assert_eq!(cached.by_domain.len(), MAX_HOST_CERTS);
5170        assert_eq!(cached.order.len(), MAX_HOST_CERTS);
5171        // Oldest first out, newest retained.
5172        assert!(cached.get("h0.localhost").is_none());
5173        assert!(
5174            cached
5175                .get(&format!("h{}.localhost", MAX_HOST_CERTS + 7))
5176                .is_some()
5177        );
5178        drop(cached);
5179
5180        // The files went with them, so the disk cache is bounded too.
5181        let on_disk = std::fs::read_dir(&host_certs).unwrap().count();
5182        assert!(
5183            on_disk <= MAX_HOST_CERTS,
5184            "{on_disk} files cached, expected at most {MAX_HOST_CERTS}"
5185        );
5186    }
5187
5188    #[cfg(feature = "proxy-tls")]
5189    #[test]
5190    fn the_disk_cache_is_pruned_at_startup() {
5191        // Eviction during a run only knows the names that run has seen, so
5192        // files left by earlier processes have to be cleared on the way in or
5193        // the directory grows across restarts.
5194        let dir = tempfile::tempdir().unwrap();
5195        let host_certs = dir.path().join("host-certs");
5196        std::fs::create_dir_all(&host_certs).unwrap();
5197        for i in 0..MAX_HOST_CERTS + 20 {
5198            std::fs::write(host_certs.join(format!("old{i}.pem")), "stale").unwrap();
5199        }
5200        // A file we do not own is left alone.
5201        std::fs::write(host_certs.join("notes.txt"), "keep me").unwrap();
5202
5203        prune_host_certs(&host_certs);
5204
5205        let pems = std::fs::read_dir(&host_certs)
5206            .unwrap()
5207            .filter_map(|e| e.ok())
5208            .filter(|e| e.path().extension().is_some_and(|x| x == "pem"))
5209            .count();
5210        assert_eq!(pems, MAX_HOST_CERTS);
5211        assert!(host_certs.join("notes.txt").exists());
5212
5213        // Under the limit, nothing is touched.
5214        let small = dir.path().join("small");
5215        std::fs::create_dir_all(&small).unwrap();
5216        std::fs::write(small.join("a.pem"), "x").unwrap();
5217        prune_host_certs(&small);
5218        assert!(small.join("a.pem").exists());
5219    }
5220
5221    #[cfg(feature = "proxy-tls")]
5222    #[test]
5223    fn a_minted_certificate_never_wildcards_the_whole_tld() {
5224        let (resolver, _dir) = test_resolver("localhost");
5225
5226        // One level down: the parent is the TLD itself, so no wildcard.
5227        let sans = sans_for(&resolver, "api.localhost");
5228        assert!(sans.contains(&"api.localhost".to_string()));
5229        assert!(
5230            !sans.iter().any(|s| s.starts_with('*')),
5231            "unexpected wildcard in {sans:?}"
5232        );
5233
5234        // Deeper: the sibling wildcard is inside the TLD, which is fine.
5235        let sans = sans_for(&resolver, "core.wt.proj.localhost");
5236        assert!(sans.contains(&"*.wt.proj.localhost".to_string()));
5237
5238        // A multi-label TLD is still a TLD; `*.dev.internal` would cover it all.
5239        let (resolver, _dir) = test_resolver("dev.internal");
5240        let sans = sans_for(&resolver, "api.dev.internal");
5241        assert!(
5242            !sans.iter().any(|s| s.starts_with('*')),
5243            "unexpected wildcard in {sans:?}"
5244        );
5245    }
5246
5247    /// The placeholder has to say why there is no page: the web UI being off is
5248    /// a different problem from a checkout no registered project covers, and
5249    /// the advice differs.
5250    #[tokio::test]
5251    async fn test_page_placeholder_explains_which_step_is_missing() {
5252        async fn body_of(response: Response) -> String {
5253            let (_, body) = response.into_parts();
5254            let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
5255            String::from_utf8(bytes.to_vec()).unwrap()
5256        }
5257
5258        let disabled = page_placeholder_response("shop", None, &[], "localhost", "", None);
5259        assert_eq!(disabled.status(), StatusCode::OK);
5260        let disabled = body_of(disabled).await;
5261        assert!(disabled.contains("auto_start"), "{disabled}");
5262        assert!(!disabled.contains("[namespaces]"));
5263
5264        let running = page_placeholder_response(
5265            "shop",
5266            Some("feature-a"),
5267            &[],
5268            "localhost",
5269            "",
5270            Some("http://127.0.0.1:3120"),
5271        );
5272        let running = body_of(running).await;
5273        assert!(running.contains("[namespaces]"), "{running}");
5274        assert!(running.contains("http://127.0.0.1:3120/projects"));
5275        assert!(!running.contains("auto_start"));
5276    }
5277
5278    /// A reserved project or stack hostname sends the browser to the page in
5279    /// the web UI, which is where those pages live.
5280    #[test]
5281    fn test_page_redirect_targets_the_web_ui() {
5282        let response = page_redirect_response("http://127.0.0.1:3120", "/projects/shop/feature-a");
5283        assert_eq!(response.status(), StatusCode::FOUND);
5284        assert_eq!(
5285            response
5286                .headers()
5287                .get(axum::http::header::LOCATION)
5288                .unwrap(),
5289            "http://127.0.0.1:3120/projects/shop/feature-a"
5290        );
5291
5292        let project = page_redirect_response("http://127.0.0.1:3120/ps", "/projects/shop");
5293        assert_eq!(
5294            project.headers().get(axum::http::header::LOCATION).unwrap(),
5295            // The base carries the web UI's path prefix when one is set.
5296            "http://127.0.0.1:3120/ps/projects/shop"
5297        );
5298    }
5299
5300    #[tokio::test]
5301    async fn overlapping_startup_graphs_wait_for_each_other() {
5302        use std::time::Duration;
5303        let id = |name: &str| DaemonId::try_new("startup-lock-test", name).unwrap();
5304
5305        let first = lock_startup_graph(vec![id("shared"), id("app-a")]).await;
5306
5307        // Listed in the opposite order to the first graph: sorted acquisition
5308        // is what keeps two overlapping graphs from deadlocking.
5309        let second = tokio::spawn(lock_startup_graph(vec![id("shared"), id("app-b")]));
5310        tokio::time::sleep(Duration::from_millis(50)).await;
5311        assert!(
5312            !second.is_finished(),
5313            "a graph sharing a daemon must wait for the graph starting it"
5314        );
5315
5316        // A graph with nothing in common does not wait.
5317        let disjoint = tokio::time::timeout(
5318            Duration::from_secs(1),
5319            lock_startup_graph(vec![id("other")]),
5320        )
5321        .await;
5322        assert!(disjoint.is_ok());
5323
5324        drop(first);
5325        let second = tokio::time::timeout(Duration::from_secs(1), second)
5326            .await
5327            .expect("the waiting graph proceeds once the first releases")
5328            .unwrap();
5329        assert_eq!(second.len(), 2);
5330        drop(second);
5331        drop(disjoint);
5332
5333        // Once nothing holds or awaits them, the locks are not retained.
5334        drop(lock_startup_graph(vec![id("unrelated")]).await);
5335        let map = STARTUP_LOCKS.lock().unwrap();
5336        assert!(
5337            !map.keys()
5338                .any(|k| k.namespace() == "startup-lock-test" && k.name() != "unrelated"),
5339            "released startup locks must be pruned"
5340        );
5341    }
5342
5343    #[test]
5344    fn test_strip_tld() {
5345        assert_eq!(
5346            strip_tld("api.myproject.localhost", "localhost"),
5347            Some("api.myproject".to_string())
5348        );
5349        // Host names are case-insensitive, and browsers pass on what was typed.
5350        assert_eq!(
5351            strip_tld("API.MyProject.LOCALHOST", "localhost"),
5352            Some("API.MyProject".to_string())
5353        );
5354        assert_eq!(
5355            strip_tld("api.localhost", "LOCALHOST"),
5356            Some("api".to_string())
5357        );
5358        assert_eq!(
5359            strip_tld("api.localhost", "localhost"),
5360            Some("api".to_string())
5361        );
5362        assert_eq!(strip_tld("localhost", "localhost"), None);
5363        // Host names are case-insensitive, and a trailing root dot names the
5364        // same host. rustls hands over the SNI name as the client wrote it, so
5365        // both spellings have to resolve or a passthrough hostname would be
5366        // read as terminating.
5367        assert_eq!(
5368            strip_tld("API.LocalHost", "localhost"),
5369            Some("API".to_string())
5370        );
5371        assert_eq!(
5372            strip_tld("api.localhost.", "localhost"),
5373            Some("api".to_string())
5374        );
5375        assert_eq!(
5376            strip_tld("API.MyProject.LOCALHOST.", "localhost"),
5377            Some("API.MyProject".to_string())
5378        );
5379        assert_eq!(strip_tld("localhost.", "localhost"), None);
5380        assert_eq!(
5381            strip_tld("api.myproject.test", "test"),
5382            Some("api.myproject".to_string())
5383        );
5384        assert_eq!(strip_tld("other.com", "localhost"), None);
5385    }
5386
5387    fn make_entry(name: &str) -> CachedSlugEntry {
5388        CachedSlugEntry {
5389            slug: name.to_string(),
5390            namespace: None,
5391            daemon_name: name.to_string(),
5392            dir: std::path::PathBuf::from(format!("/tmp/{name}")),
5393            worktrees: vec![],
5394            rejected_worktree_prefixes: std::collections::HashSet::new(),
5395            tls: ProxyTlsRoute::default(),
5396            worktree_tls: std::collections::HashMap::new(),
5397            public_url: None,
5398        }
5399    }
5400
5401    /// A stopped daemon record with the given configured and resolved ports.
5402    fn make_daemon(
5403        configured: &[u16],
5404        resolved: &[u16],
5405        active: Option<u16>,
5406    ) -> crate::daemon::Daemon {
5407        crate::daemon::Daemon {
5408            id: DaemonId::try_new("proj", "api").unwrap(),
5409            port: crate::config_types::PortConfig::from_parts(
5410                configured.to_vec(),
5411                crate::config_types::PortBump(0),
5412            ),
5413            resolved_port: resolved.to_vec(),
5414            active_port: active,
5415            ..crate::daemon::Daemon::default()
5416        }
5417    }
5418
5419    /// Without `proxy_tls_port`, the detected listening port wins, exactly as
5420    /// before this setting existed.
5421    #[test]
5422    fn test_select_daemon_port_prefers_active_port() {
5423        let route = ProxyTlsRoute::default();
5424        let d = make_daemon(&[8443, 9443], &[8443, 9443], Some(8443));
5425        assert_eq!(select_daemon_port(&route, &d), Some(8443));
5426    }
5427
5428    /// A port of 0 is not connectable — it is what a daemon carries when it
5429    /// asked the operating system to choose and nothing has been detected yet
5430    /// — so it is skipped rather than spliced to.
5431    #[test]
5432    fn test_select_daemon_port_skips_port_zero() {
5433        for mode in [ProxyTlsMode::Passthrough, ProxyTlsMode::Terminate] {
5434            let route = ProxyTlsRoute {
5435                mode,
5436                protocol: Default::default(),
5437                port: None,
5438            };
5439
5440            // A later real port is used in place of the placeholder.
5441            let mixed = make_daemon(&[0, 8443], &[0, 8443], None);
5442            assert_eq!(select_daemon_port(&route, &mixed), Some(8443));
5443
5444            // A placeholder in the detected port must not shadow a real one
5445            // further down: it is skipped, not treated as the answer.
5446            let detected_placeholder = make_daemon(&[0, 8443], &[0, 8443], Some(0));
5447            assert_eq!(
5448                select_daemon_port(&route, &detected_placeholder),
5449                Some(8443)
5450            );
5451
5452            // With nothing but placeholders there is no route.
5453            let unresolved = make_daemon(&[0], &[0], Some(0));
5454            assert_eq!(select_daemon_port(&route, &unresolved), None);
5455        }
5456    }
5457
5458    /// A passthrough hostname without `proxy_tls_port` takes the daemon's
5459    /// declared first port rather than whichever listener was detected first:
5460    /// on a multi-port daemon the detected one can be a secondary plain-HTTP
5461    /// listener that came up before the TLS one.
5462    #[test]
5463    fn test_select_daemon_port_passthrough_prefers_declared_first_port() {
5464        let route = ProxyTlsRoute {
5465            protocol: Default::default(),
5466            mode: ProxyTlsMode::Passthrough,
5467            port: None,
5468        };
5469        let d = make_daemon(&[8443, 9080], &[8443, 9080], Some(9080));
5470        assert_eq!(select_daemon_port(&route, &d), Some(8443));
5471
5472        // With nothing resolved, the detected port is still better than
5473        // refusing to route.
5474        let detected_only = make_daemon(&[], &[], Some(9080));
5475        assert_eq!(select_daemon_port(&route, &detected_only), Some(9080));
5476    }
5477
5478    /// With no detected port yet, the first resolved port is used.
5479    #[test]
5480    fn test_select_daemon_port_falls_back_to_first_resolved() {
5481        let route = ProxyTlsRoute::default();
5482        let d = make_daemon(&[8443, 9443], &[8443, 9443], None);
5483        assert_eq!(select_daemon_port(&route, &d), Some(8443));
5484
5485        // A daemon with no ports at all does not route.
5486        let none = make_daemon(&[], &[], None);
5487        assert_eq!(select_daemon_port(&route, &none), None);
5488    }
5489
5490    /// `proxy_tls_port` picks a later port of a multi-port daemon, overriding
5491    /// the detected first port.
5492    #[test]
5493    fn test_select_daemon_port_honors_configured_port() {
5494        let route = ProxyTlsRoute {
5495            protocol: Default::default(),
5496            mode: ProxyTlsMode::Passthrough,
5497            port: Some(9443),
5498        };
5499        let d = make_daemon(&[8443, 9443], &[8443, 9443], Some(8443));
5500        assert_eq!(select_daemon_port(&route, &d), Some(9443));
5501    }
5502
5503    /// Auto-bump shifts the ports a daemon actually binds. The hostname still
5504    /// maps to the same *position* in its port list, so it follows the bump
5505    /// instead of pointing at a port nothing is listening on.
5506    #[test]
5507    fn test_select_daemon_port_follows_auto_bump() {
5508        let route = ProxyTlsRoute {
5509            protocol: Default::default(),
5510            mode: ProxyTlsMode::Passthrough,
5511            port: Some(9443),
5512        };
5513        let d = make_daemon(&[8443, 9443], &[8444, 9444], Some(8444));
5514        assert_eq!(select_daemon_port(&route, &d), Some(9444));
5515    }
5516
5517    /// A configured `proxy_tls_port` whose resolved port is still the
5518    /// placeholder 0 does not route either: the position matches, but nothing
5519    /// is listening there yet.
5520    #[test]
5521    fn test_select_daemon_port_skips_a_configured_port_resolved_to_zero() {
5522        let route = ProxyTlsRoute {
5523            protocol: Default::default(),
5524            mode: ProxyTlsMode::Passthrough,
5525            port: Some(9443),
5526        };
5527        // Declared [8443, 9443], but the second slot has not been resolved to
5528        // a real port yet.
5529        let pending = make_daemon(&[8443, 9443], &[8443, 0], Some(8443));
5530        assert_eq!(select_daemon_port(&route, &pending), None);
5531
5532        // Once it resolves, the same hostname routes to it.
5533        let ready = make_daemon(&[8443, 9443], &[8443, 9444], Some(8443));
5534        assert_eq!(select_daemon_port(&route, &ready), Some(9444));
5535    }
5536
5537    /// A daemon whose recorded ports contradict `proxy_tls_port` — a state
5538    /// record left by an older config — is not routed to a port it never
5539    /// bound. Config validation stops this combination from being written in
5540    /// the first place.
5541    #[test]
5542    fn test_select_daemon_port_refuses_a_port_the_daemon_never_bound() {
5543        let route = ProxyTlsRoute {
5544            protocol: Default::default(),
5545            mode: ProxyTlsMode::Passthrough,
5546            port: Some(9443),
5547        };
5548        let stale = make_daemon(&[8443], &[8443], Some(8443));
5549        assert_eq!(select_daemon_port(&route, &stale), None);
5550
5551        // With nothing recorded to contradict it, the configured port is all
5552        // the information there is, so it is used.
5553        let bare = make_daemon(&[], &[], None);
5554        assert_eq!(select_daemon_port(&route, &bare), Some(9443));
5555    }
5556
5557    /// `proxy_tls_port` selects the forwarded port in terminate mode too, not
5558    /// only for passthrough hostnames.
5559    #[test]
5560    fn test_select_daemon_port_honors_configured_port_when_terminating() {
5561        let route = ProxyTlsRoute {
5562            protocol: Default::default(),
5563            mode: ProxyTlsMode::Terminate,
5564            port: Some(9080),
5565        };
5566        let d = make_daemon(&[8080, 9080], &[8080, 9080], Some(8080));
5567        assert_eq!(select_daemon_port(&route, &d), Some(9080));
5568
5569        // Following auto-bump by position, as in passthrough mode.
5570        let bumped = make_daemon(&[8080, 9080], &[8081, 9081], Some(8081));
5571        assert_eq!(select_daemon_port(&route, &bumped), Some(9081));
5572    }
5573
5574    /// `proxy_protocol` is read with the route, defaulting to HTTP/1.1.
5575    #[test]
5576    fn test_read_proxy_tls_route_reads_protocol() {
5577        let dir = tempfile::tempdir().unwrap();
5578        std::fs::write(
5579            dir.path().join("pitchfork.toml"),
5580            "[daemons.grpc]\nrun = \"serve\"\nport = 50051\nproxy_protocol = \"h2c\"\n\n\
5581             [daemons.web]\nrun = \"serve\"\nport = 3000\n",
5582        )
5583        .unwrap();
5584        let ns = crate::pitchfork_toml::PitchforkToml::namespace_for_dir(dir.path()).unwrap();
5585        let grpc = read_proxy_tls_route(dir.path(), Some(&ns), "grpc")
5586            .unwrap()
5587            .unwrap();
5588        assert_eq!(grpc.protocol, ProxyProtocol::H2c);
5589        let web = read_proxy_tls_route(dir.path(), Some(&ns), "web")
5590            .unwrap()
5591            .unwrap();
5592        assert_eq!(web.protocol, ProxyProtocol::Http1);
5593    }
5594
5595    /// The h2c client reaches a daemon that only speaks HTTP/2, given a request
5596    /// the forwarder has tagged HTTP/2, over HTTP/2.
5597    #[tokio::test]
5598    async fn test_h2c_client_reaches_http2_only_daemon() {
5599        use http_body_util::BodyExt;
5600        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
5601        let port = listener.local_addr().unwrap().port();
5602        tokio::spawn(async move {
5603            let (stream, _) = listener.accept().await.unwrap();
5604            let svc = hyper::service::service_fn(
5605                |req: axum::http::Request<hyper::body::Incoming>| async move {
5606                    assert_eq!(req.version(), axum::http::Version::HTTP_2);
5607                    let body = http_body_util::Full::new(axum::body::Bytes::from_static(b"ok"));
5608                    Ok::<_, std::convert::Infallible>(axum::http::Response::new(body))
5609                },
5610            );
5611            let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new())
5612                .serve_connection(hyper_util::rt::TokioIo::new(stream), svc)
5613                .await;
5614        });
5615        let client: Client<HttpConnector, Body> = Client::builder(TokioExecutor::new())
5616            .http2_only(true)
5617            .build(HttpConnector::new());
5618        let mut req = axum::http::Request::new(Body::empty());
5619        *req.uri_mut() = format!("http://127.0.0.1:{port}/svc/Method")
5620            .parse()
5621            .unwrap();
5622        *req.version_mut() = axum::http::Version::HTTP_2;
5623        let resp = client.request(req).await.unwrap();
5624        assert_eq!(resp.version(), axum::http::Version::HTTP_2);
5625        let collected = resp.into_body().collect().await.unwrap();
5626        assert_eq!(collected.to_bytes(), "ok");
5627    }
5628
5629    /// A directory that says nothing about the daemon reads as no route at
5630    /// all, so a worktree the proxy cannot read inherits its slug's mode
5631    /// instead of being recorded as terminating and quietly ending a splice.
5632    #[test]
5633    fn test_read_proxy_tls_route_absent_without_config() {
5634        let dir = tempfile::tempdir().unwrap();
5635
5636        // A directory with no config at all.
5637        assert_eq!(
5638            read_proxy_tls_route(dir.path(), Some("proj"), "api").unwrap(),
5639            None
5640        );
5641
5642        // A config that describes some other daemon.
5643        std::fs::write(
5644            dir.path().join("pitchfork.toml"),
5645            "[daemons.other]\nrun = \"serve\"\n",
5646        )
5647        .unwrap();
5648        assert_eq!(
5649            read_proxy_tls_route(dir.path(), Some("proj"), "api").unwrap(),
5650            None,
5651            "a config without this daemon says nothing about it"
5652        );
5653
5654        // No namespace to resolve the daemon against.
5655        assert_eq!(read_proxy_tls_route(dir.path(), None, "api").unwrap(), None);
5656    }
5657
5658    /// A config that cannot be read — here because an unrelated daemon is
5659    /// invalid — is an error, not a route of `terminate`, and a refresh keeps
5660    /// the route it already knew instead of downgrading a passthrough daemon.
5661    #[test]
5662    fn test_unreadable_config_keeps_the_last_known_route() {
5663        let dir = tempfile::tempdir().unwrap();
5664        std::fs::write(
5665            dir.path().join("pitchfork.toml"),
5666            "[daemons.api]\nrun = \"serve\"\nport = 8443\nproxy_tls = \"passthrough\"\n\n\
5667             [daemons.broken]\nrun = \"serve\"\nproxy_tls = \"passthrough\"\n",
5668        )
5669        .unwrap();
5670        let read = read_proxy_tls_route(dir.path(), Some("proj"), "api");
5671        assert!(
5672            read.is_err(),
5673            "an invalid sibling makes the config unreadable"
5674        );
5675
5676        let known = ProxyTlsRoute {
5677            protocol: Default::default(),
5678            mode: ProxyTlsMode::Passthrough,
5679            port: Some(8443),
5680        };
5681        assert_eq!(
5682            route_or_last_known(read, Some(known), dir.path(), "api"),
5683            Some(known)
5684        );
5685
5686        // A readable answer replaces what was known, even when it is silence.
5687        assert_eq!(
5688            route_or_last_known(Ok(None), Some(known), dir.path(), "api"),
5689            None
5690        );
5691    }
5692
5693    /// A route is only carried over while the slug still points at the same
5694    /// daemon, directory and namespace; a repointed slug starts from nothing.
5695    #[test]
5696    fn test_known_route_requires_the_same_target() {
5697        let known = ProxyTlsRoute {
5698            protocol: Default::default(),
5699            mode: ProxyTlsMode::Passthrough,
5700            port: Some(8443),
5701        };
5702        let mut entry = make_entry("api");
5703        entry.namespace = Some("proj".to_string());
5704        entry.tls = known;
5705        let dir = entry.dir.clone();
5706
5707        assert_eq!(entry.known_route(&dir, Some("proj"), "api"), Some(known));
5708        assert_eq!(entry.known_route(&dir, Some("proj"), "web"), None);
5709        assert_eq!(entry.known_route(&dir, Some("other"), "api"), None);
5710        assert_eq!(
5711            entry.known_route(std::path::Path::new("/elsewhere"), Some("proj"), "api"),
5712            None
5713        );
5714
5715        let wt = make_worktree("feature/x", "feature-x");
5716        entry.worktrees = vec![wt.clone()];
5717        entry.worktree_tls.insert("feature-x".to_string(), known);
5718        assert_eq!(entry.known_worktree_route(&wt, "api"), Some(known));
5719        assert_eq!(entry.known_worktree_route(&wt, "web"), None);
5720        let moved = crate::proxy::worktree::WorktreeEntry {
5721            path: std::path::PathBuf::from("/elsewhere/feature-x"),
5722            ..wt
5723        };
5724        assert_eq!(entry.known_worktree_route(&moved, "api"), None);
5725    }
5726
5727    /// A worktree whose own config describes the daemon is authoritative,
5728    /// including when it leaves `proxy_tls` out, and one the proxy knows
5729    /// nothing about inherits the slug's route.
5730    #[test]
5731    fn test_worktree_route_inherits_when_unknown() {
5732        let mut entry = make_entry("spliced");
5733        entry.tls = ProxyTlsRoute {
5734            protocol: Default::default(),
5735            mode: ProxyTlsMode::Passthrough,
5736            port: Some(8443),
5737        };
5738        entry.worktrees = vec![
5739            make_worktree("feature/known", "feature-known"),
5740            make_worktree("feature/unknown", "feature-unknown"),
5741        ];
5742        // Only the worktree whose config was readable gets an entry.
5743        entry.worktree_tls.insert(
5744            "feature-known".to_string(),
5745            ProxyTlsRoute {
5746                protocol: Default::default(),
5747                mode: ProxyTlsMode::Terminate,
5748                port: None,
5749            },
5750        );
5751        let mut entries = std::collections::HashMap::new();
5752        entries.insert("spliced".to_string(), entry);
5753
5754        let mode =
5755            |host: &str| resolve_tls_mode_in(host, "localhost", &entries, &Default::default());
5756        assert_eq!(
5757            mode("feature-known.spliced.localhost"),
5758            ProxyTlsMode::Terminate,
5759            "an explicit worktree setting wins"
5760        );
5761        assert_eq!(
5762            mode("feature-unknown.spliced.localhost"),
5763            ProxyTlsMode::Passthrough,
5764            "a worktree with nothing recorded inherits the slug"
5765        );
5766
5767        // The port is not inherited with the mode: it names a position in one
5768        // daemon's port list, and a worktree hostname reaches a different
5769        // process with its own ports.
5770        let cached = entries.get("spliced").unwrap();
5771        assert_eq!(
5772            worktree_route(cached, "feature-unknown"),
5773            ProxyTlsRoute {
5774                protocol: Default::default(),
5775                mode: ProxyTlsMode::Passthrough,
5776                port: None,
5777            }
5778        );
5779        // An explicit worktree route is taken whole, port included.
5780        assert_eq!(
5781            worktree_route(cached, "feature-known"),
5782            ProxyTlsRoute {
5783                protocol: Default::default(),
5784                mode: ProxyTlsMode::Terminate,
5785                port: None,
5786            }
5787        );
5788    }
5789
5790    /// The route of a wildcard worktree host comes from that worktree's own
5791    /// config, and falls back to the slug's when the worktree has none.
5792    #[test]
5793    fn test_worktree_route_lookup() {
5794        let mut entry = make_entry("myapp");
5795        entry.tls = ProxyTlsRoute {
5796            protocol: Default::default(),
5797            mode: ProxyTlsMode::Terminate,
5798            port: None,
5799        };
5800        entry.worktrees = vec![
5801            make_worktree("feature/b", "feature-b"),
5802            make_worktree("feature/c", "feature-c"),
5803        ];
5804        entry.worktree_tls.insert(
5805            "feature-b".to_string(),
5806            ProxyTlsRoute {
5807                protocol: Default::default(),
5808                mode: ProxyTlsMode::Passthrough,
5809                port: Some(9443),
5810            },
5811        );
5812
5813        let lookup = |prefix: &str| match match_worktree_prefix(&entry, prefix) {
5814            PrefixMatch::Worktree(wt) => entry
5815                .worktree_tls
5816                .get(&wt.sanitized_branch.to_ascii_lowercase())
5817                .copied()
5818                .unwrap_or(entry.tls),
5819            _ => entry.tls,
5820        };
5821
5822        assert_eq!(lookup("feature-b").mode, ProxyTlsMode::Passthrough);
5823        assert_eq!(lookup("feature-b").port, Some(9443));
5824        // A worktree without its own setting inherits the slug's mode.
5825        assert_eq!(lookup("feature-c").mode, ProxyTlsMode::Terminate);
5826        // So does an ordinary wildcard subdomain.
5827        assert_eq!(lookup("tenant").mode, ProxyTlsMode::Terminate);
5828    }
5829
5830    #[test]
5831    fn test_wildcard_slug_lookup_exact_match() {
5832        let mut entries = std::collections::HashMap::new();
5833        entries.insert("myapp".to_string(), make_entry("myapp"));
5834        // Exact match takes priority.
5835        let result = wildcard_slug_lookup("myapp", &entries, true);
5836        assert!(result.is_some());
5837        assert_eq!(result.unwrap().daemon_name, "myapp");
5838    }
5839
5840    #[test]
5841    fn test_wildcard_slug_lookup_subdomain_fallback() {
5842        let mut entries = std::collections::HashMap::new();
5843        entries.insert("myapp".to_string(), make_entry("myapp"));
5844        // "tenant.myapp" falls back to "myapp".
5845        let result = wildcard_slug_lookup("tenant.myapp", &entries, true);
5846        assert!(result.is_some());
5847        assert_eq!(result.unwrap().daemon_name, "myapp");
5848    }
5849
5850    #[test]
5851    fn test_wildcard_slug_lookup_nested_fallback() {
5852        let mut entries = std::collections::HashMap::new();
5853        entries.insert("myapp".to_string(), make_entry("myapp"));
5854        // "a.b.myapp" falls back to "myapp" through "b.myapp" → "myapp".
5855        let result = wildcard_slug_lookup("a.b.myapp", &entries, true);
5856        assert!(result.is_some());
5857        assert_eq!(result.unwrap().daemon_name, "myapp");
5858    }
5859
5860    #[test]
5861    fn test_wildcard_slug_lookup_no_match() {
5862        let entries = std::collections::HashMap::new();
5863        // Empty entries → no match.
5864        let result = wildcard_slug_lookup("tenant.myapp", &entries, true);
5865        assert!(result.is_none());
5866    }
5867
5868    #[test]
5869    fn test_wildcard_slug_lookup_disabled() {
5870        let mut entries = std::collections::HashMap::new();
5871        entries.insert("myapp".to_string(), make_entry("myapp"));
5872        // With wildcard disabled, "tenant.myapp" does NOT match "myapp".
5873        let result = wildcard_slug_lookup("tenant.myapp", &entries, false);
5874        assert!(result.is_none());
5875        // But exact match still works.
5876        let result = wildcard_slug_lookup("myapp", &entries, false);
5877        assert!(result.is_some());
5878    }
5879
5880    #[test]
5881    fn test_wildcard_slug_lookup_exact_beats_wildcard() {
5882        let mut entries = std::collections::HashMap::new();
5883        entries.insert("myapp".to_string(), make_entry("myapp"));
5884        let mut tenant_entry = make_entry("tenant-daemon");
5885        tenant_entry.slug = "tenant.myapp".to_string();
5886        entries.insert("tenant.myapp".to_string(), tenant_entry);
5887        // "tenant.myapp" should match the exact slug, not fall back to "myapp".
5888        let result = wildcard_slug_lookup("tenant.myapp", &entries, true);
5889        assert!(result.is_some());
5890        assert_eq!(result.unwrap().daemon_name, "tenant-daemon");
5891    }
5892
5893    #[test]
5894    fn test_wildcard_slug_lookup_ignores_case() {
5895        let mut entries = std::collections::HashMap::new();
5896        entries.insert("myapp".to_string(), make_entry("myapp"));
5897        // Browsers lowercase the Host header, so every spelling must resolve.
5898        for host in ["MyApp", "MYAPP", "myapp"] {
5899            let result = wildcard_slug_lookup(host, &entries, true);
5900            assert!(result.is_some(), "exact lookup failed for {host}");
5901            assert_eq!(result.unwrap().daemon_name, "myapp");
5902        }
5903        // ...including through the wildcard fallback.
5904        for host in ["Tenant.MyApp", "tenant.MYAPP", "A.B.MyApp"] {
5905            let result = wildcard_slug_lookup(host, &entries, true);
5906            assert!(result.is_some(), "wildcard lookup failed for {host}");
5907            assert_eq!(result.unwrap().daemon_name, "myapp");
5908        }
5909    }
5910
5911    #[test]
5912    fn test_wildcard_slug_lookup_case_insensitive_registration() {
5913        let mut entries = std::collections::HashMap::new();
5914        let mut entry = make_entry("upper");
5915        entry.slug = "MyApp".to_string();
5916        // build_slug_entries lowercases the key while keeping the configured
5917        // spelling in `slug`, so a capitalized registration stays reachable.
5918        entries.insert("myapp".to_string(), entry);
5919        for host in ["myapp", "MyApp", "tenant.MYAPP"] {
5920            let result = wildcard_slug_lookup(host, &entries, true);
5921            assert!(result.is_some(), "lookup failed for {host}");
5922            assert_eq!(result.unwrap().daemon_name, "upper");
5923        }
5924    }
5925
5926    fn make_worktree(branch: &str, sanitized: &str) -> crate::proxy::worktree::WorktreeEntry {
5927        crate::proxy::worktree::WorktreeEntry {
5928            path: std::path::PathBuf::from(format!("/tmp/{sanitized}")),
5929            branch: branch.to_string(),
5930            sanitized_branch: sanitized.to_string(),
5931            namespace: Some(sanitized.to_string()),
5932        }
5933    }
5934
5935    #[test]
5936    fn test_reject_case_colliding_worktrees_drops_both_sides() {
5937        let wts = vec![
5938            make_worktree("Feature-A", "Feature-A"),
5939            make_worktree("feature-a", "feature-a"),
5940            make_worktree("main", "main"),
5941        ];
5942        let (kept, rejected) = reject_case_colliding_worktrees(wts);
5943        // Neither spelling routes; picking one would send the request to a
5944        // worktree the user did not name.
5945        assert_eq!(kept.len(), 1);
5946        assert_eq!(kept[0].sanitized_branch, "main");
5947        // The prefix is remembered so it is refused rather than treated as an
5948        // unknown wildcard prefix.
5949        assert!(rejected.contains("feature-a"));
5950    }
5951
5952    #[test]
5953    fn test_reject_case_colliding_worktrees_keeps_unambiguous() {
5954        let wts = vec![
5955            make_worktree("main", "main"),
5956            make_worktree("feature/a", "feature-a"),
5957        ];
5958        let (kept, rejected) = reject_case_colliding_worktrees(wts);
5959        assert_eq!(kept.len(), 2);
5960        assert!(rejected.is_empty());
5961    }
5962
5963    #[test]
5964    fn test_reject_case_colliding_worktrees_drops_sanitize_duplicates() {
5965        // Distinct branches can sanitize to the same string without any case
5966        // difference; that is ambiguous for the same reason.
5967        let wts = vec![
5968            make_worktree("feature/a", "feature-a"),
5969            make_worktree("feature.a", "feature-a"),
5970        ];
5971        let (kept, rejected) = reject_case_colliding_worktrees(wts);
5972        assert!(kept.is_empty());
5973        assert!(rejected.contains("feature-a"));
5974    }
5975
5976    #[test]
5977    fn test_match_worktree_prefix() {
5978        let mut entry = make_entry("myapp");
5979        entry.worktrees = vec![make_worktree("feature/b", "feature-b")];
5980        entry
5981            .rejected_worktree_prefixes
5982            .insert("feature-a".to_string());
5983
5984        assert!(matches!(
5985            match_worktree_prefix(&entry, "feature-b"),
5986            PrefixMatch::Worktree(_)
5987        ));
5988        // Host case does not matter for either outcome.
5989        assert!(matches!(
5990            match_worktree_prefix(&entry, "Feature-B"),
5991            PrefixMatch::Worktree(_)
5992        ));
5993        // A rejected prefix is refused, not served by the main checkout.
5994        assert!(matches!(
5995            match_worktree_prefix(&entry, "feature-a"),
5996            PrefixMatch::Ambiguous
5997        ));
5998        assert!(matches!(
5999            match_worktree_prefix(&entry, "FEATURE-A"),
6000            PrefixMatch::Ambiguous
6001        ));
6002        // An unrelated prefix is still an ordinary wildcard subdomain.
6003        assert!(matches!(
6004            match_worktree_prefix(&entry, "tenant"),
6005            PrefixMatch::Unknown
6006        ));
6007    }
6008
6009    /// Each way of reaching the HTTP path with a passthrough hostname names its
6010    /// own remedy, since the fixes are different.
6011    #[test]
6012    fn test_passthrough_unroutable_message() {
6013        let no_tls = passthrough_unroutable_message("api.localhost", false);
6014        assert!(no_tls.contains("api.localhost"), "{no_tls}");
6015        assert!(no_tls.contains("settings.proxy.https = true"), "{no_tls}");
6016
6017        // Over TLS this branch is reached when the handshake named a
6018        // different host than the request did — a connection with no host
6019        // name at all fails in the certificate resolver and never gets here.
6020        let mismatch = passthrough_unroutable_message("api.localhost", true);
6021        assert!(mismatch.contains("named a different host"), "{mismatch}");
6022        assert!(
6023            !mismatch.contains("settings.proxy.https"),
6024            "a host mismatch is not an HTTPS configuration problem: {mismatch}"
6025        );
6026    }
6027
6028    /// Routing and the certificate resolver read one table, so they cannot
6029    /// disagree about a hostname's mode: the synchronous read returns the very
6030    /// same allocation the async one does.
6031    #[tokio::test]
6032    async fn test_slug_snapshot_is_the_cached_table() {
6033        let from_async = get_cached_slugs().await;
6034        let from_sync = slug_snapshot();
6035        assert!(
6036            Arc::ptr_eq(&from_async, &from_sync),
6037            "the synchronous read must see the same table routing does"
6038        );
6039    }
6040
6041    /// Callers arriving together on an expired cache share one table rather
6042    /// than each building and holding its own. A caller holding its own build
6043    /// would route a hostname by a table the certificate resolver does not
6044    /// read.
6045    #[tokio::test]
6046    async fn test_concurrent_refresh_returns_the_published_table() {
6047        // The cache starts expired, so both calls take the refresh path; the
6048        // second waits for the first rather than building a second table.
6049        let (first, second) = tokio::join!(get_cached_slugs(), get_cached_slugs());
6050        assert!(
6051            Arc::ptr_eq(&first, &second),
6052            "overlapping refreshes must agree on one table"
6053        );
6054        assert!(
6055            Arc::ptr_eq(&first, &slug_snapshot()),
6056            "and it must be the published one"
6057        );
6058    }
6059
6060    /// The synchronous mode lookup the certificate resolver uses agrees with
6061    /// the async one: exact hosts, wildcard subdomains, worktree prefixes with
6062    /// their own setting, and anything that is not a slug at all.
6063    #[test]
6064    fn test_resolve_tls_mode_in() {
6065        let mut entries = std::collections::HashMap::new();
6066
6067        let mut spliced = make_entry("spliced");
6068        spliced.tls = ProxyTlsRoute {
6069            protocol: Default::default(),
6070            mode: ProxyTlsMode::Passthrough,
6071            port: Some(8443),
6072        };
6073        spliced.worktrees = vec![
6074            make_worktree("feature/b", "feature-b"),
6075            make_worktree("feature/c", "feature-c"),
6076        ];
6077        spliced.worktree_tls.insert(
6078            "feature-b".to_string(),
6079            ProxyTlsRoute {
6080                protocol: Default::default(),
6081                mode: ProxyTlsMode::Terminate,
6082                port: None,
6083            },
6084        );
6085        entries.insert("spliced".to_string(), spliced);
6086        entries.insert("plain".to_string(), make_entry("plain"));
6087
6088        let mode =
6089            |host: &str| resolve_tls_mode_in(host, "localhost", &entries, &Default::default());
6090
6091        assert_eq!(mode("spliced.localhost"), ProxyTlsMode::Passthrough);
6092        // Host names are case-insensitive, including the TLD, and a trailing
6093        // root dot names the same host — rustls passes the SNI name through
6094        // exactly as the client wrote it.
6095        assert_eq!(mode("SPLICED.localhost"), ProxyTlsMode::Passthrough);
6096        assert_eq!(mode("Spliced.LocalHost"), ProxyTlsMode::Passthrough);
6097        assert_eq!(mode("spliced.localhost."), ProxyTlsMode::Passthrough);
6098        assert_eq!(
6099            mode("FEATURE-C.Spliced.LOCALHOST."),
6100            ProxyTlsMode::Passthrough
6101        );
6102        // A wildcard subdomain inherits the slug's mode.
6103        assert_eq!(mode("tenant.spliced.localhost"), ProxyTlsMode::Passthrough);
6104        // A worktree with its own setting overrides the slug's …
6105        assert_eq!(mode("feature-b.spliced.localhost"), ProxyTlsMode::Terminate);
6106        // … and one without it inherits.
6107        assert_eq!(
6108            mode("feature-c.spliced.localhost"),
6109            ProxyTlsMode::Passthrough
6110        );
6111        // Everything else terminates: another slug, an unknown host, the
6112        // bare TLD, and a host outside the TLD.
6113        assert_eq!(mode("plain.localhost"), ProxyTlsMode::Terminate);
6114        assert_eq!(mode("unknown.localhost"), ProxyTlsMode::Terminate);
6115        assert_eq!(mode("localhost"), ProxyTlsMode::Terminate);
6116        assert_eq!(mode("spliced.example.com"), ProxyTlsMode::Terminate);
6117    }
6118
6119    /// A daemon reached through its automatic `<daemon>.<project>` hostname
6120    /// gets the mode from its own config, the same as one reached through a
6121    /// legacy slug. Automatic hostnames are the common case, so passthrough
6122    /// has to work without a slug registration.
6123    #[test]
6124    fn test_resolve_tls_mode_in_uses_the_hostname_registry() {
6125        let dir = tempfile::tempdir().unwrap();
6126        let project = dir.path().join("autoproj");
6127        std::fs::create_dir_all(&project).unwrap();
6128        std::fs::write(
6129            project.join("pitchfork.toml"),
6130            "[daemons.secure]\nrun = \"serve\"\nport = 8443\nproxy_tls = \"passthrough\"\n\
6131             [daemons.plain]\nrun = \"serve\"\nport = 8080\n",
6132        )
6133        .unwrap();
6134
6135        let registry =
6136            crate::proxy::hostname::HostRegistry::from_dirs(std::slice::from_ref(&project));
6137        let slugs = std::collections::HashMap::new();
6138        let mode = |host: &str| resolve_tls_mode_in(host, "localhost", &slugs, &registry);
6139
6140        assert_eq!(mode("secure.autoproj.localhost"), ProxyTlsMode::Passthrough);
6141        assert_eq!(mode("plain.autoproj.localhost"), ProxyTlsMode::Terminate);
6142
6143        // The mode travels with the registry entry, so a config that becomes
6144        // unreadable after the registry was built cannot turn the passthrough
6145        // daemon into a terminated one.
6146        std::fs::write(project.join("pitchfork.toml"), "this is not toml = [\n").unwrap();
6147        assert_eq!(mode("secure.autoproj.localhost"), ProxyTlsMode::Passthrough);
6148        // The project page is served by the proxy itself, over its own
6149        // certificate, as is a name nothing claims.
6150        assert_eq!(mode("autoproj.localhost"), ProxyTlsMode::Terminate);
6151        assert_eq!(mode("nothing.autoproj.localhost"), ProxyTlsMode::Terminate);
6152        assert_eq!(mode("unknown.localhost"), ProxyTlsMode::Terminate);
6153    }
6154
6155    /// An empty table — the snapshot before any refresh — terminates rather
6156    /// than refusing certificates for hosts it knows nothing about.
6157    #[test]
6158    fn test_resolve_tls_mode_in_empty_table() {
6159        let entries = std::collections::HashMap::new();
6160        assert_eq!(
6161            resolve_tls_mode_in(
6162                "spliced.localhost",
6163                "localhost",
6164                &entries,
6165                &Default::default()
6166            ),
6167            ProxyTlsMode::Terminate
6168        );
6169    }
6170
6171    #[test]
6172    fn test_strip_dot_suffix_ignore_case() {
6173        assert_eq!(
6174            strip_dot_suffix_ignore_case("feature-a.myapp", "myapp"),
6175            Some("feature-a".to_string())
6176        );
6177        assert_eq!(
6178            strip_dot_suffix_ignore_case("Feature-A.MyApp", "myapp"),
6179            Some("Feature-A".to_string())
6180        );
6181        assert_eq!(
6182            strip_dot_suffix_ignore_case("feature-a.myapp", "MYAPP"),
6183            Some("feature-a".to_string())
6184        );
6185        // No dot separator, no prefix left, and a non-matching suffix all fail.
6186        assert_eq!(strip_dot_suffix_ignore_case("xmyapp", "myapp"), None);
6187        assert_eq!(strip_dot_suffix_ignore_case(".myapp", "myapp"), None);
6188        assert_eq!(strip_dot_suffix_ignore_case("myapp", "myapp"), None);
6189        assert_eq!(
6190            strip_dot_suffix_ignore_case("feature-a.other", "myapp"),
6191            None
6192        );
6193        // Multi-byte input must not panic on a mid-character split.
6194        assert_eq!(
6195            strip_dot_suffix_ignore_case("café.myapp", "myapp"),
6196            Some("café".to_string())
6197        );
6198        assert_eq!(strip_dot_suffix_ignore_case("café", "afé"), None);
6199    }
6200
6201    /// Build a minimal ClientHello naming `host`, as it goes on the wire.
6202    #[cfg(feature = "proxy-tls")]
6203    fn client_hello_wire(host: &str) -> Vec<u8> {
6204        let mut entry = vec![0u8];
6205        entry.extend_from_slice(&(host.len() as u16).to_be_bytes());
6206        entry.extend_from_slice(host.as_bytes());
6207        let mut sni = (entry.len() as u16).to_be_bytes().to_vec();
6208        sni.extend_from_slice(&entry);
6209
6210        let mut ext = vec![0x00, 0x00];
6211        ext.extend_from_slice(&(sni.len() as u16).to_be_bytes());
6212        ext.extend_from_slice(&sni);
6213
6214        let mut body = vec![0x03, 0x03];
6215        body.extend_from_slice(&[0x22; 32]);
6216        body.push(0);
6217        body.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]);
6218        body.extend_from_slice(&[0x01, 0x00]);
6219        body.extend_from_slice(&(ext.len() as u16).to_be_bytes());
6220        body.extend_from_slice(&ext);
6221
6222        let mut msg = vec![0x01];
6223        let len = body.len() as u32;
6224        msg.extend_from_slice(&[(len >> 16) as u8, (len >> 8) as u8, len as u8]);
6225        msg.extend_from_slice(&body);
6226
6227        let mut record = vec![0x16, 0x03, 0x01];
6228        record.extend_from_slice(&(msg.len() as u16).to_be_bytes());
6229        record.extend_from_slice(&msg);
6230        record
6231    }
6232
6233    /// Accept one connection, hand the peeked verdict back, and report what a
6234    /// reader sees afterwards.
6235    #[cfg(feature = "proxy-tls")]
6236    async fn probe_over_socket(
6237        writes: Vec<Vec<u8>>,
6238        gap: std::time::Duration,
6239        timeout: std::time::Duration,
6240    ) -> (SniProbe, Vec<u8>) {
6241        probe_over_socket_then(writes, gap, timeout, false).await
6242    }
6243
6244    /// [`probe_over_socket`], optionally shutting down the client's write side
6245    /// once everything is sent.
6246    #[cfg(feature = "proxy-tls")]
6247    async fn probe_over_socket_then(
6248        writes: Vec<Vec<u8>>,
6249        gap: std::time::Duration,
6250        timeout: std::time::Duration,
6251        close_after: bool,
6252    ) -> (SniProbe, Vec<u8>) {
6253        use tokio::io::{AsyncReadExt, AsyncWriteExt};
6254
6255        let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
6256            .await
6257            .unwrap();
6258        let addr = listener.local_addr().unwrap();
6259        let total: usize = writes.iter().map(Vec::len).sum();
6260
6261        let client = tokio::spawn(async move {
6262            let mut sock = TcpStream::connect(addr).await.unwrap();
6263            for chunk in writes {
6264                sock.write_all(&chunk).await.unwrap();
6265                sock.flush().await.unwrap();
6266                tokio::time::sleep(gap).await;
6267            }
6268            if close_after {
6269                sock.shutdown().await.unwrap();
6270            }
6271            // Hold the connection open so the server can read back what it
6272            // only peeked at.
6273            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
6274        });
6275
6276        let (stream, _) = listener.accept().await.unwrap();
6277        let probe = peek_sni_host(&stream, timeout).await;
6278
6279        // Whatever was peeked must still be readable, byte for byte.
6280        let mut replayed = vec![0u8; total];
6281        let mut stream = stream;
6282        let read = tokio::time::timeout(
6283            std::time::Duration::from_secs(2),
6284            stream.read_exact(&mut replayed),
6285        )
6286        .await;
6287        let replayed = match read {
6288            Ok(Ok(_)) => replayed,
6289            _ => vec![],
6290        };
6291        client.abort();
6292        (probe, replayed)
6293    }
6294
6295    /// The peek loop reassembles a hello that arrives in many small writes,
6296    /// and leaves every byte in the socket for the path that handles the
6297    /// connection.
6298    #[cfg(feature = "proxy-tls")]
6299    #[tokio::test]
6300    async fn test_peek_sni_host_reads_a_hello_split_across_writes() {
6301        let wire = client_hello_wire("api.localhost");
6302        let writes: Vec<Vec<u8>> = wire.chunks(3).map(<[u8]>::to_vec).collect();
6303        let (probe, replayed) = probe_over_socket(
6304            writes,
6305            std::time::Duration::from_millis(5),
6306            std::time::Duration::from_secs(5),
6307        )
6308        .await;
6309
6310        assert_eq!(probe, SniProbe::Host("api.localhost".to_string()));
6311        assert_eq!(replayed, wire, "peeked bytes must still be readable");
6312    }
6313
6314    /// A hello that stops half way is reported as undetermined once the
6315    /// timeout expires, never as "no hostname": the caller must not terminate
6316    /// a connection that might belong to a passthrough daemon.
6317    #[cfg(feature = "proxy-tls")]
6318    #[tokio::test]
6319    async fn test_peek_sni_host_undetermined_when_a_hello_stalls() {
6320        let wire = client_hello_wire("api.localhost");
6321        let truncated = wire[..wire.len() / 2].to_vec();
6322        let (probe, _) = probe_over_socket(
6323            vec![truncated],
6324            std::time::Duration::ZERO,
6325            std::time::Duration::from_millis(150),
6326        )
6327        .await;
6328
6329        assert_eq!(probe, SniProbe::Undetermined);
6330    }
6331
6332    /// A client that sends part of a hello and then closes is given up on as
6333    /// soon as the close arrives, not after the whole timeout: `peek` keeps
6334    /// returning the buffered bytes, so only the socket's readiness shows it.
6335    #[cfg(feature = "proxy-tls")]
6336    #[tokio::test]
6337    async fn test_peek_sni_host_notices_a_client_that_closes_mid_hello() {
6338        let wire = client_hello_wire("api.localhost");
6339        let truncated = wire[..wire.len() / 2].to_vec();
6340        let started = std::time::Instant::now();
6341        let (probe, _) = probe_over_socket_then(
6342            vec![truncated],
6343            std::time::Duration::ZERO,
6344            std::time::Duration::from_secs(5),
6345            true,
6346        )
6347        .await;
6348
6349        assert_eq!(probe, SniProbe::Undetermined);
6350        assert!(
6351            started.elapsed() < std::time::Duration::from_secs(1),
6352            "the probe must end when the client closes, not at its deadline"
6353        );
6354    }
6355
6356    /// A peer that opens a connection and then sends nothing is given up on
6357    /// at the deadline. Without the read itself being bounded this waits for
6358    /// as long as the peer keeps the socket open.
6359    #[cfg(feature = "proxy-tls")]
6360    #[tokio::test]
6361    async fn test_peek_sni_host_gives_up_on_a_silent_peer() {
6362        let started = std::time::Instant::now();
6363        let (probe, _) = probe_over_socket(
6364            vec![],
6365            std::time::Duration::ZERO,
6366            std::time::Duration::from_millis(150),
6367        )
6368        .await;
6369
6370        assert_eq!(probe, SniProbe::Undetermined);
6371        assert!(
6372            started.elapsed() < std::time::Duration::from_secs(1),
6373            "the probe must end at its deadline, not wait on the peer"
6374        );
6375    }
6376
6377    /// Something that is not a TLS handshake is a definite "no hostname", so
6378    /// the connection is still served rather than dropped.
6379    #[cfg(feature = "proxy-tls")]
6380    #[tokio::test]
6381    async fn test_peek_sni_host_reports_no_host_for_non_tls() {
6382        let (probe, _) = probe_over_socket(
6383            vec![b"GET / HTTP/1.1\r\n\r\n".to_vec()],
6384            std::time::Duration::ZERO,
6385            std::time::Duration::from_secs(5),
6386        )
6387        .await;
6388
6389        assert_eq!(probe, SniProbe::NoHost);
6390    }
6391
6392    #[cfg(feature = "proxy-tls")]
6393    #[test]
6394    fn test_generate_ca() {
6395        let dir = tempfile::tempdir().unwrap();
6396        let cert_path = dir.path().join("ca.pem");
6397        let key_path = dir.path().join("ca-key.pem");
6398
6399        generate_ca(&cert_path, &key_path).unwrap();
6400
6401        assert!(cert_path.exists(), "ca.pem should be created");
6402        assert!(key_path.exists(), "ca-key.pem should be created");
6403
6404        let cert_pem = std::fs::read_to_string(&cert_path).unwrap();
6405        let key_pem = std::fs::read_to_string(&key_path).unwrap();
6406
6407        assert!(cert_pem.contains("BEGIN CERTIFICATE"), "should be PEM cert");
6408        assert!(
6409            key_pem.contains("BEGIN") && key_pem.contains("PRIVATE KEY"),
6410            "should be PEM key"
6411        );
6412    }
6413
6414    /// The raw `cookie` field values, in the order the map holds them.
6415    fn cookie_fields(headers: &HeaderMap) -> Vec<&[u8]> {
6416        headers
6417            .get_all(COOKIE)
6418            .iter()
6419            .map(HeaderValue::as_bytes)
6420            .collect()
6421    }
6422
6423    /// Several fields become one, joined with `"; "`, and a comma inside a
6424    /// value is left alone.
6425    #[test]
6426    fn test_join_cookie_fields_joins_with_semicolon_space() {
6427        let mut headers = HeaderMap::new();
6428        headers.append(COOKIE, HeaderValue::from_static("_session=abc123"));
6429        headers.append(COOKIE, HeaderValue::from_static("consent=ads,stats"));
6430        headers.append(COOKIE, HeaderValue::from_static("theme=dark"));
6431
6432        join_cookie_fields(&mut headers);
6433
6434        assert_eq!(
6435            cookie_fields(&headers),
6436            vec![&b"_session=abc123; consent=ads,stats; theme=dark"[..]]
6437        );
6438    }
6439
6440    /// A UTF-8 cookie value is joined like any other, since the join works on
6441    /// bytes rather than on visible ASCII.
6442    #[test]
6443    fn test_join_cookie_fields_joins_bytes_outside_ascii() {
6444        let mut headers = HeaderMap::new();
6445        headers.append(COOKIE, HeaderValue::from_static("_session=abc123"));
6446        headers.append(
6447            COOKIE,
6448            HeaderValue::from_bytes(b"name=Jos\xc3\xa9").unwrap(),
6449        );
6450
6451        join_cookie_fields(&mut headers);
6452
6453        assert_eq!(
6454            cookie_fields(&headers),
6455            vec![&b"_session=abc123; name=Jos\xc3\xa9"[..]]
6456        );
6457    }
6458
6459    /// A request without cookies gains none.
6460    #[test]
6461    fn test_join_cookie_fields_without_cookies() {
6462        let mut headers = HeaderMap::new();
6463        headers.insert(HOST, HeaderValue::from_static("app.localhost"));
6464
6465        join_cookie_fields(&mut headers);
6466
6467        assert!(headers.get(COOKIE).is_none());
6468    }
6469
6470    #[test]
6471    fn test_host_port_suffix() {
6472        assert_eq!(host_port_suffix("api.myproj.localhost:8088"), ":8088");
6473        assert_eq!(host_port_suffix("api.myproj.localhost"), "");
6474        assert_eq!(host_port_suffix("[::1]:8088"), ":8088");
6475        assert_eq!(host_port_suffix("[::1]"), "");
6476        // A non-numeric tail is not a port and must not reach a link.
6477        assert_eq!(host_port_suffix("host:notaport"), "");
6478    }
6479
6480    /// A daemon belongs to the checkout that contains its working directory,
6481    /// which is the worktree rather than the primary when one is nested inside
6482    /// the other, and no checkout at all when its `dir` points elsewhere.
6483    #[test]
6484    fn test_daemon_runs_in() {
6485        let temp = tempfile::tempdir().unwrap();
6486        let repo = temp.path().join("my-repo");
6487        std::fs::create_dir_all(repo.join(".git/worktrees/feature")).unwrap();
6488        std::fs::create_dir_all(repo.join("sub")).unwrap();
6489        // A worktree checked out *inside* the primary's directory tree.
6490        let nested = repo.join(".worktrees/feature");
6491        std::fs::create_dir_all(&nested).unwrap();
6492        std::fs::write(
6493            nested.join(".git"),
6494            format!(
6495                "gitdir: {}\n",
6496                repo.join(".git/worktrees/feature").display()
6497            ),
6498        )
6499        .unwrap();
6500
6501        let root = |p: &std::path::Path| crate::proxy::hostname::checkout_root_of(p);
6502        let repo_root = root(&repo);
6503        let nested_root = root(&nested);
6504
6505        let mut daemon = crate::daemon::Daemon {
6506            dir: Some(repo.join("sub")),
6507            ..Default::default()
6508        };
6509        assert!(daemon_runs_in(&daemon, &repo_root));
6510        assert!(!daemon_runs_in(&daemon, &nested_root));
6511
6512        // Lexically the nested worktree sits under the primary; by checkout it
6513        // does not, so the primary's hostname must not claim it.
6514        daemon.dir = Some(nested.clone());
6515        assert!(daemon_runs_in(&daemon, &nested_root));
6516        assert!(!daemon_runs_in(&daemon, &repo_root));
6517
6518        // An explicit dir outside every checkout belongs to none of them.
6519        daemon.dir = Some(temp.path().join("elsewhere"));
6520        assert!(!daemon_runs_in(&daemon, &repo_root));
6521
6522        daemon.dir = None;
6523        assert!(!daemon_runs_in(&daemon, &repo_root));
6524    }
6525
6526    fn forwarded(req: &Request, name: &str) -> String {
6527        req.headers()
6528            .get(name)
6529            .and_then(|v| v.to_str().ok())
6530            .unwrap_or_default()
6531            .to_string()
6532    }
6533
6534    /// Without a public URL the proxy reports the connection it received and
6535    /// discards whatever the client claimed.
6536    #[test]
6537    fn test_inject_forwarded_headers_overwrites_client_values() {
6538        let mut req = Request::new(Body::empty());
6539        req.headers_mut()
6540            .insert("x-forwarded-host", HeaderValue::from_static("evil.example"));
6541        req.headers_mut()
6542            .insert("x-forwarded-proto", HeaderValue::from_static("https"));
6543        inject_forwarded_headers(&mut req, false, "api.localhost:7777", None);
6544
6545        assert_eq!(forwarded(&req, "x-forwarded-host"), "api.localhost:7777");
6546        assert_eq!(forwarded(&req, "x-forwarded-proto"), "http");
6547        assert_eq!(forwarded(&req, "x-forwarded-port"), "7777");
6548    }
6549
6550    /// A public URL replaces the forwarded host, scheme and port, and still
6551    /// discards what the client claimed.
6552    #[test]
6553    fn test_inject_forwarded_headers_uses_the_public_url() {
6554        let public = crate::proxy::public_url::PublicUrl::parse("https://dev.example.com").unwrap();
6555        let mut req = Request::new(Body::empty());
6556        req.headers_mut()
6557            .insert("x-forwarded-host", HeaderValue::from_static("evil.example"));
6558        inject_forwarded_headers(&mut req, false, "api.localhost:7777", Some(&public));
6559
6560        assert_eq!(forwarded(&req, "x-forwarded-host"), "dev.example.com");
6561        assert_eq!(forwarded(&req, "x-forwarded-proto"), "https");
6562        assert_eq!(forwarded(&req, "x-forwarded-port"), "443");
6563    }
6564
6565    /// The public URL belongs to the slug's own hostname, not to the worktree
6566    /// subdomains under it or to other slugs.
6567    #[test]
6568    fn test_slug_public_url_applies_to_the_slug_only() {
6569        let mut entry = make_entry("api");
6570        entry.public_url =
6571            Some(crate::proxy::public_url::PublicUrl::parse("https://dev.example.com").unwrap());
6572        let docs = make_entry("docs");
6573
6574        let public = entry_public_url("API.localhost", "localhost", &entry).unwrap();
6575        assert_eq!(public.authority, "dev.example.com");
6576        assert!(entry_public_url("feature.api.localhost", "localhost", &entry).is_none());
6577        assert!(entry_public_url("docs.localhost", "localhost", &docs).is_none());
6578        assert!(entry_public_url("api.test", "localhost", &entry).is_none());
6579    }
6580
6581    /// Only a request known to come from this machine gets the detailed pages;
6582    /// an unknown peer counts as remote.
6583    #[test]
6584    fn test_is_local_client() {
6585        let build = |info: Option<SocketAddr>| {
6586            let mut req = Request::new(Body::empty());
6587            if let Some(addr) = info {
6588                req.extensions_mut()
6589                    .insert(axum::extract::ConnectInfo(addr));
6590            }
6591            req
6592        };
6593
6594        assert!(is_local_client(&build(Some(
6595            "127.0.0.1:5000".parse().unwrap()
6596        ))));
6597        assert!(is_local_client(&build(Some("[::1]:5000".parse().unwrap()))));
6598        assert!(!is_local_client(&build(Some(
6599            "192.168.1.42:5000".parse().unwrap()
6600        ))));
6601        assert!(!is_local_client(&build(None)));
6602    }
6603}