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
//! Heap-backed issuance, browser renewal and exact-result reconciliation.
//!
//! Account authentication, trusted time/authority, entropy, approval and signing
//! are host inputs. Upgrades use a checkpoint on a host-provided lease.
//! The host owns certified leaf/root publication and witness assembly. Expired records remain
//! charged until explicit bounded pruning; capacity refusal never deletes them.
//!
//! A host must commit dispatch before an external effect, authenticate its response
//! against the exact ticket/input, and own transaction rollback. A native unwind
//! during multi-record publication closes the instance. A missing checkpoint
//! leaves the prior installation closed.

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

#[cfg(test)]
mod tests;

mod certified;
mod login_rows;
use login_rows::LoginRows;
mod renewal;
mod retention;
mod types;

use crate::{
    claims::{encode_claims, validate_grants},
    work_budget::{BudgetError, WorkBucket},
};
use ic_auth_protocol_types::{DelegatedRoleGrant, PortableClaims, Principal};
use std::collections::{BTreeMap, BTreeSet};

pub use certified::{CertifiedCompletionError, CertifiedPublication};
pub use types::{
    IssueRequest, IssuedCredential, IssuedProof, IssuerAuthority, IssuerConfig, IssuerError,
    IssuerIntent, IssuerPolicy, IssuerPruned, IssuerSigning, IssuerStatus, IssuerTicket,
    IssuerUsage, RenewRequest, RenewalSelection, RetainedRenewal, SigningInput,
};

// Each call marks a completed write where unit tests can interrupt publication.
macro_rules! after_write {
    () => {
        #[cfg(test)]
        $crate::issuer_memory::tests::after_write();
    };
}
use after_write;

type Identity = (u64, [u8; 32]);
// Match reference expiry ties: time, principal length/bytes, epoch, identity.
type Expiry = (u64, u8, Principal, Identity);
fn expiry(time: u64, account: Principal, identity: Identity) -> Expiry {
    (time, account.as_slice().len() as u8, account, identity)
}

///
/// Account
///
/// Indexes one account’s retained logins and issuer operations.
///

#[derive(Default)]
#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
struct Account {
    // At most eight logins: slot/browser selection scans only this bounded owner.
    logins: LoginRows,
    operations: BTreeMap<Identity, Operation>,
    // Lookup projection only: results live in operations for both entry paths.
    renewals: BTreeMap<(Identity, u64), Identity>,
}

///
/// Login
///
/// Keeps the browser binding, grants and renewal state for one login.
///

#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
struct Login {
    browser: [u8; 32],
    grants: Vec<DelegatedRoleGrant>,
    #[cfg_attr(feature = "issuer-stable", serde(with = "checkpoint::PolicyLimits"))]
    policy: IssuerPolicy,
    slot: u8,
    generation: u64,
    started: u64,
    deadline: u64,
    revoked: bool,
    renewal: RenewalProgress,
    references: u32,
}

impl Login {
    fn idle_prune_at(&self) -> u64 {
        if self.revoked || matches!(self.renewal, RenewalProgress::Initial) {
            self.started
        } else {
            self.deadline
        }
    }
}

///
/// RenewalProgress
///
/// Tracks the sequence of an in-flight or completed renewal.
///

#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
enum RenewalProgress {
    Initial,
    InFlight(u64),
    Completed(u64),
    // An initial signing dispatch was pruned without observing completion.
    InitialOutcomeUnknown,
    // The in-flight operation passed both deadlines and its reconciliation retention.
    PrunedRenewal(u64),
}

impl RenewalProgress {
    fn sequence(&self) -> u64 {
        match self {
            Self::Initial | Self::InitialOutcomeUnknown => 0,
            Self::InFlight(n) | Self::Completed(n) | Self::PrunedRenewal(n) => *n,
        }
    }

