ic-auth 0.57.0

Canonical authentication, proof verification and bounded receiver/issuer state with optional stable upgrade checkpoints
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//! Heap-backed receiver with synchronous admission and stable upgrade checkpoints.
//!
//! Host inputs must come from one isolated transaction. This module neither
//! authenticates enrollment nor installs endpoints. Fresh activation is only for
//! a genuinely new receiver. Complete loss of volatile state permanently closes
//! that installation.
//!
//! Hosts use this module's inputs, limits, receipts and inspection projections.
//! Policy snapshots and preflight decisions are internal implementation details:
//!
//! ```compile_fail,E0603
//! use ic_auth::receiver_policy::assess_session;
//! ```
//! ```compile_fail,E0432
//! use ic_auth::receiver_memory::ReceiverSnapshot;
//! ```

mod enrollment;
mod inspection;
mod records;

#[cfg(feature = "receiver-stable")]
mod checkpoint;
#[cfg(feature = "receiver-stable")]
pub use checkpoint::StableReceiver;

#[cfg(test)]
mod publication_faults;

// Fault injection is absent from deployed builds. Keep the same mutation order
// in tests so every interrupted publication must remain terminally closed.
macro_rules! publish {
    ($change:expr) => {{
        let result = $change;
        #[cfg(test)]
        publication_faults::point();
        result
    }};
}

pub use crate::receiver_policy::{
    LoginBinding, LoginLimits, LogoutError, LogoutReceipt, SessionAuthority, SessionCapacity,
    SessionFacts, SessionPolicyError, SessionUsage, UnknownLogoutLimits,
};
use crate::{
    claims::ClaimsError,
    receiver_policy::{
        self as policy, AdmissionFootprint, LoginDecision, LoginSnapshot, RetryDecision,
    },
    session_request::{SessionRequest, SessionRequestError, SessionTtlPolicy},
    verification::{
        self, BudgetError, ContextError, CredentialError, DecodedClaims, VerificationBudget,
        VerificationCosts, VerificationProfile,
    },
    work_budget::WorkBucket,
};
pub use enrollment::{EnrollmentBinding, EnrollmentError, EnrollmentMetadata};
use ic_auth_protocol_types::{AudienceId, AuthRole, Credential, Principal, ScopeLabel};
pub use inspection::{MAX_INSPECTION_PAGE, MAX_INSPECTION_SCAN, SessionPage};
use records::{CallerRecord, Replay, Session};
use std::{
    collections::{BTreeMap, BTreeSet},
    error::Error,
    fmt,
};

#[derive(Default)]
struct AccountIndex {
    replay_count: usize,
    slots: Vec<(u8, Principal)>,
}
impl AccountIndex {
    fn set_slot(&mut self, slot: u8, caller: Principal) -> Option<Principal> {
        if let Some((_, previous)) = self.slots.iter_mut().find(|(device, _)| *device == slot) {
            return Some(std::mem::replace(previous, caller));
        }
        // Most accounts use a single slot. Avoid reserving several principals per account.
        self.slots.reserve_exact(1);
        self.slots.push((slot, caller));
        None
    }
}
type Account = (Principal, Principal);
type Slot = (Principal, Principal, u8);

///
/// MemoryConfig
///
/// Protected bounds; construction allocates no backing proportional to limits.
///

#[derive(Clone, Copy, Debug)]
#[cfg_attr(
    feature = "receiver-stable",
    derive(serde::Serialize, serde::Deserialize, Eq, PartialEq)
)]
pub struct MemoryConfig {
    /// Receiver domain, fixed for the lifetime of the instance.
    pub audience: AudienceId,
    /// Installed receiver and enrollment authority identities.
    pub enrollment: EnrollmentBinding,
    /// Physical known-login pool and original login lifetime bounds.
    pub login: LoginLimits,
    /// Physical session/replay counts and logical encoded-byte limits.
    pub capacity: SessionCapacity,
    /// Shared proof work bucket capacity.
    pub verification_capacity: u32,
    /// Nanoseconds per replenished work unit.
    pub refill_interval_ns: u64,
    /// Relative costs of each complete verification mechanism.
    pub verification_costs: VerificationCosts,
    /// Separate unknown-login denial pool and operation budget.
    pub unknown_logout: UnknownLogoutLimits,
}

