Skip to main content

session_guard/guard/
mod.rs

1//! The guard: issues, checks, rotates and revokes sessions.
2
3mod outcome;
4#[cfg(test)]
5mod tests;
6
7use std::{
8    borrow::Cow,
9    collections::HashMap,
10    marker::PhantomData,
11    net::IpAddr,
12    panic::{AssertUnwindSafe, catch_unwind},
13    sync::{
14        Arc, Mutex, PoisonError,
15        atomic::{AtomicBool, Ordering},
16    },
17    time::Duration,
18};
19
20use time::{OffsetDateTime, PrimitiveDateTime};
21use uuid::Uuid;
22use zeroize::Zeroizing;
23
24pub use outcome::{
25    AuthSession, Authenticated, IssuedToken, NewSession, Outcome, PurgeReport, Rejection, SessionInfo, StepUpOutcome,
26};
27
28use crate::{
29    checks::{Check, Checks, Decision},
30    client::{ClientContext, HeaderSource, resolve_client_ip},
31    clock::{Clock, SystemClock},
32    config::{GuardConfig, Mode, StepUpPolicy},
33    error::GuardError,
34    event::{ClientSummary, EventKind, SessionEvent, SessionOrigin, mask_ip},
35    fingerprint::{Baseline, Fingerprint, UaCache},
36    intel::{IpIntel, NoIpIntel},
37    store::{ClaimScope, Rotation, SessionRecord, SessionStore, SessionUpdate, Supersede},
38    subject::Subject,
39    token::{SessionToken, TokenHash},
40};
41
42use secrecy::SecretString;
43
44type Hook = Arc<dyn Fn(&SessionEvent) + Send + Sync>;
45
46/// Issues, checks, rotates and revokes sessions. Cheap to clone; clones share state.
47///
48/// `St` is the [`SessionStore`]; `S` is your subject type (default [`Uuid`]), stored opaquely.
49pub struct Guard<St, S = Uuid> {
50    inner: Arc<Inner<St>>,
51    _subject: PhantomData<fn() -> S>,
52}
53
54struct Inner<St> {
55    store: St,
56    config: GuardConfig,
57    intel: Box<dyn IpIntel>,
58    clock: Box<dyn Clock>,
59    hook: Option<Hook>,
60    ua_cache: UaCache,
61    xff_warned: AtomicBool,
62    shadow_seen: Mutex<ShadowSeen>,
63}
64
65/// Last time each unenforced event was recorded, for shadow-mode deduplication.
66struct ShadowSeen {
67    seen: HashMap<(Uuid, EventKind), OffsetDateTime>,
68    pruned_at: OffsetDateTime,
69}
70
71impl<St, S> Clone for Guard<St, S> {
72    fn clone(&self) -> Self {
73        Self {
74            inner: Arc::clone(&self.inner),
75            _subject: PhantomData,
76        }
77    }
78}
79
80impl<St, S> std::fmt::Debug for Guard<St, S> {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_struct("Guard")
83            .field("config", &self.inner.config)
84            .finish_non_exhaustive()
85    }
86}
87
88/// Builds a [`Guard`]. Start with [`Guard::builder`].
89#[must_use]
90pub struct GuardBuilder<St, S = Uuid> {
91    store: St,
92    config: GuardConfig,
93    intel: Box<dyn IpIntel>,
94    clock: Box<dyn Clock>,
95    hook: Option<Hook>,
96    _subject: PhantomData<fn() -> S>,
97}
98
99impl<St: SessionStore> Guard<St> {
100    /// A guard with the default configuration and [`Uuid`] subjects.
101    pub fn new(store: St) -> Self {
102        Self::builder(store, GuardConfig::default()).build()
103    }
104
105    /// Starts building a guard. Subjects are [`Uuid`] unless changed with
106    /// [`GuardBuilder::subject`].
107    pub fn builder(store: St, config: GuardConfig) -> GuardBuilder<St> {
108        GuardBuilder {
109            store,
110            config,
111            intel: Box::new(NoIpIntel),
112            clock: Box::new(SystemClock),
113            hook: None,
114            _subject: PhantomData,
115        }
116    }
117}
118
119impl<St: SessionStore, S: Subject> GuardBuilder<St, S> {
120    /// Uses `T` as the subject type.
121    pub fn subject<T: Subject>(self) -> GuardBuilder<St, T> {
122        GuardBuilder {
123            store: self.store,
124            config: self.config,
125            intel: self.intel,
126            clock: self.clock,
127            hook: self.hook,
128            _subject: PhantomData,
129        }
130    }
131
132    /// Country / ASN source. Without one, IP changes are judged by network prefix only.
133    pub fn ip_intel(mut self, intel: impl IpIntel) -> Self {
134        self.intel = Box::new(intel);
135        self
136    }
137
138    /// Called synchronously once per state change, in the process that made the change, after
139    /// the event is stored. When concurrent requests race, only the one whose change took
140    /// effect reports it; the exception is `step_up_required`, which two requests that both
141    /// trip it may each report. Keep it fast; a panic in the hook is caught and logged.
142    ///
143    /// Delivery is at most once. There is no outbox, so a crash between the change and the
144    /// hook loses the event.
145    ///
146    /// With [`alert_dedup_window`](crate::GuardConfigBuilder::alert_dedup_window) set, enforced
147    /// security-relevant events reach the hook at most once per subject and kind per window;
148    /// the rest are still logged and stored. If the store cannot claim the alert, the hook is
149    /// called anyway.
150    pub fn on_event(mut self, hook: impl Fn(&SessionEvent) + Send + Sync + 'static) -> Self {
151        self.hook = Some(Arc::new(hook));
152        self
153    }
154
155    /// Time source (default [`SystemClock`]).
156    pub fn clock(mut self, clock: impl Clock) -> Self {
157        self.clock = Box::new(clock);
158        self
159    }
160
161    /// Builds the guard.
162    pub fn build(self) -> Guard<St, S> {
163        Guard {
164            inner: Arc::new(Inner {
165                store: self.store,
166                config: self.config,
167                intel: self.intel,
168                clock: self.clock,
169                hook: self.hook,
170                ua_cache: UaCache::new(UA_CACHE_CAPACITY),
171                xff_warned: AtomicBool::new(false),
172                shadow_seen: Mutex::new(ShadowSeen {
173                    seen: HashMap::new(),
174                    pruned_at: PrimitiveDateTime::MIN.assume_utc(),
175                }),
176            }),
177            _subject: PhantomData,
178        }
179    }
180}
181
182const UA_CACHE_CAPACITY: usize = 1024;
183
184/// Most (session, kind) pairs the local shadow dedup cache holds, about 6 MB at most.
185const SHADOW_SEEN_CAPACITY: usize = 100_000;
186
187/// How a presented token relates to its session's current token.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189enum TokenState {
190    /// The current token.
191    Current,
192    /// Superseded moments ago; a request that raced the rotation.
193    Grace,
194    /// Superseded, but its successor was never used: the rotation response was lost.
195    Orphaned,
196    /// Superseded and its successor is in use: two parties hold the session.
197    Reuse,
198    /// An orphan presented again by the same client moments after it was reissued: a
199    /// parallel request that carried the orphan too. Accepted without another reissue.
200    RacedReissue,
201}
202
203/// A token resolved to a live session with a decodable subject.
204struct Resolved<S> {
205    lookup: crate::store::TokenLookup,
206    hash: TokenHash,
207    subject: S,
208    state: TokenState,
209}
210
211impl<St: SessionStore, S: Subject> Guard<St, S> {
212    /// Creates a session for `subject` and returns its first token.
213    ///
214    /// Pass the token the client presented, if any: that session is revoked first, so a token
215    /// planted before login (session fixation) never becomes authenticated. Call this only
216    /// after verifying the subject's credentials, and rate-limit that endpoint yourself.
217    ///
218    /// # Errors
219    ///
220    /// Store failures, an unavailable RNG, or a subject that does not serialize.
221    pub async fn login(
222        &self,
223        subject: &S,
224        ctx: &ClientContext,
225        previous_token: Option<&str>,
226    ) -> Result<NewSession, GuardError> {
227        let inner = &*self.inner;
228        if let Some(hash) = previous_token.and_then(|t| self.presented_hash(t))
229            && let Some(old) = inner.store.find_by_token(&hash).await?
230            && inner.store.delete_session(old.session.id).await?
231        {
232            self.emit(old.session.id, &old.session.subject, EventKind::Logout, true, ctx, None)
233                .await;
234        }
235
236        let encoded = crate::subject::encode(subject)?;
237        let session_id = Uuid::new_v4();
238        let token = self.new_token(session_id)?;
239        let now = self.now();
240        let info = inner.intel.lookup(ctx.ip);
241        let fingerprint = Fingerprint::capture_cached(ctx, &info, &inner.ua_cache);
242        let client = ClientSummary::observed(info, fingerprint.clone());
243        let keep = inner.config.keep_origin_client;
244        let origin = SessionOrigin {
245            at: now,
246            ip_prefix: mask_ip(ctx.ip),
247            ip: keep.then_some(ctx.ip),
248            user_agent: keep.then(|| self.user_agent(ctx)).flatten(),
249            client: if keep {
250                client.clone()
251            } else {
252                client.clone().minimized()
253            },
254        };
255        let record = SessionRecord {
256            id: session_id,
257            subject: encoded,
258            created_at: now,
259            authenticated_at: now,
260            last_seen_at: now,
261            expires_at: now + inner.config.session_lifetime,
262            step_up_required: false,
263            baseline: Baseline::new(fingerprint),
264            origin: Some(origin),
265        };
266        inner.store.insert_session(&record, &token.hash()).await?;
267        self.emit_with(record.id, &record.subject, EventKind::Login, true, ctx, None, client)
268            .await;
269        Ok(NewSession {
270            session_id: record.id,
271            token: self.issue(&token, record.expires_at),
272        })
273    }
274
275    /// Checks a request's token with the configured checks.
276    ///
277    /// On success the request may proceed; send [`Authenticated::rotated`] back as
278    /// `Set-Cookie` when present. Every [`Rejection`] maps to 401.
279    ///
280    /// # Errors
281    ///
282    /// Store failures only. Bad tokens and risky clients are [`Outcome::Rejected`].
283    pub async fn authenticate(&self, token: &str, ctx: &ClientContext) -> Result<Outcome<S>, GuardError> {
284        self.authenticate_with(token, ctx, &self.inner.config.checks).await
285    }
286
287    /// Like [`authenticate`](Self::authenticate) with other checks, for routes that need
288    /// stricter (or looser) treatment. The baseline learns only the signals `checks` scored.
289    ///
290    /// # Errors
291    ///
292    /// Store failures only.
293    pub async fn authenticate_with(
294        &self,
295        token: &str,
296        ctx: &ClientContext,
297        checks: &Checks,
298    ) -> Result<Outcome<S>, GuardError> {
299        self.authenticate_inner(token, ctx, checks).await
300    }
301
302    /// A token for `session_id`; on a [sharded](SessionStore::sharded) store, one that lands in
303    /// the session's bucket.
304    fn new_token(&self, session_id: Uuid) -> Result<SessionToken, GuardError> {
305        if self.inner.store.sharded() {
306            SessionToken::generate_in_bucket(crate::store::session_bucket(session_id))
307        } else {
308            SessionToken::generate()
309        }
310    }
311
312    /// The rotation due for a token in `state`, with its replacement.
313    fn plan_rotation(
314        &self,
315        session_id: Uuid,
316        state: TokenState,
317        issued_at: OffsetDateTime,
318        hash: TokenHash,
319        now: OffsetDateTime,
320    ) -> Result<Option<(Rotation, SessionToken)>, GuardError> {
321        let config = &self.inner.config;
322        let supersede = match state {
323            TokenState::Current if issued_at <= now - config.rotation_interval => Supersede::Exact(hash),
324            TokenState::Orphaned => Supersede::CurrentIssuedBefore(now - config.rotation_grace),
325            _ => return Ok(None),
326        };
327        let token = self.new_token(session_id)?;
328        let rotation = Rotation {
329            new_token: token.hash(),
330            supersede,
331            prune_superseded_before: now - config.reuse_detection,
332        };
333        Ok(Some((rotation, token)))
334    }
335
336    /// Scores the request: the fingerprint against the baseline, plus the token's own state.
337    fn assess(
338        &self,
339        baseline: &Baseline,
340        fingerprint: &Fingerprint,
341        state: TokenState,
342        now: OffsetDateTime,
343        checks: &Checks,
344    ) -> crate::risk::Assessment {
345        let window = self.inner.config.ping_pong_window;
346        let mut assessment = crate::risk::assess(baseline, fingerprint, now, window, checks);
347        if state == TokenState::Orphaned {
348            assessment.add(Check::OrphanedToken, checks);
349        }
350        assessment
351    }
352
353    async fn authenticate_inner(
354        &self,
355        token: &str,
356        ctx: &ClientContext,
357        checks: &Checks,
358    ) -> Result<Outcome<S>, GuardError> {
359        let inner = &*self.inner;
360        let config = &inner.config;
361        let now = self.now();
362        let resolved = match self.resolve(token, now).await? {
363            Ok(resolved) => resolved,
364            Err(rejection) => return Ok(Outcome::Rejected(rejection)),
365        };
366        let Resolved {
367            lookup,
368            hash,
369            subject,
370            mut state,
371        } = resolved;
372        let session = &lookup.session;
373        let fingerprint = self.fingerprint(ctx);
374        if state == TokenState::Reuse && self.raced_reissue(&lookup, &hash, &fingerprint, now).await? {
375            state = TokenState::RacedReissue;
376        }
377
378        if state == TokenState::Reuse {
379            self.revoke_for_reuse(session, ctx).await?;
380            return Ok(Outcome::Rejected(Rejection::Revoked));
381        }
382
383        let assessment = self.assess(&session.baseline, &fingerprint, state, now, checks);
384        let decision = config.thresholds.decide(assessment.score);
385        crate::telemetry::assessed(decision, &assessment.signals);
386        let shadow = config.mode == Mode::Shadow;
387        let step_up = decision == Decision::StepUp;
388
389        if decision == Decision::Revoke || (step_up && config.step_up_policy == StepUpPolicy::Revoke) {
390            self.revoke_for_risk(session, ctx, &assessment, !shadow).await?;
391            if !shadow {
392                return Ok(Outcome::Rejected(Rejection::Revoked));
393            }
394        } else if session.step_up_required && !shadow {
395            return Ok(Outcome::Rejected(Rejection::StepUpRequired));
396        } else if step_up {
397            let enforced = config.step_up_policy == StepUpPolicy::Require && !shadow;
398            if enforced {
399                let mut update = SessionUpdate::touch(session.id, now);
400                update.step_up_required = Some(true);
401                update.mark_used =
402                    (state == TokenState::Current && lookup.token.first_used_at.is_none()).then_some(hash);
403                inner.store.apply(&update).await?;
404            }
405            // `apply` does not say whether the flag was already set, so racing requests each
406            // report it.
407            self.emit(
408                session.id,
409                &session.subject,
410                EventKind::StepUpRequired,
411                enforced,
412                ctx,
413                Some(&assessment),
414            )
415            .await;
416            if enforced {
417                return Ok(Outcome::Rejected(Rejection::StepUpRequired));
418            }
419        }
420
421        let mut update = SessionUpdate::touch(session.id, now);
422        if decision == Decision::Allow {
423            let mut baseline = session.baseline.clone();
424            if baseline.absorb(&fingerprint, now, checks) {
425                update.baseline = Some(baseline);
426            }
427        }
428
429        let new_token = match self.plan_rotation(lookup.session.id, state, lookup.token.issued_at, hash, now)? {
430            Some((rotation, token)) => {
431                update.rotation = Some(rotation);
432                Some(token)
433            }
434            None => None,
435        };
436        // A reissued token counts as used from the start, so the orphan it replaces turns into
437        // reuse: one reissue per orphan, or a thief could keep a stolen token alive by
438        // dropping every successor.
439        update.mark_used = match (state, &update.rotation) {
440            (TokenState::Current, _) if lookup.token.first_used_at.is_none() => Some(hash),
441            (TokenState::Orphaned, Some(rotation)) => Some(rotation.new_token),
442            _ => None,
443        };
444
445        let stale = now - session.last_seen_at >= config.last_seen_write_interval;
446        let mut rotated = None;
447        if update.rotation.is_some() || update.mark_used.is_some() || update.baseline.is_some() || stale {
448            let did_rotate = inner.store.apply(&update).await?;
449            if did_rotate && let Some(token) = &new_token {
450                rotated = Some(self.issue(token, session.expires_at));
451                if state == TokenState::Orphaned {
452                    self.emit(session.id, &session.subject, EventKind::TokenReissued, true, ctx, None)
453                        .await;
454                }
455            }
456        }
457
458        Ok(Outcome::Authenticated(Authenticated {
459            session: AuthSession::new(session, subject),
460            rotated,
461            assessment,
462        }))
463    }
464
465    /// Looks a token up without changing anything: no rotation, no `last_seen` write, no
466    /// checks. `None` unless the token is current (or within its grace period) and the session
467    /// is live.
468    ///
469    /// # Errors
470    ///
471    /// Store failures only.
472    pub async fn peek(&self, token: &str) -> Result<Option<SessionInfo<S>>, GuardError> {
473        Ok(match self.resolve(token, self.now()).await? {
474            Ok(resolved) if matches!(resolved.state, TokenState::Current | TokenState::Grace) => {
475                SessionInfo::from_record(&resolved.lookup.session)
476            }
477            _ => None,
478        })
479    }
480
481    /// Clears a pending step-up after the app has re-verified the subject (password, passkey,
482    /// OTP…). The current client becomes the new baseline, `authenticated_at` resets and a new
483    /// token is issued.
484    ///
485    /// `verified_subject` must be the subject the app just verified; a mismatch changes
486    /// nothing. Rate-limit the verification yourself.
487    ///
488    /// # Errors
489    ///
490    /// Store failures or an unavailable RNG.
491    pub async fn complete_step_up(
492        &self,
493        token: &str,
494        ctx: &ClientContext,
495        verified_subject: &S,
496    ) -> Result<StepUpOutcome, GuardError> {
497        let inner = &*self.inner;
498        let now = self.now();
499        let resolved = match self.resolve(token, now).await? {
500            Ok(resolved) => resolved,
501            Err(rejection) => return Ok(StepUpOutcome::Rejected(rejection)),
502        };
503        let session = &resolved.lookup.session;
504        if resolved.state == TokenState::Reuse {
505            self.revoke_for_reuse(session, ctx).await?;
506            return Ok(StepUpOutcome::Rejected(Rejection::Revoked));
507        }
508        if resolved.subject != *verified_subject {
509            return Ok(StepUpOutcome::SubjectMismatch);
510        }
511
512        let token = self.new_token(session.id)?;
513        let mut update = SessionUpdate::touch(session.id, now);
514        update.baseline = Some(session.baseline.renewed(self.fingerprint(ctx)));
515        update.step_up_required = Some(false);
516        update.authenticated_at = Some(now);
517        // With the current token, only one of several concurrent submits replaces it.
518        let supersede = match resolved.state {
519            TokenState::Current => Supersede::Exact(resolved.hash),
520            _ => Supersede::Current,
521        };
522        let rotation = Rotation {
523            new_token: token.hash(),
524            supersede,
525            prune_superseded_before: now - inner.config.reuse_detection,
526        };
527        update.rotation = Some(rotation);
528        if inner.store.apply(&update).await? {
529            self.emit(
530                session.id,
531                &session.subject,
532                EventKind::StepUpCompleted,
533                true,
534                ctx,
535                None,
536            )
537            .await;
538        } else {
539            // A concurrent submit won and reports it; this one still gets a token. Or the
540            // session vanished between lookup and update.
541            update.rotation = Some(Rotation {
542                supersede: Supersede::Current,
543                ..rotation
544            });
545            if !inner.store.apply(&update).await? {
546                return Ok(StepUpOutcome::Rejected(Rejection::Revoked));
547            }
548        }
549        Ok(StepUpOutcome::Completed(self.issue(&token, session.expires_at)))
550    }
551
552    /// Ends the session the token belongs to. Returns whether there was one.
553    ///
554    /// # Errors
555    ///
556    /// Store failures only.
557    pub async fn logout(&self, token: &str, ctx: &ClientContext) -> Result<bool, GuardError> {
558        let inner = &*self.inner;
559        let Some(hash) = self.presented_hash(token) else {
560            return Ok(false);
561        };
562        let Some(lookup) = inner.store.find_by_token(&hash).await? else {
563            return Ok(false);
564        };
565        let deleted = inner.store.delete_session(lookup.session.id).await?;
566        if deleted {
567            self.emit(
568                lookup.session.id,
569                &lookup.session.subject,
570                EventKind::Logout,
571                true,
572                ctx,
573                None,
574            )
575            .await;
576        }
577        Ok(deleted)
578    }
579
580    /// Deletes one session of `subject` by id, e.g. from a "your devices" page. Returns whether
581    /// it existed; a session of another subject is left alone. `ctx` is whoever asked; it goes
582    /// into the [`EventKind::Revoked`] event.
583    ///
584    /// # Errors
585    ///
586    /// Store failures or a subject that does not serialize.
587    pub async fn revoke_session(&self, subject: &S, session_id: Uuid, ctx: &ClientContext) -> Result<bool, GuardError> {
588        let encoded = crate::subject::encode(subject)?;
589        let sessions = self.inner.store.list_subject_sessions(&encoded).await?;
590        if !sessions.iter().any(|s| s.id == session_id) {
591            return Ok(false);
592        }
593        let deleted = self.inner.store.delete_session(session_id).await?;
594        if deleted {
595            self.emit(session_id, &encoded, EventKind::Revoked, true, ctx, None)
596                .await;
597        }
598        Ok(deleted)
599    }
600
601    /// Deletes every session of `subject`, e.g. after a password change. Returns how many.
602    /// `ctx` is whoever asked; each session gets an [`EventKind::Revoked`] event.
603    ///
604    /// # Errors
605    ///
606    /// Store failures or a subject that does not serialize.
607    pub async fn revoke_all_for_subject(&self, subject: &S, ctx: &ClientContext) -> Result<u64, GuardError> {
608        let encoded = crate::subject::encode(subject)?;
609        let deleted = self.inner.store.delete_subject_sessions(&encoded).await?;
610        for &session_id in &deleted {
611            self.emit(session_id, &encoded, EventKind::Revoked, true, ctx, None)
612                .await;
613        }
614        Ok(deleted.len() as u64)
615    }
616
617    /// The live sessions of `subject`.
618    ///
619    /// # Errors
620    ///
621    /// Store failures or a subject that does not serialize.
622    pub async fn list_sessions(&self, subject: &S) -> Result<Vec<SessionInfo<S>>, GuardError> {
623        let encoded = crate::subject::encode(subject)?;
624        let now = self.now();
625        let records = self.inner.store.list_subject_sessions(&encoded).await?;
626        Ok(records
627            .iter()
628            .filter(|r| self.is_live(r, now))
629            .filter_map(SessionInfo::from_record)
630            .collect())
631    }
632
633    /// Deletes expired sessions and events older than the retention period. Run it
634    /// periodically (hourly is plenty).
635    ///
636    /// # Errors
637    ///
638    /// Store failures only.
639    pub async fn purge_expired(&self) -> Result<PurgeReport, GuardError> {
640        let config = &self.inner.config;
641        let now = self.now();
642        let sessions = self.inner.store.delete_expired(now, now - config.idle_timeout).await?;
643        let events = self
644            .inner
645            .store
646            .delete_events_before(now - config.event_retention)
647            .await?;
648        Ok(PurgeReport { sessions, events })
649    }
650
651    /// Runs [`purge_expired`](Self::purge_expired) now and then every `every` on the tokio
652    /// runtime, logging each report (`info`) or failure (`warn`) with `tracing`. A failed run
653    /// does not stop the task; abort the handle to stop it.
654    ///
655    /// # Panics
656    ///
657    /// Outside a tokio runtime, or if `every` is zero.
658    #[cfg(feature = "tokio")]
659    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
660    pub fn spawn_purge(&self, every: Duration) -> tokio::task::JoinHandle<()> {
661        let guard = self.clone();
662        tokio::spawn(async move {
663            let mut ticker = tokio::time::interval(every);
664            ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
665            loop {
666                ticker.tick().await;
667                match guard.purge_expired().await {
668                    Ok(report) => tracing::info!(
669                        sessions = report.sessions,
670                        events = report.events,
671                        "purged expired sessions"
672                    ),
673                    Err(error) => tracing::warn!(%error, "purging expired sessions failed"),
674                }
675            }
676        })
677    }
678
679    /// Builds the [`ClientContext`] for a request from the TCP peer address and the request
680    /// headers.
681    ///
682    /// `X-Forwarded-For` is honoured only when `peer` is a configured trusted proxy, walking
683    /// right to left past trusted hops. Header values are capped at the configured length.
684    pub fn client_context<H: HeaderSource + ?Sized>(&self, peer: IpAddr, headers: &H) -> ClientContext {
685        let config = &self.inner.config;
686        // A non-UTF-8 value stays in the chain as an empty, unparseable hop, so the peer is used
687        // instead of whatever valid hops surround it.
688        let forwarded: Vec<&str> = headers
689            .header_values("x-forwarded-for")
690            .map(|v| std::str::from_utf8(v).unwrap_or(""))
691            .collect();
692        if config.trusted_proxies.is_empty()
693            && !forwarded.is_empty()
694            && !self.inner.xff_warned.swap(true, Ordering::Relaxed)
695        {
696            tracing::warn!(
697                "X-Forwarded-For received but no trusted proxies are configured; using the peer address. \
698                 Configure trusted_proxies if the app runs behind a reverse proxy."
699            );
700        }
701        let ip = resolve_client_ip(peer, forwarded, &config.trusted_proxies);
702        ClientContext::from_headers(
703            ip,
704            headers,
705            config.tls_fingerprint_header.as_deref(),
706            config.max_header_len,
707        )
708    }
709
710    /// The session cookie's value from the request's `Cookie` headers, if present.
711    pub fn cookie_token<'a, H: HeaderSource + ?Sized>(&self, headers: &'a H) -> Option<&'a str> {
712        headers
713            .header_values("cookie")
714            .filter_map(|v| std::str::from_utf8(v).ok())
715            .find_map(|v| self.inner.config.cookie.find_in(v))
716    }
717
718    /// A `Set-Cookie` value that deletes the session cookie.
719    pub fn clear_cookie(&self) -> String {
720        self.inner.config.cookie.clear_cookie()
721    }
722
723    #[cfg(feature = "aide")]
724    pub(crate) fn cookie_name(&self) -> &str {
725        self.inner.config.cookie.cookie_name()
726    }
727
728    /// Whether the subject last proved who they are more than `max_age` ago. Use it to demand
729    /// a fresh login before sensitive actions.
730    ///
731    /// With a zero `max_age` it is true as soon as any time has passed since the login or
732    /// step-up, so it is true for practically every request.
733    pub fn requires_reauth(&self, session: &AuthSession<S>, max_age: Duration) -> bool {
734        self.now() - session.authenticated_at > td(max_age)
735    }
736
737    /// Whether `value` has the shape of this guard's tokens (configured prefix, then 43
738    /// base64url characters). Does not touch the store.
739    pub fn is_session_token(&self, value: &str) -> bool {
740        self.presented_hash(value).is_some()
741    }
742
743    fn now(&self) -> OffsetDateTime {
744        self.inner.clock.now()
745    }
746
747    fn fingerprint(&self, ctx: &ClientContext) -> Fingerprint {
748        Fingerprint::capture_cached(ctx, &self.inner.intel.lookup(ctx.ip), &self.inner.ua_cache)
749    }
750
751    /// The request's User-Agent, truncated to the header cap.
752    fn user_agent(&self, ctx: &ClientContext) -> Option<String> {
753        ctx.user_agent
754            .as_deref()
755            .map(|ua| crate::client::truncate(ua, self.inner.config.max_header_len).to_owned())
756    }
757
758    fn client_summary(&self, ctx: &ClientContext) -> ClientSummary {
759        let info = self.inner.intel.lookup(ctx.ip);
760        let fingerprint = Fingerprint::capture_cached(ctx, &info, &self.inner.ua_cache);
761        ClientSummary::observed(info, fingerprint)
762    }
763
764    fn presented_hash(&self, presented: &str) -> Option<TokenHash> {
765        let bare = match &self.inner.config.token_prefix {
766            Some(prefix) => presented.strip_prefix(prefix.as_str())?,
767            None => presented,
768        };
769        TokenHash::from_presented(bare)
770    }
771
772    fn issue(&self, token: &SessionToken, expires_at: OffsetDateTime) -> IssuedToken {
773        // Exact capacity, so neither building the value nor boxing it into the secret leaves an
774        // unwiped copy behind in a reallocated buffer.
775        let prefix = self.inner.config.token_prefix.as_deref().unwrap_or("");
776        let mut value = String::with_capacity(prefix.len() + token.expose().len());
777        value.push_str(prefix);
778        value.push_str(token.expose());
779        let max_age = (expires_at - self.now()).whole_seconds();
780        let set_cookie = Zeroizing::new(self.inner.config.cookie.set_cookie(&value, max_age));
781        IssuedToken {
782            value: SecretString::from(value),
783            expires_at,
784            set_cookie,
785        }
786    }
787
788    fn is_live(&self, record: &SessionRecord, now: OffsetDateTime) -> bool {
789        now < record.expires_at && now - record.last_seen_at < self.inner.config.idle_timeout
790    }
791
792    fn classify(&self, lookup: &crate::store::TokenLookup, now: OffsetDateTime) -> TokenState {
793        match lookup.token.superseded_at {
794            None => TokenState::Current,
795            Some(at) if now - at <= self.inner.config.rotation_grace => TokenState::Grace,
796            Some(_) if !lookup.newer_token_used => TokenState::Orphaned,
797            Some(_) => TokenState::Reuse,
798        }
799    }
800
801    /// Whether a token classified as reuse is really a parallel request that raced its own
802    /// orphan reissue: the only newer token ever used is the session's current one, reissued
803    /// (used from the moment it was issued) no more than `rotation_grace` ago, and the request
804    /// comes from the baseline's network prefix with the same browser and OS family. A replay
805    /// after the grace, from elsewhere, or of a token whose successor a client did use, stays
806    /// reuse.
807    async fn raced_reissue(
808        &self,
809        lookup: &crate::store::TokenLookup,
810        hash: &TokenHash,
811        fingerprint: &Fingerprint,
812        now: OffsetDateTime,
813    ) -> Result<bool, GuardError> {
814        let baseline = &lookup.session.baseline;
815        let known = &baseline.fingerprint;
816        let same_client = !fingerprint.ip_prefix.is_empty()
817            && baseline.known_prefix(&fingerprint.ip_prefix) == Some(fingerprint.ip_prefix.as_str())
818            && fingerprint.browser.is_some()
819            && fingerprint.browser == known.browser
820            && fingerprint.os.is_some()
821            && fingerprint.os == known.os;
822        if !same_client {
823            return Ok(false);
824        }
825        let Some(newer) = self.inner.store.newer_used_tokens(hash).await? else {
826            return Ok(false);
827        };
828        Ok(match newer.as_slice() {
829            [successor] => {
830                successor.superseded_at.is_none()
831                    && successor.first_used_at == Some(successor.issued_at)
832                    && now - successor.issued_at <= self.inner.config.rotation_grace
833            }
834            _ => false,
835        })
836    }
837
838    /// Whether an orphaned token was superseded longer ago than the reissue window allows.
839    fn orphan_too_old(&self, lookup: &crate::store::TokenLookup, now: OffsetDateTime) -> bool {
840        match (self.inner.config.orphan_reissue_window, lookup.token.superseded_at) {
841            (Some(window), Some(at)) => now - at > window,
842            _ => false,
843        }
844    }
845
846    /// Finds a token's live session. Expired sessions are deleted on sight.
847    async fn resolve(&self, token: &str, now: OffsetDateTime) -> Result<Result<Resolved<S>, Rejection>, GuardError> {
848        let store = &self.inner.store;
849        let Some(hash) = self.presented_hash(token) else {
850            return Ok(Err(Rejection::NotAuthenticated));
851        };
852        let Some(lookup) = store.find_by_token(&hash).await? else {
853            return Ok(Err(Rejection::NotAuthenticated));
854        };
855        if !self.is_live(&lookup.session, now) {
856            store.delete_session(lookup.session.id).await?;
857            return Ok(Err(Rejection::Expired));
858        }
859        let Some(subject) = crate::subject::decode::<S>(&lookup.session.subject) else {
860            tracing::warn!(session_id = %lookup.session.id, "stored subject does not decode as the guard's subject type");
861            return Ok(Err(Rejection::NotAuthenticated));
862        };
863        let state = self.classify(&lookup, now);
864        if state == TokenState::Orphaned && self.orphan_too_old(&lookup, now) {
865            // Treated like a pruned token: the session stays with whoever holds the successor.
866            return Ok(Err(Rejection::NotAuthenticated));
867        }
868        Ok(Ok(Resolved {
869            lookup,
870            hash,
871            subject,
872            state,
873        }))
874    }
875
876    /// Deletes the session when `enforced`. Only the request that deleted it reports the
877    /// revocation; an unenforced one is reported once per dedup window.
878    async fn revoke_for_risk(
879        &self,
880        session: &SessionRecord,
881        ctx: &ClientContext,
882        assessment: &crate::risk::Assessment,
883        enforced: bool,
884    ) -> Result<(), GuardError> {
885        if !enforced || self.inner.store.delete_session(session.id).await? {
886            self.emit(
887                session.id,
888                &session.subject,
889                EventKind::RiskRevoked,
890                enforced,
891                ctx,
892                Some(assessment),
893            )
894            .await;
895        }
896        Ok(())
897    }
898
899    /// Deletes the session. Only the request that deleted it reports the reuse.
900    async fn revoke_for_reuse(&self, session: &SessionRecord, ctx: &ClientContext) -> Result<(), GuardError> {
901        if self.inner.store.delete_session(session.id).await? {
902            self.emit(session.id, &session.subject, EventKind::TokenReuse, true, ctx, None)
903                .await;
904        }
905        Ok(())
906    }
907
908    /// Records an event, calls the hook and updates metrics. Never fails: a store error is
909    /// logged, a hook panic is caught. Unenforced events are recorded at most once per session
910    /// and kind per dedup window. With an alert dedup window, enforced security-relevant events
911    /// reach the hook at most once per subject and kind per window.
912    async fn emit(
913        &self,
914        session_id: Uuid,
915        subject: &str,
916        kind: EventKind,
917        enforced: bool,
918        ctx: &ClientContext,
919        assessment: Option<&crate::risk::Assessment>,
920    ) {
921        let client = self.client_summary(ctx);
922        self.emit_with(session_id, subject, kind, enforced, ctx, assessment, client)
923            .await;
924    }
925
926    /// [`emit`](Self::emit) with the client summary already built.
927    #[allow(clippy::too_many_arguments)]
928    async fn emit_with(
929        &self,
930        session_id: Uuid,
931        subject: &str,
932        kind: EventKind,
933        enforced: bool,
934        ctx: &ClientContext,
935        assessment: Option<&crate::risk::Assessment>,
936        client: ClientSummary,
937    ) {
938        let inner = &*self.inner;
939        let config = &inner.config;
940        let now = self.now();
941        if !enforced {
942            if self.seen_recently(session_id, kind, now) {
943                return;
944            }
945            match inner
946                .store
947                .claim_event(ClaimScope::Session(session_id), kind, now, config.shadow_dedup_window)
948                .await
949            {
950                Ok(true) => {}
951                Ok(false) => return,
952                // Better a duplicate than a lost event.
953                Err(error) => {
954                    tracing::error!(%session_id, kind = kind.as_str(), %error, "failed to claim session event");
955                }
956            }
957        }
958        let alert = if inner.hook.is_some()
959            && enforced
960            && kind.is_security_relevant()
961            && !config.alert_dedup_window.is_zero()
962        {
963            match inner
964                .store
965                .claim_event(ClaimScope::Subject(subject), kind, now, config.alert_dedup_window)
966                .await
967            {
968                Ok(claimed) => claimed,
969                // Better a duplicate than a lost alert.
970                Err(error) => {
971                    tracing::error!(%session_id, kind = kind.as_str(), %error, "failed to claim subject alert");
972                    true
973                }
974            }
975        } else {
976            true
977        };
978
979        let event = SessionEvent {
980            session_id,
981            subject: subject.to_owned(),
982            kind,
983            enforced,
984            score: assessment.map(|a| a.score),
985            signals: assessment.map(|a| a.signals.clone()).unwrap_or_default(),
986            ip: ctx.ip,
987            user_agent: self.user_agent(ctx),
988            client,
989            at: now,
990        };
991        if kind.is_security_relevant() {
992            tracing::warn!(%session_id, kind = kind.as_str(), enforced, score = ?event.score, "session event");
993        } else {
994            tracing::debug!(%session_id, kind = kind.as_str(), "session event");
995        }
996        let stored = if config.minimize_stored_events {
997            Cow::Owned(SessionEvent {
998                ip: mask_ip(event.ip),
999                user_agent: None,
1000                client: event.client.clone().minimized(),
1001                ..event.clone()
1002            })
1003        } else {
1004            Cow::Borrowed(&event)
1005        };
1006        if let Err(error) = inner.store.record_event(&stored).await {
1007            tracing::error!(%session_id, kind = kind.as_str(), %error, "failed to record session event");
1008        }
1009        if alert
1010            && let Some(hook) = &inner.hook
1011            && catch_unwind(AssertUnwindSafe(|| hook(&event))).is_err()
1012        {
1013            tracing::error!(%session_id, kind = kind.as_str(), "on_event hook panicked");
1014        }
1015        crate::telemetry::event(kind, enforced);
1016    }
1017
1018    /// Whether this process already handled an unenforced `kind` event for the session within
1019    /// the dedup window; notes this one if not. A cheap first filter in front of the store's
1020    /// cross-process [`SessionStore::claim_event`].
1021    fn seen_recently(&self, session_id: Uuid, kind: EventKind, now: OffsetDateTime) -> bool {
1022        let window = self.inner.config.shadow_dedup_window;
1023        let mut state = self.inner.shadow_seen.lock().unwrap_or_else(PoisonError::into_inner);
1024        if now - state.pruned_at >= window || state.seen.len() >= SHADOW_SEEN_CAPACITY {
1025            state.seen.retain(|_, at| now - *at < window);
1026            state.pruned_at = now;
1027            if state.seen.len() >= SHADOW_SEEN_CAPACITY {
1028                // A flood of distinct sessions: forget everything and let the store dedupe.
1029                state.seen.clear();
1030            }
1031        }
1032        match state.seen.get(&(session_id, kind)) {
1033            Some(at) if now - *at < window => true,
1034            _ => {
1035                state.seen.insert((session_id, kind), now);
1036                false
1037            }
1038        }
1039    }
1040}
1041
1042fn td(duration: Duration) -> time::Duration {
1043    time::Duration::try_from(duration).unwrap_or(time::Duration::MAX)
1044}