cheers-verify 0.8.43

Verify-only surface for cheers — PasetoV4PublicVerifier (Ed25519 public key), RevocationReader, and the EdgeVerifier facade. Holds no minter, so it is edge-safe.
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
//! Offline admission (R734-F2; `knock.md`, "Offline verification").
//!
//! [`AdmitAuthority`] answers one question: does key A hold the admit ability
//! on resource R, according to what this edge holds? [`IssuerAdmitAuthority`]
//! answers it rooted in the cheers issuer, from two artifacts that verify
//! offline:
//!
//! 1. the approver's standing binding (§7), proving which user A belongs to,
//!    unless A itself holds an issuer tuple on R; and
//! 2. the snapshot of R this edge holds **now** (§8), showing that user (or
//!    the key) holds a relation carrying the admit ability.
//!
//! [`IssuerAdmitAuthority::verify_admit_at`] then checks the [`Admit`] itself
//! against that answer. The chain is re-checked against the currently held
//! snapshot on every call, so an approver demoted in a newer snapshot takes
//! every admit they had not uploaded with them.
//!
//! **Delegation is one hop** (invariant 4). The authority never consults
//! other admits: a key admitted offline has no issuer tuple and no binding to
//! a user who holds the ability, so it is not an approver until the issuer
//! records it.

use std::collections::BTreeMap;
use std::sync::{PoisonError, RwLock};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use pasetors::token::UntrustedToken;
use pasetors::version4::V4;
use sha2::{Digest, Sha256};

use cheers_core::{
    evaluate_admit, Admit, AdmissionRefusal, AdmitFacts, CodecError, DeviceSigned, KnockError, LeaseRequest, LeaseState, PeerKey, PrincipalId, PrincipalKind, StoreError, UserId,
};

use crate::key_set::VerifyError;
use crate::public_verifier::PasetoV4PublicVerifier;
use crate::revocation::RevocationReader;
use crate::snapshot::{SnapshotError, SnapshotVerifier, VerifiedSnapshot};
use crate::standing::{StandingError, StandingVerifier};

/// Verify a [`DeviceSigned`] artifact under the key its own payload names.
///
/// The payload is read untrusted only to learn the signer, which must be a
/// `key:` principal; the signature is then checked under exactly that key
/// with `T::IMPLICIT_ASSERTION`, so a token signed by any other key, or for
/// another artifact kind, is refused.
pub fn verify_device_artifact<T: DeviceSigned>(token: &str) -> Result<T, CodecError> {
    let untrusted = UntrustedToken::<pasetors::token::Public, V4>::try_from(token).map_err(|_| CodecError::Malformed)?;
    let claimed: T = serde_json::from_slice(untrusted.untrusted_payload())?;
    let signer = claimed.signer();
    if signer.kind != PrincipalKind::Key {
        return Err(CodecError::Malformed);
    }
    let key = key_bytes(signer).ok_or(CodecError::Malformed)?;
    PasetoV4PublicVerifier::from_public_key(&key)?.verify_artifact(token)
}

/// The raw Ed25519 key of a `key:` principal.
fn key_bytes(p: &PrincipalId) -> Option<[u8; 32]> {
    if p.kind != PrincipalKind::Key {
        return None;
    }
    URL_SAFE_NO_PAD.decode(p.id.as_bytes()).ok()?.try_into().ok()
}

/// What an [`Admit`]'s `source` names: base64url-no-pad SHA-256 of the
/// [`Knock`](cheers_core::Knock) or [`Offer`](cheers_core::Offer) token.
pub fn artifact_hash(token: &str) -> String {
    URL_SAFE_NO_PAD.encode(Sha256::digest(token.as_bytes()))
}