impl MemoryConfig {
    /// Starting limits for a fresh receiver in the supplied audience and enrollment.
    ///
    /// Allows 8 device slots per account, a one-hour maximum original login
    /// lifetime and 125,000 known device slots. Up to 100,000 sessions and 400,000 replay
    /// records (16 per account) share 64 MiB of logical encoded record capacity.
    /// Capacity refusal preserves live records. The host supplies the separate
    /// session TTL, verifier, eligibility and permission policy on admission.
    ///
    /// Proof verification starts empty and earns one unit every two milliseconds
    /// up to 720. Ed25519 costs two units and certified proofs cost 360. Unknown
    /// logout has a separate initially empty 64-unit bucket, refilling once per second.
    /// Each new unknown denial costs one unit and occupies one of 64 rows for
    /// up to the login lifetime. Exhausted proof credit refuses verification;
    /// unknown logout returns a capacity refusal when credit or space runs out.
    ///
    /// Override individual public fields before passing this configuration to
    /// [`StableReceiver::new_fresh`], which validates it. Enrollment is still
    /// required before admission. Complete volatile state loss is terminal.
    #[must_use]
    pub const fn starting_profile(audience: AudienceId, enrollment: EnrollmentBinding) -> Self {
        const SECOND_NS: u64 = 1_000_000_000;
        Self {
            audience,
            enrollment,
            login: LoginLimits {
                max_device_slots: 8,
                max_login_ttl_ns: 3_600 * SECOND_NS,
                max_retained_device_slots: 125_000,
            },
            capacity: SessionCapacity {
                max_sessions: 100_000,
                max_replays: 400_000,
                max_replays_per_account: 16,
                max_encoded_bytes: 64 * 1024 * 1024,
            },
            verification_capacity: 720,
            refill_interval_ns: 2_000_000,
            verification_costs: VerificationCosts {
                ed25519: 2,
                certified: 360,
            },
            unknown_logout: UnknownLogoutLimits {
                max_denials: 64,
                capacity: 64,
                refill_interval_ns: SECOND_NS,
            },
        }
    }
}

///
/// AdmissionHost
///
/// Current protected admission inputs, supplied synchronously by the host.
///

#[derive(Clone, Copy, Debug)]
pub struct AdmissionHost<'a> {
    /// Independently selected enrolled verifier, caller and time.
    pub verifier: VerificationProfile<'a>,
    /// Protected role for narrowing.
    pub role: &'a AuthRole,
    /// Protected default and maximum session duration.
    pub ttl: SessionTtlPolicy,
    /// Current authority generation, changed with enrollment/enablement policy.
    pub generation: u64,
    /// Whether this receiver accepts authentication operations.
    pub enabled: bool,
    /// Application eligibility for the proposed issuer-qualified subject.
    pub subject_admissible: bool,
}

impl AdmissionHost<'_> {
    fn authority(&self) -> SessionAuthority<'_> {
        let c = self.verifier.context();
        SessionAuthority {
            caller: c.caller,
            now_ns: c.now_ns,
            audience: *c.audience,
            issuer: c.issuer,
            mechanism: c.mechanism,
            key_binding_id: c.key_binding_id,
            role: self.role,
            grants: c.grants.as_slice(),
            generation: self.generation,
            not_before_ns: c.authority_not_before_ns,
            expires_at_ns: c.authority_expires_at_ns,
            enrollment_expires_at_ns: c.enrollment_expires_at_ns,
            min_login_started_at_ns: c.min_login_started_at_ns,
            max_session_ttl_secs: self.ttl.maximum_secs(),
            enabled: self.enabled,
            subject_admissible: self.subject_admissible,
        }
    }
}

///
/// SessionReceipt
///
/// Account facts at a successful operation, never authority after an await.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionReceipt<E = Vec<u8>> {
    /// Opaque issuer-attested application bytes, up to 4096 bytes.
    pub ext: Option<E>,
    /// Authenticated browser caller.
    pub caller: Principal,
    /// Account issuer.
    pub issuer: Principal,
    /// Issuer-qualified subject.
    pub subject: Principal,
    /// Original exclusive session lease deadline.
    pub expires_at_ns: u64,
}

impl SessionReceipt<&[u8]> {
    /// Copy the application extension when the caller needs an owned result.
    #[must_use]
    pub fn into_owned(self) -> SessionReceipt {
        SessionReceipt {
            ext: self.ext.map(<[u8]>::to_vec),
            caller: self.caller,
            issuer: self.issuer,
            subject: self.subject,
            expires_at_ns: self.expires_at_ns,
        }
    }
}

///
/// AuthorizedSession
///
/// Current receipt and narrowed scopes available during a guarded operation.
///

