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