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 started_at_ns: u64,
78 pub deadline_ns: u64,
79}
80
81pub 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 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 #[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 #[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 pub fn audience(&self) -> AudienceId {
154 self.0.audience
155 }
156 pub fn caller(&self) -> Principal {
158 self.0.caller
159 }
160 pub fn until_ns(&self) -> u64 {
162 self.0.record.until_ns
163 }
164 pub fn state(&self) -> LoginRecordState {
167 self.0.record.state
168 }
169}
170
171pub 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 #[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 #[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 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 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 #[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 pub fn occupancy(&self) -> (usize, usize) {
330 (self.admitted, self.unknown)
331 }
332
333 pub fn observed_at_ns(&self) -> u64 {
336 self.observed_ns
337 }
338
339 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 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 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 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 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 pub fn prune(&mut self, now_ns: u64, budget: usize) -> Result<usize, LoginRevocationError> {
498 self.prune_with_commit(now_ns, budget, |_, _| Ok(()))
499 }
500 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 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;