pub struct AuthorizedSession<'a> {
    /// Account facts for the same checked session.
    pub receipt: SessionReceipt<&'a [u8]>,
    scopes: &'a [ScopeLabel],
}

impl AuthorizedSession<'_> {
    /// Whether this session holds the exact scope after admission narrowing.
    #[must_use]
    pub fn has_scope(&self, scope: &ScopeLabel) -> bool {
        self.scopes.binary_search(scope).is_ok()
    }
}

///
/// AdmissionOutcome
///
/// Successful admission; exact retries retain the original receipt and work credit.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AdmissionOutcome {
    /// Current session facts.
    pub receipt: SessionReceipt,
    /// True only when no new session or replay was published.
    pub exact_retry: bool,
}

///
/// MemoryError
///
/// Refusal leaves authorization records unchanged; clocks/charges may advance.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MemoryError {
    /// Fresh receiver has not been activated, or was permanently closed.
    Closed,
    /// Boot/refresh response did not satisfy protected enrollment admission.
    Enrollment(EnrollmentError),
    /// Shared receiver policy refused.
    Policy(SessionPolicyError),
    /// Canonical claims could not be decoded.
    Claims(ClaimsError),
    /// Fresh claims failed protected context checks.
    Context(ContextError),
    /// Requested grants or lifetime refused.
    Request(SessionRequestError),
    /// Complete proof refused, retaining any attempted-work charge.
    Proof(CredentialError),
    /// Invalid work configuration.
    Budget(BudgetError),
}

impl fmt::Display for MemoryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "memory receiver refused: {self:?}")
    }
}

impl Error for MemoryError {}
impl From<SessionPolicyError> for MemoryError {
    fn from(e: SessionPolicyError) -> Self {
        Self::Policy(e)
    }
}

///
/// Lifecycle
///
/// Tracks whether this receiver is fresh, ready or closed.
///

#[derive(Clone, Copy, Eq, PartialEq)]
#[cfg_attr(
    feature = "receiver-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
enum Lifecycle {
    Fresh,
    Ready,
    Closed,
}

///
/// MemoryReceiver
///
/// Owned bounded state. No clone, reset, unchecked restore or mutable budget API.
/// All ordinary errors occur before authorization-record publication. Allocation
/// panic during publication permanently closes this instance; a host must abort
/// its transaction or discard it and recover safely, never resume partial state.
/// IC traps remain the host's whole-message rollback boundary.
///

pub struct MemoryReceiver {
    config: MemoryConfig,
    lifecycle: Lifecycle,
    generation: u64,
    enrollment: enrollment::Enrollment,
    observed_at_ns: u64,
    budget: VerificationBudget,
    unknown_budget: WorkBucket,
    unknown: usize,
    slot_expiry: BTreeSet<(u64, Principal)>,
    unknown_expiry: BTreeSet<(u64, Principal)>,
    callers: BTreeMap<Principal, CallerRecord>,
    replays: BTreeMap<[u8; 32], Replay>,
    accounts: BTreeMap<Account, AccountIndex>,
    session_expiry: BTreeSet<(u64, Principal)>,
    replay_expiry: BTreeSet<(u64, [u8; 32])>,
    sessions: usize,
    encoded_bytes: usize,
}

impl MemoryReceiver {
    /// Create closed, empty state for a genuinely new receiver; work starts empty.
    /// This is not a recovery API for a receiver whose replay/fence state was lost.
    pub(crate) fn new_fresh(config: MemoryConfig, now_ns: u64) -> Result<Self, MemoryError> {
        config.login.validate()?;
        config.capacity.validate()?;
        if config.unknown_logout.max_denials == 0 {
            return Err(SessionPolicyError::InvalidContext.into());
        }
        now_ns
            .checked_add(config.login.max_login_ttl_ns)
            .ok_or(SessionPolicyError::InvalidContext)?;
        Ok(Self {
            config,
            lifecycle: Lifecycle::Fresh,
            generation: 0,
            enrollment: enrollment::Enrollment::new(config.enrollment)
                .map_err(MemoryError::Enrollment)?,
            observed_at_ns: now_ns,
            budget: VerificationBudget::new(
                config.verification_capacity,
                config.refill_interval_ns,
                config.verification_costs,
                now_ns,
            )
            .map_err(MemoryError::Budget)?,
            unknown_budget: WorkBucket::new(
                config.unknown_logout.capacity,
                config.unknown_logout.refill_interval_ns,
                now_ns,
            )
            .map_err(MemoryError::Budget)?,
            unknown: 0,
            slot_expiry: BTreeSet::new(),
            unknown_expiry: BTreeSet::new(),
            callers: BTreeMap::new(),
            replays: BTreeMap::new(),
            accounts: BTreeMap::new(),
            session_expiry: BTreeSet::new(),
            replay_expiry: BTreeSet::new(),
            sessions: 0,
            encoded_bytes: 0,
        })
    }