/// Why an approver or an [`Admit`] was refused.
#[derive(Debug, thiserror::Error)]
pub enum AdmitError {
    /// Bad signature, wrong artifact kind, or a signer that is not a key.
    #[error("admit refused: {0}")]
    Signature(#[from] CodecError),
    /// Decoded, but breaks an artifact invariant (lease, key principals).
    #[error("admit refused: {0}")]
    Invalid(#[from] KnockError),
    /// Past its lease's `exp`.
    #[error("admit expired at {exp}")]
    Expired { exp: i64 },
    /// Checked under an issuer this edge does not trust.
    #[error("admit names authority {got}, expected {expected}")]
    WrongAuthority { expected: String, got: String },
    /// This edge holds no snapshot of the resource.
    #[error("no snapshot held for {kind}/{id}")]
    NoSnapshot { kind: String, id: String },
    /// The held snapshot no longer verifies (superseded, revocation key).
    #[error(transparent)]
    Snapshot(#[from] SnapshotError),
    /// The approver's standing binding was refused.
    #[error(transparent)]
    Standing(#[from] StandingError),
    /// The key has no issuer-rooted path to the admit ability on the resource.
    #[error("{approver} does not hold the admit ability on {kind}/{id}")]
    NotAnApprover { approver: PrincipalId, kind: String, id: String },
    /// The admit's own `jti` is revoked (refused at reconciliation).
    #[error("admit {jti} is revoked")]
    Revoked { jti: String },
    /// The admission policy held now does not permit this admit: the mode,
    /// a confirmation below the relation's minimum, or a lease past the
    /// path maximum (`cheers_core::evaluate_admit`).
    #[error("admission policy refuses admit {jti}: {reason}")]
    PolicyRefused { jti: String, reason: AdmissionRefusal },
    #[error(transparent)]
    Store(#[from] StoreError),
}

impl From<VerifyError> for AdmitError {
    fn from(e: VerifyError) -> Self {
        AdmitError::Snapshot(SnapshotError::Verify(e))
    }
}

/// An approver the authority vouches for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Approval {
    /// The user the key's standing binding names; `None` when the key holds
    /// the relation through its own issuer tuple.
    pub user: Option<UserId>,
    /// The admit-bearing relation the approver holds.
    pub relation: String,
    /// The snapshot it was read from, verified at the asking instant.
    pub snapshot: VerifiedSnapshot,
}

/// Does key `approver` hold the admit ability on `(kind, id)`, according to
/// what this edge holds now? Implemented over the issuer by
/// [`IssuerAdmitAuthority`]; a consumer roots it elsewhere (noisetable: the
/// creator-signed room roster).
#[async_trait::async_trait]
pub trait AdmitAuthority: Send + Sync {
    async fn approval_at(
        &self,
        approver: &PrincipalId,
        approver_binding: Option<&str>,
        kind: &str,
        id: &str,
        now: i64,
    ) -> Result<Approval, AdmitError>;
}

/// A verified [`Admit`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedAdmit {
    pub admit: Admit,
    pub approval: Approval,
    /// The user the requester's standing binding names, when the Admit
    /// carried one (`users` mode admits only these).
    pub requester_user: Option<UserId>,
    /// The admit's lease at the verification instant; never `Expired`.
    pub lease: LeaseState,
}

/// [`AdmitAuthority`] rooted in the cheers issuer (§7 + §8).
pub struct IssuerAdmitAuthority<Rd> {
    standing: StandingVerifier<Rd>,
    snapshots: SnapshotVerifier<Rd>,
    /// The snapshot token held per `(kind, id)`: the newest adopted.
    held: RwLock<BTreeMap<(String, String), (u64, String)>>,
}

impl<Rd> std::fmt::Debug for IssuerAdmitAuthority<Rd> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IssuerAdmitAuthority").finish_non_exhaustive()
    }
}

impl<Rd: RevocationReader> IssuerAdmitAuthority<Rd> {
    /// Both verifiers must trust the same issuer. Which relations carry the
    /// admit ability is read from the held snapshot's
    /// [`AdmissionPolicy::admitters`](cheers_core::AdmissionPolicy::admitters).
    pub fn new(standing: StandingVerifier<Rd>, snapshots: SnapshotVerifier<Rd>) -> Self {
        Self {
            standing,
            snapshots,
            held: RwLock::new(BTreeMap::new()),
        }
    }

