1use 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
20const PITCHFORK_HEADER: &str = "x-pitchfork";
22
23const PROXY_HOPS_HEADER: &str = "x-pitchfork-hops";
26
27const MAX_PROXY_HOPS: u64 = 5;
29
30const HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
37
38const MAX_HOST_CERTS: usize = 256;
46
47const REFUSAL_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
49
50static REFUSED_HANDSHAKE: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
52
53#[cfg(feature = "proxy-tls")]
55static REFUSED_SNI: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
56
57pub(crate) const SHUTDOWN_DRAIN_BUDGET: std::time::Duration = std::time::Duration::from_secs(10);
62
63const MAX_TUNNELS: usize = 256;
70
71static REFUSED_TUNNEL: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
73
74static ABANDONED_HANDSHAKE: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
82
83static ABANDONED_TUNNEL: crate::proxy::LogThrottle = crate::proxy::LogThrottle::new();
85
86const MAX_PENDING_HANDSHAKES: usize = 512;
93
94const 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
115const SLUG_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);
128
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub struct ProxyTlsRoute {
136 pub mode: ProxyTlsMode,
138 pub protocol: ProxyProtocol,
140 pub port: Option<u16>,
143}
144
145#[derive(Clone, Debug)]
147pub struct CachedSlugEntry {
148 pub slug: String,
150 pub namespace: Option<String>,
152 pub daemon_name: String,
154 pub dir: std::path::PathBuf,
156 pub worktrees: Vec<crate::proxy::worktree::WorktreeEntry>,
158 pub rejected_worktree_prefixes: std::collections::HashSet<String>,
162 pub tls: ProxyTlsRoute,
164 pub worktree_tls: std::collections::HashMap<String, ProxyTlsRoute>,
168}
169
170impl CachedSlugEntry {
171 fn known_route(
176 &self,
177 dir: &std::path::Path,
178 namespace: Option<&str>,
179 daemon_name: &str,
180 ) -> Option<ProxyTlsRoute> {
181 (self.dir == dir
182 && self.namespace.as_deref() == namespace
183 && self.daemon_name == daemon_name)
184 .then_some(self.tls)
185 }
186
187 fn known_worktree_route(
190 &self,
191 wt: &crate::proxy::worktree::WorktreeEntry,
192 daemon_name: &str,
193 ) -> Option<ProxyTlsRoute> {
194 if self.daemon_name != daemon_name {
195 return None;
196 }
197 let branch = wt.sanitized_branch.to_ascii_lowercase();
198 self.worktrees
199 .iter()
200 .any(|known| {
201 known.sanitized_branch.eq_ignore_ascii_case(&branch)
202 && known.path == wt.path
203 && known.namespace == wt.namespace
204 })
205 .then(|| self.worktree_tls.get(&branch).copied())
206 .flatten()
207 }
208}
209
210struct SlugCache {
212 entries: Arc<std::collections::HashMap<String, CachedSlugEntry>>,
213 expires_at: std::time::Instant,
214}
215
216static SLUG_CACHE: once_cell::sync::Lazy<std::sync::RwLock<SlugCache>> =
226 once_cell::sync::Lazy::new(|| {
227 std::sync::RwLock::new(SlugCache {
228 entries: Arc::new(std::collections::HashMap::new()),
229 expires_at: std::time::Instant::now(), })
231 });
232
233fn slug_snapshot() -> Arc<std::collections::HashMap<String, CachedSlugEntry>> {
239 let guard = SLUG_CACHE
240 .read()
241 .unwrap_or_else(std::sync::PoisonError::into_inner);
242 Arc::clone(&guard.entries)
243}
244
245static SLUG_REFRESH: once_cell::sync::Lazy<tokio::sync::Mutex<()>> =
254 once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(()));
255
256fn fresh_slugs() -> Option<Arc<std::collections::HashMap<String, CachedSlugEntry>>> {
258 let cache = SLUG_CACHE
259 .read()
260 .unwrap_or_else(std::sync::PoisonError::into_inner);
261 (std::time::Instant::now() < cache.expires_at).then(|| Arc::clone(&cache.entries))
262}
263
264fn reject_case_colliding_worktrees(
271 wts: Vec<crate::proxy::worktree::WorktreeEntry>,
272) -> (
273 Vec<crate::proxy::worktree::WorktreeEntry>,
274 std::collections::HashSet<String>,
275) {
276 let collisions =
277 crate::proxy::ascii_case_collisions(wts.iter().map(|w| w.sanitized_branch.as_str()));
278 if collisions.is_empty() {
279 return (wts, collisions);
280 }
281
282 let (dropped, kept): (Vec<_>, Vec<_>) = wts
283 .into_iter()
284 .partition(|w| collisions.contains(&w.sanitized_branch.to_ascii_lowercase()));
285
286 let mut folded: Vec<&String> = collisions.iter().collect();
287 folded.sort();
288 for key in folded {
289 let mut branches: Vec<&str> = dropped
290 .iter()
291 .filter(|w| w.sanitized_branch.eq_ignore_ascii_case(key))
292 .map(|w| w.branch.as_str())
293 .collect();
294 branches.sort();
295 log::warn!(
296 "Worktree slug collision: branches [{}] all route to '{key}' under \
297 case-insensitive host matching. None of them will be routed; \
298 rename a branch to disambiguate.",
299 branches.join(", "),
300 );
301 }
302
303 (kept, collisions)
304}
305
306pub(crate) fn read_proxy_tls_route(
329 dir: &std::path::Path,
330 namespace: Option<&str>,
331 daemon_name: &str,
332) -> miette::Result<Option<ProxyTlsRoute>> {
333 let Some(id) = namespace.and_then(|ns| DaemonId::try_new(ns, daemon_name).ok()) else {
334 return Ok(None);
335 };
336 let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(dir)?;
337 Ok(pt.daemons.get(&id).map(|cfg| ProxyTlsRoute {
338 mode: cfg.proxy_tls.unwrap_or_default(),
339 protocol: cfg.proxy_protocol.unwrap_or_default(),
340 port: cfg.effective_proxy_tls_port(),
341 }))
342}
343
344fn route_or_last_known(
350 read: miette::Result<Option<ProxyTlsRoute>>,
351 known: Option<ProxyTlsRoute>,
352 dir: &std::path::Path,
353 daemon_name: &str,
354) -> Option<ProxyTlsRoute> {
355 read.unwrap_or_else(|e| {
356 crate::proxy::hostname::warn_once(&format!(
357 "Proxy TLS route for daemon '{daemon_name}': could not read config in {}; \
358 keeping its last known TLS mode until the config is fixed: {e}",
359 dir.display()
360 ));
361 known
362 })
363}
364
365fn build_slug_entries(
377 previous: &std::collections::HashMap<String, CachedSlugEntry>,
378) -> std::collections::HashMap<String, CachedSlugEntry> {
379 let global_slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
380 let collisions = crate::proxy::ascii_case_collisions(global_slugs.keys().map(String::as_str));
381 let mut folded: Vec<&String> = collisions.iter().collect();
382 folded.sort();
383 for key in folded {
384 let mut spellings: Vec<&str> = global_slugs
385 .keys()
386 .filter(|s| s.eq_ignore_ascii_case(key))
387 .map(String::as_str)
388 .collect();
389 spellings.sort();
390 log::warn!(
391 "Slug collision: [{}] differ only by case and host names are case-insensitive. \
392 None of them will be routed; remove or rename all but one.",
393 spellings.join(", "),
394 );
395 }
396
397 let mut entries: std::collections::HashMap<String, CachedSlugEntry> =
398 std::collections::HashMap::with_capacity(global_slugs.len());
399 let worktree_enabled = crate::settings::settings().general.worktree;
400 for (slug, entry) in &global_slugs {
401 let key = slug.to_ascii_lowercase();
402 if collisions.contains(&key) {
403 continue;
404 }
405 let ns = entry.resolve_namespace();
406 let daemon_name = entry.daemon.as_deref().unwrap_or(slug).to_string();
407 let (worktrees, rejected_worktree_prefixes) = if worktree_enabled {
408 let wts = match entry.resolve_dir() {
409 Some(dir) => crate::proxy::worktree::discover_worktrees(&dir),
410 None => vec![],
411 };
412 let wts = wts
413 .into_iter()
414 .map(|mut wt| {
415 wt.namespace =
416 crate::pitchfork_toml::PitchforkToml::namespace_for_dir(&wt.path).ok();
417 wt
418 })
419 .collect();
420 reject_case_colliding_worktrees(wts)
421 } else {
422 (vec![], std::collections::HashSet::new())
423 };
424 let dir = entry.resolve_dir().unwrap_or_default();
425 let prev = previous.get(&key);
426 let tls = route_or_last_known(
430 read_proxy_tls_route(&dir, ns.as_deref(), &daemon_name),
431 prev.and_then(|p| p.known_route(&dir, ns.as_deref(), &daemon_name)),
432 &dir,
433 &daemon_name,
434 )
435 .unwrap_or_default();
436 let worktree_tls = worktrees
440 .iter()
441 .filter_map(|wt| {
442 let branch = wt.sanitized_branch.to_ascii_lowercase();
443 route_or_last_known(
444 read_proxy_tls_route(&wt.path, wt.namespace.as_deref(), &daemon_name),
445 prev.and_then(|p| p.known_worktree_route(wt, &daemon_name)),
446 &wt.path,
447 &daemon_name,
448 )
449 .map(|route| (branch, route))
450 })
451 .collect();
452 entries.insert(
453 key,
454 CachedSlugEntry {
455 slug: slug.clone(),
456 namespace: ns,
457 daemon_name,
458 dir,
459 worktrees,
460 rejected_worktree_prefixes,
461 tls,
462 worktree_tls,
463 },
464 );
465 }
466 entries
467}
468
469pub async fn get_cached_slugs() -> Arc<std::collections::HashMap<String, CachedSlugEntry>> {
479 if let Some(entries) = fresh_slugs() {
481 return entries;
482 }
483
484 let _refreshing = SLUG_REFRESH.lock().await;
486
487 if let Some(entries) = fresh_slugs() {
489 return entries;
490 }
491
492 let previous = slug_snapshot();
494 let new_entries = Arc::new(
495 tokio::task::spawn_blocking(move || build_slug_entries(&previous))
496 .await
497 .unwrap_or_else(|e| {
498 log::warn!("Failed to refresh slug cache: {e}");
499 std::collections::HashMap::new()
500 }),
501 );
502
503 let mut cache = SLUG_CACHE
504 .write()
505 .unwrap_or_else(std::sync::PoisonError::into_inner);
506 cache.entries = Arc::clone(&new_entries);
507 cache.expires_at = std::time::Instant::now() + SLUG_CACHE_TTL;
508 new_entries
509}
510
511struct RegistryCache {
519 registry: Arc<crate::proxy::hostname::HostRegistry>,
520 expires_at: std::time::Instant,
521}
522
523static HOST_REGISTRY: once_cell::sync::Lazy<std::sync::RwLock<RegistryCache>> =
530 once_cell::sync::Lazy::new(|| {
531 std::sync::RwLock::new(RegistryCache {
532 registry: Arc::new(crate::proxy::hostname::HostRegistry::default()),
533 expires_at: std::time::Instant::now(), })
535 });
536
537static REGISTRY_REFRESH: once_cell::sync::Lazy<tokio::sync::Mutex<()>> =
540 once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(()));
541
542fn fresh_registry() -> Option<Arc<crate::proxy::hostname::HostRegistry>> {
544 let cache = HOST_REGISTRY
545 .read()
546 .unwrap_or_else(std::sync::PoisonError::into_inner);
547 (std::time::Instant::now() < cache.expires_at).then(|| Arc::clone(&cache.registry))
548}
549
550fn registry_snapshot() -> Arc<crate::proxy::hostname::HostRegistry> {
556 let cache = HOST_REGISTRY
557 .read()
558 .unwrap_or_else(std::sync::PoisonError::into_inner);
559 Arc::clone(&cache.registry)
560}
561
562pub async fn get_cached_host_registry() -> Arc<crate::proxy::hostname::HostRegistry> {
564 if let Some(registry) = fresh_registry() {
565 return registry;
566 }
567
568 let _refreshing = REGISTRY_REFRESH.lock().await;
570 if let Some(registry) = fresh_registry() {
571 return registry;
572 }
573
574 let registry = Arc::new(
575 tokio::task::spawn_blocking(crate::proxy::hostname::HostRegistry::build)
576 .await
577 .unwrap_or_else(|e| {
578 log::warn!("Failed to refresh hostname registry: {e}");
579 crate::proxy::hostname::HostRegistry::default()
580 }),
581 );
582 for err in ®istry.errors {
583 crate::proxy::hostname::warn_once(err);
584 }
585
586 let mut cache = HOST_REGISTRY
587 .write()
588 .unwrap_or_else(std::sync::PoisonError::into_inner);
589 cache.registry = Arc::clone(®istry);
590 cache.expires_at = std::time::Instant::now() + SLUG_CACHE_TTL;
591 registry
592}
593
594fn wildcard_slug_lookup<'a>(
604 subdomain: &str,
605 entries: &'a std::collections::HashMap<String, CachedSlugEntry>,
606 wildcard: bool,
607) -> Option<&'a CachedSlugEntry> {
608 let subdomain = subdomain.to_ascii_lowercase();
609
610 entries.get(&subdomain).or_else(|| {
611 if !wildcard {
612 return None;
613 }
614 subdomain
616 .match_indices('.')
617 .map(|(i, _)| &subdomain[i + 1..])
618 .find_map(|candidate| entries.get(candidate))
619 })
620}
621
622#[derive(Debug)]
624enum PrefixMatch<'a> {
625 Worktree(&'a crate::proxy::worktree::WorktreeEntry),
627 Unknown,
630 Ambiguous,
634}
635
636fn match_worktree_prefix<'a>(cached: &'a CachedSlugEntry, prefix: &str) -> PrefixMatch<'a> {
638 if let Some(wt) = cached
639 .worktrees
640 .iter()
641 .find(|w| w.sanitized_branch.eq_ignore_ascii_case(prefix))
642 {
643 return PrefixMatch::Worktree(wt);
644 }
645 if cached
646 .rejected_worktree_prefixes
647 .contains(&prefix.to_ascii_lowercase())
648 {
649 return PrefixMatch::Ambiguous;
650 }
651 PrefixMatch::Unknown
652}
653
654fn worktree_route(cached: &CachedSlugEntry, sanitized_branch: &str) -> ProxyTlsRoute {
668 cached
669 .worktree_tls
670 .get(&sanitized_branch.to_ascii_lowercase())
671 .copied()
672 .unwrap_or(ProxyTlsRoute {
673 mode: cached.tls.mode,
674 protocol: cached.tls.protocol,
675 port: None,
676 })
677}
678
679fn strip_dot_suffix_ignore_case(s: &str, suffix: &str) -> Option<String> {
683 let needle_len = suffix.len() + 1;
684 if s.len() <= needle_len {
685 return None;
686 }
687 let split = s.len() - needle_len;
688 if !s.is_char_boundary(split) {
689 return None;
690 }
691 let (head, tail) = s.split_at(split);
692 if tail.starts_with('.') && tail[1..].eq_ignore_ascii_case(suffix) {
693 Some(head.to_string())
694 } else {
695 None
696 }
697}
698
699async fn cached_slug_lookup(subdomain: &str) -> Option<CachedSlugEntry> {
706 let entries = get_cached_slugs().await;
707 wildcard_slug_lookup(subdomain, &entries, settings().proxy.wildcard).cloned()
708}
709
710static AUTO_START_IN_PROGRESS: once_cell::sync::Lazy<
717 tokio::sync::Mutex<std::collections::HashSet<DaemonId>>,
718> = once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
719
720enum ResolveResult {
722 Ready(u16, Option<ActivityGuard>, ProxyProtocol),
728 Starting { slug: String },
730 NotFound,
732 Page {
735 project: String,
736 worktree: Option<String>,
737 daemons: Vec<String>,
738 dir: Option<std::path::PathBuf>,
742 },
743 Unknown { heading: String, known: Vec<String> },
745 Error(String),
747}
748
749type OnErrorFn = Arc<dyn Fn(&str) + Send + Sync>;
752
753#[derive(Clone)]
754struct ProxyState {
755 client: Arc<Client<HttpConnector, Body>>,
757 h2c_client: Arc<Client<HttpConnector, Body>>,
760 tld: String,
762 is_tls: bool,
764 connect_target: Option<SocketAddr>,
766 contact_ip: std::net::IpAddr,
769 cancel: tokio_util::sync::CancellationToken,
771 tunnel_slots: Arc<tokio::sync::Semaphore>,
773 tunnels: tokio_util::task::TaskTracker,
780 on_error: Option<OnErrorFn>,
782}
783
784pub async fn serve(
792 bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
793 cancel: tokio_util::sync::CancellationToken,
794) -> crate::Result<()> {
795 let s = settings();
796 let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
797
798 let effective_tld = crate::proxy::effective_tld(&s).to_string();
799
800 let Some(effective_port) = u16::try_from(s.proxy.port).ok().filter(|&p| p > 0) else {
801 let msg = format!(
802 "proxy.port {} is out of valid port range (1-65535), proxy server cannot start",
803 s.proxy.port
804 );
805 let _ = bind_tx.send(Err(msg.clone()));
806 miette::bail!("{msg}");
807 };
808
809 let mut connector = HttpConnector::new();
810 connector.set_connect_timeout(Some(std::time::Duration::from_secs(10)));
814
815 let client = Client::builder(TokioExecutor::new())
816 .pool_idle_timeout(std::time::Duration::from_secs(30))
819 .build(connector.clone());
820
821 let h2c_client = Client::builder(TokioExecutor::new())
822 .pool_idle_timeout(std::time::Duration::from_secs(30))
823 .http2_only(true)
824 .build(connector);
825
826 let bind_ip: std::net::IpAddr = if lan_enabled && s.proxy.host == "127.0.0.1" {
830 std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)
831 } else {
832 match s.proxy.host.parse() {
833 Ok(ip) => ip,
834 Err(_) => {
835 log::warn!(
836 "proxy.host {:?} is not a valid IP address — falling back to 127.0.0.1. \
837 The proxy will only be reachable on the loopback interface.",
838 s.proxy.host
839 );
840 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
841 }
842 }
843 };
844 let addr = SocketAddr::from((bind_ip, effective_port));
845 let contact_ip = local_contact_ip(bind_ip);
850 let tunnels = tokio_util::task::TaskTracker::new();
851
852 let state = ProxyState {
853 client: Arc::new(client),
854 h2c_client: Arc::new(h2c_client),
855 tld: effective_tld.clone(),
856 is_tls: s.proxy.https,
857 connect_target: Some(SocketAddr::from((contact_ip, effective_port))),
860 contact_ip,
861 cancel: cancel.clone(),
862 tunnel_slots: Arc::new(tokio::sync::Semaphore::new(MAX_TUNNELS)),
863 tunnels: tunnels.clone(),
864 on_error: None,
865 };
866
867 let plain_state = state.clone();
872 let app = Router::new()
873 .route(crate::proxy::pac::PAC_PATH, axum::routing::any(pac_handler))
879 .fallback(proxy_handler)
880 .with_state(state);
881
882 if s.proxy.https {
883 serve_https_with_http_fallback(
884 app,
885 addr,
886 &s,
887 effective_port,
888 effective_tld,
889 plain_state,
890 bind_tx,
891 cancel,
892 )
893 .await
894 } else {
895 serve_http(app, addr, effective_port, plain_state, bind_tx, cancel).await
899 }
900}
901
902macro_rules! serve_conn_until_cancelled {
909 ($io:expr, $svc:expr, $cancel:expr) => {{
910 let builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
911 let conn = builder.serve_connection_with_upgrades($io, $svc);
912 tokio::pin!(conn);
913 tokio::select! {
914 r = conn.as_mut() => r,
915 _ = $cancel.cancelled() => {
916 conn.as_mut().graceful_shutdown();
917 conn.await
918 }
919 }
920 }};
921}
922
923async fn serve_http(
925 app: Router,
926 addr: SocketAddr,
927 effective_port: u16,
928 proxy_state: ProxyState,
929 bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
930 cancel: tokio_util::sync::CancellationToken,
931) -> crate::Result<()> {
932 let listener = match TcpListener::bind(addr).await {
933 Ok(l) => {
934 if settings().proxy.sync_hosts {
935 crate::proxy::hosts::sync_hosts_from_settings();
936 }
937 let _ = bind_tx.send(Ok(()));
938 l
939 }
940 Err(e) => {
941 let msg = bind_error_message(effective_port, &e);
942 let _ = bind_tx.send(Err(msg.clone()));
943 return Err(miette::miette!("{msg}"));
944 }
945 };
946
947 log::info!("Proxy server listening on http://{addr}");
948 if effective_port < 1024 {
949 log::info!(
950 "Note: port {effective_port} is a privileged port. \
951 The supervisor must be started with sudo to bind to this port."
952 );
953 }
954 let mut conn_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
961 loop {
962 while conn_tasks.try_join_next().is_some() {}
963 tokio::select! {
964 accept_result = listener.accept() => {
965 let (stream, peer_addr) = match accept_result {
966 Ok(conn) => conn,
967 Err(e) => {
968 log::warn!("Accept error (will retry): {e}");
969 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
970 continue;
971 }
972 };
973 let app = app
976 .clone()
977 .layer(axum::Extension(axum::extract::ConnectInfo(peer_addr)));
978 let cancel = cancel.clone();
979 conn_tasks.spawn(async move {
980 let io = hyper_util::rt::TokioIo::new(stream);
981 let svc = hyper_util::service::TowerToHyperService::new(app);
982 if let Err(e) = serve_conn_until_cancelled!(io, svc, cancel) {
983 log::debug!("Connection error: {e}");
984 }
985 });
986 }
987 _ = cancel.cancelled() => break,
988 }
989 }
990
991 let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_BUDGET;
994 if tokio::time::timeout_at(deadline, async {
995 while conn_tasks.join_next().await.is_some() {}
996 })
997 .await
998 .is_err()
999 {
1000 log::debug!("Proxy connections still open after {SHUTDOWN_DRAIN_BUDGET:?}; aborting them");
1001 }
1002 drop(conn_tasks);
1004
1005 proxy_state.tunnels.close();
1009 let _ = tokio::time::timeout_at(deadline, proxy_state.tunnels.wait()).await;
1010 Ok(())
1011}
1012
1013#[cfg(feature = "proxy-tls")]
1019#[allow(clippy::too_many_arguments)]
1020async fn serve_https_with_http_fallback(
1021 app: Router,
1022 addr: SocketAddr,
1023 s: &crate::settings::Settings,
1024 effective_port: u16,
1025 effective_tld: String,
1026 plain_proxy_state: ProxyState,
1027 bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
1028 cancel: tokio_util::sync::CancellationToken,
1029) -> crate::Result<()> {
1030 use rustls::ServerConfig;
1031 use tokio_rustls::TlsAcceptor;
1032
1033 let (cert_path, key_path) = resolve_tls_paths(s)?;
1034
1035 let _ = rustls::crypto::ring::default_provider().install_default();
1037
1038 let resolver: Arc<dyn rustls::server::ResolvesServerCert> = if s.proxy.tls_cert.is_empty() {
1043 if ensure_ca(&cert_path, &key_path, || {
1044 cert_path.exists() && key_path.exists()
1045 })? {
1046 log::info!("Generated local CA certificate at {}", cert_path.display());
1047 log::info!("To trust the CA in your browser, run: pitchfork proxy trust");
1048 }
1049 Arc::new(SniCertResolver::new(
1050 &cert_path,
1051 &key_path,
1052 effective_tld.clone(),
1053 )?)
1054 } else {
1055 log::info!(
1056 "Serving the configured certificate {} (no certificates are minted)",
1057 cert_path.display()
1058 );
1059 Arc::new(StaticCertResolver::new(
1060 &cert_path,
1061 &key_path,
1062 effective_tld.clone(),
1063 )?)
1064 };
1065
1066 let mut tls_config = ServerConfig::builder()
1067 .with_no_client_auth()
1068 .with_cert_resolver(resolver);
1069 tls_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
1072
1073 let acceptor = TlsAcceptor::from(Arc::new(tls_config));
1074
1075 let listener = match TcpListener::bind(addr).await {
1076 Ok(l) => {
1077 if settings().proxy.sync_hosts {
1078 crate::proxy::hosts::sync_hosts_from_settings();
1079 }
1080 let _ = bind_tx.send(Ok(()));
1081 l
1082 }
1083 Err(e) => {
1084 let msg = bind_error_message(effective_port, &e);
1085 let _ = bind_tx.send(Err(msg.clone()));
1086 return Err(miette::miette!("{msg}"));
1087 }
1088 };
1089
1090 log::info!("Proxy server listening on https://{addr} (HTTP also accepted)");
1091 if effective_port < 1024 {
1092 log::info!(
1093 "Note: port {effective_port} is a privileged port. \
1094 The supervisor must be started with sudo to bind to this port."
1095 );
1096 }
1097
1098 let redirect_app = Router::new()
1106 .route(
1107 crate::proxy::pac::PAC_PATH,
1110 axum::routing::any(plain_pac_handler),
1111 )
1112 .fallback(plain_fallback_handler)
1113 .with_state(PlainState {
1114 tld: effective_tld.clone(),
1115 port: effective_port,
1116 proxy: plain_proxy_state.clone(),
1117 });
1118
1119 let mut conn_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1121 let handshake_slots = Arc::new(tokio::sync::Semaphore::new(MAX_PENDING_HANDSHAKES));
1122 loop {
1123 while conn_tasks.try_join_next().is_some() {}
1126
1127 tokio::select! {
1128 accept_result = listener.accept() => {
1129 let (stream, peer_addr) = match accept_result {
1130 Ok(conn) => conn,
1131 Err(e) => {
1132 log::warn!("Accept error (will retry): {e}");
1133 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1134 continue;
1135 }
1136 };
1137
1138 let Ok(handshake_permit) = Arc::clone(&handshake_slots).try_acquire_owned() else {
1146 if let Some(suppressed) = REFUSED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL) {
1149 log::warn!(
1150 "Proxy refused a connection: {MAX_PENDING_HANDSHAKES} \
1151 still negotiating \
1152 ({suppressed} similar refusals since the last message)"
1153 );
1154 }
1155 drop(stream);
1156 continue;
1157 };
1158
1159 let acceptor = acceptor.clone();
1160 let app = app
1165 .clone()
1166 .layer(axum::Extension(axum::extract::ConnectInfo(peer_addr)));
1167 let redirect_app = redirect_app.clone();
1168 let tld = effective_tld.clone();
1169 let cancel = cancel.clone();
1170
1171 conn_tasks.spawn(async move {
1172 let handshake_deadline = tokio::time::Instant::now() + HANDSHAKE_TIMEOUT;
1179 let mut peek_buf = [0u8; 1];
1180 match tokio::time::timeout_at(handshake_deadline, stream.peek(&mut peek_buf)).await {
1181 Ok(Ok(0)) | Ok(Err(_)) => return,
1182 Err(_) => {
1183 if let Some(suppressed) =
1184 ABANDONED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL)
1185 {
1186 log::debug!(
1187 "Connection sent nothing within the handshake timeout \
1188 ({suppressed} similar since the last message)"
1189 );
1190 }
1191 return;
1192 }
1193 Ok(Ok(_)) => {}
1194 }
1195
1196 if peek_buf[0] == 0x16 {
1197 let sni_budget = SNI_PEEK_TIMEOUT.min(
1205 handshake_deadline.saturating_duration_since(tokio::time::Instant::now()),
1206 );
1207 match peek_sni_host(&stream, sni_budget).await {
1208 SniProbe::Host(host) => {
1209 let Ok(mode) = tokio::time::timeout_at(
1214 handshake_deadline,
1215 resolve_tls_mode(&host, &tld),
1216 )
1217 .await
1218 else {
1219 if let Some(suppressed) =
1220 ABANDONED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL)
1221 {
1222 log::debug!(
1223 "Routing lookup for '{host}' did not finish within the \
1224 handshake timeout ({suppressed} similar since the \
1225 last message)"
1226 );
1227 }
1228 return;
1229 };
1230 if mode.is_passthrough() {
1231 drop(handshake_permit);
1235 tokio::select! {
1239 _ = serve_passthrough(stream, &host, &tld) => {}
1240 _ = cancel.cancelled() => {}
1241 }
1242 return;
1243 }
1244 }
1245 SniProbe::NoHost => {}
1246 SniProbe::Undetermined => {
1255 log::debug!(
1256 "Could not read the ClientHello of a TLS connection; \
1257 handing it to the TLS acceptor, which refuses to terminate \
1258 a passthrough hostname."
1259 );
1260 let _ = tokio::time::timeout_at(handshake_deadline, async {
1265 let _ = get_cached_slugs().await;
1266 let _ = get_cached_host_registry().await;
1267 })
1268 .await;
1269 }
1270 }
1271
1272 let accepted = match tokio::time::timeout_at(
1274 handshake_deadline,
1275 acceptor.accept(stream),
1276 )
1277 .await
1278 {
1279 Ok(r) => r,
1280 Err(_) => {
1281 if let Some(suppressed) =
1282 ABANDONED_HANDSHAKE.allow(REFUSAL_LOG_INTERVAL)
1283 {
1284 log::debug!(
1285 "TLS handshake did not complete in time \
1286 ({suppressed} similar since the last message)"
1287 );
1288 }
1289 return;
1290 }
1291 };
1292 drop(handshake_permit);
1295 match accepted {
1296 Ok(tls_stream) => {
1297 let io = hyper_util::rt::TokioIo::new(tls_stream);
1298 let svc = hyper_util::service::TowerToHyperService::new(app);
1299 if let Err(e) = serve_conn_until_cancelled!(io, svc, cancel) {
1300 log::debug!("Connection error: {e}");
1303 }
1304 }
1305 Err(e) => {
1306 log::debug!("TLS handshake error: {e}");
1307 }
1308 }
1309 } else {
1310 drop(handshake_permit);
1313 let io = hyper_util::rt::TokioIo::new(stream);
1314 let svc = hyper_util::service::TowerToHyperService::new(redirect_app);
1315 let _ = serve_conn_until_cancelled!(io, svc, cancel);
1316 }
1317 });
1318
1319 while conn_tasks.try_join_next().is_some() {}
1320 }
1321 _ = cancel.cancelled() => {
1322 log::info!("Proxy server shutting down (cancel signal received)");
1323 break;
1324 }
1325 }
1326 }
1327
1328 let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_BUDGET;
1332
1333 let _ = tokio::time::timeout_at(deadline, async {
1335 while conn_tasks.join_next().await.is_some() {}
1336 })
1337 .await;
1338
1339 plain_proxy_state.tunnels.close();
1343 let _ = tokio::time::timeout_at(deadline, plain_proxy_state.tunnels.wait()).await;
1344
1345 Ok(())
1346}
1347
1348#[cfg(feature = "proxy-tls")]
1353const SNI_PEEK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
1354
1355#[cfg(feature = "proxy-tls")]
1360const SNI_PEEK_MAX_BYTES: usize = 16 * 1024;
1361
1362#[cfg(feature = "proxy-tls")]
1368#[derive(Debug, PartialEq, Eq)]
1369enum SniProbe {
1370 Host(String),
1372 NoHost,
1375 Undetermined,
1378}
1379
1380#[cfg(feature = "proxy-tls")]
1392async fn peek_sni_host(stream: &TcpStream, timeout: std::time::Duration) -> SniProbe {
1393 use crate::proxy::sni::{SniPeek, parse_sni};
1394
1395 const MIN_PAUSE: std::time::Duration = std::time::Duration::from_millis(10);
1396 const MAX_PAUSE: std::time::Duration = std::time::Duration::from_millis(200);
1397
1398 let deadline = tokio::time::Instant::now() + timeout;
1399 let mut buf = vec![0u8; 2048];
1400 let mut last_n = 0;
1401 let mut pause = MIN_PAUSE;
1402
1403 loop {
1404 let n = match tokio::time::timeout_at(deadline, stream.peek(&mut buf)).await {
1408 Ok(Ok(0)) => return SniProbe::NoHost,
1412 Ok(Ok(n)) => n,
1413 Ok(Err(e)) => {
1414 log::debug!("Failed to peek at a TLS connection: {e}");
1415 return SniProbe::Undetermined;
1416 }
1417 Err(_elapsed) => {
1418 log::debug!("Timed out waiting for a client that sent no ClientHello");
1419 return SniProbe::Undetermined;
1420 }
1421 };
1422 match parse_sni(&buf[..n]) {
1423 SniPeek::Found(host) => return SniProbe::Host(host),
1424 SniPeek::Absent | SniPeek::NotTls => return SniProbe::NoHost,
1425 SniPeek::Incomplete => {}
1426 }
1427
1428 if n == buf.len() && buf.len() < SNI_PEEK_MAX_BYTES {
1430 buf.resize((buf.len() * 2).min(SNI_PEEK_MAX_BYTES), 0);
1431 continue;
1432 }
1433 if n >= SNI_PEEK_MAX_BYTES {
1434 log::debug!("Giving up on SNI after {n} bytes without a complete ClientHello");
1435 return SniProbe::Undetermined;
1436 }
1437 if tokio::time::Instant::now() >= deadline {
1438 log::debug!("Timed out waiting for a complete ClientHello ({n} bytes read)");
1439 return SniProbe::Undetermined;
1440 }
1441 match stream.ready(tokio::io::Interest::READABLE).await {
1447 Ok(ready) if ready.is_read_closed() => {
1448 log::debug!("Client closed after {n} bytes of an incomplete ClientHello");
1449 return SniProbe::Undetermined;
1450 }
1451 Ok(_) => {}
1452 Err(e) => {
1453 log::debug!("Failed to poll a TLS connection: {e}");
1454 return SniProbe::Undetermined;
1455 }
1456 }
1457 pause = if n > last_n {
1460 MIN_PAUSE
1461 } else {
1462 (pause * 2).min(MAX_PAUSE)
1463 };
1464 last_n = n;
1465 tokio::time::sleep_until((tokio::time::Instant::now() + pause).min(deadline)).await;
1466 }
1467}
1468
1469#[cfg(feature = "proxy-tls")]
1482async fn serve_passthrough(mut stream: TcpStream, host: &str, tld: &str) {
1483 let (port, _activity) = match resolve_passthrough_port(host, tld).await {
1487 Ok(ready) => ready,
1488 Err(msg) => {
1489 log::warn!("TLS passthrough for '{host}' failed: {msg}");
1490 return;
1491 }
1492 };
1493
1494 let addr = SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port));
1495 let mut backend = match connect_backend(addr).await {
1496 Ok(b) => b,
1497 Err(e) => {
1498 log::warn!("TLS passthrough for '{host}': failed to connect to {addr}: {e}");
1499 return;
1500 }
1501 };
1502
1503 log::debug!("TLS passthrough: splicing '{host}' to {addr}");
1504 if let Err(e) = tokio::io::copy_bidirectional(&mut stream, &mut backend).await {
1505 log::debug!("TLS passthrough for '{host}' ended: {e}");
1507 }
1508}
1509
1510#[cfg(feature = "proxy-tls")]
1517const PASSTHROUGH_CONNECT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
1518
1519#[cfg(feature = "proxy-tls")]
1521async fn connect_backend(addr: SocketAddr) -> std::io::Result<TcpStream> {
1522 let deadline = tokio::time::Instant::now() + PASSTHROUGH_CONNECT_GRACE;
1523 loop {
1524 match TcpStream::connect(addr).await {
1525 Ok(stream) => return Ok(stream),
1526 Err(e) => {
1527 let retryable = e.kind() == std::io::ErrorKind::ConnectionRefused;
1528 if !retryable || tokio::time::Instant::now() >= deadline {
1529 return Err(e);
1530 }
1531 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1532 }
1533 }
1534 }
1535}
1536
1537#[cfg(feature = "proxy-tls")]
1545async fn resolve_passthrough_port(
1546 host: &str,
1547 tld: &str,
1548) -> std::result::Result<(u16, Option<ActivityGuard>), String> {
1549 let budget = settings().proxy_auto_start_timeout();
1550 match tokio::time::timeout(budget, resolve_passthrough_port_inner(host, tld)).await {
1551 Ok(result) => result,
1552 Err(_elapsed) => Err(format!(
1553 "no daemon was ready for '{host}' within proxy.auto_start_timeout ({budget:?})"
1554 )),
1555 }
1556}
1557
1558#[cfg(feature = "proxy-tls")]
1561async fn resolve_passthrough_port_inner(
1562 host: &str,
1563 tld: &str,
1564) -> std::result::Result<(u16, Option<ActivityGuard>), String> {
1565 loop {
1566 match resolve_target(host, tld).await {
1567 ResolveResult::Ready(port, activity, _) => return Ok((port, activity)),
1568 ResolveResult::Starting { slug: _ } => {
1573 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
1574 }
1575 ResolveResult::NotFound => {
1576 return Err(
1577 "no running daemon with a port matched this hostname, and it could not \
1578 be auto-started"
1579 .to_string(),
1580 );
1581 }
1582 ResolveResult::Page {
1587 project, worktree, ..
1588 } => {
1589 return Err(match worktree {
1590 Some(worktree) => {
1591 format!("'{worktree}' of project '{project}' is a stack page, not a daemon")
1592 }
1593 None => format!("'{project}' is a project page, not a daemon"),
1594 });
1595 }
1596 ResolveResult::Unknown { heading, .. } => return Err(heading),
1597 ResolveResult::Error(msg) => return Err(msg),
1598 }
1599 }
1600}
1601
1602#[cfg(not(feature = "proxy-tls"))]
1604#[allow(clippy::too_many_arguments)]
1605async fn serve_https_with_http_fallback(
1606 _app: Router,
1607 _addr: SocketAddr,
1608 _s: &crate::settings::Settings,
1609 _effective_port: u16,
1610 _effective_tld: String,
1611 _plain_proxy_state: ProxyState,
1612 bind_tx: tokio::sync::oneshot::Sender<std::result::Result<(), String>>,
1613 _cancel: tokio_util::sync::CancellationToken,
1614) -> crate::Result<()> {
1615 let msg = "HTTPS proxy support requires the `proxy-tls` feature.\n\
1616 Rebuild pitchfork with: cargo build --features proxy-tls"
1617 .to_string();
1618 let _ = bind_tx.send(Err(msg.clone()));
1619 miette::bail!("{msg}");
1620}
1621
1622#[cfg(feature = "proxy-tls")]
1632fn resolve_tls_paths(
1633 s: &crate::settings::Settings,
1634) -> crate::Result<(std::path::PathBuf, std::path::PathBuf)> {
1635 if let Some(problem) = tls_pair_problem(&s.proxy.tls_cert, &s.proxy.tls_key) {
1636 miette::bail!("{problem}");
1637 }
1638 let proxy_dir = crate::env::PITCHFORK_STATE_DIR.join("proxy");
1639 let resolve = |configured: &str, default: &str| {
1640 if configured.is_empty() {
1641 proxy_dir.join(default)
1642 } else {
1643 std::path::PathBuf::from(configured)
1644 }
1645 };
1646 Ok((
1647 resolve(&s.proxy.tls_cert, "ca.pem"),
1648 resolve(&s.proxy.tls_key, "ca-key.pem"),
1649 ))
1650}
1651
1652pub(crate) fn tls_pair_problem(cert: &str, key: &str) -> Option<String> {
1655 match (cert.is_empty(), key.is_empty()) {
1656 (false, true) => Some(
1657 "proxy.tls_cert is set but proxy.tls_key is empty; set both, or neither to use \
1658 the generated CA"
1659 .to_string(),
1660 ),
1661 (true, false) => Some(
1662 "proxy.tls_key is set but proxy.tls_cert is empty; set both, or neither to use \
1663 the generated CA"
1664 .to_string(),
1665 ),
1666 _ => None,
1667 }
1668}
1669
1670#[cfg(feature = "proxy-tls")]
1680pub fn ensure_ca(
1681 cert_path: &std::path::Path,
1682 key_path: &std::path::Path,
1683 usable: impl FnOnce() -> bool,
1684) -> crate::Result<bool> {
1685 let _lock = xx::fslock::get(cert_path, false)
1686 .map_err(|e| miette::miette!("Failed to lock {}: {e}", cert_path.display()))?;
1687 if usable() {
1688 return Ok(false);
1689 }
1690 generate_ca(cert_path, key_path)?;
1691 clear_host_certs(&host_certs_dir_for(cert_path), None);
1695 Ok(true)
1696}
1697
1698#[cfg(feature = "proxy-tls")]
1700fn host_certs_dir_for(ca_cert_path: &std::path::Path) -> std::path::PathBuf {
1701 ca_cert_path
1702 .parent()
1703 .unwrap_or(std::path::Path::new("."))
1704 .join("host-certs")
1705}
1706
1707#[cfg(feature = "proxy-tls")]
1715fn ca_cache_id(ca_cert_pem: &str) -> String {
1716 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
1717 for b in ca_cert_pem.bytes() {
1718 hash ^= u64::from(b);
1719 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1720 }
1721 format!("ca-{hash:016x}")
1722}
1723
1724#[cfg(feature = "proxy-tls")]
1728fn clear_host_certs(root: &std::path::Path, keep: Option<&str>) {
1729 let Ok(entries) = std::fs::read_dir(root) else {
1730 return;
1731 };
1732 for entry in entries.filter_map(|e| e.ok()) {
1733 let path = entry.path();
1734 let name = entry.file_name();
1735 let result = if path.is_dir() {
1736 let is_ca_dir = name.to_str().is_some_and(|n| n.starts_with("ca-"));
1737 if !is_ca_dir || keep.is_some_and(|k| name == k) {
1738 continue;
1739 }
1740 std::fs::remove_dir_all(&path)
1741 } else if path.extension().is_some_and(|x| x == "pem") {
1742 std::fs::remove_file(&path)
1743 } else {
1744 continue;
1745 };
1746 if let Err(e) = result {
1747 log::debug!(
1748 "Could not remove stale cached certs {}: {e}",
1749 path.display()
1750 );
1751 }
1752 }
1753}
1754
1755#[cfg(feature = "proxy-tls")]
1762fn generate_ca(cert_path: &std::path::Path, key_path: &std::path::Path) -> crate::Result<()> {
1763 use rcgen::{
1764 BasicConstraints, CertificateParams, DistinguishedName, DnType, IsCa, KeyUsagePurpose,
1765 };
1766
1767 if let Some(parent) = cert_path.parent() {
1769 std::fs::create_dir_all(parent)
1770 .map_err(|e| miette::miette!("Failed to create proxy cert directory: {e}"))?;
1771 }
1772
1773 let mut params = CertificateParams::default();
1774 let mut dn = DistinguishedName::new();
1775 dn.push(DnType::CommonName, "Pitchfork Local CA");
1776 dn.push(DnType::OrganizationName, "Pitchfork");
1777 params.distinguished_name = dn;
1778 params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1779 params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
1780
1781 let key_pair = rcgen::KeyPair::generate()
1782 .map_err(|e| miette::miette!("Failed to generate CA key pair: {e}"))?;
1783 let ca_cert = params
1784 .self_signed(&key_pair)
1785 .map_err(|e| miette::miette!("Failed to self-sign CA certificate: {e}"))?;
1786
1787 std::fs::write(cert_path, ca_cert.pem()).map_err(|e| {
1789 miette::miette!(
1790 "Failed to write CA certificate to {}: {e}",
1791 cert_path.display()
1792 )
1793 })?;
1794
1795 {
1799 #[cfg(unix)]
1800 {
1801 use std::io::Write;
1802 use std::os::unix::fs::OpenOptionsExt;
1803 std::fs::OpenOptions::new()
1804 .write(true)
1805 .create(true)
1806 .truncate(true)
1807 .mode(0o600)
1808 .open(key_path)
1809 .and_then(|mut f| f.write_all(key_pair.serialize_pem().as_bytes()))
1810 .map_err(|e| {
1811 miette::miette!("Failed to write CA key to {}: {e}", key_path.display())
1812 })?;
1813 }
1814 #[cfg(not(unix))]
1815 {
1816 std::fs::write(key_path, key_pair.serialize_pem()).map_err(|e| {
1817 miette::miette!("Failed to write CA key to {}: {e}", key_path.display())
1818 })?;
1819 log::debug!(
1820 "CA private key written to {} (file permissions are not restricted \
1821 on non-Unix platforms — consider restricting access manually)",
1822 key_path.display()
1823 );
1824 }
1825 }
1826
1827 Ok(())
1828}
1829
1830#[cfg(feature = "proxy-tls")]
1836struct StaticCertResolver {
1837 certified: Arc<rustls::sign::CertifiedKey>,
1838 tld: String,
1841}
1842
1843#[cfg(feature = "proxy-tls")]
1844impl std::fmt::Debug for StaticCertResolver {
1845 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1846 f.debug_struct("StaticCertResolver").finish_non_exhaustive()
1847 }
1848}
1849
1850#[cfg(feature = "proxy-tls")]
1851impl StaticCertResolver {
1852 fn new(
1853 cert_path: &std::path::Path,
1854 key_path: &std::path::Path,
1855 tld: String,
1856 ) -> crate::Result<Self> {
1857 use rustls::pki_types::CertificateDer;
1858 use rustls_pemfile::{certs, private_key};
1859
1860 let cert_pem = std::fs::read(cert_path).map_err(|e| {
1861 miette::miette!("Failed to read proxy.tls_cert {}: {e}", cert_path.display())
1862 })?;
1863 let key_pem = std::fs::read(key_path).map_err(|e| {
1864 miette::miette!("Failed to read proxy.tls_key {}: {e}", key_path.display())
1865 })?;
1866
1867 let cert_ders: Vec<CertificateDer<'static>> = certs(&mut cert_pem.as_slice())
1868 .collect::<Result<Vec<_>, _>>()
1869 .map_err(|e| miette::miette!("Failed to parse {}: {e}", cert_path.display()))?;
1870 if cert_ders.is_empty() {
1871 miette::bail!("No certificates found in {}", cert_path.display());
1872 }
1873
1874 let key_der = private_key(&mut key_pem.as_slice())
1875 .map_err(|e| miette::miette!("Failed to parse {}: {e}", key_path.display()))?
1876 .ok_or_else(|| miette::miette!("No private key found in {}", key_path.display()))?;
1877 let signing_key = rustls::crypto::ring::sign::any_supported_type(&key_der)
1878 .map_err(|e| miette::miette!("Failed to use the configured private key: {e}"))?;
1879
1880 let certified = rustls::sign::CertifiedKey::new(cert_ders, signing_key);
1881 certified.keys_match().map_err(|e| {
1885 miette::miette!(
1886 "proxy.tls_key {} does not match proxy.tls_cert {}: {e}",
1887 key_path.display(),
1888 cert_path.display()
1889 )
1890 })?;
1891
1892 Ok(Self {
1893 certified: Arc::new(certified),
1894 tld,
1895 })
1896 }
1897}
1898
1899#[cfg(feature = "proxy-tls")]
1900impl rustls::server::ResolvesServerCert for StaticCertResolver {
1901 fn resolve(
1902 &self,
1903 client_hello: rustls::server::ClientHello<'_>,
1904 ) -> Option<Arc<rustls::sign::CertifiedKey>> {
1905 if let Some(domain) = client_hello.server_name()
1909 && resolve_tls_mode_in(domain, &self.tld, &slug_snapshot(), ®istry_snapshot())
1910 .is_passthrough()
1911 {
1912 log::warn!(
1913 "Refusing to terminate TLS for '{domain}', which is configured for \
1914 proxy_tls = \"passthrough\": its ClientHello could not be inspected before the \
1915 handshake, so the stream could not be spliced to the daemon."
1916 );
1917 return None;
1918 }
1919 Some(Arc::clone(&self.certified))
1920 }
1921}
1922
1923#[cfg(feature = "proxy-tls")]
1943struct SniCertResolver {
1944 issuer: rcgen::Issuer<'static, rcgen::KeyPair>,
1946 tld: String,
1950 host_certs_dir: std::path::PathBuf,
1952 cache: std::sync::Mutex<CertCache>,
1955 pending: std::sync::Mutex<std::collections::HashSet<String>>,
1959 pending_cv: std::sync::Condvar,
1961}
1962
1963#[cfg(feature = "proxy-tls")]
1969fn prune_host_certs(dir: &std::path::Path) {
1970 let Ok(entries) = std::fs::read_dir(dir) else {
1971 return;
1972 };
1973 let mut files: Vec<(std::time::SystemTime, std::path::PathBuf)> = entries
1974 .filter_map(|e| e.ok())
1975 .filter(|e| e.path().extension().is_some_and(|x| x == "pem"))
1976 .filter_map(|e| {
1977 let modified = e.metadata().and_then(|m| m.modified()).ok()?;
1978 Some((modified, e.path()))
1979 })
1980 .collect();
1981 if files.len() <= MAX_HOST_CERTS {
1982 return;
1983 }
1984 files.sort_by_key(|(t, _)| *t);
1985 let excess = files.len() - MAX_HOST_CERTS;
1986 for (_, path) in files.into_iter().take(excess) {
1987 if let Err(e) = std::fs::remove_file(&path) {
1988 log::debug!("Could not prune cached cert {}: {e}", path.display());
1989 }
1990 }
1991}
1992
1993#[cfg(feature = "proxy-tls")]
1995#[derive(Default)]
1996struct CertCache {
1997 by_domain: std::collections::HashMap<String, Arc<rustls::sign::CertifiedKey>>,
1998 order: std::collections::VecDeque<String>,
2000}
2001
2002#[cfg(feature = "proxy-tls")]
2003impl CertCache {
2004 fn get(&self, domain: &str) -> Option<&Arc<rustls::sign::CertifiedKey>> {
2005 self.by_domain.get(domain)
2006 }
2007
2008 fn insert(&mut self, domain: String, key: Arc<rustls::sign::CertifiedKey>) -> Option<String> {
2012 if self.by_domain.insert(domain.clone(), key).is_none() {
2013 self.order.push_back(domain);
2014 }
2015 if self.by_domain.len() <= MAX_HOST_CERTS {
2016 return None;
2017 }
2018 let evicted = self.order.pop_front()?;
2019 self.by_domain.remove(&evicted);
2020 Some(evicted)
2021 }
2022}
2023
2024#[cfg(feature = "proxy-tls")]
2025impl std::fmt::Debug for SniCertResolver {
2026 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2027 f.debug_struct("SniCertResolver").finish_non_exhaustive()
2028 }
2029}
2030
2031#[cfg(feature = "proxy-tls")]
2032impl SniCertResolver {
2033 fn new(
2035 ca_cert_path: &std::path::Path,
2036 ca_key_path: &std::path::Path,
2037 tld: String,
2038 ) -> crate::Result<Self> {
2039 let ca_key_pem = std::fs::read_to_string(ca_key_path)
2040 .map_err(|e| miette::miette!("Failed to read CA key {}: {e}", ca_key_path.display()))?;
2041 let ca_cert_pem = std::fs::read_to_string(ca_cert_path).map_err(|e| {
2042 miette::miette!("Failed to read CA cert {}: {e}", ca_cert_path.display())
2043 })?;
2044
2045 if !ca_cert_pem.contains("BEGIN CERTIFICATE") {
2047 miette::bail!("CA cert file does not contain a valid PEM certificate");
2048 }
2049
2050 let ca_key = rcgen::KeyPair::from_pem(&ca_key_pem)
2051 .map_err(|e| miette::miette!("Failed to parse CA key: {e}"))?;
2052
2053 let issuer = rcgen::Issuer::from_ca_cert_pem(&ca_cert_pem, ca_key)
2055 .map_err(|e| miette::miette!("Failed to parse CA cert: {e}"))?;
2056
2057 let host_certs_root = host_certs_dir_for(ca_cert_path);
2060 let cache_id = ca_cache_id(&ca_cert_pem);
2061 clear_host_certs(&host_certs_root, Some(&cache_id));
2062 let host_certs_dir = host_certs_root.join(&cache_id);
2063 std::fs::create_dir_all(&host_certs_dir)
2064 .map_err(|e| miette::miette!("Failed to create host-certs dir: {e}"))?;
2065 prune_host_certs(&host_certs_dir);
2069
2070 Ok(Self {
2071 issuer,
2072 tld,
2073 host_certs_dir,
2074 cache: std::sync::Mutex::new(CertCache::default()),
2075 pending: std::sync::Mutex::new(std::collections::HashSet::new()),
2076 pending_cv: std::sync::Condvar::new(),
2077 })
2078 }
2079
2080 fn get_or_create_checked(&self, domain: &str) -> Option<Arc<rustls::sign::CertifiedKey>> {
2089 if !crate::proxy::owns_name(&self.tld, domain) {
2090 if let Some(suppressed) = REFUSED_SNI.allow(REFUSAL_LOG_INTERVAL) {
2093 log::warn!(
2094 "Refusing to issue a certificate for {domain:?}: \
2095 the pitchfork CA only signs names under .{} \
2096 ({suppressed} similar refusals since the last message)",
2097 self.tld
2098 );
2099 }
2100 return None;
2101 }
2102 self.get_or_create(domain)
2103 }
2104
2105 fn get_or_create(&self, domain: &str) -> Option<Arc<rustls::sign::CertifiedKey>> {
2128 {
2130 let cache = self.cache.lock().ok()?;
2131 if let Some(ck) = cache.get(domain) {
2132 return Some(Arc::clone(ck));
2133 }
2134 } loop {
2147 {
2148 let mut pending = self.pending.lock().ok()?;
2149 if pending.contains(domain) {
2150 pending = self.pending_cv.wait(pending).ok()?;
2152 drop(pending);
2154 } else {
2155 pending.insert(domain.to_string());
2157 break;
2158 }
2159 } {
2165 let cache = self.cache.lock().ok()?;
2166 if let Some(ck) = cache.get(domain) {
2167 return Some(Arc::clone(ck));
2168 }
2169 } } let result = self.get_or_create_inner(domain);
2173
2174 {
2180 let mut pending = match self.pending.lock() {
2181 Ok(g) => g,
2182 Err(e) => e.into_inner(),
2183 };
2184 pending.remove(domain);
2185 self.pending_cv.notify_all();
2186 }
2187
2188 result
2189 }
2190
2191 fn get_or_create_inner(&self, domain: &str) -> Option<Arc<rustls::sign::CertifiedKey>> {
2193 let disk_path = self.disk_path(domain);
2194
2195 if disk_path.exists() {
2197 if let Ok(ck) = self.load_from_disk(&disk_path) {
2198 let ck = Arc::new(ck);
2199 self.remember(domain, &ck);
2200 return Some(ck);
2201 }
2202 let _ = std::fs::remove_file(&disk_path);
2204 }
2205
2206 let ck = self.sign_for_domain(domain).ok()?;
2208
2209 let ck = Arc::new(ck);
2210 self.remember(domain, &ck);
2211 Some(ck)
2212 }
2213
2214 fn remember(&self, domain: &str, ck: &Arc<rustls::sign::CertifiedKey>) {
2219 let evicted = match self.cache.lock() {
2220 Ok(mut cache) => cache.insert(domain.to_string(), Arc::clone(ck)),
2221 Err(_) => return,
2222 };
2223 if let Some(evicted) = evicted {
2224 let path = self.disk_path(&evicted);
2225 if let Err(e) = std::fs::remove_file(&path)
2226 && e.kind() != std::io::ErrorKind::NotFound
2227 {
2228 log::debug!("Could not evict cached cert {}: {e}", path.display());
2229 }
2230 }
2231 }
2232
2233 fn disk_path(&self, domain: &str) -> std::path::PathBuf {
2235 self.host_certs_dir
2236 .join(format!("{}.pem", cert_cache_file_stem(domain)))
2237 }
2238
2239 fn load_from_disk(&self, path: &std::path::Path) -> crate::Result<rustls::sign::CertifiedKey> {
2244 use rustls::pki_types::CertificateDer;
2245 use rustls_pemfile::{certs, private_key};
2246
2247 let pem = std::fs::read_to_string(path)
2248 .map_err(|e| miette::miette!("Failed to read disk cert {}: {e}", path.display()))?;
2249
2250 let cert_ders: Vec<CertificateDer<'static>> = certs(&mut pem.as_bytes())
2251 .collect::<Result<Vec<_>, _>>()
2252 .map_err(|e| miette::miette!("Failed to parse certs from {}: {e}", path.display()))?;
2253
2254 if cert_ders.is_empty() {
2255 miette::bail!("No certificates found in {}", path.display());
2256 }
2257
2258 {
2260 let (_, cert) = x509_parser::parse_x509_certificate(&cert_ders[0]).map_err(|e| {
2261 miette::miette!("Failed to parse certificate from {}: {e}", path.display())
2262 })?;
2263 use chrono::Utc;
2264 let now_ts = Utc::now().timestamp();
2265 let not_after_ts = cert.validity().not_after.timestamp();
2266 if not_after_ts < now_ts {
2267 miette::bail!(
2268 "Cached certificate at {} has expired — will regenerate",
2269 path.display()
2270 );
2271 }
2272 }
2273
2274 let key_der = private_key(&mut pem.as_bytes())
2275 .map_err(|e| miette::miette!("Failed to parse key from {}: {e}", path.display()))?
2276 .ok_or_else(|| miette::miette!("No private key found in {}", path.display()))?;
2277
2278 let signing_key = rustls::crypto::ring::sign::any_supported_type(&key_der)
2279 .map_err(|e| miette::miette!("Failed to create signing key from disk: {e}"))?;
2280
2281 Ok(rustls::sign::CertifiedKey::new(cert_ders, signing_key))
2282 }
2283
2284 fn sign_for_domain(&self, domain: &str) -> crate::Result<rustls::sign::CertifiedKey> {
2292 use rcgen::date_time_ymd;
2293 use rcgen::{CertificateParams, DistinguishedName, DnType, SanType};
2294 use rustls::pki_types::CertificateDer;
2295 use rustls_pemfile::private_key;
2296
2297 let mut params = CertificateParams::default();
2298 let mut dn = DistinguishedName::new();
2299 dn.push(DnType::CommonName, domain);
2300 params.distinguished_name = dn;
2301
2302 {
2304 use chrono::{Datelike, Duration, Utc};
2305 let yesterday = Utc::now() - Duration::days(1);
2306 let expiry = Utc::now() + Duration::days(397);
2309 params.not_before = date_time_ymd(
2310 yesterday.year(),
2311 yesterday.month() as u8,
2312 yesterday.day() as u8,
2313 );
2314 params.not_after =
2315 date_time_ymd(expiry.year(), expiry.month() as u8, expiry.day() as u8);
2316 }
2317
2318 let mut sans =
2320 vec![SanType::DnsName(domain.to_string().try_into().map_err(
2321 |e| miette::miette!("Invalid domain name '{domain}': {e}"),
2322 )?)];
2323 if let Some(dot_pos) = domain.find('.') {
2330 let parent = &domain[dot_pos + 1..];
2331 if crate::proxy::is_strictly_under_tld(&self.tld, parent) {
2332 let wildcard = format!("*.{parent}");
2333 if let Ok(wc) = wildcard.try_into() {
2334 sans.push(SanType::DnsName(wc));
2335 }
2336 }
2337 }
2338 params.subject_alt_names = sans;
2339
2340 let leaf_key = rcgen::KeyPair::generate()
2341 .map_err(|e| miette::miette!("Failed to generate leaf key: {e}"))?;
2342 let leaf_cert = params
2343 .signed_by(&leaf_key, &self.issuer)
2344 .map_err(|e| miette::miette!("Failed to sign leaf cert for '{domain}': {e}"))?;
2345
2346 let cert_der = CertificateDer::from(leaf_cert.der().to_vec());
2348 let key_pem = leaf_key.serialize_pem();
2349 let key_der = private_key(&mut key_pem.as_bytes())
2350 .map_err(|e| miette::miette!("Failed to parse leaf key PEM: {e}"))?
2351 .ok_or_else(|| miette::miette!("No private key found in generated PEM"))?;
2352
2353 let signing_key = rustls::crypto::ring::sign::any_supported_type(&key_der)
2354 .map_err(|e| miette::miette!("Failed to create signing key: {e}"))?;
2355
2356 let disk_path = self.disk_path(domain);
2359 let combined_pem = format!("{}{}", leaf_cert.pem(), key_pem);
2360 {
2361 #[cfg(unix)]
2362 {
2363 use std::io::Write;
2364 use std::os::unix::fs::OpenOptionsExt;
2365 if let Err(e) = std::fs::OpenOptions::new()
2366 .write(true)
2367 .create(true)
2368 .truncate(true)
2369 .mode(0o600)
2370 .open(&disk_path)
2371 .and_then(|mut f| f.write_all(combined_pem.as_bytes()))
2372 {
2373 log::warn!(
2374 "Failed to persist cert for '{domain}' to {}: {e}",
2375 disk_path.display()
2376 );
2377 }
2378 }
2379 #[cfg(not(unix))]
2380 {
2381 if let Err(e) = std::fs::write(&disk_path, combined_pem) {
2382 log::warn!(
2383 "Failed to persist cert for '{domain}' to {}: {e}",
2384 disk_path.display()
2385 );
2386 } else {
2387 log::debug!(
2388 "Leaf cert for '{domain}' written to {} (file permissions are not \
2389 restricted on non-Unix platforms — consider restricting access manually)",
2390 disk_path.display()
2391 );
2392 }
2393 }
2394 }
2395
2396 Ok(rustls::sign::CertifiedKey::new(vec![cert_der], signing_key))
2397 }
2398}
2399
2400#[cfg(feature = "proxy-tls")]
2401impl rustls::server::ResolvesServerCert for SniCertResolver {
2402 fn resolve(
2403 &self,
2404 client_hello: rustls::server::ClientHello<'_>,
2405 ) -> Option<Arc<rustls::sign::CertifiedKey>> {
2406 let domain = client_hello.server_name()?;
2407 if resolve_tls_mode_in(domain, &self.tld, &slug_snapshot(), ®istry_snapshot())
2414 .is_passthrough()
2415 {
2416 log::warn!(
2417 "Refusing to terminate TLS for '{domain}', which is configured for \
2418 proxy_tls = \"passthrough\": its ClientHello could not be inspected before the \
2419 handshake, so the stream could not be spliced to the daemon."
2420 );
2421 return None;
2422 }
2423
2424 self.get_or_create_checked(domain)
2433 }
2434}
2435
2436#[cfg(feature = "proxy-tls")]
2442pub(crate) fn ca_pair_problem(cert: &std::path::Path, key: &std::path::Path) -> Option<String> {
2443 use rcgen::PublicKeyData;
2444
2445 let cert_pem = match std::fs::read_to_string(cert) {
2446 Ok(p) => p,
2447 Err(e) => return Some(format!("cannot read {}: {e}", cert.display())),
2448 };
2449 let key_pem = match std::fs::read_to_string(key) {
2450 Ok(p) => p,
2451 Err(e) => return Some(format!("cannot read {}: {e}", key.display())),
2452 };
2453 let key_pair = match rcgen::KeyPair::from_pem(&key_pem) {
2454 Ok(k) => k,
2455 Err(e) => return Some(format!("cannot parse {}: {e}", key.display())),
2456 };
2457 let Some(Ok(der)) = rustls_pemfile::certs(&mut cert_pem.as_bytes()).next() else {
2458 return Some(format!("no certificate in {}", cert.display()));
2459 };
2460 let parsed = match x509_parser::parse_x509_certificate(&der) {
2461 Ok((_, c)) => c,
2462 Err(e) => return Some(format!("cannot parse {}: {e}", cert.display())),
2463 };
2464 if parsed.public_key().subject_public_key.data.as_ref() != key_pair.der_bytes() {
2465 return Some(format!(
2466 "{} is not the key for {}",
2467 key.display(),
2468 cert.display()
2469 ));
2470 }
2471 if let Err(e) = rcgen::Issuer::from_ca_cert_pem(&cert_pem, key_pair) {
2472 return Some(format!("{} cannot sign certificates: {e}", cert.display()));
2473 }
2474 None
2475}
2476
2477#[cfg(feature = "proxy-tls")]
2484fn cert_cache_file_stem(domain: &str) -> String {
2485 let mut out = String::with_capacity(domain.len());
2486 for b in domain.bytes() {
2487 if b.is_ascii_alphanumeric() || b == b'-' || b == b'.' {
2488 out.push(char::from(b));
2489 } else {
2490 out.push_str(&format!("%{b:02X}"));
2491 }
2492 }
2493 out
2494}
2495
2496#[derive(Clone)]
2498struct PlainState {
2499 tld: String,
2500 port: u16,
2501 proxy: ProxyState,
2504}
2505
2506async fn plain_fallback_handler(State(state): State<PlainState>, req: Request) -> Response {
2511 if req.method() == axum::http::Method::CONNECT {
2512 let raw_host = get_request_host(&req).unwrap_or_default();
2513 return connect_handler(&state.proxy, req, &raw_host).await;
2514 }
2515 redirect_to_https_handler(req).await
2516}
2517
2518fn reject_non_read(method: &axum::http::Method) -> Option<Response> {
2525 if matches!(*method, axum::http::Method::GET | axum::http::Method::HEAD) {
2526 return None;
2527 }
2528 let mut res = error_response(
2529 StatusCode::METHOD_NOT_ALLOWED,
2530 "the proxy auto-config file is read-only\n",
2531 );
2532 res.headers_mut().insert(
2533 axum::http::header::ALLOW,
2534 HeaderValue::from_static("GET, HEAD"),
2535 );
2536 Some(res)
2537}
2538
2539fn pac_response(tld: &str, host: &str, port: u16) -> Response {
2540 match crate::proxy::pac::generate(tld, host, port) {
2541 Ok(body) => (
2542 StatusCode::OK,
2543 [(
2544 axum::http::header::CONTENT_TYPE,
2545 "application/x-ns-proxy-autoconfig",
2546 )],
2547 body,
2548 )
2549 .into_response(),
2550 Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
2551 }
2552}
2553
2554async fn pac_handler(State(state): State<ProxyState>, req: Request) -> Response {
2561 let host = get_request_host(&req).unwrap_or_default();
2562 let bare = host.split(':').next().unwrap_or("");
2563 if !bare.is_empty() && crate::proxy::is_strictly_under_tld(&state.tld, bare) {
2564 return proxy_handler(State(state), req).await;
2565 }
2566 if let Some(deny) = reject_non_read(req.method()) {
2569 return deny;
2570 }
2571 let port = req
2572 .uri()
2573 .authority()
2574 .and_then(|a| a.port_u16())
2575 .or_else(|| host.rsplit(':').next().and_then(|p| p.parse().ok()))
2576 .unwrap_or(if state.is_tls { 443 } else { 80 });
2577 pac_response(&state.tld, &url_host(state.contact_ip), port)
2578}
2579
2580async fn plain_pac_handler(State(state): State<PlainState>, req: Request) -> Response {
2582 let host = get_request_host(&req).unwrap_or_default();
2586 let bare = host.split(':').next().unwrap_or("");
2587 if !bare.is_empty() && crate::proxy::is_strictly_under_tld(&state.tld, bare) {
2588 return redirect_to_https_handler(req).await;
2589 }
2590 if let Some(deny) = reject_non_read(req.method()) {
2591 return deny;
2592 }
2593 pac_response(&state.tld, &url_host(state.proxy.contact_ip), state.port)
2594}
2595
2596fn local_contact_ip(bind_ip: std::net::IpAddr) -> std::net::IpAddr {
2602 match bind_ip {
2603 std::net::IpAddr::V4(ip) if ip.is_unspecified() => {
2604 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
2605 }
2606 std::net::IpAddr::V6(ip) if ip.is_unspecified() => {
2607 std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)
2608 }
2609 ip => ip,
2610 }
2611}
2612
2613fn url_host(ip: std::net::IpAddr) -> String {
2615 match ip {
2616 std::net::IpAddr::V6(ip) => format!("[{ip}]"),
2617 std::net::IpAddr::V4(ip) => ip.to_string(),
2618 }
2619}
2620
2621fn connect_port(authority: &str) -> Option<u16> {
2623 let (host, port) = authority.rsplit_once(':')?;
2624 if host.contains(':') && !host.ends_with(']') {
2626 return None;
2627 }
2628 port.parse().ok()
2629}
2630
2631async fn connect_handler(state: &ProxyState, req: Request, raw_host: &str) -> Response {
2646 let authority = req
2647 .uri()
2648 .authority()
2649 .map(|a| a.as_str().to_string())
2650 .unwrap_or_else(|| raw_host.to_string());
2651 let host = authority
2652 .rsplit_once(':')
2653 .map(|(h, _)| h)
2654 .unwrap_or(&authority)
2655 .trim_start_matches('[')
2656 .trim_end_matches(']')
2657 .to_string();
2658
2659 if !crate::proxy::owns_name(&state.tld, &host) {
2662 return error_response(
2663 StatusCode::FORBIDDEN,
2664 &format!(
2665 "pitchfork only tunnels CONNECT for names under .{} — refusing {host}",
2666 state.tld
2667 ),
2668 );
2669 }
2670
2671 if !state.is_tls && connect_port(&authority) == Some(443) {
2676 return error_response(
2677 StatusCode::BAD_GATEWAY,
2678 &format!(
2679 "proxy.https is false, so pitchfork cannot serve https://{host}; \
2680 use http:// or enable proxy.https"
2681 ),
2682 );
2683 }
2684
2685 let Some(target) = state.connect_target else {
2686 return error_response(
2687 StatusCode::SERVICE_UNAVAILABLE,
2688 "The proxy listener address is unknown, so CONNECT cannot be tunnelled",
2689 );
2690 };
2691
2692 if state.cancel.is_cancelled() {
2695 return error_response(
2696 StatusCode::SERVICE_UNAVAILABLE,
2697 "The proxy is shutting down",
2698 );
2699 }
2700
2701 let Ok(permit) = Arc::clone(&state.tunnel_slots).try_acquire_owned() else {
2704 if let Some(suppressed) = REFUSED_TUNNEL.allow(REFUSAL_LOG_INTERVAL) {
2705 log::warn!(
2706 "Proxy refused a CONNECT tunnel: {MAX_TUNNELS} already open \
2707 ({suppressed} similar refusals since the last message)"
2708 );
2709 }
2710 return error_response(
2711 StatusCode::SERVICE_UNAVAILABLE,
2712 "Too many CONNECT tunnels are open",
2713 );
2714 };
2715 let cancel = state.cancel.clone();
2716
2717 state.tunnels.spawn(async move {
2723 let _permit = permit;
2725
2726 macro_rules! setup_step {
2739 ($what:literal, $fut:expr) => {
2740 tokio::select! {
2741 r = tokio::time::timeout(HANDSHAKE_TIMEOUT, $fut) => match r {
2742 Ok(Ok(v)) => v,
2743 Ok(Err(e)) => {
2744 if let Some(n) = ABANDONED_TUNNEL.allow(REFUSAL_LOG_INTERVAL) {
2745 log::debug!(
2746 concat!(
2747 "CONNECT {} for {target} failed: {e}",
2748 " ({n} similar since the last message)"
2749 ),
2750 $what,
2751 target = target,
2752 e = e,
2753 n = n
2754 );
2755 }
2756 return;
2757 }
2758 Err(_) => {
2759 if let Some(n) = ABANDONED_TUNNEL.allow(REFUSAL_LOG_INTERVAL) {
2760 log::debug!(
2761 concat!(
2762 "CONNECT {} for {target} did not finish within",
2763 " {timeout:?}",
2764 " ({n} similar since the last message)"
2765 ),
2766 $what,
2767 target = target,
2768 timeout = HANDSHAKE_TIMEOUT,
2769 n = n
2770 );
2771 }
2772 return;
2773 }
2774 },
2775 _ = cancel.cancelled() => {
2778 log::debug!("CONNECT {} for {target} abandoned by shutdown", $what);
2779 return;
2780 }
2781 }
2782 };
2783 }
2784
2785 let upgraded = setup_step!("upgrade", hyper::upgrade::on(req));
2786 let mut client = hyper_util::rt::TokioIo::new(upgraded);
2787 let mut server = setup_step!("connect", tokio::net::TcpStream::connect(target));
2788
2789 tokio::select! {
2794 r = tokio::io::copy_bidirectional(&mut client, &mut server) => {
2795 if let Err(e) = r
2798 && let Some(n) = ABANDONED_TUNNEL.allow(REFUSAL_LOG_INTERVAL)
2799 {
2800 log::debug!(
2801 "CONNECT tunnel to {target} ended: {e} ({n} similar since the last message)"
2802 );
2803 }
2804 }
2805 _ = cancel.cancelled() => {
2806 log::debug!("CONNECT tunnel to {target} closed by shutdown");
2807 }
2808 }
2809 });
2810
2811 Response::builder()
2812 .status(StatusCode::OK)
2813 .header(PITCHFORK_HEADER, "1")
2814 .body(Body::empty())
2815 .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
2816}
2817
2818fn get_request_host(req: &Request) -> Option<String> {
2824 let authority = req
2826 .uri()
2827 .authority()
2828 .map(|a| a.as_str().to_string())
2829 .filter(|s| !s.is_empty());
2830
2831 authority.or_else(|| {
2832 req.headers()
2833 .get(HOST)
2834 .and_then(|h| h.to_str().ok())
2835 .map(str::to_string)
2836 })
2837}
2838
2839fn join_cookie_fields(headers: &mut HeaderMap) {
2845 let fields: Vec<&[u8]> = headers
2846 .get_all(COOKIE)
2847 .iter()
2848 .map(HeaderValue::as_bytes)
2849 .collect();
2850 if fields.len() < 2 {
2851 return;
2852 }
2853
2854 let joined = HeaderValue::from_bytes(&fields.join(b"; ".as_slice()))
2855 .expect("valid header values joined with \"; \" form a valid header value");
2856 headers.insert(COOKIE, joined);
2857}
2858
2859fn inject_forwarded_headers(req: &mut Request, is_tls: bool, host_header: &str) {
2870 let remote_addr = req
2871 .extensions()
2872 .get::<axum::extract::ConnectInfo<SocketAddr>>()
2873 .map(|ci| ci.0.ip().to_string())
2874 .unwrap_or_else(|| "127.0.0.1".to_string());
2875
2876 let proto = if is_tls { "https" } else { "http" };
2877 let default_port = if is_tls { "443" } else { "80" };
2878
2879 let forwarded_for = remote_addr.clone();
2882 let forwarded_proto = proto.to_string();
2883 let forwarded_host = host_header.to_string();
2884 let forwarded_port = host_header
2885 .rsplit_once(':')
2886 .map(|(_, port)| port.to_string())
2887 .unwrap_or_else(|| default_port.to_string());
2888
2889 for name in [
2895 "x-forwarded-for",
2896 "x-forwarded-proto",
2897 "x-forwarded-host",
2898 "x-forwarded-port",
2899 "forwarded",
2900 ] {
2901 if let Ok(header_name) = axum::http::HeaderName::from_bytes(name.as_bytes()) {
2902 req.headers_mut().remove(&header_name);
2903 }
2904 }
2905
2906 let headers = [
2907 ("x-forwarded-for", forwarded_for),
2908 ("x-forwarded-proto", forwarded_proto),
2909 ("x-forwarded-host", forwarded_host),
2910 ("x-forwarded-port", forwarded_port),
2911 ];
2912
2913 for (name, value) in headers {
2914 if let Ok(v) = HeaderValue::from_str(&value) {
2915 let header_name = axum::http::HeaderName::from_static(name);
2916 req.headers_mut().insert(header_name, v);
2917 }
2918 }
2919}
2920
2921async fn proxy_handler(State(state): State<ProxyState>, mut req: Request) -> Response {
2926 let Some(raw_host) = get_request_host(&req) else {
2928 return error_response(StatusCode::BAD_REQUEST, "Missing Host header");
2929 };
2930
2931 if req.method() == axum::http::Method::CONNECT {
2935 return connect_handler(&state, req, &raw_host).await;
2936 }
2937 let host = if raw_host.starts_with('[') {
2941 raw_host
2943 .split("]:")
2944 .next()
2945 .unwrap_or(&raw_host)
2946 .trim_start_matches('[')
2947 .trim_end_matches(']')
2948 .to_string()
2949 } else {
2950 raw_host.split(':').next().unwrap_or(&raw_host).to_string()
2952 };
2953 let host = host.trim_end_matches('.').to_string();
2958
2959 let is_from_pitchfork = req.headers().contains_key(PROXY_HOPS_HEADER);
2970 let hops: u64 = if is_from_pitchfork {
2971 req.headers()
2972 .get(PROXY_HOPS_HEADER)
2973 .and_then(|v| v.to_str().ok())
2974 .and_then(|s| s.parse().ok())
2975 .unwrap_or(0)
2976 } else {
2977 0
2979 };
2980 if hops >= MAX_PROXY_HOPS {
2981 return error_response(
2982 StatusCode::LOOP_DETECTED,
2983 &format!(
2984 "Loop detected for '{host}': request has passed through the proxy {hops} times.\n\
2985 This usually means a backend is proxying back through pitchfork without rewriting \n\
2986 the Host header. If you use Vite/webpack proxy, set changeOrigin: true."
2987 ),
2988 );
2989 }
2990
2991 let local_client = is_local_client(&req);
2992
2993 let target_port = if let Some(subdomain) = strip_tld(&host, &state.tld) {
2995 if subdomain.eq_ignore_ascii_case("pitchfork") {
2996 if let Some(origin) = crate::web::https_origin() {
3000 let path = req
3001 .uri()
3002 .path_and_query()
3003 .map(|pq| pq.as_str())
3004 .unwrap_or("/");
3005 return page_redirect_response(&origin, path);
3006 }
3007 crate::web::port()
3008 } else {
3009 None
3010 }
3011 } else {
3012 None
3013 };
3014
3015 let (target_port, activity, protocol) = if let Some(port) = target_port {
3016 (port, None, ProxyProtocol::Http1)
3017 } else {
3018 if resolve_tls_mode(&host, &state.tld).await.is_passthrough() {
3022 return error_response(
3023 StatusCode::BAD_GATEWAY,
3024 &passthrough_unroutable_message(&host, state.is_tls),
3025 );
3026 }
3027 match resolve_target(&host, &state.tld).await {
3028 ResolveResult::Ready(port, activity, protocol) => (port, activity, protocol),
3029 ResolveResult::Starting { slug } => {
3030 return starting_html_response(&slug, &raw_host);
3031 }
3032 ResolveResult::Page {
3033 project,
3034 worktree,
3035 daemons,
3036 dir,
3037 } => {
3038 if !local_client {
3042 return unknown_host_response(&host, "Not found", &[]);
3043 }
3044 if let Some(base) = crate::web::url()
3051 && let Some(resolved) = dir.clone()
3052 && let Some(path) = tokio::task::spawn_blocking(move || {
3053 crate::web::routes::api::projects::page_path_for_dir(&resolved)
3054 })
3055 .await
3056 .ok()
3057 .flatten()
3058 {
3059 return page_redirect_response(&base, &path);
3060 }
3061 return page_placeholder_response(
3062 &project,
3063 worktree.as_deref(),
3064 &daemons,
3065 &state.tld,
3066 &host_port_suffix(&raw_host),
3067 crate::web::url().as_deref(),
3068 );
3069 }
3070 ResolveResult::Unknown { heading, known } => {
3071 return unknown_host_response(
3074 &host,
3075 if local_client { &heading } else { "Not found" },
3076 if local_client { &known } else { &[] },
3077 );
3078 }
3079 ResolveResult::NotFound => {
3080 return error_response(
3081 StatusCode::BAD_GATEWAY,
3082 &format!(
3083 "No daemon found for host '{host}'.\n\
3084 A daemon is reachable once it configures a `port` and its project is \
3085 known to pitchfork; run `pitchfork proxy status` to see the hostnames \
3086 it serves.\n\
3087 Expected format: <daemon>.<project>.{tld}",
3088 tld = state.tld
3089 ),
3090 );
3091 }
3092 ResolveResult::Error(msg) => {
3093 if local_client {
3094 return error_response(StatusCode::BAD_GATEWAY, &msg);
3095 }
3096 log::warn!("Refused '{host}' for a non-local client: {msg}");
3098 return error_response(
3099 StatusCode::BAD_GATEWAY,
3100 &format!("'{host}' is not available."),
3101 );
3102 }
3103 }
3104 };
3105 let path_and_query = req
3107 .uri()
3108 .path_and_query()
3109 .map(|pq| pq.as_str())
3110 .unwrap_or("/");
3111
3112 let forward_uri = match Uri::builder()
3113 .scheme("http")
3114 .authority(format!("localhost:{target_port}"))
3115 .path_and_query(path_and_query)
3116 .build()
3117 {
3118 Ok(uri) => uri,
3119 Err(e) => {
3120 return error_response(
3121 StatusCode::INTERNAL_SERVER_ERROR,
3122 &format!("Failed to build forward URI: {e}"),
3123 );
3124 }
3125 };
3126
3127 let h2c = protocol.is_h2c();
3128 if h2c && req.headers().contains_key(axum::http::header::UPGRADE) {
3129 return error_response(
3130 StatusCode::NOT_IMPLEMENTED,
3131 &format!(
3132 "'{host}' uses proxy_protocol = \"h2c\", which cannot carry protocol upgrades \
3133 such as WebSocket. Remove proxy_protocol, or connect without an Upgrade header."
3134 ),
3135 );
3136 }
3137 if h2c {
3138 let nominated: Vec<axum::http::HeaderName> = req
3142 .headers()
3143 .get_all(axum::http::header::CONNECTION)
3144 .iter()
3145 .filter_map(|v| v.to_str().ok())
3146 .flat_map(|v| v.split(','))
3147 .filter_map(|t| axum::http::HeaderName::from_bytes(t.trim().as_bytes()).ok())
3148 .collect();
3149 for name in nominated {
3150 if name != axum::http::header::TE {
3151 req.headers_mut().remove(&name);
3152 }
3153 }
3154 for h in HOP_BY_HOP_HEADERS {
3155 if let Ok(name) = axum::http::HeaderName::from_bytes(h.as_bytes()) {
3156 req.headers_mut().remove(&name);
3157 }
3158 }
3159 }
3160
3161 *req.uri_mut() = forward_uri;
3163 req.headers_mut().insert(
3164 HOST,
3165 HeaderValue::from_str(&format!("localhost:{target_port}"))
3166 .unwrap_or_else(|_| HeaderValue::from_static("localhost")),
3167 );
3168
3169 inject_forwarded_headers(&mut req, state.is_tls, &raw_host);
3171
3172 if let Ok(v) = HeaderValue::from_str(&(hops + 1).to_string()) {
3174 req.headers_mut()
3175 .insert(axum::http::HeaderName::from_static(PROXY_HOPS_HEADER), v);
3176 }
3177
3178 let pseudo_headers: Vec<_> = req
3183 .headers()
3184 .keys()
3185 .filter(|k| k.as_str().starts_with(':'))
3186 .cloned()
3187 .collect();
3188 for key in pseudo_headers {
3189 req.headers_mut().remove(&key);
3190 }
3191
3192 join_cookie_fields(req.headers_mut());
3193
3194 *req.version_mut() = if h2c {
3199 axum::http::Version::HTTP_2
3200 } else {
3201 axum::http::Version::HTTP_11
3202 };
3203
3204 let client_upgrade = hyper::upgrade::on(&mut req);
3206
3207 let result = match tokio::time::timeout(std::time::Duration::from_secs(120), async {
3215 if h2c {
3216 state.h2c_client.request(req).await
3217 } else {
3218 state.client.request(req).await
3219 }
3220 })
3221 .await
3222 {
3223 Ok(r) => r,
3224 Err(_elapsed) => {
3225 let msg = format!(
3226 "Request to daemon on port {target_port} timed out after 120 s.\n\
3227 The daemon accepted the connection but did not respond in time."
3228 );
3229 log::warn!("{msg}");
3230 if let Some(ref on_error) = state.on_error {
3231 on_error(&msg);
3232 }
3233 return error_response(StatusCode::GATEWAY_TIMEOUT, &msg);
3234 }
3235 };
3236 match result {
3237 Ok(mut resp) => {
3238 let backend_upgrade = hyper::upgrade::on(&mut resp);
3240 let (mut parts, body) = resp.into_parts();
3241
3242 parts.headers.insert(
3244 axum::http::HeaderName::from_static(PITCHFORK_HEADER),
3245 HeaderValue::from_static("1"),
3246 );
3247
3248 parts.headers.remove(PROXY_HOPS_HEADER);
3250
3251 if state.is_tls && parts.status != StatusCode::SWITCHING_PROTOCOLS {
3256 for h in HOP_BY_HOP_HEADERS {
3257 if let Ok(name) = axum::http::HeaderName::from_bytes(h.as_bytes()) {
3258 parts.headers.remove(&name);
3259 }
3260 }
3261 }
3262
3263 if parts.status == StatusCode::SWITCHING_PROTOCOLS {
3265 let cancel = state.cancel.clone();
3273 state.tunnels.spawn(async move {
3274 let _activity = activity;
3277 let splice = async move {
3278 if let (Ok(client_upgraded), Ok(backend_upgraded)) =
3279 (client_upgrade.await, backend_upgrade.await)
3280 {
3281 let mut client_io = hyper_util::rt::TokioIo::new(client_upgraded);
3282 let mut backend_io = hyper_util::rt::TokioIo::new(backend_upgraded);
3283 let _ = tokio::io::copy_bidirectional(&mut client_io, &mut backend_io)
3291 .await;
3292 }
3293 };
3294 tokio::select! {
3298 _ = splice => {}
3299 _ = cancel.cancelled() => {}
3300 }
3301 });
3302 return Response::from_parts(parts, Body::empty());
3303 }
3304
3305 Response::from_parts(parts, Body::new(GuardedBody::new(body, activity)))
3311 }
3312 Err(e) => {
3313 let msg = format!(
3314 "Failed to connect to daemon on port {target_port}: {e}\n\
3315 The daemon may have stopped or is not yet ready."
3316 );
3317 if let Some(ref on_error) = state.on_error {
3318 on_error(&msg);
3319 } else {
3320 log::warn!("{msg}");
3321 }
3322 error_response(StatusCode::BAD_GATEWAY, &msg)
3323 }
3324 }
3325}
3326
3327fn passthrough_unroutable_message(host: &str, is_tls: bool) -> String {
3337 if is_tls {
3338 format!(
3339 "'{host}' uses proxy_tls = \"passthrough\", which routes on the host name \
3340 in the TLS ClientHello.\n\
3341 This connection's TLS handshake named a different host, so it was \
3342 terminated here and the request inside it cannot be spliced to the \
3343 daemon.\n\
3344 Make the connection itself name '{host}' rather than overriding the Host \
3345 header of a connection opened to something else."
3346 )
3347 } else {
3348 format!(
3349 "'{host}' uses proxy_tls = \"passthrough\", but the proxy is serving \
3350 plain HTTP.\n\
3351 Passthrough splices a TLS stream to the daemon, so it requires \
3352 settings.proxy.https = true.\n\
3353 Enable HTTPS on the proxy, or set proxy_tls = \"terminate\" on the daemon."
3354 )
3355 }
3356}
3357
3358async fn resolve_target(host: &str, tld: &str) -> ResolveResult {
3377 let deadline = auto_start_deadline();
3380 let ctx = match resolve_route_context(host, tld).await {
3381 Ok(ctx) => ctx,
3382 Err(result) => return result,
3383 };
3384
3385 let daemons = {
3386 let state_file = SUPERVISOR.state_file.lock().await;
3387 state_file.daemons.clone()
3388 };
3389
3390 let daemon_name = &ctx.cached.daemon_name;
3391 let running_matches: Vec<(&DaemonId, &crate::daemon::Daemon)> = daemons
3392 .iter()
3393 .filter(|(id, d)| {
3394 id.name() == daemon_name
3395 && d.status.is_running()
3396 && match &ctx.expected_namespace {
3397 Some(ns) => id.namespace() == ns,
3398 None => true,
3399 }
3400 })
3401 .collect();
3402
3403 match running_matches.as_slice() {
3404 [] => {
3405 try_auto_start(
3406 &ctx.cached.slug,
3407 &ctx.cached,
3408 ctx.worktree_dir.as_deref(),
3409 ctx.expected_namespace.as_deref(),
3410 &ctx.route,
3411 deadline,
3412 )
3413 .await
3414 }
3415 [(id, d), ..] => match select_daemon_port(&ctx.route, d) {
3418 Some(port) => match begin_running(id, deadline).await {
3419 Running::Yes(activity) => {
3420 ResolveResult::Ready(port, Some(activity), ctx.route.protocol)
3421 }
3422 Running::Stopping => ResolveResult::Starting {
3423 slug: ctx.cached.slug.clone(),
3424 },
3425 Running::No => {
3426 try_auto_start(
3427 &ctx.cached.slug,
3428 &ctx.cached,
3429 ctx.worktree_dir.as_deref(),
3430 ctx.expected_namespace.as_deref(),
3431 &ctx.route,
3432 deadline,
3433 )
3434 .await
3435 }
3436 },
3437 None => ResolveResult::NotFound,
3438 },
3439 }
3440}
3441
3442enum Running {
3445 Yes(ActivityGuard),
3447 Stopping,
3449 No,
3452}
3453
3454fn auto_start_deadline() -> tokio::time::Instant {
3457 tokio::time::Instant::now() + settings().proxy_auto_start_timeout()
3458}
3459
3460async fn wait_out_idle_stops(ids: &[DaemonId], deadline: tokio::time::Instant) -> bool {
3467 while ids.iter().any(|id| ACTIVITY.is_idle_stopping(id)) {
3468 if tokio::time::Instant::now() >= deadline {
3469 return false;
3470 }
3471 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3472 }
3473 true
3474}
3475
3476async fn begin_running(id: &DaemonId, deadline: tokio::time::Instant) -> Running {
3487 let activity = match ACTIVITY.begin(id) {
3488 Some(activity) => activity,
3489 None => {
3490 if !wait_out_idle_stops(std::slice::from_ref(id), deadline).await {
3491 return Running::Stopping;
3492 }
3493 match ACTIVITY.begin(id) {
3494 Some(activity) => activity,
3495 None => return Running::Stopping,
3497 }
3498 }
3499 };
3500 let running = {
3501 let state_file = SUPERVISOR.state_file.lock().await;
3502 state_file
3503 .daemons
3504 .get(id)
3505 .is_some_and(|d| d.status.is_running())
3506 };
3507 if running {
3508 Running::Yes(activity)
3509 } else {
3510 Running::No
3511 }
3512}
3513
3514struct RouteContext {
3518 cached: CachedSlugEntry,
3519 expected_namespace: Option<String>,
3520 worktree_dir: Option<std::path::PathBuf>,
3521 route: ProxyTlsRoute,
3522}
3523
3524async fn resolve_route_context(host: &str, tld: &str) -> Result<RouteContext, ResolveResult> {
3533 let Some(subdomain) = strip_tld(host, tld) else {
3534 return Err(ResolveResult::NotFound);
3535 };
3536
3537 let cached = cached_slug_lookup(&subdomain).await.filter(|cached| {
3538 if crate::proxy::hostname::hostname_fits(&cached.slug) {
3542 return true;
3543 }
3544 crate::proxy::hostname::warn_once(&format!(
3545 "Slug '{}' plus the configured proxy.tld is over the DNS length limit, \
3546 so it is not routed.",
3547 cached.slug
3548 ));
3549 false
3550 });
3551 let Some(cached) = cached else {
3552 return Err(resolve_registry_target(&subdomain).await);
3555 };
3556
3557 let (expected_namespace, worktree_dir, route) = if !subdomain.eq_ignore_ascii_case(&cached.slug)
3561 {
3562 let prefix = strip_dot_suffix_ignore_case(&subdomain, &cached.slug);
3563 match prefix {
3564 Some(ref p) => match match_worktree_prefix(&cached, p) {
3565 PrefixMatch::Worktree(wt) => {
3566 let ns = wt.namespace.clone().or_else(|| {
3567 log::warn!(
3568 "Worktree '{}' has no cached namespace; \
3569 falling back to parent slug namespace.",
3570 wt.path.display()
3571 );
3572 cached.namespace.clone()
3573 });
3574 let route = worktree_route(&cached, &wt.sanitized_branch);
3575 (ns, Some(wt.path.clone()), route)
3576 }
3577 PrefixMatch::Ambiguous => {
3578 return Err(ResolveResult::Error(format!(
3579 "'{host}' is ambiguous: more than one branch or workspace of '{slug}' \
3580 sanitizes to the prefix '{p}', and host names are case-insensitive.\n\
3581 Rename one of them so the prefixes differ by more than case, then \
3582 reload.\n\
3583 The supervisor log lists the colliding branches.",
3584 slug = cached.slug,
3585 )));
3586 }
3587 PrefixMatch::Unknown => (cached.namespace.clone(), None, cached.tls),
3588 },
3589 None => (cached.namespace.clone(), None, cached.tls),
3590 }
3591 } else {
3592 (cached.namespace.clone(), None, cached.tls)
3593 };
3594
3595 Ok(RouteContext {
3596 cached,
3597 expected_namespace,
3598 worktree_dir,
3599 route,
3600 })
3601}
3602
3603pub(crate) async fn resolve_tls_mode(host: &str, tld: &str) -> ProxyTlsMode {
3610 let entries = get_cached_slugs().await;
3611 let registry = get_cached_host_registry().await;
3612 resolve_tls_mode_in(host, tld, &entries, ®istry)
3613}
3614
3615fn resolve_tls_mode_in(
3620 host: &str,
3621 tld: &str,
3622 entries: &std::collections::HashMap<String, CachedSlugEntry>,
3623 registry: &crate::proxy::hostname::HostRegistry,
3624) -> ProxyTlsMode {
3625 let Some(subdomain) = strip_tld(host, tld) else {
3626 return ProxyTlsMode::Terminate;
3627 };
3628 let wildcard = settings().proxy.wildcard;
3629
3630 if let Some(cached) = wildcard_slug_lookup(&subdomain, entries, wildcard)
3632 && crate::proxy::hostname::hostname_fits(&cached.slug)
3633 {
3634 if !subdomain.eq_ignore_ascii_case(&cached.slug)
3636 && let Some(prefix) = strip_dot_suffix_ignore_case(&subdomain, &cached.slug)
3637 && let PrefixMatch::Worktree(wt) = match_worktree_prefix(cached, &prefix)
3638 {
3639 return worktree_route(cached, &wt.sanitized_branch).mode;
3640 }
3641 return cached.tls.mode;
3642 }
3643
3644 match registry.resolve(&subdomain, wildcard) {
3647 crate::proxy::hostname::HostTarget::Daemon { proxy_tls, .. } => {
3648 proxy_tls.unwrap_or_default()
3649 }
3650 _ => ProxyTlsMode::Terminate,
3653 }
3654}
3655
3656fn select_daemon_port(route: &ProxyTlsRoute, daemon: &crate::daemon::Daemon) -> Option<u16> {
3673 let Some(want) = route.port else {
3674 let detected = daemon.active_port.filter(|&p| p != 0);
3683 let first_declared = daemon.resolved_port.iter().copied().find(|&p| p != 0);
3684 return if route.mode.is_passthrough() {
3685 first_declared.or(detected)
3686 } else {
3687 detected.or(first_declared)
3688 };
3689 };
3690
3691 let configured = daemon
3692 .port
3693 .as_ref()
3694 .map(|p| p.expect.as_slice())
3695 .unwrap_or(&[]);
3696 if let Some(idx) = configured.iter().position(|&p| p == want)
3697 && let Some(&resolved) = daemon.resolved_port.get(idx)
3698 {
3699 return (resolved != 0).then_some(resolved);
3705 }
3706 if daemon.resolved_port.contains(&want) {
3707 return Some(want);
3708 }
3709 if daemon.resolved_port.is_empty() {
3710 return Some(want);
3713 }
3714 crate::proxy::hostname::warn_once(&format!(
3717 "Daemon {} has proxy_tls_port {want}, which is not among its resolved ports {:?}; \
3718 refusing to route rather than forwarding to a port it never bound. \
3719 Restart the daemon if its ports changed.",
3720 daemon.id, daemon.resolved_port,
3721 ));
3722 None
3723}
3724
3725struct AutoStartGuard {
3732 daemon_id: DaemonId,
3733}
3734
3735impl Drop for AutoStartGuard {
3736 fn drop(&mut self) {
3737 let daemon_id = self.daemon_id.clone();
3738 tokio::spawn(async move {
3742 AUTO_START_IN_PROGRESS.lock().await.remove(&daemon_id);
3743 });
3744 }
3745}
3746
3747static STARTUP_LOCKS: once_cell::sync::Lazy<
3761 std::sync::Mutex<std::collections::HashMap<DaemonId, std::sync::Weak<tokio::sync::Mutex<()>>>>,
3762> = once_cell::sync::Lazy::new(Default::default);
3763
3764async fn lock_startup_graph(mut ids: Vec<DaemonId>) -> Vec<tokio::sync::OwnedMutexGuard<()>> {
3767 ids.sort();
3768 ids.dedup();
3769 let locks: Vec<Arc<tokio::sync::Mutex<()>>> = {
3770 let mut map = STARTUP_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
3771 map.retain(|_, lock| lock.strong_count() > 0);
3772 ids.into_iter()
3773 .map(|id| {
3774 let entry = map.entry(id).or_default();
3775 entry.upgrade().unwrap_or_else(|| {
3776 let lock = Arc::new(tokio::sync::Mutex::new(()));
3777 *entry = Arc::downgrade(&lock);
3778 lock
3779 })
3780 })
3781 .collect()
3782 };
3783 let mut guards = Vec::with_capacity(locks.len());
3784 for lock in locks {
3785 guards.push(lock.lock_owned().await);
3786 }
3787 guards
3788}
3789
3790async fn try_auto_start(
3804 slug: &str,
3805 cached: &CachedSlugEntry,
3806 worktree_dir: Option<&std::path::Path>,
3807 expected_namespace: Option<&str>,
3808 route: &ProxyTlsRoute,
3809 deadline: tokio::time::Instant,
3810) -> ResolveResult {
3811 let s = settings();
3812 if !s.proxy.auto_start {
3813 return ResolveResult::NotFound;
3814 }
3815
3816 let ns = expected_namespace
3817 .map(|s| s.to_string())
3818 .or_else(|| cached.namespace.clone())
3819 .unwrap_or_else(|| "global".to_string());
3820 let daemon_id = match DaemonId::try_new(&ns, &cached.daemon_name) {
3821 Ok(id) => id,
3822 Err(_) => return ResolveResult::NotFound,
3823 };
3824
3825 {
3826 let mut in_progress = AUTO_START_IN_PROGRESS.lock().await;
3827 if !in_progress.insert(daemon_id.clone()) {
3828 return ResolveResult::Starting {
3829 slug: slug.to_string(),
3830 };
3831 }
3832 }
3833
3834 let guard = Arc::new(AutoStartGuard {
3837 daemon_id: daemon_id.clone(),
3838 });
3839
3840 let timeout = s.proxy_auto_start_timeout();
3843 let timed_out = || {
3844 log::warn!("Auto-start: total timeout ({timeout:?}) exceeded for daemon {daemon_id}");
3845 ResolveResult::Error(format!(
3846 "Auto-start for '{daemon_id}' timed out after {timeout:?}.\n\
3847 The daemon and its dependencies did not all become ready, with the daemon \
3848 bound to a port, within the configured proxy_auto_start_timeout.\n\
3849 Startup continues in the background; reload to check again.\n\
3850 Increase the timeout or check the logs of the daemon and its dependencies \
3851 for slow startup."
3852 ))
3853 };
3854
3855 log::info!("Auto-start: starting daemon {daemon_id} for slug '{slug}'");
3856 let start = tokio::spawn({
3857 let guard = guard.clone();
3858 let daemon_id = daemon_id.clone();
3859 let config_dir = worktree_dir.unwrap_or(&cached.dir).to_path_buf();
3860 async move {
3861 let _guard = guard;
3862 start_with_dependencies(&daemon_id, &config_dir).await
3863 }
3864 });
3865 match tokio::time::timeout_at(deadline, start).await {
3866 Ok(Ok(Ok(()))) => {}
3867 Ok(Ok(Err(result))) => return result,
3868 Ok(Err(e)) => {
3869 log::warn!("Auto-start: start task for {daemon_id} failed: {e}");
3870 return ResolveResult::Error(format!("Failed to start daemon '{daemon_id}': {e}"));
3871 }
3872 Err(_elapsed) => return timed_out(),
3873 }
3874
3875 let result =
3876 tokio::time::timeout_at(deadline, wait_for_active_port(slug, &daemon_id, route)).await;
3877 drop(guard);
3878 result.unwrap_or_else(|_elapsed| timed_out())
3879}
3880
3881async fn start_with_dependencies(
3891 daemon_id: &DaemonId,
3892 config_dir: &std::path::Path,
3893) -> std::result::Result<(), ResolveResult> {
3894 let loaded =
3895 crate::pitchfork_toml::PitchforkToml::all_merged_all_namespaces_from(config_dir).await;
3896 let pt = match loaded {
3897 Ok(pt) => pt,
3898 Err(e) => {
3899 log::warn!(
3900 "Auto-start: failed to load config from {}: {e}",
3901 config_dir.display()
3902 );
3903 return Err(ResolveResult::NotFound);
3904 }
3905 };
3906
3907 if !pt.daemons.contains_key(daemon_id) {
3908 log::debug!(
3909 "Auto-start: daemon {daemon_id} not found in config at {}",
3910 config_dir.display()
3911 );
3912 return Err(ResolveResult::NotFound);
3913 }
3914
3915 if SUPERVISOR
3917 .state_file
3918 .lock()
3919 .await
3920 .disabled
3921 .contains(daemon_id)
3922 {
3923 return Err(ResolveResult::Error(format!(
3924 "Daemon '{daemon_id}' is disabled, so it is not started.\n\
3925 Enable it with: pitchfork enable {daemon_id}"
3926 )));
3927 }
3928
3929 let graph: Vec<DaemonId> =
3930 match crate::deps::resolve_dependencies(std::slice::from_ref(daemon_id), &pt.daemons) {
3931 Ok(order) => order.levels.into_iter().flatten().collect(),
3932 Err(e) => {
3933 log::warn!("Auto-start: cannot resolve dependencies of {daemon_id}: {e}");
3934 return Err(ResolveResult::Error(format!(
3935 "Cannot start '{daemon_id}': {e}"
3936 )));
3937 }
3938 };
3939 let _activity = match ACTIVITY.begin_all(&graph) {
3947 Some(activity) => activity,
3948 None => {
3949 wait_out_idle_stops(&graph, auto_start_deadline()).await;
3950 match ACTIVITY.begin_all(&graph) {
3951 Some(activity) => activity,
3952 None => {
3953 return Err(ResolveResult::Error(format!(
3954 "A dependency of '{daemon_id}' is still being stopped for inactivity.\n\
3955 Reload to start it again."
3956 )));
3957 }
3958 }
3959 }
3960 };
3961 let proxy_idle = proxy_idle_timeouts(daemon_id, &graph, &pt).await;
3962 let _locks = lock_startup_graph(graph).await;
3963
3964 let ipc = match crate::ipc::client::IpcClient::connect(false).await {
3967 Ok(ipc) => Arc::new(ipc),
3968 Err(e) => {
3969 log::warn!("Auto-start: failed to connect to the supervisor: {e}");
3970 return Err(ResolveResult::Error(format!(
3971 "Failed to start daemon '{daemon_id}': {e}"
3972 )));
3973 }
3974 };
3975 let opts = crate::ipc::batch::StartOptions {
3976 quiet: true,
3977 proxy_idle: Some(proxy_idle),
3978 ..Default::default()
3979 };
3980 let result = match ipc
3981 .start_daemons_with_config(std::slice::from_ref(daemon_id), opts, pt)
3982 .await
3983 {
3984 Ok(result) => result,
3985 Err(e) => {
3986 log::warn!("Auto-start: failed to start {daemon_id}: {e}");
3987 return Err(ResolveResult::Error(format!(
3988 "Failed to start daemon '{daemon_id}': {e}"
3989 )));
3990 }
3991 };
3992 if !result.any_failed {
3993 return Ok(());
3994 }
3995
3996 let message = match result.failed.first() {
3997 Some((id, reason)) if id == daemon_id => {
3998 format!("Daemon '{daemon_id}' failed to start: {reason}\nCheck its logs for errors.")
3999 }
4000 Some((dep, reason)) => format!(
4001 "Daemon '{daemon_id}' was not started because its dependency '{dep}' failed: \
4002 {reason}\n\
4003 Check the logs of '{dep}' for errors."
4004 ),
4005 None => format!(
4006 "Daemon '{daemon_id}' or one of its dependencies failed to start.\n\
4007 Check the supervisor log for errors."
4008 ),
4009 };
4010 log::warn!("Auto-start: {message}");
4011 Err(ResolveResult::Error(message))
4012}
4013
4014async fn wait_for_active_port(
4016 slug: &str,
4017 daemon_id: &DaemonId,
4018 route: &ProxyTlsRoute,
4019) -> ResolveResult {
4020 let poll_interval = std::time::Duration::from_millis(250);
4021
4022 loop {
4023 let daemons = {
4024 let sf = SUPERVISOR.state_file.lock().await;
4025 sf.daemons.clone()
4026 };
4027
4028 if let Some(d) = daemons.get(daemon_id) {
4029 if d.status.is_running() {
4030 if let Some(port) = select_daemon_port(route, d) {
4035 return match ACTIVITY.begin(daemon_id) {
4043 Some(activity) => {
4044 log::info!("Auto-start: daemon {daemon_id} is ready on port {port}");
4045 ResolveResult::Ready(port, Some(activity), route.protocol)
4046 }
4047 None => ResolveResult::Starting {
4048 slug: slug.to_string(),
4049 },
4050 };
4051 }
4052 } else {
4053 log::warn!(
4054 "Auto-start: daemon {daemon_id} is no longer running (status: {})",
4055 d.status
4056 );
4057 return ResolveResult::Error(format!(
4058 "Daemon '{daemon_id}' started but exited unexpectedly.\n\
4059 Check its logs for errors."
4060 ));
4061 }
4062 } else {
4063 log::warn!("Auto-start: daemon {daemon_id} not found in state file after start");
4064 return ResolveResult::Error(format!(
4065 "Daemon '{daemon_id}' started but disappeared from the state file.\n\
4066 Check its logs for errors."
4067 ));
4068 }
4069
4070 tokio::time::sleep(poll_interval).await;
4071 }
4072}
4073
4074async fn proxy_idle_timeouts(
4086 daemon_id: &DaemonId,
4087 closure: &[DaemonId],
4088 pt: &crate::pitchfork_toml::PitchforkToml,
4089) -> std::collections::HashMap<DaemonId, u64> {
4090 let own = |id: &DaemonId| pt.daemons.get(id).and_then(|d| d.proxy_idle_timeout);
4091 let target = match own(daemon_id) {
4092 Some(configured) => configured.duration(),
4093 None => {
4094 let project_dir = crate::ipc::batch::resolve_config_base_dir(
4096 pt.daemons.get(daemon_id).and_then(|d| d.path.as_deref()),
4097 );
4098 tokio::task::spawn_blocking(move || {
4099 crate::settings::Settings::load_from_dir(&project_dir).proxy_idle_timeout()
4100 })
4101 .await
4102 .ok()
4103 .flatten()
4104 }
4105 };
4106 let millis = |d: std::time::Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
4107 closure
4108 .iter()
4109 .filter_map(|id| {
4110 let grace = if id == daemon_id {
4111 target
4112 } else {
4113 own(id).map_or(target, |configured| configured.duration())
4114 };
4115 grace.map(|g| (id.clone(), millis(g)))
4116 })
4117 .collect()
4118}
4119
4120async fn resolve_registry_target(subdomain: &str) -> ResolveResult {
4125 let registry = get_cached_host_registry().await;
4126 if !crate::proxy::hostname::hostname_fits(subdomain) {
4127 return ResolveResult::Unknown {
4129 heading: "Host name too long".to_string(),
4130 known: registry.project_labels(),
4131 };
4132 }
4133 match registry.resolve(subdomain, settings().proxy.wildcard) {
4134 crate::proxy::hostname::HostTarget::Daemon {
4135 ref dir,
4136 ref namespace,
4137 ref daemon,
4138 proxy_tls,
4139 proxy_protocol,
4140 proxy_tls_port,
4141 ..
4142 } => {
4143 let route = ProxyTlsRoute {
4148 mode: proxy_tls.unwrap_or_default(),
4149 protocol: proxy_protocol.unwrap_or_default(),
4150 port: proxy_tls_port,
4151 };
4152 let per_checkout = registry.shares_daemon_id(namespace, daemon);
4157 resolve_registry_daemon(subdomain, dir, namespace, daemon, per_checkout, &route).await
4158 }
4159 crate::proxy::hostname::HostTarget::ProjectPage { project } => {
4160 let entry = registry.projects.get(&project);
4161 ResolveResult::Page {
4162 daemons: entry.map(|p| p.primary.labels()).unwrap_or_default(),
4163 dir: entry.map(|p| p.primary.dir.clone()),
4164 project,
4165 worktree: None,
4166 }
4167 }
4168 crate::proxy::hostname::HostTarget::WorktreePage { project, worktree } => {
4169 let checkout = registry
4170 .projects
4171 .get(&project)
4172 .and_then(|p| p.worktrees.get(&worktree));
4173 ResolveResult::Page {
4174 daemons: checkout.map(|c| c.labels()).unwrap_or_default(),
4175 dir: checkout.map(|c| c.dir.clone()),
4176 project,
4177 worktree: Some(worktree),
4178 }
4179 }
4180 crate::proxy::hostname::HostTarget::UnknownProject { known } => ResolveResult::Unknown {
4181 heading: "Unknown project".to_string(),
4182 known,
4183 },
4184 crate::proxy::hostname::HostTarget::UnknownDaemon {
4185 project,
4186 worktree,
4187 known,
4188 } => ResolveResult::Unknown {
4189 heading: match worktree {
4190 Some(wt) => format!("Unknown daemon in '{wt}' of project '{project}'"),
4191 None => format!("Unknown daemon in project '{project}'"),
4192 },
4193 known,
4194 },
4195 }
4196}
4197
4198async fn resolve_registry_daemon(
4205 host: &str,
4206 dir: &std::path::Path,
4207 namespace: &str,
4208 daemon: &str,
4209 per_checkout: bool,
4210 route: &ProxyTlsRoute,
4211) -> ResolveResult {
4212 let deadline = auto_start_deadline();
4214 let daemons = {
4215 let state_file = SUPERVISOR.state_file.lock().await;
4216 state_file.daemons.clone()
4217 };
4218
4219 let mut matches: Vec<crate::daemon::Daemon> = daemons
4220 .iter()
4221 .filter(|(id, d)| {
4222 id.name() == daemon && id.namespace() == namespace && d.status.is_running()
4223 })
4224 .map(|(_, d)| d.clone())
4225 .collect();
4226 matches = sort_by_checkout(matches, dir).await;
4229
4230 if let Some(d) = matches.first() {
4231 if per_checkout && !runs_in_checkout(d.clone(), dir).await {
4234 return ResolveResult::Error(format!(
4235 "'{host}' belongs to the checkout at {}, but daemon '{namespace}/{daemon}' is \
4236 running from {}.\n\
4237 These checkouts share the namespace '{namespace}', so pitchfork cannot run \
4238 both copies at once.\n\
4239 Give each checkout its own top-level `namespace`, or stop the other one first.",
4240 dir.display(),
4241 d.dir
4242 .as_deref()
4243 .map(|p| p.display().to_string())
4244 .unwrap_or_else(|| "an unknown directory".to_string()),
4245 ));
4246 }
4247 let Some(port) = select_daemon_port(route, d) else {
4248 return ResolveResult::NotFound;
4249 };
4250 match begin_running(&d.id, deadline).await {
4251 Running::Yes(activity) => {
4252 return ResolveResult::Ready(port, Some(activity), route.protocol);
4253 }
4254 Running::Stopping => {
4255 return ResolveResult::Starting {
4256 slug: host.to_string(),
4257 };
4258 }
4259 Running::No => {}
4261 }
4262 }
4263
4264 let cached = CachedSlugEntry {
4265 slug: host.to_string(),
4266 namespace: Some(namespace.to_string()),
4267 daemon_name: daemon.to_string(),
4268 dir: dir.to_path_buf(),
4269 worktrees: vec![],
4270 rejected_worktree_prefixes: std::collections::HashSet::new(),
4271 tls: *route,
4272 worktree_tls: std::collections::HashMap::new(),
4273 };
4274 let result = try_auto_start(host, &cached, None, Some(namespace), route, deadline).await;
4275
4276 if per_checkout && let ResolveResult::Ready(..) = result {
4280 let started = {
4281 let state_file = SUPERVISOR.state_file.lock().await;
4282 state_file
4283 .daemons
4284 .iter()
4285 .find(|(id, _)| id.name() == daemon && id.namespace() == namespace)
4286 .map(|(_, d)| d.clone())
4287 };
4288 if let Some(d) = started
4289 && !runs_in_checkout(d.clone(), dir).await
4290 {
4291 return ResolveResult::Error(format!(
4292 "'{host}' belongs to the checkout at {}, but daemon '{namespace}/{daemon}' is \
4293 running from {}.\n\
4294 These checkouts share the namespace '{namespace}', so pitchfork cannot run \
4295 both copies at once.\n\
4296 Give each checkout its own top-level `namespace`, or stop the other one first.",
4297 dir.display(),
4298 d.dir
4299 .as_deref()
4300 .map(|p| p.display().to_string())
4301 .unwrap_or_else(|| "an unknown directory".to_string()),
4302 ));
4303 }
4304 }
4305
4306 result
4307}
4308
4309fn is_local_client(req: &Request) -> bool {
4316 req.extensions()
4319 .get::<axum::extract::ConnectInfo<SocketAddr>>()
4320 .is_some_and(|ci| ci.0.ip().is_loopback())
4321}
4322
4323fn daemon_runs_in(daemon: &crate::daemon::Daemon, checkout: &std::path::Path) -> bool {
4332 daemon
4333 .dir
4334 .as_deref()
4335 .is_some_and(|d| crate::proxy::hostname::checkout_root_of(d) == checkout)
4336}
4337
4338async fn runs_in_checkout(daemon: crate::daemon::Daemon, checkout: &std::path::Path) -> bool {
4340 let checkout = checkout.to_path_buf();
4341 tokio::task::spawn_blocking(move || daemon_runs_in(&daemon, &checkout))
4342 .await
4343 .unwrap_or(false)
4344}
4345
4346async fn sort_by_checkout(
4352 daemons: Vec<crate::daemon::Daemon>,
4353 checkout: &std::path::Path,
4354) -> Vec<crate::daemon::Daemon> {
4355 if daemons.len() < 2 {
4356 return daemons;
4357 }
4358 let dirs: Vec<Option<std::path::PathBuf>> = daemons.iter().map(|d| d.dir.clone()).collect();
4359 let checkout = checkout.to_path_buf();
4360 let here = tokio::task::spawn_blocking(move || {
4361 dirs.iter()
4362 .map(|dir| {
4363 dir.as_deref()
4364 .is_some_and(|d| crate::proxy::hostname::checkout_root_of(d) == checkout)
4365 })
4366 .collect::<Vec<bool>>()
4367 })
4368 .await;
4369
4370 match here {
4371 Ok(here) => {
4372 let mut ordered: Vec<(bool, crate::daemon::Daemon)> =
4373 here.into_iter().zip(daemons).collect();
4374 ordered.sort_by_key(|(here, _)| !here);
4375 ordered.into_iter().map(|(_, d)| d).collect()
4376 }
4377 Err(e) => {
4378 log::warn!("Checkout attribution task failed: {e}");
4379 daemons
4380 }
4381 }
4382}
4383
4384fn escape_html(s: &str) -> String {
4386 s.replace('&', "&")
4387 .replace('<', "<")
4388 .replace('>', ">")
4389 .replace('"', """)
4390 .replace('\'', "'")
4391}
4392
4393fn html_page(status: StatusCode, title: &str, body: String) -> Response {
4395 let html = format!(
4396 r##"<!DOCTYPE html>
4397<html lang="en">
4398<head>
4399 <meta charset="UTF-8">
4400 <meta name="viewport" content="width=device-width, initial-scale=1">
4401 <title>{title} — pitchfork</title>
4402 <style>
4403 * {{ margin: 0; padding: 0; box-sizing: border-box; }}
4404 body {{
4405 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
4406 background: #0f1117;
4407 color: #e1e4e8;
4408 display: flex;
4409 align-items: center;
4410 justify-content: center;
4411 min-height: 100vh;
4412 }}
4413 .container {{ max-width: 640px; padding: 2rem; }}
4414 h1 {{ font-size: 1.5rem; font-weight: 600; margin-bottom: 0.75rem; }}
4415 p {{ color: #8b949e; font-size: 0.9rem; margin-bottom: 0.75rem; }}
4416 ul {{ list-style: none; margin: 0.5rem 0 1rem; }}
4417 li {{ margin: 0.25rem 0; }}
4418 code, a {{
4419 color: #58a6ff;
4420 font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
4421 text-decoration: none;
4422 }}
4423 </style>
4424</head>
4425<body>
4426 <div class="container">{body}</div>
4427</body>
4428</html>"##
4429 );
4430 Response::builder()
4431 .status(status)
4432 .header("content-type", "text/html; charset=utf-8")
4433 .body(Body::from(html))
4434 .unwrap_or_else(|_| (status, title.to_string()).into_response())
4435}
4436
4437fn host_port_suffix(raw_host: &str) -> String {
4442 let port = if raw_host.starts_with('[') {
4443 raw_host.split_once("]:").map(|(_, port)| port)
4444 } else {
4445 raw_host.rsplit_once(':').map(|(_, port)| port)
4446 };
4447 port.filter(|p| p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty())
4448 .map(|p| format!(":{p}"))
4449 .unwrap_or_default()
4450}
4451
4452fn page_redirect_response(base: &str, path: &str) -> Response {
4458 let target = format!("{base}{path}");
4459 Response::builder()
4460 .status(StatusCode::FOUND)
4461 .header(axum::http::header::LOCATION, &target)
4462 .header(axum::http::header::CACHE_CONTROL, "no-store")
4463 .body(axum::body::Body::from(format!(
4464 "This page is at {target}\n"
4465 )))
4466 .unwrap_or_else(|_| {
4467 html_page(
4468 StatusCode::INTERNAL_SERVER_ERROR,
4469 "pitchfork",
4470 String::new(),
4471 )
4472 })
4473}
4474
4475fn page_placeholder_response(
4482 project: &str,
4483 worktree: Option<&str>,
4484 daemons: &[String],
4485 tld: &str,
4486 port_suffix: &str,
4487 web_url: Option<&str>,
4488) -> Response {
4489 let heading = match worktree {
4490 Some(wt) => format!("{} · {}", escape_html(project), escape_html(wt)),
4491 None => escape_html(project),
4492 };
4493 let suffix = match worktree {
4494 Some(wt) => format!(
4495 "{}.{}.{}",
4496 escape_html(wt),
4497 escape_html(project),
4498 escape_html(tld)
4499 ),
4500 None => format!("{}.{}", escape_html(project), escape_html(tld)),
4501 };
4502 let list = if daemons.is_empty() {
4503 "<p>No daemon in this checkout has a port configured.</p>".to_string()
4504 } else {
4505 let items: String = daemons
4506 .iter()
4507 .map(|d| {
4508 let d = escape_html(d);
4509 format!("<li><a href=\"//{d}.{suffix}{port_suffix}\">{d}.{suffix}</a></li>")
4510 })
4511 .collect();
4512 format!("<p>Daemons here:</p><ul>{items}</ul>")
4513 };
4514 let page = if worktree.is_some() {
4515 "stack"
4516 } else {
4517 "project"
4518 };
4519 let explanation = match web_url {
4524 Some(url) => format!(
4525 "<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>",
4526 url = escape_html(url),
4527 ),
4528 None => format!(
4529 "<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>"
4530 ),
4531 };
4532 let body = format!("<h1>{heading}</h1>{explanation}{list}");
4533 html_page(StatusCode::OK, "pitchfork", body)
4534}
4535
4536fn unknown_host_response(host: &str, heading: &str, known: &[String]) -> Response {
4538 let list = if known.is_empty() {
4539 "<p>Nothing is registered under this name yet.</p>".to_string()
4540 } else {
4541 let items: String = known
4542 .iter()
4543 .map(|k| format!("<li><code>{}</code></li>", escape_html(k)))
4544 .collect();
4545 format!("<p>Known names:</p><ul>{items}</ul>")
4546 };
4547 let body = format!(
4548 "<h1>{heading}</h1><p>No route for <code>{host}</code>.</p>{list}",
4549 heading = escape_html(heading),
4550 host = escape_html(host),
4551 );
4552 html_page(StatusCode::NOT_FOUND, "Not found", body)
4553}
4554
4555fn strip_tld(host: &str, tld: &str) -> Option<String> {
4570 strip_dot_suffix_ignore_case(host.trim_end_matches('.'), tld)
4571}
4572
4573fn bind_error_message(port: u16, err: &std::io::Error) -> String {
4575 if port < 1024 {
4576 format!(
4577 "Failed to bind proxy server to port {port}: {err}\n\
4578 Hint: ports below 1024 require elevated privileges. Run \
4579 `pitchfork proxy setup`, which grants the bind capability on Linux, \
4580 or set an unprivileged proxy.port and let setup redirect {port} to it."
4581 )
4582 } else {
4583 format!(
4584 "Failed to bind proxy server to port {port}: {err}\n\
4585 Hint: another process may already be using this port."
4586 )
4587 }
4588}
4589
4590fn starting_html_response(slug: &str, raw_host: &str) -> Response {
4595 let escaped_slug = slug
4596 .replace('&', "&")
4597 .replace('<', "<")
4598 .replace('>', ">")
4599 .replace('"', """)
4600 .replace('\'', "'");
4601 let escaped_host = raw_host
4602 .replace('&', "&")
4603 .replace('<', "<")
4604 .replace('>', ">")
4605 .replace('"', """)
4606 .replace('\'', "'");
4607
4608 let html = format!(
4609 r##"<!DOCTYPE html>
4610<html lang="en">
4611<head>
4612 <meta charset="UTF-8">
4613 <meta name="viewport" content="width=device-width, initial-scale=1">
4614 <meta http-equiv="refresh" content="2">
4615 <title>Starting {escaped_slug}… — pitchfork</title>
4616 <style>
4617 * {{ margin: 0; padding: 0; box-sizing: border-box; }}
4618 body {{
4619 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
4620 background: #0f1117;
4621 color: #e1e4e8;
4622 display: flex;
4623 align-items: center;
4624 justify-content: center;
4625 min-height: 100vh;
4626 }}
4627 .container {{
4628 text-align: center;
4629 max-width: 480px;
4630 padding: 2rem;
4631 }}
4632 .spinner {{
4633 width: 48px;
4634 height: 48px;
4635 border: 4px solid rgba(255, 255, 255, 0.1);
4636 border-top-color: #58a6ff;
4637 border-radius: 50%;
4638 animation: spin 0.8s linear infinite;
4639 margin: 0 auto 1.5rem;
4640 }}
4641 @keyframes spin {{
4642 to {{ transform: rotate(360deg); }}
4643 }}
4644 h1 {{
4645 font-size: 1.5rem;
4646 font-weight: 600;
4647 margin-bottom: 0.5rem;
4648 }}
4649 .slug {{
4650 color: #58a6ff;
4651 font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
4652 }}
4653 .host {{
4654 color: #8b949e;
4655 font-size: 0.875rem;
4656 margin-top: 0.25rem;
4657 }}
4658 .hint {{
4659 color: #8b949e;
4660 font-size: 0.8rem;
4661 margin-top: 1.5rem;
4662 }}
4663 </style>
4664</head>
4665<body>
4666 <div class="container">
4667 <div class="spinner"></div>
4668 <h1>Starting <span class="slug">{escaped_slug}</span>…</h1>
4669 <p class="host">{escaped_host}</p>
4670 <p class="hint">This page will refresh automatically when the daemon is ready.</p>
4671 </div>
4672</body>
4673</html>"##
4674 );
4675
4676 Response::builder()
4677 .status(StatusCode::SERVICE_UNAVAILABLE)
4678 .header("content-type", "text/html; charset=utf-8")
4679 .header("retry-after", "2")
4680 .body(Body::from(html))
4681 .unwrap_or_else(|_| (StatusCode::SERVICE_UNAVAILABLE, "Starting…").into_response())
4682}
4683
4684async fn redirect_to_https_handler(req: Request) -> Response {
4693 if req.headers().contains_key("upgrade") {
4695 log::warn!("Dropping plain-HTTP WebSocket upgrade attempt — use wss:// instead of ws://");
4696 return (
4697 StatusCode::BAD_REQUEST,
4698 "WebSocket over plain HTTP is not supported on the HTTPS port. Use wss:// instead.",
4699 )
4700 .into_response();
4701 }
4702
4703 let raw_host = get_request_host(&req);
4704 let Some(raw_host) = raw_host else {
4705 return (StatusCode::BAD_REQUEST, "Missing Host header").into_response();
4706 };
4707
4708 let hostname = if raw_host.starts_with('[') {
4710 raw_host
4712 .split_once("]:")
4713 .map(|(host, _)| host)
4714 .unwrap_or(&raw_host)
4715 .trim_start_matches('[')
4716 .trim_end_matches(']')
4717 } else {
4718 let mut parts = raw_host.rsplitn(2, ':');
4720 let last = parts.next().unwrap_or(&raw_host);
4721 parts.next().unwrap_or(last)
4722 };
4723
4724 let path = req
4725 .uri()
4726 .path_and_query()
4727 .map(|pq| pq.as_str())
4728 .unwrap_or("/");
4729
4730 let https_port = match u16::try_from(settings().proxy.port).ok().filter(|&p| p > 0) {
4731 Some(443) | None => String::new(),
4732 Some(port) => format!(":{port}"),
4733 };
4734
4735 let host_for_url = if raw_host.starts_with('[') {
4736 format!("[{hostname}]")
4737 } else {
4738 hostname.to_string()
4739 };
4740
4741 let location = format!("https://{host_for_url}{https_port}{path}");
4742 (
4743 StatusCode::FOUND,
4744 [
4745 (axum::http::header::LOCATION, location),
4746 (
4749 axum::http::HeaderName::from_static(PITCHFORK_HEADER),
4750 "1".to_string(),
4751 ),
4752 ],
4753 )
4754 .into_response()
4755}
4756
4757fn error_response(status: StatusCode, message: &str) -> Response {
4759 (
4763 status,
4764 [(
4765 axum::http::HeaderName::from_static(PITCHFORK_HEADER),
4766 HeaderValue::from_static("1"),
4767 )],
4768 message.to_string(),
4769 )
4770 .into_response()
4771}
4772
4773#[cfg(test)]
4774mod tests {
4775 use super::*;
4776
4777 #[tokio::test]
4781 async fn a_request_forwards_after_an_idle_stop_is_called_off() {
4782 let id = DaemonId::new("calledoff", "api");
4783 SUPERVISOR.state_file.lock().await.daemons.insert(
4784 id.clone(),
4785 crate::daemon::Daemon {
4786 id: id.clone(),
4787 status: crate::daemon_status::DaemonStatus::Running,
4788 ..Default::default()
4789 },
4790 );
4791 assert!(ACTIVITY.claim_idle_stop(&id, std::time::Duration::ZERO));
4792 let releaser = {
4793 let id = id.clone();
4794 tokio::spawn(async move {
4795 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4796 ACTIVITY.release_idle_stop(&id);
4797 })
4798 };
4799 assert!(matches!(
4800 begin_running(&id, auto_start_deadline()).await,
4801 Running::Yes(_)
4802 ));
4803 releaser.await.unwrap();
4804 SUPERVISOR.state_file.lock().await.daemons.remove(&id);
4805 }
4806
4807 #[tokio::test]
4810 async fn a_request_waits_out_an_idle_stop() {
4811 let id = DaemonId::new("waitproj", "api");
4812 assert!(ACTIVITY.claim_idle_stop(&id, std::time::Duration::ZERO));
4813 let releaser = {
4814 let id = id.clone();
4815 tokio::spawn(async move {
4816 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
4817 ACTIVITY.release_idle_stop(&id);
4818 })
4819 };
4820 assert!(matches!(
4821 begin_running(&id, auto_start_deadline()).await,
4822 Running::No
4823 ));
4824 releaser.await.unwrap();
4825 assert!(ACTIVITY.begin(&id).is_some());
4826 }
4827
4828 #[tokio::test]
4834 async fn a_get_only_route_never_reaches_the_fallback() {
4835 async fn routed() -> &'static str {
4836 "routed"
4837 }
4838 async fn fell_through() -> &'static str {
4839 "fell-through"
4840 }
4841
4842 async fn post_to(app: Router) -> String {
4845 use tokio::io::{AsyncReadExt, AsyncWriteExt};
4846
4847 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4848 let addr = listener.local_addr().unwrap();
4849 let server = tokio::spawn(async move {
4850 let _ = axum::serve(listener, app).await;
4851 });
4852
4853 let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
4854 sock.write_all(
4855 b"POST /proxy.pac HTTP/1.1\r\nHost: example\r\nConnection: close\r\n\r\n",
4856 )
4857 .await
4858 .unwrap();
4859 let mut raw = Vec::new();
4860 sock.read_to_end(&mut raw).await.unwrap();
4861 server.abort();
4862
4863 let text = String::from_utf8_lossy(&raw).into_owned();
4864 let status = text.split_whitespace().nth(1).unwrap_or("").to_string();
4865 if status == "405" {
4866 return status;
4867 }
4868 text.rsplit("\r\n").next().unwrap_or("").to_string()
4869 }
4870
4871 let get_only = Router::new()
4872 .route("/proxy.pac", axum::routing::get(routed))
4873 .fallback(fell_through);
4874 assert_eq!(
4875 post_to(get_only).await,
4876 "405",
4877 "axum reached the fallback on a method mismatch, so `any` is unnecessary"
4878 );
4879
4880 let any_method = Router::new()
4881 .route("/proxy.pac", axum::routing::any(routed))
4882 .fallback(fell_through);
4883 assert_eq!(
4884 post_to(any_method).await,
4885 "routed",
4886 "`any` did not deliver the POST to the handler"
4887 );
4888 }
4889
4890 #[cfg(feature = "proxy-tls")]
4891 #[test]
4892 fn a_ca_pair_is_checked_not_just_found() {
4893 let dir = tempfile::tempdir().unwrap();
4894 let (cert, key) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem"));
4895 generate_ca(&cert, &key).unwrap();
4896 assert_eq!(ca_pair_problem(&cert, &key), None);
4897
4898 let (other_cert, other_key) = (dir.path().join("b.pem"), dir.path().join("b-key.pem"));
4900 generate_ca(&other_cert, &other_key).unwrap();
4901 assert!(ca_pair_problem(&cert, &other_key).is_some());
4902
4903 std::fs::write(&cert, "-----BEGIN CERTIFICATE-----\nAAAA\n").unwrap();
4905 assert!(ca_pair_problem(&cert, &key).is_some());
4906 }
4907
4908 #[cfg(feature = "proxy-tls")]
4909 #[test]
4910 fn a_new_ca_clears_leaves_signed_by_the_old_one() {
4911 let dir = tempfile::tempdir().unwrap();
4914 let (cert, key) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem"));
4915 let host_certs = host_certs_dir_for(&cert);
4916 std::fs::create_dir_all(&host_certs).unwrap();
4917 std::fs::write(host_certs.join("api.localhost.pem"), "old leaf").unwrap();
4918 std::fs::write(host_certs.join("notes.txt"), "keep me").unwrap();
4919
4920 assert!(!ensure_ca(&cert, &key, || true).unwrap());
4922 assert!(host_certs.join("api.localhost.pem").exists());
4923
4924 assert!(ensure_ca(&cert, &key, || false).unwrap());
4926 assert!(!host_certs.join("api.localhost.pem").exists());
4927 assert!(host_certs.join("notes.txt").exists());
4928 }
4929
4930 #[cfg(feature = "proxy-tls")]
4931 #[test]
4932 fn leaves_are_cached_per_ca_so_a_replaced_ca_is_never_served() {
4933 let dir = tempfile::tempdir().unwrap();
4937 let (cert, key) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem"));
4938 let _ = rustls::crypto::ring::default_provider().install_default();
4939 ensure_ca(&cert, &key, || false).unwrap();
4940 let first = SniCertResolver::new(&cert, &key, "localhost".into()).unwrap();
4941 assert!(first.get_or_create_checked("api.localhost").is_some());
4942 let old_dir = first.host_certs_dir.clone();
4943 assert!(std::fs::read_dir(&old_dir).unwrap().count() > 0);
4944
4945 ensure_ca(&cert, &key, || false).unwrap();
4946 std::fs::create_dir_all(&old_dir).unwrap();
4948 std::fs::write(old_dir.join("late.localhost.pem"), "old leaf").unwrap();
4949
4950 let second = SniCertResolver::new(&cert, &key, "localhost".into()).unwrap();
4951 assert_ne!(second.host_certs_dir, old_dir);
4952 assert!(!old_dir.exists());
4954 }
4955
4956 #[cfg(feature = "proxy-tls")]
4957 #[test]
4958 fn cert_cache_file_names_do_not_collide() {
4959 assert_ne!(
4961 cert_cache_file_stem("a_b.localhost"),
4962 cert_cache_file_stem("a.b.localhost")
4963 );
4964 assert_eq!(cert_cache_file_stem("api.localhost"), "api.localhost");
4965 assert_eq!(cert_cache_file_stem("a_b.localhost"), "a%5Fb.localhost");
4966 assert_eq!(
4967 cert_cache_file_stem("*.proj.localhost"),
4968 "%2A.proj.localhost"
4969 );
4970 assert!(!cert_cache_file_stem("../x").contains('/'));
4972 }
4973
4974 #[test]
4975 fn connect_port_reads_the_authority() {
4976 assert_eq!(connect_port("api.localhost:443"), Some(443));
4977 assert_eq!(connect_port("api.localhost:80"), Some(80));
4978 assert_eq!(connect_port("[::1]:443"), Some(443));
4979 assert_eq!(connect_port("api.localhost"), None);
4980 assert_eq!(connect_port("::1"), None);
4981 }
4982
4983 #[test]
4984 fn a_half_configured_certificate_pair_is_refused() {
4985 assert!(tls_pair_problem("", "/k.pem").is_some());
4989 assert!(tls_pair_problem("/c.pem", "").is_some());
4990 assert!(tls_pair_problem("", "").is_none());
4991 assert!(tls_pair_problem("/c.pem", "/k.pem").is_none());
4992 }
4993
4994 #[cfg(feature = "proxy-tls")]
4996 fn test_resolver(tld: &str) -> (SniCertResolver, tempfile::TempDir) {
4997 let dir = tempfile::tempdir().unwrap();
4998 let cert = dir.path().join("ca.pem");
4999 let key = dir.path().join("ca-key.pem");
5000 generate_ca(&cert, &key).unwrap();
5001 let _ = rustls::crypto::ring::default_provider().install_default();
5002 (
5003 SniCertResolver::new(&cert, &key, tld.to_string()).unwrap(),
5004 dir,
5005 )
5006 }
5007
5008 #[cfg(feature = "proxy-tls")]
5010 fn sans_for(resolver: &SniCertResolver, domain: &str) -> Vec<String> {
5011 let ck = resolver.get_or_create(domain).expect("a certificate");
5012 let (_, cert) = x509_parser::parse_x509_certificate(&ck.cert[0]).unwrap();
5013 cert.subject_alternative_name()
5014 .unwrap()
5015 .map(|ext| {
5016 ext.value
5017 .general_names
5018 .iter()
5019 .filter_map(|n| match n {
5020 x509_parser::extensions::GeneralName::DNSName(d) => Some(d.to_string()),
5021 _ => None,
5022 })
5023 .collect()
5024 })
5025 .unwrap_or_default()
5026 }
5027
5028 #[cfg(feature = "proxy-tls")]
5029 #[test]
5030 fn the_ca_refuses_to_sign_for_a_name_outside_the_tld() {
5031 use rustls::server::ResolvesServerCert;
5032
5033 let (resolver, _dir) = test_resolver("localhost");
5034 let cache = resolver.host_certs_dir.clone();
5035
5036 for foreign in [
5040 "login.microsoftonline.com",
5041 "example.com",
5042 "notlocalhost",
5043 "localhost.evil.com",
5044 ] {
5045 assert!(
5046 resolver.get_or_create_checked(foreign).is_none(),
5047 "expected {foreign:?} to be refused"
5048 );
5049 }
5050
5051 let cached: Vec<String> = std::fs::read_dir(&cache)
5053 .map(|rd| {
5054 rd.filter_map(|e| e.ok())
5055 .map(|e| e.file_name().to_string_lossy().into_owned())
5056 .collect()
5057 })
5058 .unwrap_or_default();
5059 assert!(
5060 cached.is_empty(),
5061 "unexpected cached certificates: {cached:?}"
5062 );
5063
5064 for ours in ["localhost", "api.localhost", "core.wt.proj.localhost"] {
5066 assert!(
5067 resolver.get_or_create_checked(ours).is_some(),
5068 "expected {ours:?} to be issued"
5069 );
5070 }
5071 let _ = &resolver as &dyn ResolvesServerCert;
5073 }
5074
5075 #[cfg(feature = "proxy-tls")]
5076 #[test]
5077 fn the_certificate_cache_is_bounded_and_evicts_the_oldest() {
5078 let (resolver, _dir) = test_resolver("localhost");
5081 let host_certs = resolver.host_certs_dir.clone();
5082
5083 for i in 0..MAX_HOST_CERTS + 8 {
5084 assert!(
5085 resolver
5086 .get_or_create_checked(&format!("h{i}.localhost"))
5087 .is_some()
5088 );
5089 }
5090
5091 let cached = resolver.cache.lock().unwrap();
5092 assert_eq!(cached.by_domain.len(), MAX_HOST_CERTS);
5093 assert_eq!(cached.order.len(), MAX_HOST_CERTS);
5094 assert!(cached.get("h0.localhost").is_none());
5096 assert!(
5097 cached
5098 .get(&format!("h{}.localhost", MAX_HOST_CERTS + 7))
5099 .is_some()
5100 );
5101 drop(cached);
5102
5103 let on_disk = std::fs::read_dir(&host_certs).unwrap().count();
5105 assert!(
5106 on_disk <= MAX_HOST_CERTS,
5107 "{on_disk} files cached, expected at most {MAX_HOST_CERTS}"
5108 );
5109 }
5110
5111 #[cfg(feature = "proxy-tls")]
5112 #[test]
5113 fn the_disk_cache_is_pruned_at_startup() {
5114 let dir = tempfile::tempdir().unwrap();
5118 let host_certs = dir.path().join("host-certs");
5119 std::fs::create_dir_all(&host_certs).unwrap();
5120 for i in 0..MAX_HOST_CERTS + 20 {
5121 std::fs::write(host_certs.join(format!("old{i}.pem")), "stale").unwrap();
5122 }
5123 std::fs::write(host_certs.join("notes.txt"), "keep me").unwrap();
5125
5126 prune_host_certs(&host_certs);
5127
5128 let pems = std::fs::read_dir(&host_certs)
5129 .unwrap()
5130 .filter_map(|e| e.ok())
5131 .filter(|e| e.path().extension().is_some_and(|x| x == "pem"))
5132 .count();
5133 assert_eq!(pems, MAX_HOST_CERTS);
5134 assert!(host_certs.join("notes.txt").exists());
5135
5136 let small = dir.path().join("small");
5138 std::fs::create_dir_all(&small).unwrap();
5139 std::fs::write(small.join("a.pem"), "x").unwrap();
5140 prune_host_certs(&small);
5141 assert!(small.join("a.pem").exists());
5142 }
5143
5144 #[cfg(feature = "proxy-tls")]
5145 #[test]
5146 fn a_minted_certificate_never_wildcards_the_whole_tld() {
5147 let (resolver, _dir) = test_resolver("localhost");
5148
5149 let sans = sans_for(&resolver, "api.localhost");
5151 assert!(sans.contains(&"api.localhost".to_string()));
5152 assert!(
5153 !sans.iter().any(|s| s.starts_with('*')),
5154 "unexpected wildcard in {sans:?}"
5155 );
5156
5157 let sans = sans_for(&resolver, "core.wt.proj.localhost");
5159 assert!(sans.contains(&"*.wt.proj.localhost".to_string()));
5160
5161 let (resolver, _dir) = test_resolver("dev.internal");
5163 let sans = sans_for(&resolver, "api.dev.internal");
5164 assert!(
5165 !sans.iter().any(|s| s.starts_with('*')),
5166 "unexpected wildcard in {sans:?}"
5167 );
5168 }
5169
5170 #[tokio::test]
5174 async fn test_page_placeholder_explains_which_step_is_missing() {
5175 async fn body_of(response: Response) -> String {
5176 let (_, body) = response.into_parts();
5177 let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
5178 String::from_utf8(bytes.to_vec()).unwrap()
5179 }
5180
5181 let disabled = page_placeholder_response("shop", None, &[], "localhost", "", None);
5182 assert_eq!(disabled.status(), StatusCode::OK);
5183 let disabled = body_of(disabled).await;
5184 assert!(disabled.contains("auto_start"), "{disabled}");
5185 assert!(!disabled.contains("[namespaces]"));
5186
5187 let running = page_placeholder_response(
5188 "shop",
5189 Some("feature-a"),
5190 &[],
5191 "localhost",
5192 "",
5193 Some("http://127.0.0.1:3120"),
5194 );
5195 let running = body_of(running).await;
5196 assert!(running.contains("[namespaces]"), "{running}");
5197 assert!(running.contains("http://127.0.0.1:3120/projects"));
5198 assert!(!running.contains("auto_start"));
5199 }
5200
5201 #[test]
5204 fn test_page_redirect_targets_the_web_ui() {
5205 let response = page_redirect_response("http://127.0.0.1:3120", "/projects/shop/feature-a");
5206 assert_eq!(response.status(), StatusCode::FOUND);
5207 assert_eq!(
5208 response
5209 .headers()
5210 .get(axum::http::header::LOCATION)
5211 .unwrap(),
5212 "http://127.0.0.1:3120/projects/shop/feature-a"
5213 );
5214
5215 let project = page_redirect_response("http://127.0.0.1:3120/ps", "/projects/shop");
5216 assert_eq!(
5217 project.headers().get(axum::http::header::LOCATION).unwrap(),
5218 "http://127.0.0.1:3120/ps/projects/shop"
5220 );
5221 }
5222
5223 #[tokio::test]
5224 async fn overlapping_startup_graphs_wait_for_each_other() {
5225 use std::time::Duration;
5226 let id = |name: &str| DaemonId::try_new("startup-lock-test", name).unwrap();
5227
5228 let first = lock_startup_graph(vec![id("shared"), id("app-a")]).await;
5229
5230 let second = tokio::spawn(lock_startup_graph(vec![id("shared"), id("app-b")]));
5233 tokio::time::sleep(Duration::from_millis(50)).await;
5234 assert!(
5235 !second.is_finished(),
5236 "a graph sharing a daemon must wait for the graph starting it"
5237 );
5238
5239 let disjoint = tokio::time::timeout(
5241 Duration::from_secs(1),
5242 lock_startup_graph(vec![id("other")]),
5243 )
5244 .await;
5245 assert!(disjoint.is_ok());
5246
5247 drop(first);
5248 let second = tokio::time::timeout(Duration::from_secs(1), second)
5249 .await
5250 .expect("the waiting graph proceeds once the first releases")
5251 .unwrap();
5252 assert_eq!(second.len(), 2);
5253 drop(second);
5254 drop(disjoint);
5255
5256 drop(lock_startup_graph(vec![id("unrelated")]).await);
5258 let map = STARTUP_LOCKS.lock().unwrap();
5259 assert!(
5260 !map.keys()
5261 .any(|k| k.namespace() == "startup-lock-test" && k.name() != "unrelated"),
5262 "released startup locks must be pruned"
5263 );
5264 }
5265
5266 #[test]
5267 fn test_strip_tld() {
5268 assert_eq!(
5269 strip_tld("api.myproject.localhost", "localhost"),
5270 Some("api.myproject".to_string())
5271 );
5272 assert_eq!(
5274 strip_tld("API.MyProject.LOCALHOST", "localhost"),
5275 Some("API.MyProject".to_string())
5276 );
5277 assert_eq!(
5278 strip_tld("api.localhost", "LOCALHOST"),
5279 Some("api".to_string())
5280 );
5281 assert_eq!(
5282 strip_tld("api.localhost", "localhost"),
5283 Some("api".to_string())
5284 );
5285 assert_eq!(strip_tld("localhost", "localhost"), None);
5286 assert_eq!(
5291 strip_tld("API.LocalHost", "localhost"),
5292 Some("API".to_string())
5293 );
5294 assert_eq!(
5295 strip_tld("api.localhost.", "localhost"),
5296 Some("api".to_string())
5297 );
5298 assert_eq!(
5299 strip_tld("API.MyProject.LOCALHOST.", "localhost"),
5300 Some("API.MyProject".to_string())
5301 );
5302 assert_eq!(strip_tld("localhost.", "localhost"), None);
5303 assert_eq!(
5304 strip_tld("api.myproject.test", "test"),
5305 Some("api.myproject".to_string())
5306 );
5307 assert_eq!(strip_tld("other.com", "localhost"), None);
5308 }
5309
5310 fn make_entry(name: &str) -> CachedSlugEntry {
5311 CachedSlugEntry {
5312 slug: name.to_string(),
5313 namespace: None,
5314 daemon_name: name.to_string(),
5315 dir: std::path::PathBuf::from(format!("/tmp/{name}")),
5316 worktrees: vec![],
5317 rejected_worktree_prefixes: std::collections::HashSet::new(),
5318 tls: ProxyTlsRoute::default(),
5319 worktree_tls: std::collections::HashMap::new(),
5320 }
5321 }
5322
5323 fn make_daemon(
5325 configured: &[u16],
5326 resolved: &[u16],
5327 active: Option<u16>,
5328 ) -> crate::daemon::Daemon {
5329 crate::daemon::Daemon {
5330 id: DaemonId::try_new("proj", "api").unwrap(),
5331 port: crate::config_types::PortConfig::from_parts(
5332 configured.to_vec(),
5333 crate::config_types::PortBump(0),
5334 ),
5335 resolved_port: resolved.to_vec(),
5336 active_port: active,
5337 ..crate::daemon::Daemon::default()
5338 }
5339 }
5340
5341 #[test]
5344 fn test_select_daemon_port_prefers_active_port() {
5345 let route = ProxyTlsRoute::default();
5346 let d = make_daemon(&[8443, 9443], &[8443, 9443], Some(8443));
5347 assert_eq!(select_daemon_port(&route, &d), Some(8443));
5348 }
5349
5350 #[test]
5354 fn test_select_daemon_port_skips_port_zero() {
5355 for mode in [ProxyTlsMode::Passthrough, ProxyTlsMode::Terminate] {
5356 let route = ProxyTlsRoute {
5357 mode,
5358 protocol: Default::default(),
5359 port: None,
5360 };
5361
5362 let mixed = make_daemon(&[0, 8443], &[0, 8443], None);
5364 assert_eq!(select_daemon_port(&route, &mixed), Some(8443));
5365
5366 let detected_placeholder = make_daemon(&[0, 8443], &[0, 8443], Some(0));
5369 assert_eq!(
5370 select_daemon_port(&route, &detected_placeholder),
5371 Some(8443)
5372 );
5373
5374 let unresolved = make_daemon(&[0], &[0], Some(0));
5376 assert_eq!(select_daemon_port(&route, &unresolved), None);
5377 }
5378 }
5379
5380 #[test]
5385 fn test_select_daemon_port_passthrough_prefers_declared_first_port() {
5386 let route = ProxyTlsRoute {
5387 protocol: Default::default(),
5388 mode: ProxyTlsMode::Passthrough,
5389 port: None,
5390 };
5391 let d = make_daemon(&[8443, 9080], &[8443, 9080], Some(9080));
5392 assert_eq!(select_daemon_port(&route, &d), Some(8443));
5393
5394 let detected_only = make_daemon(&[], &[], Some(9080));
5397 assert_eq!(select_daemon_port(&route, &detected_only), Some(9080));
5398 }
5399
5400 #[test]
5402 fn test_select_daemon_port_falls_back_to_first_resolved() {
5403 let route = ProxyTlsRoute::default();
5404 let d = make_daemon(&[8443, 9443], &[8443, 9443], None);
5405 assert_eq!(select_daemon_port(&route, &d), Some(8443));
5406
5407 let none = make_daemon(&[], &[], None);
5409 assert_eq!(select_daemon_port(&route, &none), None);
5410 }
5411
5412 #[test]
5415 fn test_select_daemon_port_honors_configured_port() {
5416 let route = ProxyTlsRoute {
5417 protocol: Default::default(),
5418 mode: ProxyTlsMode::Passthrough,
5419 port: Some(9443),
5420 };
5421 let d = make_daemon(&[8443, 9443], &[8443, 9443], Some(8443));
5422 assert_eq!(select_daemon_port(&route, &d), Some(9443));
5423 }
5424
5425 #[test]
5429 fn test_select_daemon_port_follows_auto_bump() {
5430 let route = ProxyTlsRoute {
5431 protocol: Default::default(),
5432 mode: ProxyTlsMode::Passthrough,
5433 port: Some(9443),
5434 };
5435 let d = make_daemon(&[8443, 9443], &[8444, 9444], Some(8444));
5436 assert_eq!(select_daemon_port(&route, &d), Some(9444));
5437 }
5438
5439 #[test]
5443 fn test_select_daemon_port_skips_a_configured_port_resolved_to_zero() {
5444 let route = ProxyTlsRoute {
5445 protocol: Default::default(),
5446 mode: ProxyTlsMode::Passthrough,
5447 port: Some(9443),
5448 };
5449 let pending = make_daemon(&[8443, 9443], &[8443, 0], Some(8443));
5452 assert_eq!(select_daemon_port(&route, &pending), None);
5453
5454 let ready = make_daemon(&[8443, 9443], &[8443, 9444], Some(8443));
5456 assert_eq!(select_daemon_port(&route, &ready), Some(9444));
5457 }
5458
5459 #[test]
5464 fn test_select_daemon_port_refuses_a_port_the_daemon_never_bound() {
5465 let route = ProxyTlsRoute {
5466 protocol: Default::default(),
5467 mode: ProxyTlsMode::Passthrough,
5468 port: Some(9443),
5469 };
5470 let stale = make_daemon(&[8443], &[8443], Some(8443));
5471 assert_eq!(select_daemon_port(&route, &stale), None);
5472
5473 let bare = make_daemon(&[], &[], None);
5476 assert_eq!(select_daemon_port(&route, &bare), Some(9443));
5477 }
5478
5479 #[test]
5482 fn test_select_daemon_port_honors_configured_port_when_terminating() {
5483 let route = ProxyTlsRoute {
5484 protocol: Default::default(),
5485 mode: ProxyTlsMode::Terminate,
5486 port: Some(9080),
5487 };
5488 let d = make_daemon(&[8080, 9080], &[8080, 9080], Some(8080));
5489 assert_eq!(select_daemon_port(&route, &d), Some(9080));
5490
5491 let bumped = make_daemon(&[8080, 9080], &[8081, 9081], Some(8081));
5493 assert_eq!(select_daemon_port(&route, &bumped), Some(9081));
5494 }
5495
5496 #[test]
5498 fn test_read_proxy_tls_route_reads_protocol() {
5499 let dir = tempfile::tempdir().unwrap();
5500 std::fs::write(
5501 dir.path().join("pitchfork.toml"),
5502 "[daemons.grpc]\nrun = \"serve\"\nport = 50051\nproxy_protocol = \"h2c\"\n\n\
5503 [daemons.web]\nrun = \"serve\"\nport = 3000\n",
5504 )
5505 .unwrap();
5506 let ns = crate::pitchfork_toml::PitchforkToml::namespace_for_dir(dir.path()).unwrap();
5507 let grpc = read_proxy_tls_route(dir.path(), Some(&ns), "grpc")
5508 .unwrap()
5509 .unwrap();
5510 assert_eq!(grpc.protocol, ProxyProtocol::H2c);
5511 let web = read_proxy_tls_route(dir.path(), Some(&ns), "web")
5512 .unwrap()
5513 .unwrap();
5514 assert_eq!(web.protocol, ProxyProtocol::Http1);
5515 }
5516
5517 #[tokio::test]
5520 async fn test_h2c_client_reaches_http2_only_daemon() {
5521 use http_body_util::BodyExt;
5522 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
5523 let port = listener.local_addr().unwrap().port();
5524 tokio::spawn(async move {
5525 let (stream, _) = listener.accept().await.unwrap();
5526 let svc = hyper::service::service_fn(
5527 |req: axum::http::Request<hyper::body::Incoming>| async move {
5528 assert_eq!(req.version(), axum::http::Version::HTTP_2);
5529 let body = http_body_util::Full::new(axum::body::Bytes::from_static(b"ok"));
5530 Ok::<_, std::convert::Infallible>(axum::http::Response::new(body))
5531 },
5532 );
5533 let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new())
5534 .serve_connection(hyper_util::rt::TokioIo::new(stream), svc)
5535 .await;
5536 });
5537 let client: Client<HttpConnector, Body> = Client::builder(TokioExecutor::new())
5538 .http2_only(true)
5539 .build(HttpConnector::new());
5540 let mut req = axum::http::Request::new(Body::empty());
5541 *req.uri_mut() = format!("http://127.0.0.1:{port}/svc/Method")
5542 .parse()
5543 .unwrap();
5544 *req.version_mut() = axum::http::Version::HTTP_2;
5545 let resp = client.request(req).await.unwrap();
5546 assert_eq!(resp.version(), axum::http::Version::HTTP_2);
5547 let collected = resp.into_body().collect().await.unwrap();
5548 assert_eq!(collected.to_bytes(), "ok");
5549 }
5550
5551 #[test]
5555 fn test_read_proxy_tls_route_absent_without_config() {
5556 let dir = tempfile::tempdir().unwrap();
5557
5558 assert_eq!(
5560 read_proxy_tls_route(dir.path(), Some("proj"), "api").unwrap(),
5561 None
5562 );
5563
5564 std::fs::write(
5566 dir.path().join("pitchfork.toml"),
5567 "[daemons.other]\nrun = \"serve\"\n",
5568 )
5569 .unwrap();
5570 assert_eq!(
5571 read_proxy_tls_route(dir.path(), Some("proj"), "api").unwrap(),
5572 None,
5573 "a config without this daemon says nothing about it"
5574 );
5575
5576 assert_eq!(read_proxy_tls_route(dir.path(), None, "api").unwrap(), None);
5578 }
5579
5580 #[test]
5584 fn test_unreadable_config_keeps_the_last_known_route() {
5585 let dir = tempfile::tempdir().unwrap();
5586 std::fs::write(
5587 dir.path().join("pitchfork.toml"),
5588 "[daemons.api]\nrun = \"serve\"\nport = 8443\nproxy_tls = \"passthrough\"\n\n\
5589 [daemons.broken]\nrun = \"serve\"\nproxy_tls = \"passthrough\"\n",
5590 )
5591 .unwrap();
5592 let read = read_proxy_tls_route(dir.path(), Some("proj"), "api");
5593 assert!(
5594 read.is_err(),
5595 "an invalid sibling makes the config unreadable"
5596 );
5597
5598 let known = ProxyTlsRoute {
5599 protocol: Default::default(),
5600 mode: ProxyTlsMode::Passthrough,
5601 port: Some(8443),
5602 };
5603 assert_eq!(
5604 route_or_last_known(read, Some(known), dir.path(), "api"),
5605 Some(known)
5606 );
5607
5608 assert_eq!(
5610 route_or_last_known(Ok(None), Some(known), dir.path(), "api"),
5611 None
5612 );
5613 }
5614
5615 #[test]
5618 fn test_known_route_requires_the_same_target() {
5619 let known = ProxyTlsRoute {
5620 protocol: Default::default(),
5621 mode: ProxyTlsMode::Passthrough,
5622 port: Some(8443),
5623 };
5624 let mut entry = make_entry("api");
5625 entry.namespace = Some("proj".to_string());
5626 entry.tls = known;
5627 let dir = entry.dir.clone();
5628
5629 assert_eq!(entry.known_route(&dir, Some("proj"), "api"), Some(known));
5630 assert_eq!(entry.known_route(&dir, Some("proj"), "web"), None);
5631 assert_eq!(entry.known_route(&dir, Some("other"), "api"), None);
5632 assert_eq!(
5633 entry.known_route(std::path::Path::new("/elsewhere"), Some("proj"), "api"),
5634 None
5635 );
5636
5637 let wt = make_worktree("feature/x", "feature-x");
5638 entry.worktrees = vec![wt.clone()];
5639 entry.worktree_tls.insert("feature-x".to_string(), known);
5640 assert_eq!(entry.known_worktree_route(&wt, "api"), Some(known));
5641 assert_eq!(entry.known_worktree_route(&wt, "web"), None);
5642 let moved = crate::proxy::worktree::WorktreeEntry {
5643 path: std::path::PathBuf::from("/elsewhere/feature-x"),
5644 ..wt
5645 };
5646 assert_eq!(entry.known_worktree_route(&moved, "api"), None);
5647 }
5648
5649 #[test]
5653 fn test_worktree_route_inherits_when_unknown() {
5654 let mut entry = make_entry("spliced");
5655 entry.tls = ProxyTlsRoute {
5656 protocol: Default::default(),
5657 mode: ProxyTlsMode::Passthrough,
5658 port: Some(8443),
5659 };
5660 entry.worktrees = vec![
5661 make_worktree("feature/known", "feature-known"),
5662 make_worktree("feature/unknown", "feature-unknown"),
5663 ];
5664 entry.worktree_tls.insert(
5666 "feature-known".to_string(),
5667 ProxyTlsRoute {
5668 protocol: Default::default(),
5669 mode: ProxyTlsMode::Terminate,
5670 port: None,
5671 },
5672 );
5673 let mut entries = std::collections::HashMap::new();
5674 entries.insert("spliced".to_string(), entry);
5675
5676 let mode =
5677 |host: &str| resolve_tls_mode_in(host, "localhost", &entries, &Default::default());
5678 assert_eq!(
5679 mode("feature-known.spliced.localhost"),
5680 ProxyTlsMode::Terminate,
5681 "an explicit worktree setting wins"
5682 );
5683 assert_eq!(
5684 mode("feature-unknown.spliced.localhost"),
5685 ProxyTlsMode::Passthrough,
5686 "a worktree with nothing recorded inherits the slug"
5687 );
5688
5689 let cached = entries.get("spliced").unwrap();
5693 assert_eq!(
5694 worktree_route(cached, "feature-unknown"),
5695 ProxyTlsRoute {
5696 protocol: Default::default(),
5697 mode: ProxyTlsMode::Passthrough,
5698 port: None,
5699 }
5700 );
5701 assert_eq!(
5703 worktree_route(cached, "feature-known"),
5704 ProxyTlsRoute {
5705 protocol: Default::default(),
5706 mode: ProxyTlsMode::Terminate,
5707 port: None,
5708 }
5709 );
5710 }
5711
5712 #[test]
5715 fn test_worktree_route_lookup() {
5716 let mut entry = make_entry("myapp");
5717 entry.tls = ProxyTlsRoute {
5718 protocol: Default::default(),
5719 mode: ProxyTlsMode::Terminate,
5720 port: None,
5721 };
5722 entry.worktrees = vec![
5723 make_worktree("feature/b", "feature-b"),
5724 make_worktree("feature/c", "feature-c"),
5725 ];
5726 entry.worktree_tls.insert(
5727 "feature-b".to_string(),
5728 ProxyTlsRoute {
5729 protocol: Default::default(),
5730 mode: ProxyTlsMode::Passthrough,
5731 port: Some(9443),
5732 },
5733 );
5734
5735 let lookup = |prefix: &str| match match_worktree_prefix(&entry, prefix) {
5736 PrefixMatch::Worktree(wt) => entry
5737 .worktree_tls
5738 .get(&wt.sanitized_branch.to_ascii_lowercase())
5739 .copied()
5740 .unwrap_or(entry.tls),
5741 _ => entry.tls,
5742 };
5743
5744 assert_eq!(lookup("feature-b").mode, ProxyTlsMode::Passthrough);
5745 assert_eq!(lookup("feature-b").port, Some(9443));
5746 assert_eq!(lookup("feature-c").mode, ProxyTlsMode::Terminate);
5748 assert_eq!(lookup("tenant").mode, ProxyTlsMode::Terminate);
5750 }
5751
5752 #[test]
5753 fn test_wildcard_slug_lookup_exact_match() {
5754 let mut entries = std::collections::HashMap::new();
5755 entries.insert("myapp".to_string(), make_entry("myapp"));
5756 let result = wildcard_slug_lookup("myapp", &entries, true);
5758 assert!(result.is_some());
5759 assert_eq!(result.unwrap().daemon_name, "myapp");
5760 }
5761
5762 #[test]
5763 fn test_wildcard_slug_lookup_subdomain_fallback() {
5764 let mut entries = std::collections::HashMap::new();
5765 entries.insert("myapp".to_string(), make_entry("myapp"));
5766 let result = wildcard_slug_lookup("tenant.myapp", &entries, true);
5768 assert!(result.is_some());
5769 assert_eq!(result.unwrap().daemon_name, "myapp");
5770 }
5771
5772 #[test]
5773 fn test_wildcard_slug_lookup_nested_fallback() {
5774 let mut entries = std::collections::HashMap::new();
5775 entries.insert("myapp".to_string(), make_entry("myapp"));
5776 let result = wildcard_slug_lookup("a.b.myapp", &entries, true);
5778 assert!(result.is_some());
5779 assert_eq!(result.unwrap().daemon_name, "myapp");
5780 }
5781
5782 #[test]
5783 fn test_wildcard_slug_lookup_no_match() {
5784 let entries = std::collections::HashMap::new();
5785 let result = wildcard_slug_lookup("tenant.myapp", &entries, true);
5787 assert!(result.is_none());
5788 }
5789
5790 #[test]
5791 fn test_wildcard_slug_lookup_disabled() {
5792 let mut entries = std::collections::HashMap::new();
5793 entries.insert("myapp".to_string(), make_entry("myapp"));
5794 let result = wildcard_slug_lookup("tenant.myapp", &entries, false);
5796 assert!(result.is_none());
5797 let result = wildcard_slug_lookup("myapp", &entries, false);
5799 assert!(result.is_some());
5800 }
5801
5802 #[test]
5803 fn test_wildcard_slug_lookup_exact_beats_wildcard() {
5804 let mut entries = std::collections::HashMap::new();
5805 entries.insert("myapp".to_string(), make_entry("myapp"));
5806 let mut tenant_entry = make_entry("tenant-daemon");
5807 tenant_entry.slug = "tenant.myapp".to_string();
5808 entries.insert("tenant.myapp".to_string(), tenant_entry);
5809 let result = wildcard_slug_lookup("tenant.myapp", &entries, true);
5811 assert!(result.is_some());
5812 assert_eq!(result.unwrap().daemon_name, "tenant-daemon");
5813 }
5814
5815 #[test]
5816 fn test_wildcard_slug_lookup_ignores_case() {
5817 let mut entries = std::collections::HashMap::new();
5818 entries.insert("myapp".to_string(), make_entry("myapp"));
5819 for host in ["MyApp", "MYAPP", "myapp"] {
5821 let result = wildcard_slug_lookup(host, &entries, true);
5822 assert!(result.is_some(), "exact lookup failed for {host}");
5823 assert_eq!(result.unwrap().daemon_name, "myapp");
5824 }
5825 for host in ["Tenant.MyApp", "tenant.MYAPP", "A.B.MyApp"] {
5827 let result = wildcard_slug_lookup(host, &entries, true);
5828 assert!(result.is_some(), "wildcard lookup failed for {host}");
5829 assert_eq!(result.unwrap().daemon_name, "myapp");
5830 }
5831 }
5832
5833 #[test]
5834 fn test_wildcard_slug_lookup_case_insensitive_registration() {
5835 let mut entries = std::collections::HashMap::new();
5836 let mut entry = make_entry("upper");
5837 entry.slug = "MyApp".to_string();
5838 entries.insert("myapp".to_string(), entry);
5841 for host in ["myapp", "MyApp", "tenant.MYAPP"] {
5842 let result = wildcard_slug_lookup(host, &entries, true);
5843 assert!(result.is_some(), "lookup failed for {host}");
5844 assert_eq!(result.unwrap().daemon_name, "upper");
5845 }
5846 }
5847
5848 fn make_worktree(branch: &str, sanitized: &str) -> crate::proxy::worktree::WorktreeEntry {
5849 crate::proxy::worktree::WorktreeEntry {
5850 path: std::path::PathBuf::from(format!("/tmp/{sanitized}")),
5851 branch: branch.to_string(),
5852 sanitized_branch: sanitized.to_string(),
5853 namespace: Some(sanitized.to_string()),
5854 }
5855 }
5856
5857 #[test]
5858 fn test_reject_case_colliding_worktrees_drops_both_sides() {
5859 let wts = vec![
5860 make_worktree("Feature-A", "Feature-A"),
5861 make_worktree("feature-a", "feature-a"),
5862 make_worktree("main", "main"),
5863 ];
5864 let (kept, rejected) = reject_case_colliding_worktrees(wts);
5865 assert_eq!(kept.len(), 1);
5868 assert_eq!(kept[0].sanitized_branch, "main");
5869 assert!(rejected.contains("feature-a"));
5872 }
5873
5874 #[test]
5875 fn test_reject_case_colliding_worktrees_keeps_unambiguous() {
5876 let wts = vec![
5877 make_worktree("main", "main"),
5878 make_worktree("feature/a", "feature-a"),
5879 ];
5880 let (kept, rejected) = reject_case_colliding_worktrees(wts);
5881 assert_eq!(kept.len(), 2);
5882 assert!(rejected.is_empty());
5883 }
5884
5885 #[test]
5886 fn test_reject_case_colliding_worktrees_drops_sanitize_duplicates() {
5887 let wts = vec![
5890 make_worktree("feature/a", "feature-a"),
5891 make_worktree("feature.a", "feature-a"),
5892 ];
5893 let (kept, rejected) = reject_case_colliding_worktrees(wts);
5894 assert!(kept.is_empty());
5895 assert!(rejected.contains("feature-a"));
5896 }
5897
5898 #[test]
5899 fn test_match_worktree_prefix() {
5900 let mut entry = make_entry("myapp");
5901 entry.worktrees = vec![make_worktree("feature/b", "feature-b")];
5902 entry
5903 .rejected_worktree_prefixes
5904 .insert("feature-a".to_string());
5905
5906 assert!(matches!(
5907 match_worktree_prefix(&entry, "feature-b"),
5908 PrefixMatch::Worktree(_)
5909 ));
5910 assert!(matches!(
5912 match_worktree_prefix(&entry, "Feature-B"),
5913 PrefixMatch::Worktree(_)
5914 ));
5915 assert!(matches!(
5917 match_worktree_prefix(&entry, "feature-a"),
5918 PrefixMatch::Ambiguous
5919 ));
5920 assert!(matches!(
5921 match_worktree_prefix(&entry, "FEATURE-A"),
5922 PrefixMatch::Ambiguous
5923 ));
5924 assert!(matches!(
5926 match_worktree_prefix(&entry, "tenant"),
5927 PrefixMatch::Unknown
5928 ));
5929 }
5930
5931 #[test]
5934 fn test_passthrough_unroutable_message() {
5935 let no_tls = passthrough_unroutable_message("api.localhost", false);
5936 assert!(no_tls.contains("api.localhost"), "{no_tls}");
5937 assert!(no_tls.contains("settings.proxy.https = true"), "{no_tls}");
5938
5939 let mismatch = passthrough_unroutable_message("api.localhost", true);
5943 assert!(mismatch.contains("named a different host"), "{mismatch}");
5944 assert!(
5945 !mismatch.contains("settings.proxy.https"),
5946 "a host mismatch is not an HTTPS configuration problem: {mismatch}"
5947 );
5948 }
5949
5950 #[tokio::test]
5954 async fn test_slug_snapshot_is_the_cached_table() {
5955 let from_async = get_cached_slugs().await;
5956 let from_sync = slug_snapshot();
5957 assert!(
5958 Arc::ptr_eq(&from_async, &from_sync),
5959 "the synchronous read must see the same table routing does"
5960 );
5961 }
5962
5963 #[tokio::test]
5968 async fn test_concurrent_refresh_returns_the_published_table() {
5969 let (first, second) = tokio::join!(get_cached_slugs(), get_cached_slugs());
5972 assert!(
5973 Arc::ptr_eq(&first, &second),
5974 "overlapping refreshes must agree on one table"
5975 );
5976 assert!(
5977 Arc::ptr_eq(&first, &slug_snapshot()),
5978 "and it must be the published one"
5979 );
5980 }
5981
5982 #[test]
5986 fn test_resolve_tls_mode_in() {
5987 let mut entries = std::collections::HashMap::new();
5988
5989 let mut spliced = make_entry("spliced");
5990 spliced.tls = ProxyTlsRoute {
5991 protocol: Default::default(),
5992 mode: ProxyTlsMode::Passthrough,
5993 port: Some(8443),
5994 };
5995 spliced.worktrees = vec![
5996 make_worktree("feature/b", "feature-b"),
5997 make_worktree("feature/c", "feature-c"),
5998 ];
5999 spliced.worktree_tls.insert(
6000 "feature-b".to_string(),
6001 ProxyTlsRoute {
6002 protocol: Default::default(),
6003 mode: ProxyTlsMode::Terminate,
6004 port: None,
6005 },
6006 );
6007 entries.insert("spliced".to_string(), spliced);
6008 entries.insert("plain".to_string(), make_entry("plain"));
6009
6010 let mode =
6011 |host: &str| resolve_tls_mode_in(host, "localhost", &entries, &Default::default());
6012
6013 assert_eq!(mode("spliced.localhost"), ProxyTlsMode::Passthrough);
6014 assert_eq!(mode("SPLICED.localhost"), ProxyTlsMode::Passthrough);
6018 assert_eq!(mode("Spliced.LocalHost"), ProxyTlsMode::Passthrough);
6019 assert_eq!(mode("spliced.localhost."), ProxyTlsMode::Passthrough);
6020 assert_eq!(
6021 mode("FEATURE-C.Spliced.LOCALHOST."),
6022 ProxyTlsMode::Passthrough
6023 );
6024 assert_eq!(mode("tenant.spliced.localhost"), ProxyTlsMode::Passthrough);
6026 assert_eq!(mode("feature-b.spliced.localhost"), ProxyTlsMode::Terminate);
6028 assert_eq!(
6030 mode("feature-c.spliced.localhost"),
6031 ProxyTlsMode::Passthrough
6032 );
6033 assert_eq!(mode("plain.localhost"), ProxyTlsMode::Terminate);
6036 assert_eq!(mode("unknown.localhost"), ProxyTlsMode::Terminate);
6037 assert_eq!(mode("localhost"), ProxyTlsMode::Terminate);
6038 assert_eq!(mode("spliced.example.com"), ProxyTlsMode::Terminate);
6039 }
6040
6041 #[test]
6046 fn test_resolve_tls_mode_in_uses_the_hostname_registry() {
6047 let dir = tempfile::tempdir().unwrap();
6048 let project = dir.path().join("autoproj");
6049 std::fs::create_dir_all(&project).unwrap();
6050 std::fs::write(
6051 project.join("pitchfork.toml"),
6052 "[daemons.secure]\nrun = \"serve\"\nport = 8443\nproxy_tls = \"passthrough\"\n\
6053 [daemons.plain]\nrun = \"serve\"\nport = 8080\n",
6054 )
6055 .unwrap();
6056
6057 let registry =
6058 crate::proxy::hostname::HostRegistry::from_dirs(std::slice::from_ref(&project));
6059 let slugs = std::collections::HashMap::new();
6060 let mode = |host: &str| resolve_tls_mode_in(host, "localhost", &slugs, ®istry);
6061
6062 assert_eq!(mode("secure.autoproj.localhost"), ProxyTlsMode::Passthrough);
6063 assert_eq!(mode("plain.autoproj.localhost"), ProxyTlsMode::Terminate);
6064
6065 std::fs::write(project.join("pitchfork.toml"), "this is not toml = [\n").unwrap();
6069 assert_eq!(mode("secure.autoproj.localhost"), ProxyTlsMode::Passthrough);
6070 assert_eq!(mode("autoproj.localhost"), ProxyTlsMode::Terminate);
6073 assert_eq!(mode("nothing.autoproj.localhost"), ProxyTlsMode::Terminate);
6074 assert_eq!(mode("unknown.localhost"), ProxyTlsMode::Terminate);
6075 }
6076
6077 #[test]
6080 fn test_resolve_tls_mode_in_empty_table() {
6081 let entries = std::collections::HashMap::new();
6082 assert_eq!(
6083 resolve_tls_mode_in(
6084 "spliced.localhost",
6085 "localhost",
6086 &entries,
6087 &Default::default()
6088 ),
6089 ProxyTlsMode::Terminate
6090 );
6091 }
6092
6093 #[test]
6094 fn test_strip_dot_suffix_ignore_case() {
6095 assert_eq!(
6096 strip_dot_suffix_ignore_case("feature-a.myapp", "myapp"),
6097 Some("feature-a".to_string())
6098 );
6099 assert_eq!(
6100 strip_dot_suffix_ignore_case("Feature-A.MyApp", "myapp"),
6101 Some("Feature-A".to_string())
6102 );
6103 assert_eq!(
6104 strip_dot_suffix_ignore_case("feature-a.myapp", "MYAPP"),
6105 Some("feature-a".to_string())
6106 );
6107 assert_eq!(strip_dot_suffix_ignore_case("xmyapp", "myapp"), None);
6109 assert_eq!(strip_dot_suffix_ignore_case(".myapp", "myapp"), None);
6110 assert_eq!(strip_dot_suffix_ignore_case("myapp", "myapp"), None);
6111 assert_eq!(
6112 strip_dot_suffix_ignore_case("feature-a.other", "myapp"),
6113 None
6114 );
6115 assert_eq!(
6117 strip_dot_suffix_ignore_case("café.myapp", "myapp"),
6118 Some("café".to_string())
6119 );
6120 assert_eq!(strip_dot_suffix_ignore_case("café", "afé"), None);
6121 }
6122
6123 #[cfg(feature = "proxy-tls")]
6125 fn client_hello_wire(host: &str) -> Vec<u8> {
6126 let mut entry = vec![0u8];
6127 entry.extend_from_slice(&(host.len() as u16).to_be_bytes());
6128 entry.extend_from_slice(host.as_bytes());
6129 let mut sni = (entry.len() as u16).to_be_bytes().to_vec();
6130 sni.extend_from_slice(&entry);
6131
6132 let mut ext = vec![0x00, 0x00];
6133 ext.extend_from_slice(&(sni.len() as u16).to_be_bytes());
6134 ext.extend_from_slice(&sni);
6135
6136 let mut body = vec![0x03, 0x03];
6137 body.extend_from_slice(&[0x22; 32]);
6138 body.push(0);
6139 body.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]);
6140 body.extend_from_slice(&[0x01, 0x00]);
6141 body.extend_from_slice(&(ext.len() as u16).to_be_bytes());
6142 body.extend_from_slice(&ext);
6143
6144 let mut msg = vec![0x01];
6145 let len = body.len() as u32;
6146 msg.extend_from_slice(&[(len >> 16) as u8, (len >> 8) as u8, len as u8]);
6147 msg.extend_from_slice(&body);
6148
6149 let mut record = vec![0x16, 0x03, 0x01];
6150 record.extend_from_slice(&(msg.len() as u16).to_be_bytes());
6151 record.extend_from_slice(&msg);
6152 record
6153 }
6154
6155 #[cfg(feature = "proxy-tls")]
6158 async fn probe_over_socket(
6159 writes: Vec<Vec<u8>>,
6160 gap: std::time::Duration,
6161 timeout: std::time::Duration,
6162 ) -> (SniProbe, Vec<u8>) {
6163 probe_over_socket_then(writes, gap, timeout, false).await
6164 }
6165
6166 #[cfg(feature = "proxy-tls")]
6169 async fn probe_over_socket_then(
6170 writes: Vec<Vec<u8>>,
6171 gap: std::time::Duration,
6172 timeout: std::time::Duration,
6173 close_after: bool,
6174 ) -> (SniProbe, Vec<u8>) {
6175 use tokio::io::{AsyncReadExt, AsyncWriteExt};
6176
6177 let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
6178 .await
6179 .unwrap();
6180 let addr = listener.local_addr().unwrap();
6181 let total: usize = writes.iter().map(Vec::len).sum();
6182
6183 let client = tokio::spawn(async move {
6184 let mut sock = TcpStream::connect(addr).await.unwrap();
6185 for chunk in writes {
6186 sock.write_all(&chunk).await.unwrap();
6187 sock.flush().await.unwrap();
6188 tokio::time::sleep(gap).await;
6189 }
6190 if close_after {
6191 sock.shutdown().await.unwrap();
6192 }
6193 tokio::time::sleep(std::time::Duration::from_secs(2)).await;
6196 });
6197
6198 let (stream, _) = listener.accept().await.unwrap();
6199 let probe = peek_sni_host(&stream, timeout).await;
6200
6201 let mut replayed = vec![0u8; total];
6203 let mut stream = stream;
6204 let read = tokio::time::timeout(
6205 std::time::Duration::from_secs(2),
6206 stream.read_exact(&mut replayed),
6207 )
6208 .await;
6209 let replayed = match read {
6210 Ok(Ok(_)) => replayed,
6211 _ => vec![],
6212 };
6213 client.abort();
6214 (probe, replayed)
6215 }
6216
6217 #[cfg(feature = "proxy-tls")]
6221 #[tokio::test]
6222 async fn test_peek_sni_host_reads_a_hello_split_across_writes() {
6223 let wire = client_hello_wire("api.localhost");
6224 let writes: Vec<Vec<u8>> = wire.chunks(3).map(<[u8]>::to_vec).collect();
6225 let (probe, replayed) = probe_over_socket(
6226 writes,
6227 std::time::Duration::from_millis(5),
6228 std::time::Duration::from_secs(5),
6229 )
6230 .await;
6231
6232 assert_eq!(probe, SniProbe::Host("api.localhost".to_string()));
6233 assert_eq!(replayed, wire, "peeked bytes must still be readable");
6234 }
6235
6236 #[cfg(feature = "proxy-tls")]
6240 #[tokio::test]
6241 async fn test_peek_sni_host_undetermined_when_a_hello_stalls() {
6242 let wire = client_hello_wire("api.localhost");
6243 let truncated = wire[..wire.len() / 2].to_vec();
6244 let (probe, _) = probe_over_socket(
6245 vec![truncated],
6246 std::time::Duration::ZERO,
6247 std::time::Duration::from_millis(150),
6248 )
6249 .await;
6250
6251 assert_eq!(probe, SniProbe::Undetermined);
6252 }
6253
6254 #[cfg(feature = "proxy-tls")]
6258 #[tokio::test]
6259 async fn test_peek_sni_host_notices_a_client_that_closes_mid_hello() {
6260 let wire = client_hello_wire("api.localhost");
6261 let truncated = wire[..wire.len() / 2].to_vec();
6262 let started = std::time::Instant::now();
6263 let (probe, _) = probe_over_socket_then(
6264 vec![truncated],
6265 std::time::Duration::ZERO,
6266 std::time::Duration::from_secs(5),
6267 true,
6268 )
6269 .await;
6270
6271 assert_eq!(probe, SniProbe::Undetermined);
6272 assert!(
6273 started.elapsed() < std::time::Duration::from_secs(1),
6274 "the probe must end when the client closes, not at its deadline"
6275 );
6276 }
6277
6278 #[cfg(feature = "proxy-tls")]
6282 #[tokio::test]
6283 async fn test_peek_sni_host_gives_up_on_a_silent_peer() {
6284 let started = std::time::Instant::now();
6285 let (probe, _) = probe_over_socket(
6286 vec![],
6287 std::time::Duration::ZERO,
6288 std::time::Duration::from_millis(150),
6289 )
6290 .await;
6291
6292 assert_eq!(probe, SniProbe::Undetermined);
6293 assert!(
6294 started.elapsed() < std::time::Duration::from_secs(1),
6295 "the probe must end at its deadline, not wait on the peer"
6296 );
6297 }
6298
6299 #[cfg(feature = "proxy-tls")]
6302 #[tokio::test]
6303 async fn test_peek_sni_host_reports_no_host_for_non_tls() {
6304 let (probe, _) = probe_over_socket(
6305 vec![b"GET / HTTP/1.1\r\n\r\n".to_vec()],
6306 std::time::Duration::ZERO,
6307 std::time::Duration::from_secs(5),
6308 )
6309 .await;
6310
6311 assert_eq!(probe, SniProbe::NoHost);
6312 }
6313
6314 #[cfg(feature = "proxy-tls")]
6315 #[test]
6316 fn test_generate_ca() {
6317 let dir = tempfile::tempdir().unwrap();
6318 let cert_path = dir.path().join("ca.pem");
6319 let key_path = dir.path().join("ca-key.pem");
6320
6321 generate_ca(&cert_path, &key_path).unwrap();
6322
6323 assert!(cert_path.exists(), "ca.pem should be created");
6324 assert!(key_path.exists(), "ca-key.pem should be created");
6325
6326 let cert_pem = std::fs::read_to_string(&cert_path).unwrap();
6327 let key_pem = std::fs::read_to_string(&key_path).unwrap();
6328
6329 assert!(cert_pem.contains("BEGIN CERTIFICATE"), "should be PEM cert");
6330 assert!(
6331 key_pem.contains("BEGIN") && key_pem.contains("PRIVATE KEY"),
6332 "should be PEM key"
6333 );
6334 }
6335
6336 fn cookie_fields(headers: &HeaderMap) -> Vec<&[u8]> {
6338 headers
6339 .get_all(COOKIE)
6340 .iter()
6341 .map(HeaderValue::as_bytes)
6342 .collect()
6343 }
6344
6345 #[test]
6348 fn test_join_cookie_fields_joins_with_semicolon_space() {
6349 let mut headers = HeaderMap::new();
6350 headers.append(COOKIE, HeaderValue::from_static("_session=abc123"));
6351 headers.append(COOKIE, HeaderValue::from_static("consent=ads,stats"));
6352 headers.append(COOKIE, HeaderValue::from_static("theme=dark"));
6353
6354 join_cookie_fields(&mut headers);
6355
6356 assert_eq!(
6357 cookie_fields(&headers),
6358 vec![&b"_session=abc123; consent=ads,stats; theme=dark"[..]]
6359 );
6360 }
6361
6362 #[test]
6365 fn test_join_cookie_fields_joins_bytes_outside_ascii() {
6366 let mut headers = HeaderMap::new();
6367 headers.append(COOKIE, HeaderValue::from_static("_session=abc123"));
6368 headers.append(
6369 COOKIE,
6370 HeaderValue::from_bytes(b"name=Jos\xc3\xa9").unwrap(),
6371 );
6372
6373 join_cookie_fields(&mut headers);
6374
6375 assert_eq!(
6376 cookie_fields(&headers),
6377 vec![&b"_session=abc123; name=Jos\xc3\xa9"[..]]
6378 );
6379 }
6380
6381 #[test]
6383 fn test_join_cookie_fields_without_cookies() {
6384 let mut headers = HeaderMap::new();
6385 headers.insert(HOST, HeaderValue::from_static("app.localhost"));
6386
6387 join_cookie_fields(&mut headers);
6388
6389 assert!(headers.get(COOKIE).is_none());
6390 }
6391
6392 #[test]
6393 fn test_host_port_suffix() {
6394 assert_eq!(host_port_suffix("api.myproj.localhost:8088"), ":8088");
6395 assert_eq!(host_port_suffix("api.myproj.localhost"), "");
6396 assert_eq!(host_port_suffix("[::1]:8088"), ":8088");
6397 assert_eq!(host_port_suffix("[::1]"), "");
6398 assert_eq!(host_port_suffix("host:notaport"), "");
6400 }
6401
6402 #[test]
6406 fn test_daemon_runs_in() {
6407 let temp = tempfile::tempdir().unwrap();
6408 let repo = temp.path().join("my-repo");
6409 std::fs::create_dir_all(repo.join(".git/worktrees/feature")).unwrap();
6410 std::fs::create_dir_all(repo.join("sub")).unwrap();
6411 let nested = repo.join(".worktrees/feature");
6413 std::fs::create_dir_all(&nested).unwrap();
6414 std::fs::write(
6415 nested.join(".git"),
6416 format!(
6417 "gitdir: {}\n",
6418 repo.join(".git/worktrees/feature").display()
6419 ),
6420 )
6421 .unwrap();
6422
6423 let root = |p: &std::path::Path| crate::proxy::hostname::checkout_root_of(p);
6424 let repo_root = root(&repo);
6425 let nested_root = root(&nested);
6426
6427 let mut daemon = crate::daemon::Daemon {
6428 dir: Some(repo.join("sub")),
6429 ..Default::default()
6430 };
6431 assert!(daemon_runs_in(&daemon, &repo_root));
6432 assert!(!daemon_runs_in(&daemon, &nested_root));
6433
6434 daemon.dir = Some(nested.clone());
6437 assert!(daemon_runs_in(&daemon, &nested_root));
6438 assert!(!daemon_runs_in(&daemon, &repo_root));
6439
6440 daemon.dir = Some(temp.path().join("elsewhere"));
6442 assert!(!daemon_runs_in(&daemon, &repo_root));
6443
6444 daemon.dir = None;
6445 assert!(!daemon_runs_in(&daemon, &repo_root));
6446 }
6447
6448 #[test]
6451 fn test_is_local_client() {
6452 let build = |info: Option<SocketAddr>| {
6453 let mut req = Request::new(Body::empty());
6454 if let Some(addr) = info {
6455 req.extensions_mut()
6456 .insert(axum::extract::ConnectInfo(addr));
6457 }
6458 req
6459 };
6460
6461 assert!(is_local_client(&build(Some(
6462 "127.0.0.1:5000".parse().unwrap()
6463 ))));
6464 assert!(is_local_client(&build(Some("[::1]:5000".parse().unwrap()))));
6465 assert!(!is_local_client(&build(Some(
6466 "192.168.1.42:5000".parse().unwrap()
6467 ))));
6468 assert!(!is_local_client(&build(None)));
6469 }
6470}