    /// Begin host-administered boot or refresh. The host supplies a fresh,
    /// unpredictable challenge and owns response scheduling/authentication.
    /// Replacing a pending request fences its late response. Existing enrollment
    /// remains usable until its original expiry while refresh is pending.
    pub fn request_enrollment(
        &mut self,
        now_ns: u64,
        challenge: [u8; 32],
        receipt_deadline_ns: u64,
    ) -> Result<(), MemoryError> {
        if self.lifecycle == Lifecycle::Closed {
            return Err(MemoryError::Closed);
        }
        self.observe(now_ns)?;
        self.enrollment
            .request(now_ns, challenge, receipt_deadline_ns)
            .map_err(MemoryError::Enrollment)
    }

    /// Install metadata from the exact installed authority's IC-authenticated
    /// response. The host must validate and install the complete entry/revocation
    /// snapshot in the same transaction. Neither a browser-supplied principal
    /// nor a relayed signed document satisfies `authenticated_authority`.
    /// This cannot reopen a closed instance or recover lost safety state.
    pub fn install_enrollment(
        &mut self,
        now_ns: u64,
        authenticated_authority: Principal,
        snapshot: EnrollmentMetadata,
    ) -> Result<(), MemoryError> {
        if self.lifecycle == Lifecycle::Closed {
            return Err(MemoryError::Closed);
        }
        self.observe(now_ns)?;
        self.enrollment
            .install(
                self.config.audience,
                self.generation,
                now_ns,
                self.lifecycle == Lifecycle::Ready,
                authenticated_authority,
                snapshot,
            )
            .map_err(MemoryError::Enrollment)?;
        self.generation = snapshot.generation;
        self.lifecycle = Lifecycle::Ready;
        Ok(())
    }

    /// Retained accepted metadata, including expired enrollment; not authority.
    #[must_use]
    pub fn enrollment(&self) -> Option<EnrollmentMetadata> {
        self.enrollment.current()
    }

    /// Permanently stop admission and authorization without discarding safety state.
    pub fn close(&mut self) {
        self.lifecycle = Lifecycle::Closed;
    }

    /// Host administrative invalidation, atomically paired with authority changes.
    /// Retains replay, device fences and work credit; overflow refuses.
    pub fn advance_generation(&mut self, now_ns: u64) -> Result<u64, MemoryError> {
        self.ready()?;
        let next = self
            .generation
            .checked_add(1)
            .ok_or(SessionPolicyError::StaleAuthority)?;
        self.observe(now_ns)?;
        self.generation = next;
        Ok(next)
    }

    /// Physical occupancy including expired records awaiting bounded pruning.
    #[must_use]
    pub fn usage(&self, account: Account) -> SessionUsage {
        SessionUsage {
            account,
            sessions: self.sessions,
            replays: self.replays.len(),
            replays_for_account: self
                .accounts
                .get(&account)
                .map(|account| account.replay_count)
                .unwrap_or(0),
            encoded_bytes: self.encoded_bytes,
        }
    }

    /// Physical retained known logins, including denied/expired generation fences.
    #[must_use]
    pub fn known_logins(&self) -> usize {
        self.callers.len() - self.unknown
    }

    /// Physical unknown denials, including expired rows awaiting explicit pruning.
    #[must_use]
    pub const fn unknown_logins(&self) -> usize {
        self.unknown
    }

    /// Retained unknown-logout credit; this getter does not observe time or refill.
    #[must_use]
    pub const fn unknown_logout_credit(&self) -> u32 {
        self.unknown_budget.available()
    }

    /// Read-only work accounting; callers cannot reset or refill it.
    #[must_use]
    pub fn verification_budget(&self) -> &VerificationBudget {
        &self.budget
    }

    /// Latest retained trusted time, including normal operation refusals.
    #[must_use]
    pub const fn observed_at_ns(&self) -> u64 {
        self.observed_at_ns
    }

