pitchfork_cli/proxy/
mod.rs1pub 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
28pub(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 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
71pub(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 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
97pub(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
108pub(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
126pub 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
137pub 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 assert_eq!(throttle.allow(Duration::from_secs(60)), Some(0));
179 for _ in 0..5 {
181 assert_eq!(throttle.allow(Duration::from_secs(60)), None);
182 }
183 assert_eq!(throttle.allow(Duration::ZERO), Some(5));
185 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 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 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 let exact = ascii_case_collisions(["dup", "dup"].into_iter());
228 assert!(exact.contains("dup"));
229
230 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 #[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 #[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 #[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 #[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}