Skip to main content

session_guard/
config.rs

1//! Guard configuration.
2
3use std::{net::IpAddr, time::Duration};
4
5use ipnet::IpNet;
6
7use crate::{
8    checks::{Checks, Thresholds},
9    cookie::CookieConfig,
10    error::ConfigError,
11};
12
13/// Longest accepted duration (100 years), so timestamp arithmetic cannot overflow.
14const MAX_DURATION: Duration = Duration::from_hours(100 * 365 * 24);
15
16/// Whether risk decisions are enforced.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18pub enum Mode {
19    /// Step-up and revoke decisions take effect.
20    #[default]
21    Enforce,
22    /// Decisions are only recorded as events with `enforced = false`; requests pass. Use this to
23    /// tune weights on real traffic before enforcing. Token reuse is always enforced.
24    Shadow,
25}
26
27/// What a step-up decision (score between the step-up and revoke thresholds) does.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum StepUpPolicy {
31    /// Reject with `step_up_required` until the app re-verifies the subject and calls
32    /// [`Guard::complete_step_up`](crate::Guard::complete_step_up).
33    #[default]
34    Require,
35    /// Revoke the session, as if the revoke threshold had been reached. For apps without a
36    /// re-authentication flow that prefer a fresh login.
37    Revoke,
38    /// Let the request through and record a `step_up_required` event with `enforced = false`.
39    /// For apps without a re-authentication flow that only want revoke-level protection.
40    Allow,
41}
42
43/// Token rotation settings.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct RotationConfig {
46    /// How old the current token may get before a request rotates it. Default 10 minutes.
47    pub interval: Duration,
48    /// How long a superseded token stays valid, for parallel requests and lost responses.
49    /// Default 30 seconds. Must be shorter than `interval`.
50    pub grace: Duration,
51    /// How long superseded tokens are kept to detect reuse. A stolen token replayed after this
52    /// is simply unknown. Default 7 days.
53    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/// Validated guard configuration. Build with [`GuardConfig::builder`] or take the
67/// [`Default`].
68#[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    /// Starts from the defaults.
104    pub fn builder() -> GuardConfigBuilder {
105        GuardConfigBuilder::default()
106    }
107
108    /// Cookie attributes.
109    pub fn cookie(&self) -> &CookieConfig {
110        &self.cookie
111    }
112
113    /// Absolute session lifetime.
114    pub fn session_lifetime(&self) -> Duration {
115        to_std(self.session_lifetime)
116    }
117
118    /// Inactivity after which a session expires.
119    pub fn idle_timeout(&self) -> Duration {
120        to_std(self.idle_timeout)
121    }
122
123    /// Proxies whose `X-Forwarded-For` is honoured.
124    pub fn trusted_proxies(&self) -> &[IpNet] {
125        &self.trusted_proxies
126    }
127
128    /// Request header carrying a TLS fingerprint (e.g. JA4) set by the proxy, lowercase.
129    pub fn tls_fingerprint_header(&self) -> Option<&str> {
130        self.tls_fingerprint_header.as_deref()
131    }
132
133    /// Rotation settings.
134    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    /// Default checks (routes can override).
143    pub fn checks(&self) -> &Checks {
144        &self.checks
145    }
146
147    /// Score thresholds.
148    pub fn thresholds(&self) -> Thresholds {
149        self.thresholds
150    }
151
152    /// Enforcement mode.
153    pub fn mode(&self) -> Mode {
154        self.mode
155    }
156
157    /// What a step-up decision does.
158    pub fn step_up_policy(&self) -> StepUpPolicy {
159        self.step_up_policy
160    }
161
162    /// Window in which returning to the previous network counts as ping-pong.
163    pub fn ping_pong_window(&self) -> Duration {
164        to_std(self.ping_pong_window)
165    }
166
167    /// How stale `last_seen` may get before an otherwise unchanged request writes it.
168    pub fn last_seen_write_interval(&self) -> Duration {
169        to_std(self.last_seen_write_interval)
170    }
171
172    /// How long events are kept before [`Guard::purge_expired`](crate::Guard::purge_expired)
173    /// deletes them.
174    pub fn event_retention(&self) -> Duration {
175        to_std(self.event_retention)
176    }
177
178    /// Whether the store gets a reduced copy of each event; see
179    /// [`GuardConfigBuilder::minimize_stored_events`].
180    pub fn minimize_stored_events(&self) -> bool {
181        self.minimize_stored_events
182    }
183
184    /// Whether a session's origin keeps the full IP, User-Agent and city; see
185    /// [`GuardConfigBuilder::keep_origin_client`].
186    pub fn keep_origin_client(&self) -> bool {
187        self.keep_origin_client
188    }
189
190    /// Window in which repeated shadow events for the same session and kind are dropped.
191    pub fn shadow_dedup_window(&self) -> Duration {
192        to_std(self.shadow_dedup_window)
193    }
194
195    /// Window in which repeated security alerts for the same subject and kind skip the hook.
196    /// Zero means off.
197    pub fn alert_dedup_window(&self) -> Duration {
198        to_std(self.alert_dedup_window)
199    }
200
201    /// Maximum length of a header value considered for fingerprinting.
202    pub fn max_header_len(&self) -> usize {
203        self.max_header_len
204    }
205
206    /// Prefix of issued tokens, if any.
207    pub fn token_prefix(&self) -> Option<&str> {
208        self.token_prefix.as_deref()
209    }
210
211    /// How long after being superseded an orphaned token is still reissued, if limited.
212    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/// Builder for [`GuardConfig`].
222#[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    /// Cookie attributes. See [`CookieConfig`].
278    pub fn cookie(mut self, cookie: CookieConfig) -> Self {
279        self.cookie = cookie;
280        self
281    }
282
283    /// Shorthand for changing only the cookie name.
284    pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
285        self.cookie = self.cookie.name(name);
286        self
287    }
288
289    /// Absolute session lifetime, counted from login. Activity, rotation and step-up never extend
290    /// it; the subject must log in again. Default 30 days.
291    pub fn session_lifetime(mut self, lifetime: Duration) -> Self {
292        self.session_lifetime = lifetime;
293        self
294    }
295
296    /// Inactivity timeout. Default 7 days.
297    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
298        self.idle_timeout = timeout;
299        self
300    }
301
302    /// Reverse proxies (IP addresses or CIDR ranges) whose `X-Forwarded-For` is honoured.
303    /// Without any, the TCP peer address is the client address.
304    ///
305    /// # Errors
306    ///
307    /// [`ConfigError::InvalidProxy`] for an entry that is not an IP or CIDR range.
308    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    /// Header with a TLS fingerprint (e.g. JA4) set by your proxy. Enables
327    /// [`Check::TlsChanged`](crate::Check::TlsChanged). Only use a header your proxy
328    /// overwrites on every request.
329    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    /// Token rotation settings.
335    pub fn rotation(mut self, rotation: RotationConfig) -> Self {
336        self.rotation = rotation;
337        self
338    }
339
340    /// Checks and weights. Default: all checks at default weights.
341    pub fn checks(mut self, checks: Checks) -> Self {
342        self.checks = checks;
343        self
344    }
345
346    /// Score thresholds. Default: step-up at 40, revoke at 80.
347    pub fn thresholds(mut self, thresholds: Thresholds) -> Self {
348        self.thresholds = thresholds;
349        self
350    }
351
352    /// Enforce or shadow mode. Default enforce.
353    pub fn mode(mut self, mode: Mode) -> Self {
354        self.mode = mode;
355        self
356    }
357
358    /// What a step-up decision does. Default [`StepUpPolicy::Require`].
359    pub fn step_up_policy(mut self, policy: StepUpPolicy) -> Self {
360        self.step_up_policy = policy;
361        self
362    }
363
364    /// How long after being superseded an orphaned token (its successor never presented) is
365    /// still reissued. Past it the token is rejected as unknown and the session is left to
366    /// whoever holds the successor. Default off: orphans are reissued until
367    /// `rotation.reuse_detection` prunes them.
368    ///
369    /// Zero never reissues: a client that loses a single rotation response is signed out.
370    pub fn orphan_reissue_window(mut self, window: Duration) -> Self {
371        self.orphan_reissue_window = Some(window);
372        self
373    }
374
375    /// Ping-pong window. Default 5 minutes. Zero disables ping-pong detection.
376    pub fn ping_pong_window(mut self, window: Duration) -> Self {
377        self.ping_pong_window = window;
378        self
379    }
380
381    /// How stale `last_seen` may get before an unchanged request writes it. Default 60 seconds.
382    /// Zero writes on every request.
383    pub fn last_seen_write_interval(mut self, interval: Duration) -> Self {
384        self.last_seen_write_interval = interval;
385        self
386    }
387
388    /// Event retention. Default 90 days.
389    pub fn event_retention(mut self, retention: Duration) -> Self {
390        self.event_retention = retention;
391        self
392    }
393
394    /// Write a reduced copy of each event to the store: the IP's /24 (IPv4) or /48 (IPv6)
395    /// network instead of the address, no raw User-Agent (the browser and OS families stay in
396    /// [`ClientSummary`](crate::ClientSummary)) and no city. Default on. The
397    /// [`on_event`](crate::GuardBuilder::on_event) hook always gets the full event.
398    pub fn minimize_stored_events(mut self, minimize: bool) -> Self {
399        self.minimize_stored_events = minimize;
400        self
401    }
402
403    /// Keep the full IP, raw User-Agent and city in each session's
404    /// [`SessionOrigin`](crate::SessionOrigin). Default off: the origin holds only the IP's
405    /// /24 (IPv4) or /48 (IPv6) network and the [`ClientSummary`](crate::ClientSummary)
406    /// without city, which is enough for a "your devices" page.
407    pub fn keep_origin_client(mut self, keep: bool) -> Self {
408        self.keep_origin_client = keep;
409        self
410    }
411
412    /// Shadow event dedup window. Default 10 minutes. Zero records every shadow event.
413    pub fn shadow_dedup_window(mut self, window: Duration) -> Self {
414        self.shadow_dedup_window = window;
415        self
416    }
417
418    /// Per-subject alert dedup window. Default zero (off).
419    ///
420    /// When set, the hook sees at most one enforced security-relevant event per subject and
421    /// kind per window, across processes through [`SessionStore::claim_event`] with
422    /// [`ClaimScope::Subject`]. Use it so an attacker hammering many sessions of one subject
423    /// pages its owner once instead of once per session. Every event is still logged and
424    /// stored; login, logout and step-up completion always reach the hook.
425    ///
426    /// [`SessionStore::claim_event`]: crate::SessionStore::claim_event
427    /// [`ClaimScope::Subject`]: crate::ClaimScope::Subject
428    pub fn alert_dedup_window(mut self, window: Duration) -> Self {
429        self.alert_dedup_window = window;
430        self
431    }
432
433    /// Maximum header value length considered. Longer values are truncated. Default 512.
434    pub fn max_header_len(mut self, len: usize) -> Self {
435        self.max_header_len = len;
436        self
437    }
438
439    /// Prefix for issued tokens, such as `"sess_"`. Default none.
440    ///
441    /// The cookie value becomes the prefix followed by the usual 43 characters, and any presented
442    /// token without the prefix is rejected before the store is consulted. Use it to tell browser
443    /// sessions apart from other credentials at a glance (for example `pat_` and `svc_` API keys
444    /// handled elsewhere), and to let secret scanners recognise leaked tokens. The prefix is not
445    /// secret and is not part of the stored hash.
446    pub fn token_prefix(mut self, prefix: impl Into<String>) -> Self {
447        self.token_prefix = Some(prefix.into());
448        self
449    }
450
451    /// Validates and builds.
452    ///
453    /// # Errors
454    ///
455    /// [`ConfigError`] for invalid cookie attributes, zero or oversized durations, a grace not
456    /// shorter than the rotation interval, invalid thresholds, header names or token prefix.
457    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}