1use 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#[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#[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))]
72pub 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
83pub 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 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 #[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 #[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 pub fn audience(&self) -> AudienceId {
182 self.0.audience
183 }
184 pub fn caller(&self) -> Principal {
186 self.0.caller
187 }
188 pub fn displaced_caller(&self) -> Option<Principal> {
191 self.1
192 }
193 pub fn until_ns(&self) -> u64 {
195 self.0.record.until_ns
196 }
197 pub fn state(&self) -> LoginRecordState {
200 self.0.record.state
201 }
202}
203
204pub struct MemoryLoginRevocations {
227 audience: AudienceId,
228 records: BTreeMap<Principal, Record>,
229 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 #[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 #[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 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 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 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 #[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 pub fn occupancy(&self) -> (usize, usize) {
404 (self.admitted, self.unknown)
405 }
406
407 pub fn observed_at_ns(&self) -> u64 {
410 self.observed_ns
411 }
412
413 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 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 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 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 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 pub fn prune(&mut self, now_ns: u64, budget: usize) -> Result<usize, LoginRevocationError> {
590 self.prune_with_commit(now_ns, budget, |_, _| Ok(()))
591 }
592 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 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 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 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;