    fn check_next(&self, next: u64) -> Result<(), IssuerError> {
        if next <= self.sequence() {
            return Err(IssuerError::EpochClosed);
        }
        if !matches!(self, Self::Completed(n) | Self::PrunedRenewal(n) if n.checked_add(1) == Some(next))
        {
            return Err(IssuerError::Conflict);
        }
        Ok(())
    }
}

///
/// Operation
///
/// Retains the ticket, login binding and completion phase of an issuer request.
///

#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
struct Operation {
    #[cfg_attr(
        feature = "issuer-stable",
        serde(with = "crate::stable_upgrade::extension")
    )]
    ext: Option<Vec<u8>>,
    #[cfg_attr(feature = "issuer-stable", serde(with = "checkpoint::TicketFields"))]
    ticket: IssuerTicket,
    login: Identity,
    issued: u64,
    admission: u64,
    receipt: u64,
    phase: Phase,
    renewal: Option<u64>,
    remove_at: u64,
    result_bytes: u64,
}

///
/// Approval
///
/// Keeps the nonce, commitment and claims selected for signing.
///

#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
struct Approval {
    nonce: [u8; 16],
    commitment: [u8; 32],
    claims: Vec<u8>,
}

///
/// Phase
///
/// Tracks an issuer operation from reservation through completion.
///

#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
enum Phase {
    Reserved,
    Challenged([u8; 16]),
    Approved(Approval),
    Dispatched(Approval),
    Completed(Approval, Completion),
}

///
/// Completion
///
/// Records which proof material is available for a completed operation.
///

#[derive(Clone, Copy, Eq, PartialEq)]
#[cfg_attr(
    feature = "issuer-stable",
    derive(serde::Serialize, serde::Deserialize)
)]
enum Completion {
    Ed25519(#[cfg_attr(feature = "issuer-stable", serde(with = "signature_bytes"))] [u8; 64]),
    Certified,
}

impl Phase {
    fn evidence(&self) -> (Option<[u8; 16]>, Option<[u8; 32]>) {
        match self {
            Self::Reserved => (None, None),
            Self::Challenged(nonce) => (Some(*nonce), None),
            Self::Approved(a) | Self::Dispatched(a) | Self::Completed(a, _) => {
                (Some(a.nonce), Some(a.commitment))
            }
        }
    }
}

impl Operation {
    fn status(&self) -> IssuerStatus<'_> {
        match &self.phase {
            Phase::Completed(a, completion) => IssuerStatus::Completed(IssuedCredential {
                claims: &a.claims,
                proof: match completion {
                    Completion::Ed25519(signature) => IssuedProof::Ed25519(signature),
                    Completion::Certified => {
                        let IssuerSigning::Certified { seed_hash } = self.ticket.authority.signing
                        else {
                            unreachable!("certified completion authority")
                        };
                        IssuedProof::Certified { seed_hash }
                    }
                },
                admission_deadline_ns: self.admission,
            }),
            Phase::Dispatched(_) => IssuerStatus::Unknown(self.ticket),
            _ => IssuerStatus::Pending(self.ticket),
        }
    }
}

///
/// MemoryIssuer
///
/// One bounded owner of account bindings, issuer operations and fresh-intent credit.
/// Do not clone a live instance or reconstruct it to recover lost state.
///

pub struct MemoryIssuer {
    config: IssuerConfig,
    accounts: BTreeMap<Principal, Account>,
    operation_expiry: BTreeSet<Expiry>,
    idle_logins: BTreeSet<Expiry>,
    usage: IssuerUsage,
    budget: WorkBucket,
    observed: u64,
    epoch: u64,
    boot: u64,
    generation: u64,
    open: bool,
}