    pub fn standing(&self) -> &StandingVerifier<Rd> {
        &self.standing
    }

    pub fn snapshots(&self) -> &SnapshotVerifier<Rd> {
        &self.snapshots
    }

    /// Adopt a snapshot (signature only) and hold it for its resource if it
    /// is at least as new as the one held. Returns the epoch now held.
    pub async fn hold_snapshot(&self, token: &str) -> Result<u64, VerifyError> {
        let snapshot = self.snapshots.adopt(token).await?;
        let mut held = self.held.write().unwrap_or_else(PoisonError::into_inner);
        let slot = held.entry((snapshot.kind, snapshot.id)).or_insert((0, String::new()));
        if snapshot.epoch >= slot.0 {
            *slot = (snapshot.epoch, token.to_owned());
        }
        Ok(slot.0)
    }

    fn held_token(&self, kind: &str, id: &str) -> Option<String> {
        let held = self.held.read().unwrap_or_else(PoisonError::into_inner);
        held.get(&(kind.to_owned(), id.to_owned())).map(|(_, t)| t.clone())
    }

    /// Verify an offline [`Admit`] token at `now`, re-checking the whole
    /// chain against the snapshot held now.
    ///
    /// In order: device signature, artifact invariants (key principals, a
    /// lease with `exp`, the midpoint), authority, expiry, the admit's `jti`
    /// against the revocation set, the approver's issuer-rooted path, the
    /// requester's standing binding when it carries one, then the admission
    /// policy of the held snapshot (no policy reads as closed).
    pub async fn verify_admit_at(&self, token: &str, now: i64) -> Result<VerifiedAdmit, AdmitError> {
        let admit: Admit = verify_device_artifact(token)?;
        admit.validate()?;
        let issuer = self.snapshots.trust().issuer();
        if admit.authority != issuer {
            return Err(AdmitError::WrongAuthority { expected: issuer.to_owned(), got: admit.authority });
        }
        let lease = admit.lease.state_at(now);
        if lease == LeaseState::Expired {
            return Err(AdmitError::Expired { exp: admit.lease.exp().unwrap_or(now) });
        }
        if self.snapshots.revocations().is_revoked(&admit.jti).await? {
            return Err(AdmitError::Revoked { jti: admit.jti });
        }
        let approval = self
            .approval_at(&admit.approver, admit.approver_binding.as_deref(), &admit.kind, &admit.id, now)
            .await?;
        let requester_user = match &admit.requester_binding {
            Some(binding) => {
                let key = key_bytes(&admit.requester).ok_or(KnockError::NotAKey(admit.requester.clone()))?;
                Some(self.standing.verify_standing_at(binding, &PeerKey::ed25519(key), now).await?.binding.sub)
            }
            None => None,
        };
        let facts = AdmitFacts {
            relation: &admit.relation,
            path: admit.path(),
            confirmation: Some(admit.confirmation),
            requester_is_user: requester_user.is_some(),
        };
        let policy = approval.snapshot.admission_policy();
        if let Err(reason) = evaluate_admit(policy, &facts, admit.iat, Some(LeaseRequest::Exact(admit.lease))) {
            return Err(AdmitError::PolicyRefused { jti: admit.jti, reason });
        }
        Ok(VerifiedAdmit { admit, approval, requester_user, lease })
    }

