Skip to main content

pitchfork_cli/proxy/
mod.rs

1//! Reverse proxy server for pitchfork daemons.
2//!
3//! Routes `<slug>.<tld>:<port>` to the daemon's actual listening port.
4//! Slugs are defined in the global config (`~/.config/pitchfork/config.toml`)
5//! under `[slugs]`. Each slug maps to a project directory and daemon name.
6//!
7//! # URL Routing
8//!
9//! ```text
10//! myapp.localhost:7777          →  localhost:8080  (via slug)
11//! ```
12
13pub mod activity;
14pub mod dns;
15pub mod doctor;
16pub mod hostname;
17pub mod hosts;
18pub mod lan_ip;
19pub mod mdns;
20pub mod pac;
21pub mod public_url;
22pub mod server;
23pub mod setup;
24pub mod sni;
25pub mod trust;
26pub mod worktree;
27
28/// Rate limiter for a log line that an outside party can trigger at will.
29///
30/// The proxy and the resolver both refuse work under load, and a client can
31/// provoke those refusals as fast as it can open sockets. Logging each one
32/// hands that client a way to fill the disk, so the message is emitted at most
33/// once per interval and carries the number suppressed since.
34pub(crate) struct LogThrottle {
35    last: std::sync::Mutex<Option<std::time::Instant>>,
36    suppressed: std::sync::atomic::AtomicU64,
37}
38
39impl LogThrottle {
40    pub(crate) const fn new() -> Self {
41        Self {
42            last: std::sync::Mutex::new(None),
43            suppressed: std::sync::atomic::AtomicU64::new(0),
44        }
45    }
46
47    /// Whether to log now, and how many were suppressed since the last time.
48    ///
49    /// `None` means stay quiet. A poisoned lock logs rather than goes silent,
50    /// since losing the message entirely is the worse failure.
51    pub(crate) fn allow(&self, every: std::time::Duration) -> Option<u64> {
52        use std::sync::atomic::Ordering;
53        let now = std::time::Instant::now();
54        let mut last = match self.last.lock() {
55            Ok(g) => g,
56            Err(e) => e.into_inner(),
57        };
58        match *last {
59            Some(t) if now.duration_since(t) < every => {
60                self.suppressed.fetch_add(1, Ordering::Relaxed);
61                None
62            }
63            _ => {
64                *last = Some(now);
65                Some(self.suppressed.swap(0, Ordering::Relaxed))
66            }
67        }
68    }
69}
70
71/// Whether `name` is the TLD itself or a name beneath it.
72///
73/// One definition shared by the DNS responder, which uses it to decide what it
74/// is authoritative for, and the certificate resolver, which uses it to decide
75/// what the local CA is allowed to sign. Those two answers must agree: a name
76/// the proxy will not resolve is a name it must not issue a certificate for.
77///
78/// Comparison is ASCII case-insensitive, per RFC 4343, and a trailing root dot
79/// is ignored.
80pub(crate) fn owns_name(tld: &str, name: &str) -> bool {
81    let name = name.trim_end_matches('.');
82    let tld = tld.trim_matches('.');
83    if tld.is_empty() || name.is_empty() {
84        return false;
85    }
86    if name.eq_ignore_ascii_case(tld) {
87        return true;
88    }
89    // Byte comparison: a DNS label may hold non-UTF-8 data, so slicing a
90    // lossily-decoded string could land mid-character.
91    let (name, tld) = (name.as_bytes(), tld.as_bytes());
92    name.len() > tld.len() + 1
93        && name[name.len() - tld.len() - 1] == b'.'
94        && name[name.len() - tld.len()..].eq_ignore_ascii_case(tld)
95}
96
97/// Whether `name` sits strictly beneath `tld`, rather than being the TLD itself.
98///
99/// Used for the sibling wildcard on a minted certificate: `*.<tld>` would cover
100/// the entire TLD, which is broader than the one host the certificate is for.
101pub(crate) fn is_strictly_under_tld(tld: &str, name: &str) -> bool {
102    !name
103        .trim_end_matches('.')
104        .eq_ignore_ascii_case(tld.trim_matches('.'))
105        && owns_name(tld, name)
106}
107
108/// Lowercased keys that more than one spelling in `keys` maps to.
109///
110/// Host names are case-insensitive (RFC 4343), so such keys are ambiguous as
111/// routing targets no matter which spelling a request uses.
112pub(crate) fn ascii_case_collisions<'a>(
113    keys: impl Iterator<Item = &'a str>,
114) -> std::collections::HashSet<String> {
115    let mut seen = std::collections::HashSet::new();
116    let mut collisions = std::collections::HashSet::new();
117    for key in keys {
118        let folded = key.to_ascii_lowercase();
119        if !seen.insert(folded.clone()) {
120            collisions.insert(folded);
121        }
122    }
123    collisions
124}
125
126/// The TLD the proxy actually serves on.
127///
128/// LAN mode forces `.local`, because mDNS publishes names in that domain.
129pub fn effective_tld(s: &crate::settings::Settings) -> &str {
130    if s.proxy.lan || !s.proxy.lan_ip.is_empty() {
131        "local"
132    } else {
133        &s.proxy.tld
134    }
135}
136
137/// Build the URL for a proxy hostname: a legacy slug, or an automatic
138/// `<daemon>.<worktree>.<project>` host.
139///
140/// This is the one place a pitchfork URL is spelled out, so everything that
141/// shows a URL, injects `PITCHFORK_URL`, or renders a template agrees with what
142/// the proxy serves.
143///
144/// Returns `None` if:
145/// - `host` is `None` (not proxied)
146/// - Proxy is disabled in settings
147/// - `proxy.port` is invalid (out of range or zero)
148pub fn build_proxy_url(host: Option<&str>, s: &crate::settings::Settings) -> Option<String> {
149    if !s.proxy.enable {
150        return None;
151    }
152    let host = host?;
153
154    let scheme = if s.proxy.https { "https" } else { "http" };
155    let tld = effective_tld(s);
156    let standard_port = if s.proxy.https { 443u16 } else { 80u16 };
157
158    let effective_port = u16::try_from(s.proxy.port).ok().filter(|&p| p > 0)?;
159
160    let authority = format!("{host}.{tld}");
161
162    Some(if effective_port == standard_port {
163        format!("{scheme}://{authority}")
164    } else {
165        format!("{scheme}://{authority}:{effective_port}")
166    })
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn a_throttled_message_reports_what_it_suppressed() {
175        use std::time::Duration;
176        let throttle = LogThrottle::new();
177        // First call goes through, with nothing suppressed yet.
178        assert_eq!(throttle.allow(Duration::from_secs(60)), Some(0));
179        // Everything inside the window stays quiet.
180        for _ in 0..5 {
181            assert_eq!(throttle.allow(Duration::from_secs(60)), None);
182        }
183        // A zero window always allows, and reports the five it swallowed.
184        assert_eq!(throttle.allow(Duration::ZERO), Some(5));
185        // The count resets after being reported.
186        assert_eq!(throttle.allow(Duration::ZERO), Some(0));
187    }
188
189    #[test]
190    fn owns_name_matches_the_apex_and_names_beneath_it() {
191        assert!(owns_name("localhost", "localhost"));
192        assert!(owns_name("localhost", "api.localhost"));
193        assert!(owns_name("localhost", "core.fix-refs.proj.localhost"));
194        assert!(owns_name("localhost", "API.LocalHost"));
195        assert!(owns_name("localhost", "api.localhost."));
196        assert!(owns_name("dev.internal", "api.dev.internal"));
197
198        assert!(!owns_name("localhost", "example.com"));
199        // Ends with the letters but not at a label boundary.
200        assert!(!owns_name("localhost", "notlocalhost"));
201        assert!(!owns_name("localhost", "localhost.evil.com"));
202        assert!(!owns_name("localhost", ""));
203        assert!(!owns_name("", "api.localhost"));
204    }
205
206    #[test]
207    fn is_strictly_under_tld_excludes_the_apex() {
208        assert!(is_strictly_under_tld("localhost", "api.localhost"));
209        // The apex itself is not "under" the TLD: a wildcard there would cover
210        // every name in it.
211        assert!(!is_strictly_under_tld("localhost", "localhost"));
212        assert!(!is_strictly_under_tld("dev.internal", "dev.internal"));
213        assert!(is_strictly_under_tld("dev.internal", "a.dev.internal"));
214        assert!(!is_strictly_under_tld("localhost", "example.com"));
215    }
216
217    #[test]
218    fn test_ascii_case_collisions() {
219        let none = ascii_case_collisions(["myapp", "other", "third"].into_iter());
220        assert!(none.is_empty());
221
222        let folded = ascii_case_collisions(["MyApp", "myapp", "other"].into_iter());
223        assert_eq!(folded.len(), 1);
224        assert!(folded.contains("myapp"));
225
226        // Identical spellings collide too, not just case-only variants.
227        let exact = ascii_case_collisions(["dup", "dup"].into_iter());
228        assert!(exact.contains("dup"));
229
230        // Folding is ASCII-only: DNS does not case-fold non-ASCII labels.
231        let unicode = ascii_case_collisions(["café", "CAFÉ"].into_iter());
232        assert!(unicode.is_empty());
233    }
234
235    fn proxy_settings() -> crate::settings::Settings {
236        let mut s = crate::settings::Settings::default();
237        s.proxy.enable = true;
238        s.proxy.https = true;
239        s.proxy.port = 443;
240        s.proxy.tld = "localhost".to_string();
241        s
242    }
243
244    /// The standard port is omitted, a custom one is not.
245    #[test]
246    fn test_build_proxy_url_port_suffix() {
247        let mut s = proxy_settings();
248        assert_eq!(
249            build_proxy_url(Some("api.myproj"), &s).as_deref(),
250            Some("https://api.myproj.localhost")
251        );
252        s.proxy.port = 8088;
253        assert_eq!(
254            build_proxy_url(Some("api.myproj"), &s).as_deref(),
255            Some("https://api.myproj.localhost:8088")
256        );
257        s.proxy.https = false;
258        s.proxy.port = 80;
259        assert_eq!(
260            build_proxy_url(Some("api.myproj"), &s).as_deref(),
261            Some("http://api.myproj.localhost")
262        );
263    }
264
265    /// Nothing advertises a URL while the proxy is off, and an unrouted daemon
266    /// has none either.
267    #[test]
268    fn test_build_proxy_url_requires_enabled_proxy_and_host() {
269        let mut s = proxy_settings();
270        assert_eq!(build_proxy_url(None, &s), None);
271        s.proxy.enable = false;
272        assert_eq!(build_proxy_url(Some("api.myproj"), &s), None);
273    }
274
275    /// LAN mode serves `.local`, whatever `proxy.tld` says, so URLs must follow.
276    #[test]
277    fn test_build_proxy_url_uses_lan_tld() {
278        let mut s = proxy_settings();
279        s.proxy.tld = "test".to_string();
280        assert_eq!(effective_tld(&s), "test");
281
282        s.proxy.lan = true;
283        assert_eq!(effective_tld(&s), "local");
284        assert_eq!(
285            build_proxy_url(Some("api.myproj"), &s).as_deref(),
286            Some("https://api.myproj.local")
287        );
288
289        s.proxy.lan = false;
290        s.proxy.lan_ip = "192.168.1.42".to_string();
291        assert_eq!(
292            build_proxy_url(Some("api.myproj"), &s).as_deref(),
293            Some("https://api.myproj.local")
294        );
295    }
296
297    /// An out-of-range port has no URL to show rather than a broken one.
298    #[test]
299    fn test_build_proxy_url_rejects_invalid_port() {
300        let mut s = proxy_settings();
301        s.proxy.port = 0;
302        assert_eq!(build_proxy_url(Some("api.myproj"), &s), None);
303        s.proxy.port = 70000;
304        assert_eq!(build_proxy_url(Some("api.myproj"), &s), None);
305    }
306}