impl MemoryIssuer {
    /// Create genuinely new state with full initial fresh-intent credit.
    /// This cannot restore old login, nonce, result or external-effect evidence.
    pub(crate) fn new_fresh(config: IssuerConfig, now_ns: u64) -> Result<Self, IssuerError> {
        if config.issuer == Principal::anonymous()
            || config.max_logins == 0
            || config.max_operations == 0
            || config.max_operations_per_account == 0
            || config.max_operations_per_account > config.max_operations
            || !(1..=login_rows::MAX_LOGINS).contains(&config.max_devices_per_account)
            || config.max_result_bytes == 0
        {
            return Err(IssuerError::Invalid);
        }
        Ok(Self {
            budget: WorkBucket::new_full(
                config.issuance_burst,
                config.issuance_refill_interval_ns,
                now_ns,
            )
            .map_err(|_| IssuerError::Invalid)?,
            config,
            accounts: BTreeMap::new(),
            operation_expiry: BTreeSet::new(),
            idle_logins: BTreeSet::new(),
            usage: IssuerUsage::default(),
            observed: now_ns,
            epoch: 1,
            boot: 1,
            generation: 0,
            open: true,
        })
    }

    /// Current epoch for new work. Pruning closes consumed IDs; restart also fences
    /// callbacks. Neither resets retained state, generation counters or credit.
    #[must_use]
    pub const fn epoch(&self) -> u64 {
        self.epoch
    }

    /// Physical counts; expired rows remain charged until explicit pruning.
    #[must_use]
    pub const fn usage(&self) -> IssuerUsage {
        self.usage
    }

    /// Retained credit, without lazy refill or a clock observation.
    #[must_use]
    pub const fn available_credit(&self) -> u32 {
        self.budget.available()
    }

    /// Most recently observed trusted operation time, including ordinary refusals.
    #[must_use]
    pub const fn observed_at_ns(&self) -> u64 {
        self.observed
    }

    /// Terminal containment after lost state or host failure. It cannot be reopened.
    pub fn close(&mut self) {
        self.open = false;
    }

    /// Reserve an exact account-authenticated intent and its completed-result bytes
    /// before entropy, approval or signing. `account` must come from host authentication.
    /// Only a newly retained intent spends credit. Exact retries keep their original deadlines.
    pub fn prepare_issue(
        &mut self,
        account: Principal,
        request: &IssueRequest,
        policy: IssuerPolicy,
        authority: IssuerAuthority,
        now_ns: u64,
    ) -> Result<IssuerTicket, IssuerError> {
        self.prepare(account, request, policy, authority, None, now_ns)
    }

