1use std::{net::IpAddr, time::Duration};
4
5use ipnet::IpNet;
6
7use crate::{
8 checks::{Checks, Thresholds},
9 cookie::CookieConfig,
10 error::ConfigError,
11};
12
13const MAX_DURATION: Duration = Duration::from_hours(100 * 365 * 24);
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18pub enum Mode {
19 #[default]
21 Enforce,
22 Shadow,
25}
26
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum StepUpPolicy {
31 #[default]
34 Require,
35 Revoke,
38 Allow,
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct RotationConfig {
46 pub interval: Duration,
48 pub grace: Duration,
51 pub reuse_detection: Duration,
54}
55
56impl Default for RotationConfig {
57 fn default() -> Self {
58 Self {
59 interval: Duration::from_mins(10),
60 grace: Duration::from_secs(30),
61 reuse_detection: Duration::from_hours(7 * 24),
62 }
63 }
64}
65
66#[derive(Clone, Debug)]
69pub struct GuardConfig {
70 pub(crate) cookie: CookieConfig,
71 pub(crate) session_lifetime: time::Duration,
72 pub(crate) idle_timeout: time::Duration,
73 pub(crate) trusted_proxies: Vec<IpNet>,
74 pub(crate) tls_fingerprint_header: Option<String>,
75 pub(crate) rotation_interval: time::Duration,
76 pub(crate) rotation_grace: time::Duration,
77 pub(crate) reuse_detection: time::Duration,
78 pub(crate) checks: Checks,
79 pub(crate) thresholds: Thresholds,
80 pub(crate) mode: Mode,
81 pub(crate) step_up_policy: StepUpPolicy,
82 pub(crate) ping_pong_window: time::Duration,
83 pub(crate) last_seen_write_interval: time::Duration,
84 pub(crate) event_retention: time::Duration,
85 pub(crate) minimize_stored_events: bool,
86 pub(crate) keep_origin_client: bool,
87 pub(crate) shadow_dedup_window: time::Duration,
88 pub(crate) alert_dedup_window: time::Duration,
89 pub(crate) max_header_len: usize,
90 pub(crate) token_prefix: Option<String>,
91 pub(crate) orphan_reissue_window: Option<time::Duration>,
92}
93
94impl Default for GuardConfig {
95 fn default() -> Self {
96 GuardConfigBuilder::default()
97 .build()
98 .unwrap_or_else(|_| unreachable!("default configuration is valid"))
99 }
100}
101
102impl GuardConfig {
103 pub fn builder() -> GuardConfigBuilder {
105 GuardConfigBuilder::default()
106 }
107
108 pub fn cookie(&self) -> &CookieConfig {
110 &self.cookie
111 }
112
113 pub fn session_lifetime(&self) -> Duration {
115 to_std(self.session_lifetime)
116 }
117
118 pub fn idle_timeout(&self) -> Duration {
120 to_std(self.idle_timeout)
121 }
122
123 pub fn trusted_proxies(&self) -> &[IpNet] {
125 &self.trusted_proxies
126 }
127
128 pub fn tls_fingerprint_header(&self) -> Option<&str> {
130 self.tls_fingerprint_header.as_deref()
131 }
132
133 pub fn rotation(&self) -> RotationConfig {
135 RotationConfig {
136 interval: to_std(self.rotation_interval),
137 grace: to_std(self.rotation_grace),
138 reuse_detection: to_std(self.reuse_detection),
139 }
140 }
141
142 pub fn checks(&self) -> &Checks {
144 &self.checks
145 }
146
147 pub fn thresholds(&self) -> Thresholds {
149 self.thresholds
150 }
151
152 pub fn mode(&self) -> Mode {
154 self.mode
155 }
156
157 pub fn step_up_policy(&self) -> StepUpPolicy {
159 self.step_up_policy
160 }
161
162 pub fn ping_pong_window(&self) -> Duration {
164 to_std(self.ping_pong_window)
165 }
166
167 pub fn last_seen_write_interval(&self) -> Duration {
169 to_std(self.last_seen_write_interval)
170 }
171
172 pub fn event_retention(&self) -> Duration {
175 to_std(self.event_retention)
176 }
177
178 pub fn minimize_stored_events(&self) -> bool {
181 self.minimize_stored_events
182 }
183
184 pub fn keep_origin_client(&self) -> bool {
187 self.keep_origin_client
188 }
189
190 pub fn shadow_dedup_window(&self) -> Duration {
192 to_std(self.shadow_dedup_window)
193 }
194
195 pub fn alert_dedup_window(&self) -> Duration {
198 to_std(self.alert_dedup_window)
199 }
200
201 pub fn max_header_len(&self) -> usize {
203 self.max_header_len
204 }
205
206 pub fn token_prefix(&self) -> Option<&str> {
208 self.token_prefix.as_deref()
209 }
210
211 pub fn orphan_reissue_window(&self) -> Option<Duration> {
213 self.orphan_reissue_window.map(to_std)
214 }
215}
216
217fn to_std(delta: time::Duration) -> Duration {
218 Duration::try_from(delta).unwrap_or_default()
219}
220
221#[derive(Clone, Debug)]
223#[must_use]
224pub struct GuardConfigBuilder {
225 cookie: CookieConfig,
226 session_lifetime: Duration,
227 idle_timeout: Duration,
228 trusted_proxies: Vec<IpNet>,
229 tls_fingerprint_header: Option<String>,
230 rotation: RotationConfig,
231 checks: Checks,
232 thresholds: Thresholds,
233 mode: Mode,
234 step_up_policy: StepUpPolicy,
235 ping_pong_window: Duration,
236 last_seen_write_interval: Duration,
237 event_retention: Duration,
238 minimize_stored_events: bool,
239 keep_origin_client: bool,
240 shadow_dedup_window: Duration,
241 alert_dedup_window: Duration,
242 max_header_len: usize,
243 token_prefix: Option<String>,
244 orphan_reissue_window: Option<Duration>,
245}
246
247impl Default for GuardConfigBuilder {
248 fn default() -> Self {
249 const MINUTE: u64 = 60;
250 const DAY: u64 = 24 * 60 * MINUTE;
251 Self {
252 cookie: CookieConfig::default(),
253 session_lifetime: Duration::from_secs(30 * DAY),
254 idle_timeout: Duration::from_secs(7 * DAY),
255 trusted_proxies: Vec::new(),
256 tls_fingerprint_header: None,
257 rotation: RotationConfig::default(),
258 checks: Checks::default(),
259 thresholds: Thresholds::default(),
260 mode: Mode::Enforce,
261 step_up_policy: StepUpPolicy::Require,
262 ping_pong_window: Duration::from_secs(5 * MINUTE),
263 last_seen_write_interval: Duration::from_secs(MINUTE),
264 event_retention: Duration::from_secs(90 * DAY),
265 minimize_stored_events: true,
266 keep_origin_client: false,
267 shadow_dedup_window: Duration::from_secs(10 * MINUTE),
268 alert_dedup_window: Duration::ZERO,
269 max_header_len: 512,
270 token_prefix: None,
271 orphan_reissue_window: None,
272 }
273 }
274}
275
276impl GuardConfigBuilder {
277 pub fn cookie(mut self, cookie: CookieConfig) -> Self {
279 self.cookie = cookie;
280 self
281 }
282
283 pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
285 self.cookie = self.cookie.name(name);
286 self
287 }
288
289 pub fn session_lifetime(mut self, lifetime: Duration) -> Self {
292 self.session_lifetime = lifetime;
293 self
294 }
295
296 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
298 self.idle_timeout = timeout;
299 self
300 }
301
302 pub fn trusted_proxies<I, T>(mut self, proxies: I) -> Result<Self, ConfigError>
309 where
310 I: IntoIterator<Item = T>,
311 T: AsRef<str>,
312 {
313 self.trusted_proxies = proxies
314 .into_iter()
315 .map(|p| {
316 let p = p.as_ref().trim();
317 p.parse::<IpNet>()
318 .or_else(|_| p.parse::<IpAddr>().map(IpNet::from))
319 .map(|net| net.trunc())
320 .map_err(|_| ConfigError::InvalidProxy(p.to_owned()))
321 })
322 .collect::<Result<_, _>>()?;
323 Ok(self)
324 }
325
326 pub fn tls_fingerprint_header(mut self, header: impl Into<String>) -> Self {
330 self.tls_fingerprint_header = Some(header.into().to_ascii_lowercase());
331 self
332 }
333
334 pub fn rotation(mut self, rotation: RotationConfig) -> Self {
336 self.rotation = rotation;
337 self
338 }
339
340 pub fn checks(mut self, checks: Checks) -> Self {
342 self.checks = checks;
343 self
344 }
345
346 pub fn thresholds(mut self, thresholds: Thresholds) -> Self {
348 self.thresholds = thresholds;
349 self
350 }
351
352 pub fn mode(mut self, mode: Mode) -> Self {
354 self.mode = mode;
355 self
356 }
357
358 pub fn step_up_policy(mut self, policy: StepUpPolicy) -> Self {
360 self.step_up_policy = policy;
361 self
362 }
363
364 pub fn orphan_reissue_window(mut self, window: Duration) -> Self {
371 self.orphan_reissue_window = Some(window);
372 self
373 }
374
375 pub fn ping_pong_window(mut self, window: Duration) -> Self {
377 self.ping_pong_window = window;
378 self
379 }
380
381 pub fn last_seen_write_interval(mut self, interval: Duration) -> Self {
384 self.last_seen_write_interval = interval;
385 self
386 }
387
388 pub fn event_retention(mut self, retention: Duration) -> Self {
390 self.event_retention = retention;
391 self
392 }
393
394 pub fn minimize_stored_events(mut self, minimize: bool) -> Self {
399 self.minimize_stored_events = minimize;
400 self
401 }
402
403 pub fn keep_origin_client(mut self, keep: bool) -> Self {
408 self.keep_origin_client = keep;
409 self
410 }
411
412 pub fn shadow_dedup_window(mut self, window: Duration) -> Self {
414 self.shadow_dedup_window = window;
415 self
416 }
417
418 pub fn alert_dedup_window(mut self, window: Duration) -> Self {
429 self.alert_dedup_window = window;
430 self
431 }
432
433 pub fn max_header_len(mut self, len: usize) -> Self {
435 self.max_header_len = len;
436 self
437 }
438
439 pub fn token_prefix(mut self, prefix: impl Into<String>) -> Self {
447 self.token_prefix = Some(prefix.into());
448 self
449 }
450
451 pub fn build(self) -> Result<GuardConfig, ConfigError> {
458 self.cookie.validate()?;
459 if !self.thresholds.is_valid() {
460 return Err(ConfigError::InvalidThresholds);
461 }
462 if self.rotation.grace >= self.rotation.interval {
463 return Err(ConfigError::GraceTooLong);
464 }
465 if self.max_header_len == 0 {
466 return Err(ConfigError::InvalidDuration("max_header_len"));
467 }
468 if let Some(h) = &self.tls_fingerprint_header
469 && (h.is_empty() || !h.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
470 {
471 return Err(ConfigError::InvalidHeaderName(h.clone()));
472 }
473 if let Some(p) = &self.token_prefix
474 && (p.is_empty() || p.len() > 32 || !p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
475 {
476 return Err(ConfigError::InvalidTokenPrefix(p.clone()));
477 }
478 Ok(GuardConfig {
479 cookie: self.cookie,
480 session_lifetime: positive(self.session_lifetime, "session_lifetime")?,
481 idle_timeout: positive(self.idle_timeout, "idle_timeout")?,
482 trusted_proxies: self.trusted_proxies,
483 tls_fingerprint_header: self.tls_fingerprint_header,
484 rotation_interval: positive(self.rotation.interval, "rotation.interval")?,
485 rotation_grace: bounded(self.rotation.grace, "rotation.grace")?,
486 reuse_detection: positive(self.rotation.reuse_detection, "rotation.reuse_detection")?,
487 checks: self.checks,
488 thresholds: self.thresholds,
489 mode: self.mode,
490 step_up_policy: self.step_up_policy,
491 ping_pong_window: bounded(self.ping_pong_window, "ping_pong_window")?,
492 last_seen_write_interval: bounded(self.last_seen_write_interval, "last_seen_write_interval")?,
493 event_retention: positive(self.event_retention, "event_retention")?,
494 minimize_stored_events: self.minimize_stored_events,
495 keep_origin_client: self.keep_origin_client,
496 shadow_dedup_window: bounded(self.shadow_dedup_window, "shadow_dedup_window")?,
497 alert_dedup_window: bounded(self.alert_dedup_window, "alert_dedup_window")?,
498 max_header_len: self.max_header_len,
499 token_prefix: self.token_prefix,
500 orphan_reissue_window: self
501 .orphan_reissue_window
502 .map(|w| bounded(w, "orphan_reissue_window"))
503 .transpose()?,
504 })
505 }
506}
507
508fn positive(d: Duration, name: &'static str) -> Result<time::Duration, ConfigError> {
509 if d.is_zero() {
510 return Err(ConfigError::InvalidDuration(name));
511 }
512 bounded(d, name)
513}
514
515fn bounded(d: Duration, name: &'static str) -> Result<time::Duration, ConfigError> {
516 if d > MAX_DURATION {
517 return Err(ConfigError::InvalidDuration(name));
518 }
519 time::Duration::try_from(d).map_err(|_| ConfigError::InvalidDuration(name))
520}
521
522#[cfg(test)]
523mod tests {
524 use super::*;
525 use crate::checks::Check;
526
527 #[test]
528 fn defaults_match_the_spec() {
529 let c = GuardConfig::default();
530 assert_eq!(c.cookie().cookie_name(), "__Host-sid");
531 assert_eq!(c.session_lifetime(), Duration::from_hours(30 * 24));
532 assert_eq!(c.idle_timeout(), Duration::from_hours(7 * 24));
533 assert_eq!(c.rotation(), RotationConfig::default());
534 assert_eq!(c.rotation().interval, Duration::from_secs(600));
535 assert_eq!(c.rotation().grace, Duration::from_secs(30));
536 assert_eq!(c.mode(), Mode::Enforce);
537 assert_eq!(c.step_up_policy(), StepUpPolicy::Require);
538 assert_eq!(c.checks(), &Checks::default());
539 assert_eq!(c.thresholds(), Thresholds::default());
540 assert_eq!(c.event_retention(), Duration::from_hours(90 * 24));
541 assert!(c.minimize_stored_events());
542 assert!(!c.keep_origin_client());
543 assert_eq!(c.trusted_proxies(), &[]);
544 assert_eq!(c.orphan_reissue_window(), None);
545 assert_eq!(c.alert_dedup_window(), Duration::ZERO);
546 }
547
548 #[test]
549 fn builder_sets_everything() {
550 let c = GuardConfig::builder()
551 .cookie_name("__Host-app")
552 .session_lifetime(Duration::from_secs(3600))
553 .idle_timeout(Duration::from_secs(600))
554 .trusted_proxies(["10.0.0.0/8", "::1", " 192.168.1.7 "])
555 .unwrap()
556 .tls_fingerprint_header("X-JA4")
557 .checks(Checks::default().disable(Check::AsnChanged))
558 .thresholds(Thresholds {
559 step_up: 30,
560 revoke: 90,
561 })
562 .mode(Mode::Shadow)
563 .step_up_policy(StepUpPolicy::Allow)
564 .minimize_stored_events(false)
565 .keep_origin_client(true)
566 .orphan_reissue_window(Duration::from_secs(3600))
567 .alert_dedup_window(Duration::from_mins(15))
568 .build()
569 .unwrap();
570 assert_eq!(c.cookie().cookie_name(), "__Host-app");
571 assert_eq!(c.alert_dedup_window(), Duration::from_mins(15));
572 assert_eq!(c.orphan_reissue_window(), Some(Duration::from_secs(3600)));
573 assert_eq!(c.trusted_proxies().len(), 3);
574 assert!(
575 c.trusted_proxies()
576 .iter()
577 .any(|n| n.contains(&"10.1.2.3".parse::<IpAddr>().unwrap()))
578 );
579 assert!(
580 c.trusted_proxies()
581 .iter()
582 .any(|n| n.contains(&"192.168.1.7".parse::<IpAddr>().unwrap()))
583 );
584 assert!(
585 !c.trusted_proxies()
586 .iter()
587 .any(|n| n.contains(&"192.168.1.8".parse::<IpAddr>().unwrap()))
588 );
589 assert_eq!(c.tls_fingerprint_header(), Some("x-ja4"));
590 assert_eq!(c.mode(), Mode::Shadow);
591 assert_eq!(c.step_up_policy(), StepUpPolicy::Allow);
592 assert!(!c.minimize_stored_events());
593 assert!(c.keep_origin_client());
594 }
595
596 #[test]
597 fn invalid_configs_are_rejected() {
598 let b = GuardConfig::builder;
599 assert_eq!(
600 b().trusted_proxies(["nope"]).unwrap_err(),
601 ConfigError::InvalidProxy("nope".into())
602 );
603 assert!(matches!(
604 b().cookie(CookieConfig::default().secure(false)).build(),
605 Err(ConfigError::InvalidCookie(_))
606 ));
607 assert_eq!(
608 b().thresholds(Thresholds {
609 step_up: 90,
610 revoke: 80
611 })
612 .build()
613 .unwrap_err(),
614 ConfigError::InvalidThresholds
615 );
616 assert_eq!(
617 b().rotation(RotationConfig {
618 grace: Duration::from_secs(600),
619 ..RotationConfig::default()
620 })
621 .build()
622 .unwrap_err(),
623 ConfigError::GraceTooLong
624 );
625 assert_eq!(
626 b().session_lifetime(Duration::ZERO).build().unwrap_err(),
627 ConfigError::InvalidDuration("session_lifetime")
628 );
629 assert_eq!(
630 b().idle_timeout(Duration::MAX).build().unwrap_err(),
631 ConfigError::InvalidDuration("idle_timeout")
632 );
633 assert_eq!(
634 b().orphan_reissue_window(Duration::MAX).build().unwrap_err(),
635 ConfigError::InvalidDuration("orphan_reissue_window")
636 );
637 assert_eq!(
638 b().alert_dedup_window(Duration::MAX).build().unwrap_err(),
639 ConfigError::InvalidDuration("alert_dedup_window")
640 );
641 assert!(matches!(
642 b().tls_fingerprint_header("x ja4").build(),
643 Err(ConfigError::InvalidHeaderName(_))
644 ));
645 }
646
647 #[test]
648 fn token_prefix_is_optional_and_validated() {
649 assert_eq!(GuardConfig::default().token_prefix(), None);
650 let c = GuardConfig::builder().token_prefix("sess_").build().unwrap();
651 assert_eq!(c.token_prefix(), Some("sess_"));
652 for bad in ["", "se ss_", "sess;", "sess=", "é_", &"a".repeat(33)] {
653 assert_eq!(
654 GuardConfig::builder().token_prefix(bad).build().unwrap_err(),
655 ConfigError::InvalidTokenPrefix(bad.to_owned()),
656 "{bad:?}"
657 );
658 }
659 }
660
661 #[test]
662 fn zero_is_allowed_where_it_means_off() {
663 let c = GuardConfig::builder()
664 .ping_pong_window(Duration::ZERO)
665 .last_seen_write_interval(Duration::ZERO)
666 .shadow_dedup_window(Duration::ZERO)
667 .alert_dedup_window(Duration::ZERO)
668 .orphan_reissue_window(Duration::ZERO)
669 .rotation(RotationConfig {
670 grace: Duration::ZERO,
671 ..RotationConfig::default()
672 })
673 .build()
674 .unwrap();
675 assert_eq!(c.rotation().grace, Duration::ZERO);
676 assert_eq!(c.orphan_reissue_window(), Some(Duration::ZERO));
677 }
678}