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