    fn admit_relation(&self, snapshot: &VerifiedSnapshot, principal: &PrincipalId) -> Option<String> {
        // The policy held now names the admit ability (R734-F4); no policy,
        // or no admitters, means nobody may admit.
        let admitters = &snapshot.admission_policy()?.admitters;
        admitters.iter().find(|r| snapshot.holds(principal, r)).cloned()
    }
}

#[async_trait::async_trait]
impl<Rd: RevocationReader + Send + Sync> AdmitAuthority for IssuerAdmitAuthority<Rd> {
    async fn approval_at(
        &self,
        approver: &PrincipalId,
        approver_binding: Option<&str>,
        kind: &str,
        id: &str,
        now: i64,
    ) -> Result<Approval, AdmitError> {
        let not_an_approver = || AdmitError::NotAnApprover {
            approver: approver.clone(),
            kind: kind.to_owned(),
            id: id.to_owned(),
        };
        if approver.kind != PrincipalKind::Key {
            return Err(not_an_approver());
        }
        let token = self.held_token(kind, id).ok_or_else(|| AdmitError::NoSnapshot {
            kind: kind.to_owned(),
            id: id.to_owned(),
        })?;
        let snapshot = self.snapshots.verify_snapshot_at(&token, now).await?;

        // The key's own issuer tuple.
        if let Some(relation) = self.admit_relation(&snapshot, approver) {
            return Ok(Approval { user: None, relation, snapshot });
        }
        // Otherwise a standing binding to a user who holds the ability.
        let Some(binding) = approver_binding else {
            return Err(not_an_approver());
        };
        let key = key_bytes(approver).ok_or_else(not_an_approver)?;
        let standing = self.standing.verify_standing_at(binding, &PeerKey::ed25519(key), now).await?;
        let user = standing.binding.sub;
        match self.admit_relation(&snapshot, &PrincipalId::from(&user)) {
            Some(relation) => Ok(Approval { user: Some(user), relation, snapshot }),
            None => Err(not_an_approver()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::artifact::IssuerTrust;
    use crate::jwks::{JwkKey, JwksDoc, KeySet};
    use crate::key_set::KeySetVerifier;
    use crate::revocation::{revocation_entry, test_revocation_key, ReplicatedRevocations};
    use cheers_core::{
        AdmissionMode, AdmissionPolicy, AdmitSource, Confirmation, DeviceId, Knock, KeyRole, Lease, ResourceRevocationKey, RevocationSet, Revoked,
        SetSnapshot, SignedArtifact, SnapshotMember, StandingBinding,
    };
    use pasetors::keys::{AsymmetricKeyPair, AsymmetricSecretKey, Generate};
    use pasetors::version4::PublicToken;
    use serde::Serialize;
    use std::sync::Arc;

    const ISS: &str = "https://cheers.test";
    const IAT: i64 = 1_000;
    const DAY: i64 = 24 * 60 * 60;

    fn kp() -> AsymmetricKeyPair<V4> {
        AsymmetricKeyPair::<V4>::generate().unwrap()
    }

    fn pub_bytes(k: &AsymmetricKeyPair<V4>) -> [u8; 32] {
        k.public.as_bytes().try_into().unwrap()
    }

    fn key_of(k: &AsymmetricKeyPair<V4>) -> PrincipalId {
        PrincipalId::from_public_key(&pub_bytes(k))
    }

    fn sign_with(secret: &AsymmetricSecretKey<V4>, kid: &str, payload: &impl Serialize, ia: &[u8]) -> String {
        let body = serde_json::to_vec(payload).unwrap();
        let footer = format!(r#"{{"kid":"{kid}"}}"#);
        PublicToken::sign(secret, &body, Some(footer.as_bytes()), Some(ia)).unwrap()
    }

    fn member(principal: PrincipalId, relation: &str) -> SnapshotMember {
        SnapshotMember { principal, relation: relation.into(), via: vec![("namespace".into(), "ed".into())], lease: None }
    }

    struct Rig {
        issuer: AsymmetricKeyPair<V4>,
        replica: Arc<ReplicatedRevocations>,
        auth: IssuerAdmitAuthority<Arc<ReplicatedRevocations>>,
        /// alice's device key, bound to user alice.
        device: AsymmetricKeyPair<V4>,
        binding: String,
    }

    impl Rig {
        fn snapshot(&self, epoch: u64, members: Vec<SnapshotMember>) {
            self.snapshot_with(epoch, members, Some(AdmissionPolicy::new(AdmissionMode::Knock, "guest")));
        }

        /// As [`Self::snapshot_exact`], with `owner` as the admit relation.
        fn snapshot_with(&self, epoch: u64, members: Vec<SnapshotMember>, policy: Option<AdmissionPolicy>) {
            self.snapshot_exact(epoch, members, policy.map(|p| p.with_admitters(["owner"])));
        }

        fn snapshot_exact(&self, epoch: u64, members: Vec<SnapshotMember>, policy: Option<AdmissionPolicy>) {
            let s = SetSnapshot::new(
                ISS,
                "namespace",
                "ed",
                epoch,
                members,
                vec![ResourceRevocationKey {
                    kind: "namespace".into(),
                    id: "ed".into(),
                    key: test_revocation_key("namespace", "ed"),
                }],
                IAT,
                Lease::new(IAT, IAT + 7 * DAY, None).unwrap(),
            )
            .with_policy(policy);
            let t = sign_with(&self.issuer.secret, "iss-1", &s, SetSnapshot::IMPLICIT_ASSERTION);
            pollster::block_on(self.auth.hold_snapshot(&t)).unwrap();
        }

        fn admit(&self, signer: &AsymmetricKeyPair<V4>, binding: Option<&str>, level: Confirmation) -> Admit {
            Admit {
                approver: key_of(signer),
                approver_binding: binding.map(str::to_owned),
                authority: ISS.into(),
                requester: key_of(&kp()),
                requester_binding: None,
                kind: "namespace".into(),
                id: "ed".into(),
                relation: "guest".into(),
                source: AdmitSource::Knock(artifact_hash("knock-token")),
                confirmation: level,
                epoch: 10,
                jti: "admit-1".into(),
                iat: IAT,
                lease: Lease::new(IAT, IAT + DAY, Some(IAT + 7 * DAY)).unwrap(),
            }
        }

        /// A standing binding for `user` on node key `peer`, signed by `by`.
        fn bind(&self, by: &AsymmetricSecretKey<V4>, user: &str, peer: &AsymmetricKeyPair<V4>) -> String {
            let b = StandingBinding {
                issuer: ISS.into(),
                sub: UserId::new(user),
                device: DeviceId::new(format!("node:{user}")),
                peer_key: PeerKey::ed25519(pub_bytes(peer)),
                seq: 1,
                iat: IAT,
                jti: format!("bind-{user}"),
                lease: Lease::new(IAT, IAT + 7 * DAY, None).unwrap(),
            };
            sign_with(by, "iss-1", &b, StandingBinding::IMPLICIT_ASSERTION)
        }

        fn sign(&self, signer: &AsymmetricKeyPair<V4>, a: &Admit) -> String {
            sign_with(&signer.secret, "dev", a, Admit::IMPLICIT_ASSERTION)
        }

        fn verify(&self, token: &str, now: i64) -> Result<VerifiedAdmit, AdmitError> {
            pollster::block_on(self.auth.verify_admit_at(token, now))
        }
    }

    fn rig() -> Rig {
        let issuer = kp();
        let doc = JwksDoc { keys: vec![JwkKey::ed25519("iss-1", &pub_bytes(&issuer), ISS, KeyRole::Issuer)] };
        let trust = IssuerTrust::key_set(ISS, KeySetVerifier::from_key_set(KeySet::from_doc(doc).unwrap()));
        let replica = Arc::new(ReplicatedRevocations::new(trust.clone()));
        let auth = IssuerAdmitAuthority::new(
            StandingVerifier::new(trust.clone(), replica.clone()),
            SnapshotVerifier::new(trust, replica.clone()),
        );
        let device = kp();
        let b = StandingBinding {
            issuer: ISS.into(),
            sub: UserId::new("alice"),
            device: DeviceId::new("node:alice"),
            peer_key: PeerKey::ed25519(pub_bytes(&device)),
            seq: 1,
            iat: IAT,
            jti: "bind-1".into(),
            lease: Lease::new(IAT, IAT + 7 * DAY, None).unwrap(),
        };
        let binding = sign_with(&issuer.secret, "iss-1", &b, StandingBinding::IMPLICIT_ASSERTION);
        let r = Rig { issuer, replica, auth, device, binding };
        r.snapshot(10, vec![member(PrincipalId::user("alice"), "owner")]);
        r
    }

    #[test]
    fn a_valid_chain_admits() {
        let r = rig();
        let a = r.admit(&r.device, Some(&r.binding), Confirmation::Compare);
        let ok = r.verify(&r.sign(&r.device, &a), IAT + 1).unwrap();
        assert_eq!(ok.admit, a);
        assert_eq!(ok.approval.user, Some(UserId::new("alice")));
        assert_eq!(ok.approval.relation, "owner");
        assert_eq!(ok.lease, LeaseState::Current);
    }

    #[test]
    fn a_key_with_its_own_issuer_tuple_admits_without_a_binding() {
        let r = rig();
        let k = kp();
        r.snapshot(11, vec![member(key_of(&k), "owner")]);
        let a = r.admit(&k, None, Confirmation::Accept);
        assert_eq!(r.verify(&r.sign(&k, &a), IAT).unwrap().approval.user, None);
    }

    #[test]
    fn a_demoted_approver_loses_unreconciled_admits() {
        let r = rig();
        let token = r.sign(&r.device, &r.admit(&r.device, Some(&r.binding), Confirmation::Accept));
        assert!(r.verify(&token, IAT).is_ok());
        r.snapshot(11, vec![member(PrincipalId::user("alice"), "guest")]);
        assert!(matches!(r.verify(&token, IAT).unwrap_err(), AdmitError::NotAnApprover { .. }));
    }

    #[test]
    fn a_two_hop_chain_is_refused() {
        let r = rig();
        // alice admits guest key G offline; G then admits H.
        let g = kp();
        let mut first = r.admit(&r.device, Some(&r.binding), Confirmation::Accept);
        first.requester = key_of(&g);
        assert!(r.verify(&r.sign(&r.device, &first), IAT).is_ok());
        let second = r.admit(&g, None, Confirmation::Accept);
        let err = r.verify(&r.sign(&g, &second), IAT).unwrap_err();
        assert!(matches!(err, AdmitError::NotAnApprover { .. }), "got {err:?}");
        // Borrowing alice's binding does not help: it names alice's key, not G.
        let borrowed = r.admit(&g, Some(&r.binding), Confirmation::Accept);
        let err = r.verify(&r.sign(&g, &borrowed), IAT).unwrap_err();
        assert!(matches!(err, AdmitError::Standing(StandingError::PeerKeyMismatch)), "got {err:?}");
    }

    #[test]
    fn the_policy_held_now_decides() {
        let r = rig();
        let members = || vec![member(PrincipalId::user("alice"), "owner")];
        let token = r.sign(&r.device, &r.admit(&r.device, Some(&r.binding), Confirmation::Compare));
        assert!(r.verify(&token, IAT).is_ok());
        // Below the relation's minimum confirmation.
        let strict = AdmissionPolicy::new(AdmissionMode::Knock, "guest").with_min_confirmation("guest", Confirmation::Scan);
        r.snapshot_with(11, members(), Some(strict));
        let err = r.verify(&token, IAT).unwrap_err();
        assert!(
            matches!(err, AdmitError::PolicyRefused { reason: AdmissionRefusal::BelowConfirmation { .. }, .. }),
            "got {err:?}"
        );
        // No policy row reads as closed, and names no admitters, so the
        // approver is refused before the dial is even read; `users` makes
        // this key-only admit inert.
        r.snapshot_with(12, members(), None);
        assert!(matches!(r.verify(&token, IAT).unwrap_err(), AdmitError::NotAnApprover { .. }));
        r.snapshot_with(13, members(), Some(AdmissionPolicy::new(AdmissionMode::Users, "guest")));
        assert!(matches!(r.verify(&token, IAT).unwrap_err(), AdmitError::PolicyRefused { .. }));
        // Moving the dial back restores it.
        r.snapshot(14, members());
        assert!(r.verify(&token, IAT).is_ok());
    }

    #[test]
    fn the_admit_ability_comes_from_the_held_policy() {
        let r = rig();
        let members = || vec![member(PrincipalId::user("alice"), "owner")];
        let token = r.sign(&r.device, &r.admit(&r.device, Some(&r.binding), Confirmation::Accept));
        // A policy naming no admitters fails closed even for an owner.
        r.snapshot_exact(20, members(), Some(AdmissionPolicy::new(AdmissionMode::Knock, "guest")));
        assert!(matches!(r.verify(&token, IAT).unwrap_err(), AdmitError::NotAnApprover { .. }));
        // Naming the owner's relation restores it.
        r.snapshot(21, members());
        assert!(r.verify(&token, IAT).is_ok());
    }

    #[test]
    fn a_lease_past_the_path_maximum_is_refused() {
        let r = rig();
        let mut a = r.admit(&r.device, Some(&r.binding), Confirmation::Accept);
        a.lease = Lease::new(IAT, IAT + DAY, Some(IAT + 8 * DAY)).unwrap();
        let err = r.verify(&r.sign(&r.device, &a), IAT).unwrap_err();
        assert!(matches!(err, AdmitError::PolicyRefused { reason: AdmissionRefusal::LeaseOverMax { .. }, .. }), "got {err:?}");
    }

    #[test]
    fn a_lease_past_its_midpoint_is_refused() {
        let r = rig();
        let mut v = serde_json::to_value(r.admit(&r.device, Some(&r.binding), Confirmation::Accept)).unwrap();
        v["refresh_after"] = (IAT + 4 * DAY).into();
        let forged: Admit = serde_json::from_value(v).unwrap();
        let err = r.verify(&r.sign(&r.device, &forged), IAT).unwrap_err();
        assert!(matches!(err, AdmitError::Invalid(KnockError::Lease(_))), "got {err:?}");
    }

    #[test]
    fn lease_state_through_exp_then_refused() {
        let r = rig();
        let token = r.sign(&r.device, &r.admit(&r.device, Some(&r.binding), Confirmation::Accept));
        let (ra, exp) = (IAT + DAY, IAT + 7 * DAY);
        assert_eq!(r.verify(&token, ra - 1).unwrap().lease, LeaseState::Current);
        assert_eq!(r.verify(&token, ra).unwrap().lease, LeaseState::Warning { exp: Some(exp) });
        assert_eq!(r.verify(&token, exp - 1).unwrap().lease, LeaseState::Warning { exp: Some(exp) });
        assert!(matches!(r.verify(&token, exp).unwrap_err(), AdmitError::Expired { .. }));
    }

    #[test]
    fn tampered_and_wrong_assertion_artifacts_are_refused() {
        let r = rig();
        let a = r.admit(&r.device, Some(&r.binding), Confirmation::Accept);
        // Signed by a key other than the one the payload names.
        let other = kp();
        assert!(matches!(r.verify(&r.sign(&other, &a), IAT).unwrap_err(), AdmitError::Signature(_)));
        // A flipped signature byte.
        let token = r.sign(&r.device, &a);
        let mut bytes = token.into_bytes();
        let i = bytes.len() - 10;
        bytes[i] = if bytes[i] == b'A' { b'B' } else { b'A' };
        assert!(r.verify(&String::from_utf8(bytes).unwrap(), IAT).is_err());
        // The right key, the wrong artifact kind.
        let as_knock = sign_with(&r.device.secret, "dev", &a, Knock::IMPLICIT_ASSERTION);
        assert!(matches!(r.verify(&as_knock, IAT).unwrap_err(), AdmitError::Signature(_)));
    }

    #[test]
    fn a_revoked_admit_jti_is_refused() {
        let r = rig();
        let token = r.sign(&r.device, &r.admit(&r.device, Some(&r.binding), Confirmation::Accept));
        let entries = [Revoked::Jti { jti: "admit-1".into(), exp: Some(IAT + 7 * DAY) }]
            .iter()
            .map(|e| revocation_entry(e, test_revocation_key))
            .collect();
        let set = RevocationSet::new(ISS, 5, entries);
        let t = sign_with(&r.issuer.secret, "iss-1", &set, RevocationSet::IMPLICIT_ASSERTION);
        pollster::block_on(r.replica.adopt(&t)).unwrap();
        assert!(matches!(r.verify(&token, IAT).unwrap_err(), AdmitError::Revoked { .. }));
    }

    /// alice admits key `k`, presenting `binding` as k's standing binding,
    /// under a `users`-mode policy.
    fn users_mode_admit(r: &Rig, k: &AsymmetricKeyPair<V4>, binding: String) -> String {
        r.snapshot_with(
            11,
            vec![member(PrincipalId::user("alice"), "owner")],
            Some(AdmissionPolicy::new(AdmissionMode::Users, "guest")),
        );
        let mut a = r.admit(&r.device, Some(&r.binding), Confirmation::Accept);
        a.requester = key_of(k);
        a.requester_binding = Some(binding);
        r.sign(&r.device, &a)
    }

    #[test]
    fn users_mode_admits_a_requester_with_its_own_binding() {
        let r = rig();
        let k = kp();
        let token = users_mode_admit(&r, &k, r.bind(&r.issuer.secret, "bob", &k));
        let ok = r.verify(&token, IAT).unwrap();
        assert_eq!(ok.requester_user, Some(UserId::new("bob")));
        assert_eq!(ok.admit.requester, key_of(&k));
    }

    #[test]
    fn a_requester_binding_for_another_key_is_refused() {
        let r = rig();
        let (k, other) = (kp(), kp());
        let token = users_mode_admit(&r, &k, r.bind(&r.issuer.secret, "bob", &other));
        let err = r.verify(&token, IAT).unwrap_err();
        assert!(matches!(err, AdmitError::Standing(StandingError::PeerKeyMismatch)), "got {err:?}");
    }

    #[test]
    fn a_requester_binding_from_an_untrusted_issuer_is_refused() {
        let r = rig();
        let k = kp();
        let rogue = kp();
        let token = users_mode_admit(&r, &k, r.bind(&rogue.secret, "bob", &k));
        let err = r.verify(&token, IAT).unwrap_err();
        assert!(matches!(err, AdmitError::Standing(StandingError::Verify(_))), "got {err:?}");
    }

    #[test]
    fn a_knock_verifies_under_its_requester_key() {
        let k = kp();
        let knock = Knock {
            requester: key_of(&k),
            kind: "namespace".into(),
            id: "ed".into(),
            relation: "guest".into(),
            nonce: "n".into(),
            label: "Ann's phone".into(),
            standing: None,
            renews: Some("admit-1".into()),
            iat: IAT,
        };
        let t = sign_with(&k.secret, "dev", &knock, Knock::IMPLICIT_ASSERTION);
        assert_eq!(verify_device_artifact::<Knock>(&t).unwrap(), knock);
        assert!(verify_device_artifact::<Admit>(&t).is_err());
    }
}