    /// Admit a complete credential in one synchronous host transaction.
    /// Canonical decoding and caller binding precede lookup. Exact retry precedes
    /// proof freshness/shape/charging; fresh preflight cannot reserve state.
    pub fn admit(
        &mut self,
        credential: &Credential,
        request: SessionRequest,
        host: AdmissionHost<'_>,
    ) -> Result<AdmissionOutcome, MemoryError> {
        self.ready()?;
        let mut authority = host.authority();
        self.enrolled(&mut authority)?;
        let checked = policy::CheckedAuthority::new(&authority, self.config.audience)?;
        let decoded = DecodedClaims::new(&credential.claims).map_err(MemoryError::Claims)?;
        let claims = decoded.claims();
        if decoded.caller() != authority.caller {
            return Err(MemoryError::Context(ContextError::CallerMismatch));
        }
        self.observe(authority.now_ns)?;
        let fingerprint = decoded.fingerprint();
        let selected = self.selected(authority.caller);
        if let RetryDecision::ExactRetry { .. } = policy::assess_retry_checked(
            &selected.snapshot(self),
            checked,
            fingerprint,
            &request,
            self.replays.contains_key(&fingerprint),
        )? {
            return Ok(AdmissionOutcome {
                receipt: selected
                    .session
                    .ok_or(SessionPolicyError::InvalidFacts)?
                    .receipt()
                    .into_owned(),
                exact_retry: true,
            });
        }
        verification::check_context(&decoded, host.verifier.context())
            .map_err(MemoryError::Context)?;
        let expires_at_ns = request
            .evaluate_canonical_grants(&claims.grants, host.role, authority.now_ns, host.ttl)
            .map_err(MemoryError::Request)?
            .min(claims.login_deadline_ns)
            .min(authority.expires_at_ns);
        let binding = LoginBinding {
            issuer: claims.issuer,
            subject: claims.account_subject,
            device_slot: claims.device_slot,
            device_generation: claims.device_generation,
            started_at_ns: claims.login_started_at_ns,
            deadline_ns: claims.login_deadline_ns,
        };
        let slot = (binding.issuer, binding.subject, binding.device_slot);
        let owner = self
            .slot_owner(slot)
            .and_then(|caller| self.callers.get(caller));
        let device = owner.and_then(CallerRecord::device);
        let login = policy::assess_login(
            &LoginSnapshot {
                audience: self.config.audience,
                caller: authority.caller,
                observed_at_ns: self.observed_at_ns,
                caller_login: selected.login.as_ref(),
                device: device.as_ref(),
                slot_owner: owner.map(|row| &row.login),
                admitted_logins: self.known_logins(),
            },
            binding,
            authority.now_ns,
            self.config.login,
        )?;
        let displaced = match login {
            LoginDecision::Replacement { displaced_caller } => displaced_caller,
            _ => authority.caller,
        };
        let previous_expiry = owner.map(|row| row.reclaim_at(self.config.login.max_login_ttl_ns));
        let displaced_denial = owner
            .filter(|row| {
                row.login.caller != authority.caller
                    && row.login.denied
                    && authority.now_ns < row.login.until_ns
            })
            .map(|row| row.login.until_ns);
        if displaced_denial.is_some()
            && self.unknown >= self.config.unknown_logout.max_denials
            && !selected.login.is_some_and(|row| row.binding.is_none())
        {
            return Err(SessionPolicyError::Capacity.into());
        }
        let old = self
            .callers
            .get(&displaced)
            .and_then(|r| r.session.as_ref());
        let session = Session::prepare(claims, request, &authority, expires_at_ns, fingerprint)?;
        let replay = Replay::prepare(
            &fingerprint,
            (binding.issuer, binding.subject),
            claims.admission_expires_at_ns,
        )?;
        let usage = policy::assess_capacity(
            (binding.issuer, binding.subject),
            self.usage((binding.issuer, binding.subject)),
            AdmissionFootprint {
                session_bytes: session.bytes,
                replay_bytes: replay.bytes,
                replaced_session_bytes: old.map(|s| s.bytes),
            },
            self.config.capacity,
        )?;
        let until_ns = selected.login.map_or(binding.deadline_ns, |row| {
            row.until_ns.max(binding.deadline_ns)
        });
        let horizon = binding
            .started_at_ns
            .saturating_add(self.config.login.max_login_ttl_ns);
        let until_ns = previous_expiry
            .filter(|old| *old > horizon)
            .unwrap_or(0)
            .max(until_ns);
        let reclaim_at = horizon.max(until_ns);
        // The private verifier consumes this exact canonical decode. All ordinary
        // failures precede publication; attempted crypto charges remain in budget.
        let verified = verification::verify_decoded(
            decoded,
            &credential.proof,
            host.verifier,
            &mut self.budget,
        )
        .map_err(MemoryError::Proof)?;
        let receipt = SessionReceipt {
            ext: verified.into_extension(),
            caller: authority.caller,
            issuer: binding.issuer,
            subject: binding.subject,
            expires_at_ns,
        };
        let record = CallerRecord::new(
            authority.caller,
            self.config.audience,
            binding,
            until_ns,
            session,
        );
        // No fallible return after this point. Poison before any map allocation,
        // so even a caught panic cannot expose a partially published receiver.
        publish!(self.lifecycle = Lifecycle::Closed);
        if previous_expiry != Some(reclaim_at) || displaced != authority.caller {
            if let Some(previous) = previous_expiry {
                publish!(self.slot_expiry.remove(&(previous, displaced)));
            }
            publish!(self.slot_expiry.insert((reclaim_at, authority.caller)));
        }
        self.remove_session(displaced);
        self.remove_unknown(authority.caller);
        if let Some(deadline) = displaced_denial {
            self.store_unbound_denial(displaced, deadline);
        } else if displaced != authority.caller {
            publish!(self.callers.remove(&displaced));
        }
        publish!(self.callers.insert(authority.caller, record));
        let account = self.accounts.entry(usage.account).or_default();
        publish!(account.set_slot(binding.device_slot, authority.caller));
        publish!(account.replay_count = usage.replays_for_account);
        publish!(
            self.session_expiry
                .insert((expires_at_ns, authority.caller))
        );
        publish!(
            self.replay_expiry
                .insert((replay.remove_at_ns, fingerprint))
        );
        publish!(self.replays.insert(fingerprint, replay));
        publish!(self.sessions = usage.sessions);
        publish!(self.encoded_bytes = usage.encoded_bytes);
        self.lifecycle = Lifecycle::Ready;
        Ok(AdmissionOutcome {
            receipt,
            exact_retry: false,
        })
    }