    fn prepare(
        &mut self,
        account: Principal,
        request: &IssueRequest,
        policy: IssuerPolicy,
        authority: IssuerAuthority,
        renewal: Option<u64>,
        now_ns: u64,
    ) -> Result<IssuerTicket, IssuerError> {
        self.observe(now_ns)?;
        validate_request(account, request, &policy)?;
        let operation_key = (request.epoch, request.operation_id);
        let login_key = (request.login_epoch, request.login_id);
        let owner = self.accounts.get(&account);
        if let Some(op) = owner.and_then(|a| a.operations.get(&operation_key)) {
            let login = &self.accounts[&account].logins[&op.login];
            if op.login != login_key
                || op.renewal != renewal
                || op.ext != policy.ext
                || !login.matches_request_and_limits(request, &policy)
            {
                return Err(IssuerError::Conflict);
            }
            if !matches!(op.phase, Phase::Completed(..)) {
                self.check_pending(op, authority, now_ns)?;
            }
            return Ok(op.ticket);
        }
        if request.epoch != self.epoch {
            return Err(IssuerError::EpochClosed);
        }
        if authority.generation == 0
            || authority.key_binding_id == [0; 32]
            || now_ns >= authority.expires_at_ns
        {
            return Err(IssuerError::Denied);
        }
        if self.usage.operations >= self.config.max_operations
            || owner.is_some_and(|a| {
                a.operations.len() >= self.config.max_operations_per_account as usize
            })
        {
            return Err(IssuerError::Capacity);
        }
        let previous = owner.and_then(|a| a.logins.get(&login_key));
        let new_login;
        let login = if let Some(login) = previous {
            if !login.matches_request_and_limits(request, &policy)
                || (login.policy.ext.is_some() && login.policy.ext != policy.ext)
            {
                return Err(IssuerError::Conflict);
            }
            if login.revoked {
                return Err(IssuerError::Denied);
            }
            if now_ns >= login.deadline {
                return Err(IssuerError::Expired);
            }
            new_login = None;
            login
        } else {
            if request.login_epoch != self.epoch {
                return Err(IssuerError::EpochClosed);
            }
            if self.usage.logins >= self.config.max_logins {
                return Err(IssuerError::Capacity);
            }
            if owner.is_some_and(|a| {
                a.logins
                    .values()
                    .any(|l| l.browser == request.browser_public_key)
            }) {
                return Err(IssuerError::Conflict);
            }
            let slot = (0..self.config.max_devices_per_account)
                .find(|slot| owner.is_none_or(|a| a.logins.values().all(|l| l.slot != *slot)))
                .ok_or(IssuerError::Capacity)?;
            new_login = Some(Login {
                browser: request.browser_public_key,
                grants: request.grants.clone(),
                policy: policy.clone(),
                slot,
                generation: self
                    .generation
                    .checked_add(1)
                    .ok_or(IssuerError::Capacity)?,
                started: now_ns,
                deadline: now_ns
                    .checked_add(policy.login_ttl_ns)
                    .ok_or(IssuerError::Invalid)?,
                revoked: false,
                renewal: RenewalProgress::Initial,
                references: 0,
            });
            new_login.as_ref().ok_or(IssuerError::Invalid)?
        };
        if let Some(sequence) = renewal {
            login.renewal.check_next(sequence)?;
        }
        let ticket = IssuerTicket {
            account,
            epoch: request.epoch,
            operation_id: request.operation_id,
            authority,
            boot: self.boot,
        };
        let (admission, receipt, remove_at) = policy
            .deadlines(now_ns, login.deadline, authority.expires_at_ns)
            .ok_or(IssuerError::Invalid)?;
        let mut op = Operation {
            ext: policy.ext.clone(),
            ticket,
            login: login_key,
            issued: now_ns,
            admission,
            receipt,
            phase: Phase::Reserved,
            renewal,
            remove_at,
            result_bytes: 0,
        };
        // Nonce contents do not change encoded length. Reserve the exact largest
        // result before publishing; no retained record is encoded for accounting.
        let bytes = self.claims(&op, login, [0; 16])?.len() as u64
            + if authority.signing == IssuerSigning::Ed25519 {
                64
            } else {
                0
            };
        op.result_bytes = bytes;
        let references = login
            .references
            .checked_add(1)
            .ok_or(IssuerError::Capacity)?;
        let idle_key = expiry(login.idle_prune_at(), account, login_key);
        let operation_expiry = expiry(op.remove_at, account, operation_key);
        let result_bytes = self
            .usage
            .result_bytes
            .checked_add(bytes)
            .filter(|n| *n <= self.config.max_result_bytes)
            .ok_or(IssuerError::Capacity)?;
        self.budget.charge(now_ns, 1).map_err(|e| match e {
            BudgetError::Exhausted => IssuerError::Throttled,
            BudgetError::ClockRollback => IssuerError::Clock,
            BudgetError::InvalidPolicy => IssuerError::Invalid,
        })?;
        // No fallible tail. A native unwind between these writes leaves us closed;
        // an IC host still owns rollback of the enclosing transaction.
        self.open = false;
        let owner = self.accounts.entry(account).or_default();
        after_write!();
        if let Some(login) = new_login {
            self.generation = login.generation;
            owner.logins.insert(login_key, login);
            self.usage.logins += 1;
            after_write!();
        }
        self.idle_logins.remove(&idle_key);
        after_write!();
        let login = owner
            .logins
            .get_mut(&login_key)
            .expect("selected operation login");
        login.references = references;
        login.policy.ext = policy.ext;
        after_write!();
        if let Some(sequence) = renewal {
            // Existing login was selected above; advance its watermark in the
            // same publication as the one shared operation and lookup index.
            owner
                .logins
                .get_mut(&login_key)
                .expect("selected renewal login")
                .renewal = RenewalProgress::InFlight(sequence);
            after_write!();
            owner.renewals.insert((login_key, sequence), operation_key);
            after_write!();
        }
        self.operation_expiry.insert(operation_expiry);
        after_write!();
        owner.operations.insert(operation_key, op);
        after_write!();
        self.usage.operations += 1;
        self.usage.result_bytes = result_bytes;
        after_write!();
        self.open = true;
        Ok(ticket)
    }

