Skip to main content

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