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