    /// Lookup only, using the authenticated account. Missing evidence never creates
    /// an intent or authorizes another effect. Expiry/revocation do not erase results.
    pub fn reconcile(
        &self,
        account: Principal,
        epoch: u64,
        operation_id: [u8; 32],
    ) -> Result<Option<IssuerStatus<'_>>, IssuerError> {
        self.check_open()?;
        Ok(self
            .accounts
            .get(&account)
            .and_then(|a| a.operations.get(&(epoch, operation_id)))
            .map(Operation::status))
    }

    /// Borrow exact inputs for host approval. A ticket alone does not authenticate
    /// an external caller; the host must restrict access to this projection.
    pub fn intent(&self, ticket: IssuerTicket) -> Result<IssuerIntent<'_>, IssuerError> {
        let op = self.operation(ticket)?;
        let login = &self.accounts[&ticket.account].logins[&op.login];
        let (nonce, approval) = op.phase.evidence();
        Ok(IssuerIntent {
            ext: op.ext.as_deref(),
            ticket,
            browser_public_key: login.browser,
            grants: &login.grants,
            nonce,
            approval,
            admission_deadline_ns: op.admission,
            receipt_deadline_ns: op.receipt,
        })
    }

    /// Retain the first host-supplied entropy result. Repeats must match exactly.
    pub fn record_nonce(
        &mut self,
        ticket: IssuerTicket,
        authority: IssuerAuthority,
        nonce: [u8; 16],
        now_ns: u64,
    ) -> Result<(), IssuerError> {
        self.observe(now_ns)?;
        let op = self.operation(ticket)?;
        self.check_pending(op, authority, now_ns)?;
        if let Some(old) = op.phase.evidence().0 {
            return if nonce == old {
                Ok(())
            } else {
                Err(IssuerError::Conflict)
            };
        }
        self.operation_mut(ticket)?.phase = Phase::Challenged(nonce);
        Ok(())
    }

    /// Record a host-authenticated approval of the exact intent and nonce, after
    /// rechecking application permission. An untrusted response hash is insufficient.
    pub fn record_approval(
        &mut self,
        ticket: IssuerTicket,
        authority: IssuerAuthority,
        commitment: [u8; 32],
        now_ns: u64,
    ) -> Result<(), IssuerError> {
        self.observe(now_ns)?;
        let op = self.operation(ticket)?;
        self.check_pending(op, authority, now_ns)?;
        let (nonce, old) = op.phase.evidence();
        if let Some(old) = old {
            return if old == commitment {
                Ok(())
            } else {
                Err(IssuerError::Conflict)
            };
        }
        let nonce = nonce.ok_or(IssuerError::Pending)?;
        let claims = self.claims(op, &self.accounts[&ticket.account].logins[&op.login], nonce)?;
        self.operation_mut(ticket)?.phase = Phase::Approved(Approval {
            nonce,
            commitment,
            claims,
        });
        Ok(())
    }

    /// Record Ed25519 dispatch and return canonical input exactly once. The host commits
    /// this transition before signing. A lost response is lookup-only; no retry
    /// of this method yields a second signing permission.
    pub fn dispatch(
        &mut self,
        ticket: IssuerTicket,
        authority: IssuerAuthority,
        now_ns: u64,
    ) -> Result<SigningInput, IssuerError> {
        self.observe(now_ns)?;
        let op = self.operation(ticket)?;
        self.check_pending(op, authority, now_ns)?;
        if ticket.authority.signing != IssuerSigning::Ed25519 {
            return Err(IssuerError::Invalid);
        }
        let input = match &op.phase {
            Phase::Approved(a) => SigningInput {
                ticket,
                claims: a.claims.clone(),
            },
            Phase::Dispatched(_) | Phase::Completed(..) => return Err(IssuerError::Dispatched),
            _ => return Err(IssuerError::Pending),
        };
        let op = self.operation_mut(ticket)?;
        if let Phase::Approved(a) = std::mem::replace(&mut op.phase, Phase::Reserved) {
            op.phase = Phase::Dispatched(a);
        }
        Ok(input)
    }

    /// Retain a host-authenticated Ed25519 signing response for the dispatched
    /// ticket/input. This does not verify a signature or authenticate a remote
    /// callback: the host must do that before calling. Exact completed repeats
    /// remain readable after expiry/revocation/restart, without granting authority.
    pub fn complete(
        &mut self,
        ticket: IssuerTicket,
        authority: IssuerAuthority,
        signature: [u8; 64],
        now_ns: u64,
    ) -> Result<IssuedCredential<'_>, IssuerError> {
        self.observe(now_ns)?;
        let op = self.operation(ticket)?;
        if ticket.authority.signing != IssuerSigning::Ed25519 {
            return Err(IssuerError::Invalid);
        }
        if let Phase::Completed(_, old) = &op.phase {
            if *old != Completion::Ed25519(signature) {
                return Err(IssuerError::Conflict);
            }
        } else {
            self.check_pending(op, authority, now_ns)?;
            if !matches!(op.phase, Phase::Dispatched(_)) {
                return Err(IssuerError::Pending);
            }
            self.finish(ticket, Completion::Ed25519(signature));
        }
        self.completed(ticket)
    }

    fn completed(&self, ticket: IssuerTicket) -> Result<IssuedCredential<'_>, IssuerError> {
        match self.operation(ticket)?.status() {
            IssuerStatus::Completed(result) => Ok(result),
            _ => Err(IssuerError::Pending),
        }
    }

    // Both entry paths preflight their phase and current authority. No ordinary
    // refusal after an external publication; interrupted writes stay closed.
    fn finish(&mut self, ticket: IssuerTicket, completion: Completion) {
        self.open = false;
        let owner = self
            .accounts
            .get_mut(&ticket.account)
            .expect("selected account");
        let op = owner
            .operations
            .get_mut(&(ticket.epoch, ticket.operation_id))
            .expect("selected operation");
        let login = owner.logins.get_mut(&op.login).expect("selected login");
        let approval = match std::mem::replace(&mut op.phase, Phase::Reserved) {
            Phase::Approved(a) | Phase::Dispatched(a) => a,
            _ => unreachable!("preflighted completion phase"),
        };
        op.phase = Phase::Completed(approval, completion);
        after_write!();
        match (op.renewal, &login.renewal) {
            (None, RenewalProgress::Initial | RenewalProgress::InitialOutcomeUnknown) => {
                login.renewal = RenewalProgress::Completed(0)
            }
            (Some(n), RenewalProgress::InFlight(current)) if n == *current => {
                login.renewal = RenewalProgress::Completed(n)
            }
            _ => {}
        }
        after_write!();
        self.open = true;
    }

    /// Account-authenticated revocation, retaining all fences and result evidence.
    /// The host must authenticate `account`; browser callers use `revoke_browser`.
    pub fn revoke(
        &mut self,
        account: Principal,
        login_epoch: u64,
        login_id: [u8; 32],
        now_ns: u64,
    ) -> Result<(), IssuerError> {
        self.observe(now_ns)?;
        self.revoke_login(account, (login_epoch, login_id))
            .map(|_| ())
    }

    /// Revoke one retained login after authenticating its browser binding.
    /// The host supplies the actual caller and time; account/epoch/id are only
    /// selectors. This synchronous operation fences pending completion and future
    /// renewal without deleting results, uncertainty or other account logins.
    /// Repeats, expired logins and old epochs retain the original login deadline,
    /// returned as metadata, not proof of logout at any separate receiver.
    /// Missing/pruned bindings refuse; volatile state loss cannot confirm logout.
    ///
    /// # Errors
    /// Returns `Denied` for an absent or mismatched browser/login binding, or the
    /// ordinary closed-owner/clock refusal. The host owns transaction rollback.
    pub fn revoke_browser(
        &mut self,
        browser: Principal,
        account: Principal,
        login_epoch: u64,
        login_id: [u8; 32],
        now_ns: u64,
    ) -> Result<u64, IssuerError> {
        self.observe(now_ns)?;
        let identity = (login_epoch, login_id);
        self.browser_login(browser, account, identity)?;
        self.revoke_login(account, identity)
    }

    // Called only after the public operation has observed time and authenticated
    // either the account or its retained browser. No await separates these steps.
    fn revoke_login(&mut self, account: Principal, identity: Identity) -> Result<u64, IssuerError> {
        let login = self
            .accounts
            .get_mut(&account)
            .and_then(|a| a.logins.get_mut(&identity))
            .ok_or(IssuerError::Denied)?;
        if !login.revoked {
            let old_prune_at = login.idle_prune_at();
            self.open = false;
            login.revoked = true;
            after_write!();
            if login.references == 0 && old_prune_at != login.idle_prune_at() {
                self.idle_logins
                    .remove(&expiry(old_prune_at, account, identity));
                after_write!();
                self.idle_logins
                    .insert(expiry(login.idle_prune_at(), account, identity));
                after_write!();
            }
            self.open = true;
        }
        Ok(login.deadline)
    }

    fn browser_login(
        &self,
        browser: Principal,
        account: Principal,
        identity: Identity,
    ) -> Result<(&Account, &Login), IssuerError> {
        let owner = self.accounts.get(&account).ok_or(IssuerError::Denied)?;
        let login = owner.logins.get(&identity).ok_or(IssuerError::Denied)?;
        if browser == Principal::anonymous()
            || browser != crate::browser_identity::browser_principal(&login.browser)
        {
            return Err(IssuerError::Denied);
        }
        Ok((owner, login))
    }

    /// Fence all old callbacks/new operation IDs without clearing logins, results
    /// or credit. This retains memory; it is not restoration after state loss.
    pub fn restart(&mut self, now_ns: u64) -> Result<(), IssuerError> {
        self.observe(now_ns)?;
        let epoch = self.epoch.checked_add(1).ok_or(IssuerError::Capacity)?;
        let boot = self.boot.checked_add(1).ok_or(IssuerError::Capacity)?;
        self.open = false;
        self.epoch = epoch;
        after_write!();
        self.boot = boot;
        after_write!();
        self.open = true;
        Ok(())
    }

    fn check_open(&self) -> Result<(), IssuerError> {
        if self.open {
            Ok(())
        } else {
            Err(IssuerError::Closed)
        }
    }

    fn observe(&mut self, now: u64) -> Result<(), IssuerError> {
        self.check_open()?;
        if now < self.observed || now < self.budget.observed_at_ns() {
            return Err(IssuerError::Clock);
        }
        self.observed = now;
        Ok(())
    }

    fn operation(&self, ticket: IssuerTicket) -> Result<&Operation, IssuerError> {
        self.check_open()?;
        self.accounts
            .get(&ticket.account)
            .and_then(|a| a.operations.get(&(ticket.epoch, ticket.operation_id)))
            .filter(|op| op.ticket == ticket)
            .ok_or(IssuerError::Denied)
    }

    fn operation_mut(&mut self, ticket: IssuerTicket) -> Result<&mut Operation, IssuerError> {
        self.accounts
            .get_mut(&ticket.account)
            .and_then(|a| a.operations.get_mut(&(ticket.epoch, ticket.operation_id)))
            .filter(|op| op.ticket == ticket)
            .ok_or(IssuerError::Denied)
    }

    fn check_pending(
        &self,
        op: &Operation,
        authority: IssuerAuthority,
        now: u64,
    ) -> Result<(), IssuerError> {
        if op.ticket.boot != self.boot || op.ticket.authority != authority {
            return Err(IssuerError::Denied);
        }
        if now >= op.receipt.min(op.admission).min(authority.expires_at_ns) {
            return Err(IssuerError::Expired);
        }
        if self.accounts[&op.ticket.account].logins[&op.login].revoked {
            return Err(IssuerError::Denied);
        }
        Ok(())
    }

    fn claims(
        &self,
        op: &Operation,
        login: &Login,
        nonce: [u8; 16],
    ) -> Result<Vec<u8>, IssuerError> {
        encode_claims(&PortableClaims {
            mechanism: op.ticket.authority.signing.mechanism(),
            audience: self.config.audience,
            issuer: self.config.issuer,
            key_binding_id: op.ticket.authority.key_binding_id,
            browser_public_key: login.browser,
            account_subject: op.ticket.account,
            ext: op.ext.clone(),
            device_slot: login.slot,
            device_generation: login.generation,
            login_started_at_ns: login.started,
            login_deadline_ns: login.deadline,
            issued_at_ns: op.issued,
            admission_expires_at_ns: op.admission,
            nonce,
            grants: login.grants.clone(),
        })
        .map_err(|_| IssuerError::Invalid)
    }
}

