Skip to main content

ic_auth/portable/revocation/
mod.rs

1//! Bounded volatile revocation bookkeeping, not an authentication endpoint.
2
3use super::{VerifiedPortableClaims, browser_principal, is_login_caller, validate_shape};
4use crate::admission_budget::{AdmissionBudgetError, SessionAdmissionBudget};
5use ic_auth_protocol_types::{AudienceId, PortableClaims, Principal};
6use std::collections::{BTreeMap, BTreeSet};
7use thiserror::Error;
8
9#[cfg(feature = "sessions")]
10const MAX_RECORD_BYTES: usize = 1024;
11
12/// A refusal leaves records unchanged; trusted clock observations are retained.
13#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
14pub enum LoginRevocationError {
15    #[error("logout requires an authenticated self-authenticating caller")]
16    InvalidCaller,
17    #[error("invalid revocation limits or authenticated login deadline")]
18    InvalidPolicy,
19    #[error("login is locally revoked")]
20    Revoked,
21    #[error("revocation capacity is exhausted")]
22    Capacity,
23    #[error("revocation clock rolled back or retention arithmetic overflowed")]
24    Clock,
25    #[error("host session/replay transaction failed")]
26    Storage,
27}
28
29#[derive(Clone, Copy)]
30#[cfg_attr(feature = "sessions", derive(serde::Serialize))]
31#[cfg_attr(feature = "session-restore", derive(serde::Deserialize))]
32struct Record {
33    until_ns: u64,
34    state: LoginRecordState,
35}
36
37// A reservation always owns admitted capacity; a tombstone retains that pool
38// exactly when it retains an authenticated login binding.
39/// Ledger state projected without inferring state from independent flags.
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41#[cfg_attr(feature = "sessions", derive(serde::Serialize))]
42#[cfg_attr(feature = "session-restore", derive(serde::Deserialize))]
43pub enum LoginRecordState {
44    Reserved(LoginBinding),
45    Revoked(Option<LoginBinding>),
46}
47
48impl Record {
49    #[cfg(feature = "session-restore")]
50    fn check_stored(
51        &self,
52        observed_ns: u64,
53        max_until: u64,
54        maximum_ttl: u64,
55        devices: u8,
56    ) -> Result<(), LoginRevocationError> {
57        if self.until_ns == 0 || self.until_ns > max_until {
58            return Err(LoginRevocationError::InvalidPolicy);
59        }
60        if let Some(login) = self.login()
61            && (login
62                .deadline_ns
63                .checked_sub(login.started_at_ns)
64                .is_none_or(|ttl| ttl == 0 || ttl > maximum_ttl)
65                || login.device_slot >= devices
66                || login.started_at_ns > observed_ns
67                || self.until_ns < login.deadline_ns
68                || (!self.revoked() && self.until_ns != login.deadline_ns))
69        {
70            return Err(LoginRevocationError::InvalidPolicy);
71        }
72        Ok(())
73    }
74    #[cfg(feature = "sessions")]
75    fn live_binding(&self, now_ns: u64) -> Result<Option<LoginBinding>, LoginRevocationError> {
76        if self.until_ns <= now_ns {
77            return Ok(None);
78        }
79        if self.revoked() {
80            return Err(LoginRevocationError::Revoked);
81        }
82        Ok(self.login())
83    }
84    fn login(&self) -> Option<LoginBinding> {
85        match &self.state {
86            LoginRecordState::Reserved(login) => Some(*login),
87            LoginRecordState::Revoked(login) => *login,
88        }
89    }
90
91    fn revoked(&self) -> bool {
92        matches!(self.state, LoginRecordState::Revoked(_))
93    }
94
95    fn admitted_pool(&self) -> bool {
96        matches!(
97            self.state,
98            LoginRecordState::Reserved(_) | LoginRecordState::Revoked(Some(_))
99        )
100    }
101}
102
103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104#[cfg_attr(feature = "sessions", derive(serde::Serialize))]
105#[cfg_attr(feature = "session-restore", derive(serde::Deserialize))]
106#[cfg_attr(feature = "sessions", serde(deny_unknown_fields))]
107/// Authenticated login association retained by a reservation or known tombstone.
108/// This value alone is not authentication or admission evidence.
109pub struct LoginBinding {
110    pub issuer: Principal,
111    pub subject: Principal,
112    pub device_slot: u8,
113    pub device_generation: u64,
114    pub started_at_ns: u64,
115    pub deadline_ns: u64,
116}
117
118/// Proposed ledger record from a serialized commit callback or trusted storage.
119/// A durable host must persist this with its session/replay changes before
120/// returning success. This is not a credential or reusable authorization result.
121pub struct LoginRevocationChange(LoginData, Option<Principal>);
122
123#[cfg_attr(feature = "sessions", derive(serde::Serialize))]
124#[cfg_attr(feature = "session-restore", derive(serde::Deserialize))]
125#[cfg_attr(feature = "sessions", serde(deny_unknown_fields))]
126struct LoginData {
127    #[cfg_attr(feature = "sessions", serde(with = "crate::storage_codec::audience"))]
128    audience: AudienceId,
129    caller: Principal,
130    record: Record,
131}
132
133impl LoginRevocationChange {
134    // A retained active session already contains its exact reserved binding.
135    // This reconstructs trusted backing only, never verifies client material.
136    #[cfg(feature = "persistent")]
137    pub(crate) fn from_session(session: &crate::session::Session) -> Self {
138        let binding = session.login_binding();
139        Self(
140            LoginData {
141                audience: session.audience(),
142                caller: session.caller(),
143                record: Record {
144                    until_ns: binding.deadline_ns,
145                    state: LoginRecordState::Reserved(binding),
146                },
147            },
148            None,
149        )
150    }
151    #[cfg(feature = "persistent")]
152    pub(crate) fn check_stored(
153        &self,
154        observed_ns: u64,
155        maximum_ttl: u64,
156        devices: u8,
157    ) -> Result<(), LoginRevocationError> {
158        self.0.record.check_stored(
159            observed_ns,
160            retention(observed_ns, maximum_ttl)?,
161            maximum_ttl,
162            devices,
163        )
164    }
165    #[cfg(feature = "persistent")]
166    pub(crate) fn live_binding(
167        &self,
168        now_ns: u64,
169    ) -> Result<Option<LoginBinding>, LoginRevocationError> {
170        self.0.record.live_binding(now_ns)
171    }
172    /// Check replacement of a trusted retained slot. An equal generation keeps
173    /// its caller, binding and denial even after expiry. A greater generation
174    /// requires a reservation with a different browser key in the same slot.
175    /// Unknown denials remain caller-bound until expiry. This does not authenticate storage, admit a proposed record,
176    /// observe the clock, charge a budget or commit anything. Hosts retain those
177    /// checks and exact pool accounting under their atomic transaction boundary.
178    pub fn check_replacement(
179        &self,
180        previous: &Self,
181        now_ns: u64,
182    ) -> Result<(), LoginRevocationError> {
183        if self.0.audience != previous.0.audience {
184            return Err(LoginRevocationError::InvalidPolicy);
185        }
186        if let Some(old) = previous.0.record.login() {
187            let new = self
188                .0
189                .record
190                .login()
191                .ok_or(LoginRevocationError::InvalidPolicy)?;
192            if slot(old) != slot(new) || new.device_generation < old.device_generation {
193                return Err(LoginRevocationError::InvalidPolicy);
194            }
195            if new.device_generation == old.device_generation {
196                if new != old
197                    || self.caller() != previous.caller()
198                    || (previous.0.record.revoked() && !self.0.record.revoked())
199                    || self.until_ns() < previous.until_ns()
200                {
201                    return Err(LoginRevocationError::InvalidPolicy);
202                }
203            } else if !matches!(self.state(), LoginRecordState::Reserved(_))
204                || self.caller() == previous.caller()
205            {
206                return Err(LoginRevocationError::InvalidPolicy);
207            }
208        } else if self.caller() != previous.caller()
209            || (previous.until_ns() > now_ns
210                && (self.0.record.login().is_some()
211                    || !self.0.record.revoked()
212                    || self.until_ns() < previous.until_ns()))
213        {
214            return Err(LoginRevocationError::InvalidPolicy);
215        }
216        Ok(())
217    }
218    /// Encode the proposed record for the host's atomic durable commit.
219    #[cfg(feature = "sessions")]
220    pub fn encode(&self) -> Result<Vec<u8>, LoginRevocationError> {
221        crate::storage_codec::encode(&self.0, crate::storage_codec::LOGIN, MAX_RECORD_BYTES)
222            .map_err(|error| match error {
223                ic_wire::Error::Limit | ic_wire::Error::Allocation => {
224                    LoginRevocationError::InvalidPolicy
225                }
226                _ => LoginRevocationError::Storage,
227            })
228    }
229
230    /// Decode trusted storage only; never accept these bytes from a client.
231    /// This checks shape, not provenance, completeness, rollback or live authority.
232    #[cfg(feature = "session-restore")]
233    pub fn decode(bytes: &[u8]) -> Result<Self, LoginRevocationError> {
234        let data: LoginData =
235            crate::storage_codec::decode(bytes, crate::storage_codec::LOGIN, MAX_RECORD_BYTES)
236                .map_err(|_| LoginRevocationError::InvalidPolicy)?;
237        if !is_login_caller(data.caller) {
238            return Err(LoginRevocationError::InvalidCaller);
239        }
240        if let Some(login) = data.record.login()
241            && (login.issuer == Principal::anonymous()
242                || login.subject == Principal::anonymous()
243                || login.device_slot >= ic_auth_protocol_types::limits::MAX_DEVICE_SLOTS
244                || login.device_generation == 0
245                || login.started_at_ns >= login.deadline_ns
246                || login.deadline_ns - login.started_at_ns > crate::limits::MAX_LOGIN_NS)
247        {
248            return Err(LoginRevocationError::InvalidPolicy);
249        }
250        Ok(Self(data, None))
251    }
252
253    /// Protected trust domain owning the record.
254    pub fn audience(&self) -> AudienceId {
255        self.0.audience
256    }
257    /// Authenticated runtime caller whose record changes.
258    pub fn caller(&self) -> Principal {
259        self.0.caller
260    }
261    /// Previous browser binding removed in this same atomic admission transaction.
262    /// This is a transaction delta, not retained checkpoint data.
263    pub fn displaced_caller(&self) -> Option<Principal> {
264        self.1
265    }
266    /// Exclusive receiver-local retention deadline.
267    pub fn until_ns(&self) -> u64 {
268        self.0.record.until_ns
269    }
270    /// Typed state from this checked ledger record. Storage codecs retain their
271    /// existing frozen representation independently of this Rust projection.
272    pub fn state(&self) -> LoginRecordState {
273        self.0.record.state
274    }
275}
276
277/// Bounded reference ledger for one host-installed trust domain. Callers are
278/// runtime principals, never request fields; this ledger cannot authenticate them.
279/// Each issuer-qualified account has at most eight retained device slots.
280/// Their generation fences survive lease/login expiry and logout. Only a fully
281/// verified newer generation may replace a slot; clock-based pruning never
282/// deletes it. Global admitted capacity bounds retained slots across accounts.
283/// Unknown callers have a separate pool and cannot consume admitted capacity.
284///
285/// The host MUST serialize these operations with proof/session/replay state and
286/// authority changes. Commit callbacks receive the exact proposed login record
287/// and must atomically write it with that other state in durable backends, or
288/// return an error without effects. No await/reentrancy may split the operation.
289/// This ledger commits its staged record only after callback success, with no
290/// further fallible policy/storage checks. Callbacks must not return success
291/// before their commit, or commit and then return an error.
292///
293/// This is not portable admission or a logout endpoint. No proof verification,
294/// startup/enrollment readiness or durable storage is supplied here. Hosts MUST
295/// apply those gates separately. Unknown local denial is unconfirmed and consumes
296/// an explicit host-retained budget before the commit callback. After losing the
297/// complete ledger, fail closed pending trusted recovery; timestamp floors and
298/// fresh enrollment alone cannot fence old logins. Never recreate per request.
299pub struct MemoryLoginRevocations {
300    audience: AudienceId,
301    records: BTreeMap<Principal, Record>,
302    // One physical record per issuer-qualified account slot. Replacement removes
303    // the displaced caller in the same transaction; history does not accumulate.
304    accounts: BTreeMap<(Principal, Principal, u8), Principal>,
305    expiry: BTreeSet<(u64, Principal)>,
306    max_admitted: usize,
307    max_device_slots: u8,
308    max_unknown: usize,
309    admitted: usize,
310    unknown: usize,
311    max_login_ttl_ns: u64,
312    observed_ns: u64,
313}
314
315impl MemoryLoginRevocations {
316    // Reuse the canonical ledger checks over only the touched persistent rows.
317    // Physical global counts remain authoritative even though the read snapshot
318    // contains at most the caller and displaced device. Never export or prune it.
319    #[cfg(feature = "persistent")]
320    pub(crate) fn selected(
321        audience: AudienceId,
322        limits: (usize, usize, u64, u8),
323        now_ns: u64,
324        counts: (usize, usize),
325        records: Vec<LoginRevocationChange>,
326    ) -> Result<Self, LoginRevocationError> {
327        if counts.0 > limits.0 || counts.1 > limits.1 || records.len() > 2 {
328            return Err(LoginRevocationError::InvalidPolicy);
329        }
330        let admitted = records
331            .iter()
332            .filter(|row| row.0.record.admitted_pool())
333            .count();
334        let unknown = records.len() - admitted;
335        if admitted > counts.0 || unknown > counts.1 {
336            return Err(LoginRevocationError::InvalidPolicy);
337        }
338        let mut snapshot = Self::new(audience, limits.0, limits.1, limits.2, now_ns)?
339            .with_device_limit(limits.3)?
340            .restore_records(now_ns, (admitted, unknown), records)?;
341        snapshot.admitted = counts.0;
342        snapshot.unknown = counts.1;
343        Ok(snapshot)
344    }
345    /// Stream the complete physical ledger under a serialized host checkpoint.
346    /// Persist these records with occupancy, clock and session/replay/authority
347    /// state atomically; known slot fences remain after expiry.
348    #[cfg(feature = "session-restore")]
349    pub fn records(&self) -> impl ExactSizeIterator<Item = LoginRevocationChange> + '_ {
350        self.records.iter().map(|(&caller, &record)| {
351            LoginRevocationChange(
352                LoginData {
353                    audience: self.audience,
354                    caller,
355                    record,
356                },
357                None,
358            )
359        })
360    }
361
362    /// Rebuild a fresh ledger from a complete, trusted atomic storage generation.
363    /// `self` must be newly constructed at current trusted time. The host supplies
364    /// that generation's persisted clock high-water mark and physical pool counts,
365    /// including expired records, from the same transaction as the records.
366    /// Failure consumes the partial ledger; no usable partial state is returned.
367    /// Counts detect missing entries, not malicious rollback: hosts MUST protect
368    /// snapshot provenance/generation and restore reset/authority/session/replay
369    /// state together, keeping admission closed until fresh enrollment is checked.
370    #[cfg(feature = "session-restore")]
371    pub fn restore_records(
372        mut self,
373        observed_ns: u64,
374        expected_counts: (usize, usize),
375        records: impl IntoIterator<Item = LoginRevocationChange>,
376    ) -> Result<Self, LoginRevocationError> {
377        if !self.records.is_empty()
378            || observed_ns > self.observed_ns
379            || expected_counts.0 > self.max_admitted
380            || expected_counts.1 > self.max_unknown
381        {
382            return Err(LoginRevocationError::InvalidPolicy);
383        }
384        let max_until = retention(observed_ns, self.max_login_ttl_ns)?;
385        for change in records {
386            if change.0.audience != self.audience || self.records.contains_key(&change.0.caller) {
387                return Err(LoginRevocationError::InvalidPolicy);
388            }
389            let record = change.0.record;
390            record.check_stored(
391                observed_ns,
392                max_until,
393                self.max_login_ttl_ns,
394                self.max_device_slots,
395            )?;
396            if let Some(login) = record.login()
397                && self.accounts.contains_key(&slot(login))
398            {
399                return Err(LoginRevocationError::InvalidPolicy);
400            }
401            // Stop at the persisted counts, even for an unbounded input iterator.
402            let (used, expected) = if record.admitted_pool() {
403                (self.admitted, expected_counts.0)
404            } else {
405                (self.unknown, expected_counts.1)
406            };
407            if used >= expected {
408                return Err(LoginRevocationError::Capacity);
409            }
410            self.install(change.0.caller, record);
411        }
412        if self.occupancy() != expected_counts {
413            return Err(LoginRevocationError::InvalidPolicy);
414        }
415        Ok(self)
416    }
417
418    /// Fixed record counts bound memory; no caller-supplied blobs are retained.
419    /// The positive login ceiling is protected host policy, at most 90 days;
420    /// it bounds accepted reservations and unknown denial retention together.
421    pub fn new(
422        audience: AudienceId,
423        max_admitted: usize,
424        max_unknown: usize,
425        max_login_ttl_ns: u64,
426        now_ns: u64,
427    ) -> Result<Self, LoginRevocationError> {
428        if max_admitted == 0
429            || max_unknown == 0
430            || max_login_ttl_ns == 0
431            || max_login_ttl_ns > crate::limits::MAX_LOGIN_NS
432        {
433            return Err(LoginRevocationError::InvalidPolicy);
434        }
435        retention(now_ns, max_login_ttl_ns)?;
436        Ok(Self {
437            audience,
438            records: BTreeMap::new(),
439            accounts: BTreeMap::new(),
440            expiry: BTreeSet::new(),
441            max_admitted,
442            max_device_slots: ic_auth_protocol_types::limits::MAX_DEVICE_SLOTS,
443            max_unknown,
444            admitted: 0,
445            unknown: 0,
446            max_login_ttl_ns,
447            observed_ns: now_ns,
448        })
449    }
450
451    /// Tighten the protocol's eight-slot account ceiling before admission or
452    /// restore. Persist this host policy with the checkpoint; shrinking it must
453    /// not silently discard retained fences. A populated ledger cannot change it.
454    pub fn with_device_limit(mut self, maximum: u8) -> Result<Self, LoginRevocationError> {
455        if maximum == 0
456            || maximum > ic_auth_protocol_types::limits::MAX_DEVICE_SLOTS
457            || !self.records.is_empty()
458        {
459            return Err(LoginRevocationError::InvalidPolicy);
460        }
461        self.max_device_slots = maximum;
462        Ok(self)
463    }
464
465    #[cfg(feature = "sessions")]
466    pub(crate) fn audience(&self) -> AudienceId {
467        self.audience
468    }
469
470    #[cfg(all(
471        feature = "sessions",
472        any(
473            feature = "portable-signature-verification",
474            feature = "certified-proof-verification"
475        )
476    ))]
477    pub(crate) fn slot_caller(&self, claims: &PortableClaims) -> Option<Principal> {
478        self.accounts
479            .get(&(claims.issuer, claims.account_subject, claims.device_slot))
480            .copied()
481    }
482
483    // One observation for a serialized session operation. Missing reservation is
484    // checked after the session's ordinary liveness/authority refusals; denial
485    // still precedes those refusals. This is never retained between operations.
486    #[cfg(feature = "sessions")]
487    pub(crate) fn observe_login(
488        &mut self,
489        caller: Principal,
490        now_ns: u64,
491    ) -> Result<Option<LoginBinding>, LoginRevocationError> {
492        self.observe(caller, now_ns)?;
493        self.records
494            .get(&caller)
495            .map(|record| record.live_binding(now_ns))
496            .unwrap_or(Ok(None))
497    }
498
499    /// Physical pool occupancy, including retained known slot fences.
500    pub fn occupancy(&self) -> (usize, usize) {
501        (self.admitted, self.unknown)
502    }
503
504    /// Clock high-water mark for an atomic host checkpoint, including refusals.
505    /// Durable hosts retain this with pool counts and the complete record set.
506    pub fn observed_at_ns(&self) -> u64 {
507        self.observed_ns
508    }
509
510    /// Cheap refusal before proof verification. This does not authenticate claims,
511    /// reserve capacity or permit a session commit; success is only permission to
512    /// continue checking. Untrusted claims can cause refusal, never admission.
513    /// Records and pool occupancy stay unchanged; trusted clock observations remain.
514    /// The host must serialize this check, verification and `with_reservation`
515    /// with authority/session/replay changes. The final reservation rechecks state.
516    pub fn check_reservation(
517        &mut self,
518        caller: Principal,
519        claims: &PortableClaims,
520        now_ns: u64,
521    ) -> Result<(), LoginRevocationError> {
522        self.reservation(caller, claims, now_ns).map(|_| ())
523    }
524
525    #[cfg(all(
526        feature = "sessions",
527        any(
528            feature = "portable-signature-verification",
529            feature = "certified-proof-verification"
530        )
531    ))]
532    pub(crate) fn check_prepared_reservation(
533        &mut self,
534        caller: Principal,
535        prepared: &super::ContextualClaims<'_, '_>,
536        now_ns: u64,
537    ) -> Result<(), LoginRevocationError> {
538        self.observe(caller, now_ns)?;
539        self.reservation_checked(
540            caller,
541            &prepared.decoded().claims,
542            prepared.browser_caller(),
543            now_ns,
544        )
545        .map(|_| ())
546    }
547
548    /// Reserve before committing a fully verified admission's session/replay pair.
549    /// The issuer/account and original login window stay unchanged on renewal.
550    /// Verified claims must match this ledger domain, caller and current clock.
551    /// The host still enforces current authority and replay under the same lock.
552    /// A live tombstone rejects even an exact admission retry before its callback.
553    /// No reservation is installed if session/replay storage in `commit` fails.
554    /// The callback receives the proposed record for that same atomic commit.
555    /// Its error is returned unchanged; `E` also carries ledger refusals through
556    /// `From<LoginRevocationError>`. No separate storage-error channel is needed.
557    pub fn with_reservation<T, E: From<LoginRevocationError>>(
558        &mut self,
559        caller: Principal,
560        verified: &VerifiedPortableClaims,
561        now_ns: u64,
562        commit: impl FnOnce(&LoginRevocationChange) -> Result<T, E>,
563    ) -> Result<T, E> {
564        self.observe(caller, now_ns)?;
565        let record =
566            self.reservation_checked(caller, verified.claims(), verified.browser_caller(), now_ns)?;
567        if verified.verified_at_ns() != now_ns {
568            return Err(LoginRevocationError::InvalidPolicy.into());
569        }
570        self.commit_record(caller, record, commit)
571    }
572
573    /// Stage local denial (not necessarily confirmed revocation), then atomically remove this caller's host sessions in
574    /// `commit`. Return the denial deadline only after that callback commits.
575    /// An existing live tombstone keeps its deadline; the callback still runs so
576    /// retry never falsely acknowledges a failed host operation. No proof needed.
577    /// An admitted reservation converts in its own pool even if unknowns fill theirs.
578    /// A caller without a live record consumes one unknown-logout budget credit
579    /// before the callback; exhaustion returns Capacity, never false success.
580    /// Keep that receiver-wide budget separate from fresh proof verification so
581    /// unknown logout traffic cannot spend admission credit. Failure retains the
582    /// charge; hosts must return normal errors rather than trap/roll back credit.
583    /// Live reservations and tombstone retries do not compete for this budget.
584    /// The callback receives the proposed tombstone, including retained binding.
585    /// Only `Revoked(Some(binding))` confirms the authenticated login window.
586    /// `Revoked(None)` is temporary denial: never project its deadline as confirmed
587    /// revocation. Its error is returned unchanged; `E` also carries ledger refusals
588    /// through `From<LoginRevocationError>`. Failed callbacks never install denial.
589    pub fn with_revocation<E: From<LoginRevocationError>>(
590        &mut self,
591        unknown_budget: &mut SessionAdmissionBudget,
592        caller: Principal,
593        now_ns: u64,
594        commit: impl FnOnce(&LoginRevocationChange) -> Result<(), E>,
595    ) -> Result<u64, E> {
596        self.observe(caller, now_ns)?;
597        let old = self
598            .records
599            .get(&caller)
600            .filter(|r| r.admitted_pool() || r.until_ns > now_ns);
601        let record = if let Some(old) = old {
602            Record {
603                until_ns: old.until_ns,
604                state: LoginRecordState::Revoked(old.login()),
605            }
606        } else {
607            let until_ns = retention(now_ns, self.max_login_ttl_ns)?;
608            Record {
609                until_ns,
610                state: LoginRecordState::Revoked(None),
611            }
612        };
613        self.capacity(caller, record.admitted_pool())?;
614        if old.is_none() {
615            unknown_budget
616                .consume(now_ns)
617                .map_err(|error| match error {
618                    AdmissionBudgetError::Exhausted => LoginRevocationError::Capacity,
619                    AdmissionBudgetError::ClockRollback => LoginRevocationError::Clock,
620                    AdmissionBudgetError::InvalidPolicy => LoginRevocationError::InvalidPolicy,
621                })?;
622        }
623        self.commit_record(caller, record, commit)?;
624        Ok(record.until_ns)
625    }
626
627    // One publication point: prepare all records before the host callback, and
628    // change heap state only after its atomic commit succeeds.
629    fn commit_record<T, E: From<LoginRevocationError>>(
630        &mut self,
631        caller: Principal,
632        record: Record,
633        commit: impl FnOnce(&LoginRevocationChange) -> Result<T, E>,
634    ) -> Result<T, E> {
635        let displaced = record
636            .login()
637            .and_then(|login| self.accounts.get(&slot(login)).copied())
638            .filter(|old| *old != caller);
639        let change = LoginRevocationChange(
640            LoginData {
641                audience: self.audience,
642                caller,
643                record,
644            },
645            displaced,
646        );
647        let previous_caller = displaced.unwrap_or(caller);
648        if let Some(previous) = self.records.get(&previous_caller) {
649            change.check_replacement(
650                &LoginRevocationChange(
651                    LoginData {
652                        audience: self.audience,
653                        caller: previous_caller,
654                        record: *previous,
655                    },
656                    None,
657                ),
658                self.observed_ns,
659            )?;
660        }
661        let value = commit(&change)?;
662        if let Some(old) = displaced {
663            self.remove(old);
664        }
665        self.install(caller, record);
666        Ok(value)
667    }
668
669    /// Consult local denial before any session use, including exact retries.
670    /// Absence is not authentication or authorization; other gates still apply.
671    pub fn is_revoked(
672        &mut self,
673        caller: Principal,
674        now_ns: u64,
675    ) -> Result<bool, LoginRevocationError> {
676        self.observe(caller, now_ns)?;
677        Ok(self
678            .records
679            .get(&caller)
680            .is_some_and(|r| r.revoked() && r.until_ns > now_ns))
681    }
682
683    /// Explicit maintenance, at most 128 expired unknown denials. Known slot
684    /// fences are never time-pruned; account retirement requires host recovery policy.
685    /// The host clock must be monotonic, including across failed operations.
686    pub fn prune(&mut self, now_ns: u64, budget: usize) -> Result<usize, LoginRevocationError> {
687        self.prune_with_commit(now_ns, budget, |_, _| Ok(()))
688    }
689    /// Commit bounded expired-login deletion and resulting admitted/unknown counts
690    /// before heap changes. Empty work skips the callback. Failure preserves all
691    /// records but retains the trusted clock observation, as other refusals do.
692    /// Hosts persist clock/authority metadata separately even when no rows expire.
693    pub fn prune_with_commit(
694        &mut self,
695        now_ns: u64,
696        budget: usize,
697        commit: impl FnOnce(&[Principal], (usize, usize)) -> Result<(), LoginRevocationError>,
698    ) -> Result<usize, LoginRevocationError> {
699        self.clock(now_ns)?;
700        let mut callers = Vec::new();
701        let mut counts = self.occupancy();
702        for (_, caller) in self
703            .expiry
704            .iter()
705            .take_while(|(until, _)| *until <= now_ns)
706            .take(budget.min(128))
707        {
708            if self.records[caller].admitted_pool() {
709                counts.0 -= 1;
710            } else {
711                counts.1 -= 1;
712            }
713            callers.push(*caller);
714        }
715        if callers.is_empty() {
716            return Ok(0);
717        }
718        commit(&callers, counts)?;
719        for caller in &callers {
720            self.remove(*caller);
721        }
722        Ok(callers.len())
723    }
724
725    fn reservation(
726        &mut self,
727        caller: Principal,
728        claims: &PortableClaims,
729        now_ns: u64,
730    ) -> Result<Record, LoginRevocationError> {
731        self.observe(caller, now_ns)?;
732        validate_shape(claims).map_err(|_| LoginRevocationError::InvalidPolicy)?;
733        self.reservation_checked(
734            caller,
735            claims,
736            browser_principal(&claims.browser_public_key),
737            now_ns,
738        )
739    }
740
741    // Only canonical decoded or verified claims can skip static shape checks.
742    // Caller/clock and all mutable ledger state are checked on every operation.
743    fn reservation_checked(
744        &self,
745        caller: Principal,
746        claims: &PortableClaims,
747        browser_caller: Principal,
748        now_ns: u64,
749    ) -> Result<Record, LoginRevocationError> {
750        let login_deadline_ns = claims.login_deadline_ns;
751        if claims.audience != self.audience
752            || claims.device_slot >= self.max_device_slots
753            || browser_caller != caller
754            || claims
755                .login_deadline_ns
756                .checked_sub(claims.login_started_at_ns)
757                .is_none_or(|ttl| ttl == 0 || ttl > self.max_login_ttl_ns)
758        {
759            return Err(LoginRevocationError::InvalidPolicy);
760        }
761        let until_ns = login_deadline_ns;
762        let login = LoginBinding {
763            issuer: claims.issuer,
764            subject: claims.account_subject,
765            device_slot: claims.device_slot,
766            device_generation: claims.device_generation,
767            started_at_ns: claims.login_started_at_ns,
768            deadline_ns: claims.login_deadline_ns,
769        };
770        if let Some(old) = self
771            .records
772            .get(&caller)
773            .filter(|r| r.admitted_pool() || r.until_ns > now_ns)
774        {
775            if old.revoked() {
776                return Err(LoginRevocationError::Revoked);
777            }
778            if old.login() != Some(login) {
779                return Err(LoginRevocationError::InvalidPolicy);
780            }
781        }
782        // A different browser key must advance this slot's signed fence.
783        // Preflight never changes state; installation still needs verified claims.
784        let owner = self.accounts.get(&slot(login));
785        if let Some(owner) = owner {
786            let old = self.records[owner];
787            let binding = old.login().expect("slot index has authenticated binding");
788            if login.device_generation < binding.device_generation {
789                return Err(LoginRevocationError::Revoked);
790            }
791            if login.device_generation == binding.device_generation
792                && (*owner != caller || binding != login || old.revoked())
793            {
794                return Err(LoginRevocationError::Revoked);
795            }
796        }
797        let record = Record {
798            until_ns,
799            state: LoginRecordState::Reserved(login),
800        };
801        if owner.is_none() {
802            self.capacity(caller, record.admitted_pool())?;
803        }
804        Ok(record)
805    }
806
807    fn clock(&mut self, now_ns: u64) -> Result<(), LoginRevocationError> {
808        if now_ns < self.observed_ns {
809            return Err(LoginRevocationError::Clock);
810        }
811        self.observed_ns = now_ns;
812        Ok(())
813    }
814
815    fn observe(&mut self, caller: Principal, now_ns: u64) -> Result<(), LoginRevocationError> {
816        if !is_login_caller(caller) {
817            return Err(LoginRevocationError::InvalidCaller);
818        }
819        self.clock(now_ns)
820    }
821
822    fn capacity(&self, caller: Principal, admitted_pool: bool) -> Result<(), LoginRevocationError> {
823        let reuses_pool = self
824            .records
825            .get(&caller)
826            .is_some_and(|old| old.admitted_pool() == admitted_pool);
827        let (count, limit) = if admitted_pool {
828            (self.admitted, self.max_admitted)
829        } else {
830            (self.unknown, self.max_unknown)
831        };
832        if !reuses_pool && count >= limit {
833            return Err(LoginRevocationError::Capacity);
834        }
835        Ok(())
836    }
837
838    fn remove(&mut self, caller: Principal) {
839        if let Some(old) = self.records.remove(&caller) {
840            self.unindex(caller, old);
841        }
842    }
843
844    fn unindex(&mut self, caller: Principal, old: Record) {
845        self.expiry.remove(&(old.until_ns, caller));
846        if let Some(login) = old.login() {
847            self.accounts.remove(&slot(login));
848        }
849        if old.admitted_pool() {
850            self.admitted -= 1;
851        } else {
852            self.unknown -= 1;
853        }
854    }
855
856    fn install(&mut self, caller: Principal, record: Record) {
857        if let Some(old) = self.records.insert(caller, record) {
858            self.unindex(caller, old);
859        }
860        if let Some(login) = record.login() {
861            self.accounts.insert(slot(login), caller);
862        }
863        if record.admitted_pool() {
864            self.admitted += 1;
865        } else {
866            self.unknown += 1;
867        }
868        // Known slot fences survive expiry and logout. Only proofless unknown
869        // denial is time-prunable; deleting a fence could resurrect old proofs.
870        if !record.admitted_pool() {
871            self.expiry.insert((record.until_ns, caller));
872        }
873    }
874}
875
876fn slot(login: LoginBinding) -> (Principal, Principal, u8) {
877    (login.issuer, login.subject, login.device_slot)
878}
879
880fn retention(now_ns: u64, max_login_ttl_ns: u64) -> Result<u64, LoginRevocationError> {
881    now_ns
882        .checked_add(max_login_ttl_ns)
883        .ok_or(LoginRevocationError::Clock)
884}
885
886#[cfg(test)]
887mod tests;