    /// Proof-free read under current enrollment and application policy. Recheck
    /// after every await before a privileged operation; receipts are only facts.
    pub fn read(
        &mut self,
        authority: &SessionAuthority<'_>,
        required_scopes: &[ScopeLabel],
    ) -> Result<SessionReceipt, MemoryError> {
        self.authorize_with_scopes(authority, required_scopes, |session| {
            session.receipt.into_owned()
        })
    }

    /// Run a synchronous application projection only after current session checks.
    /// The host owns authenticated inputs and transaction isolation throughout
    /// this call. An Auth refusal never invokes `project`; application errors can
    /// be returned as `R` without being confused with an authentication refusal.
    ///
    /// The borrowed receipt cannot escape this invocation. Copied account facts
    /// or a previously returned receipt are not continuing authority: after every
    /// await, obtain current host inputs and authorize again before a new effect.
    /// A returned future with copied facts does not carry authentication into its
    /// execution. This method supplies neither application rollback nor an executor.
    ///
    /// ```compile_fail
    /// use ic_auth::{receiver_memory::{MemoryReceiver, MemoryError, SessionReceipt},
    ///     receiver_memory::SessionAuthority};
    /// fn escape<'a>(r: &'a mut MemoryReceiver, host: &SessionAuthority<'_>)
    ///     -> Result<&'a [u8], MemoryError> {
    ///     r.authorize(host, &[], |receipt| receipt.ext.unwrap())
    /// }
    /// ```
    /// ```compile_fail
    /// use ic_auth::receiver_memory::{MemoryReceiver, SessionAuthority};
    /// fn defer(r: &mut MemoryReceiver, host: &SessionAuthority<'_>) {
    ///     let _ = r.authorize(host, &[], |receipt| async move { receipt.caller });
    /// }
    /// ```
    pub fn authorize<R>(
        &mut self,
        authority: &SessionAuthority<'_>,
        required_scopes: &[ScopeLabel],
        project: impl FnOnce(&SessionReceipt<&[u8]>) -> R,
    ) -> Result<R, MemoryError> {
        self.authorize_with_scopes(authority, required_scopes, |session| {
            project(&session.receipt)
        })
    }