impl Login {
    fn matches_request_and_limits(&self, request: &IssueRequest, policy: &IssuerPolicy) -> bool {
        // Each operation checks its own extension binding separately.

        self.browser == request.browser_public_key
            && self.grants == request.grants
            && self.policy.login_ttl_ns == policy.login_ttl_ns
            && self.policy.proof_ttl_ns == policy.proof_ttl_ns
            && self.policy.receipt_timeout_ns == policy.receipt_timeout_ns
            && self.policy.reconciliation_retention_ns == policy.reconciliation_retention_ns
    }
}

impl IssuerPolicy {
    fn deadlines(
        &self,
        issued: u64,
        login_deadline: u64,
        authority_expiry: u64,
    ) -> Option<(u64, u64, u64)> {
        let admission = issued
            .checked_add(self.proof_ttl_ns)?
            .min(login_deadline)
            .min(authority_expiry);
        let receipt = issued.checked_add(self.receipt_timeout_ns)?;
        let remove_at = admission
            .max(receipt)
            .checked_add(self.reconciliation_retention_ns)?;
        Some((admission, receipt, remove_at))
    }

    fn valid_limits(&self) -> bool {
        self.ext
            .as_ref()
            .is_none_or(|ext| ext.len() <= ic_auth_protocol_types::MAX_TOKEN_EXT_BYTES)
            && (1..=90 * 86_400_000_000_000).contains(&self.login_ttl_ns)
            && (1..=60_000_000_000).contains(&self.proof_ttl_ns)
            && self.receipt_timeout_ns > 0
            && self.reconciliation_retention_ns > 0
    }
}

fn validate_request(
    account: Principal,
    r: &IssueRequest,
    p: &IssuerPolicy,
) -> Result<(), IssuerError> {
    if account == Principal::anonymous()
        || r.operation_id == [0; 32]
        || r.login_id == [0; 32]
        || r.browser_public_key == [0; 32]
        || r.epoch == 0
        || r.login_epoch == 0
        || !p.valid_limits()
    {
        return Err(IssuerError::Invalid);
    }
    validate_grants(&r.grants).map_err(|_| IssuerError::Invalid)
}

#[cfg(feature = "issuer-stable")]
mod signature_bytes {
    use serde::{Deserialize, Deserializer, Serializer};

    pub(super) fn serialize<S: Serializer>(bytes: &[u8; 64], ser: S) -> Result<S::Ok, S::Error> {
        ser.serialize_bytes(bytes)
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<[u8; 64], D::Error> {
        <&[u8]>::deserialize(de)?
            .try_into()
            .map_err(|_| serde::de::Error::custom("invalid signature length"))
    }
}