    /// Run one synchronous projection after checking the session and all required
    /// scopes. Use `has_scope` for optional permissions within that operation.
    /// Reauthorize after an await before performing another privileged effect.
    ///
    /// ```compile_fail
    /// use ic_auth::receiver_memory::{AuthorizedSession, MemoryError, MemoryReceiver, SessionAuthority};
    /// fn escape<'a>(receiver: &'a mut MemoryReceiver, host: &SessionAuthority<'_>)
    ///     -> Result<AuthorizedSession<'a>, MemoryError> {
    ///     receiver.authorize_with_scopes(host, &[], |session| session)
    /// }
    /// ```
    pub fn authorize_with_scopes<R>(
        &mut self,
        authority: &SessionAuthority<'_>,
        required_scopes: &[ScopeLabel],
        project: impl FnOnce(AuthorizedSession<'_>) -> R,
    ) -> Result<R, MemoryError> {
        self.ready()?;
        let mut current = *authority;
        self.enrolled(&mut current)?;
        let authority = &current;
        let checked = policy::CheckedAuthority::new(authority, self.config.audience)?;
        self.observe(authority.now_ns)?;
        let selected = self.selected(authority.caller);
        policy::assess_session_checked(&selected.snapshot(self), checked, required_scopes)?;
        let facts = selected.session.ok_or(SessionPolicyError::InvalidFacts)?;
        Ok(project(AuthorizedSession {
            receipt: facts.receipt(),
            scopes: facts.scopes,
        }))
    }

    /// Commit local denial for the authenticated caller without requiring current
    /// enrollment or accepting a caller-selected target/deadline. Known login
    /// deadlines and live unknown retries never slide. Unknown denials remain
    /// unconfirmed, use a separate pool/bucket and cannot consume proof credit.
    pub fn logout(&mut self, caller: Principal, now_ns: u64) -> Result<LogoutReceipt, LogoutError> {
        self.ready().map_err(|_| LogoutError::Closed)?;
        if !policy::login_caller(caller) {
            return Err(LogoutError::InvalidCaller);
        }
        self.observe(now_ns).map_err(|_| LogoutError::Clock)?;
        let plan = policy::plan_logout(
            caller,
            self.config.audience,
            self.callers.get(&caller).map(|row| &row.login),
            now_ns,
            self.config.login.max_login_ttl_ns,
            (self.unknown, self.config.unknown_logout.max_denials),
        )?;
        if plan.charge_unknown {
            self.unknown_budget.charge(now_ns, 1).map_err(|e| match e {
                BudgetError::Exhausted => LogoutError::Capacity,
                BudgetError::ClockRollback => LogoutError::Clock,
                BudgetError::InvalidPolicy => LogoutError::InvalidFacts,
            })?;
        }
        match plan.receipt {
            LogoutReceipt::Revoked { .. } => {
                publish!(self.lifecycle = Lifecycle::Closed);
                self.remove_session(caller);
                if let Some(row) = self.callers.get_mut(&caller) {
                    publish!(row.login.denied = true);
                }
            }
            LogoutReceipt::Unconfirmed { deny_until_ns } if plan.charge_unknown => {
                publish!(self.lifecycle = Lifecycle::Closed);
                self.remove_unknown(caller);
                self.store_unbound_denial(caller, deny_until_ns);
            }
            LogoutReceipt::Unconfirmed { .. } => {} // already committed; deadline and credit unchanged
        }
        self.lifecycle = Lifecycle::Ready;
        Ok(plan.receipt)
    }

    /// Remove at most `limit` expired session, replay, denial and device-slot rows in total (1–128).
    /// Visits indexed deadlines only.
    pub fn prune(&mut self, now_ns: u64, limit: usize) -> Result<PruneReport, MemoryError> {
        self.ready()?;
        if !(1..=128).contains(&limit) {
            return Err(SessionPolicyError::InvalidContext.into());
        }
        self.observe(now_ns)?;
        let mut report = PruneReport::default();
        publish!(self.lifecycle = Lifecycle::Closed);
        while report.sessions + report.replays + report.unknown_denials + report.device_slots
            < limit
        {
            if let Some(&(deadline, caller)) = self.session_expiry.first()
                && deadline <= now_ns
            {
                self.remove_session(caller);
                report.sessions += 1;
            } else if let Some(&(deadline, fingerprint)) = self.replay_expiry.first()
                && deadline <= now_ns
            {
                publish!(self.replay_expiry.remove(&(deadline, fingerprint)));
                if let Some(replay) = publish!(self.replays.remove(&fingerprint)) {
                    publish!(self.encoded_bytes -= replay.bytes);
                    if let Some(account) = self.accounts.get_mut(&replay.account) {
                        publish!(account.replay_count -= 1);
                        if account.replay_count == 0 && account.slots.is_empty() {
                            publish!(self.accounts.remove(&replay.account));
                        }
                    }
                }
                report.replays += 1;
            } else if let Some(&(deadline, caller)) = self.unknown_expiry.first()
                && deadline <= now_ns
            {
                self.remove_unknown(caller);
                report.unknown_denials += 1;
            } else if let Some(&(deadline, caller)) = self.slot_expiry.first()
                && deadline <= now_ns
            {
                self.reclaim_slot(deadline, caller);
                report.device_slots += 1;
            } else {
                break;
            }
        }
        self.lifecycle = Lifecycle::Ready;
        Ok(report)
    }

    fn ready(&self) -> Result<(), MemoryError> {
        if self.lifecycle == Lifecycle::Ready {
            Ok(())
        } else {
            Err(MemoryError::Closed)
        }
    }

    fn enrolled(&self, authority: &mut SessionAuthority<'_>) -> Result<(), MemoryError> {
        let snapshot = self.enrollment.current().ok_or(MemoryError::Closed)?;
        if snapshot.generation != self.generation
            || authority.generation != self.generation
            || authority.now_ns < snapshot.issued_at_ns
            || authority.now_ns >= snapshot.expires_at_ns
        {
            return Err(SessionPolicyError::StaleAuthority.into());
        }
        authority.enrollment_expires_at_ns = authority
            .enrollment_expires_at_ns
            .min(snapshot.expires_at_ns);
        Ok(())
    }

    fn observe(&mut self, now_ns: u64) -> Result<(), MemoryError> {
        if now_ns < self.observed_at_ns {
            return Err(SessionPolicyError::ClockRollback.into());
        }
        self.observed_at_ns = now_ns;
        Ok(())
    }

    fn reclaim_slot(&mut self, deadline: u64, caller: Principal) {
        publish!(self.slot_expiry.remove(&(deadline, caller)));
        let row = publish!(self.callers.remove(&caller)).expect("indexed slot owner");
        let (issuer, subject, device) = row.slot().expect("known login");
        let key = (issuer, subject);
        let account = self.accounts.get_mut(&key).expect("indexed account");
        publish!(account.slots.retain(|(slot, _)| *slot != device));
        if account.slots.is_empty() && account.replay_count == 0 {
            publish!(self.accounts.remove(&key));
        }
    }

    fn remove_session(&mut self, caller: Principal) {
        if let Some(row) = self.callers.get_mut(&caller)
            && let Some(session) = publish!(row.session.take())
        {
            publish!(self.session_expiry.remove(&(session.expires_at_ns, caller)));
            publish!(self.sessions -= 1);
            publish!(self.encoded_bytes -= session.bytes);
        }
    }

    fn store_unbound_denial(&mut self, caller: Principal, deadline: u64) {
        let row = CallerRecord::unknown(caller, self.config.audience, deadline);
        publish!(self.callers.insert(caller, row));
        publish!(self.unknown_expiry.insert((deadline, caller)));
        publish!(self.unknown += 1);
    }

    fn remove_unknown(&mut self, caller: Principal) {
        if let Some(row) = self.callers.get(&caller)
            && row.login.binding.is_none()
        {
            publish!(self.unknown_expiry.remove(&(row.login.until_ns, caller)));
            publish!(self.callers.remove(&caller));
            publish!(self.unknown -= 1);
        }
    }

    fn slot_owner(&self, slot: Slot) -> Option<&Principal> {
        self.accounts
            .get(&(slot.0, slot.1))?
            .slots
            .iter()
            .find(|(device, _)| *device == slot.2)
            .map(|(_, caller)| caller)
    }

    fn selected(&self, caller: Principal) -> records::Selected<'_> {
        let row = self.callers.get(&caller);
        let session = row.and_then(CallerRecord::session_facts);
        let device = row
            .and_then(CallerRecord::slot)
            .and_then(|slot| self.slot_owner(slot))
            .filter(|owner| **owner == caller)
            .and(row)
            .and_then(CallerRecord::device);
        records::Selected {
            session,
            login: row.map(|r| r.login),
            device,
        }
    }
}

///
/// PruneReport
///
/// Physical rows removed by one bounded maintenance call.
///

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct PruneReport {
    /// Expired session rows removed.
    pub sessions: usize,
    /// Expired replay rows removed.
    pub replays: usize,
    /// Expired unknown denials removed.
    pub unknown_denials: usize,
    /// Known device slots safely reclaimed.
    pub device_slots: usize,
}