cratefield-auth-client 0.4.2

Verify auth-service tokens in a consuming app: JWKS fetch and cache, ES256 verification, and an axum extractor (issue #11)
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
//! Issue #11 acceptance.
//!
//! Every test here is a token that must be refused, because a client
//! crate earns its place by refusing things a hand-written check would
//! wave through. The one accepting test exists to prove the others are
//! not passing vacuously.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Barrier, RwLock};

use async_trait::async_trait;
use base64ct::{Base64UrlUnpadded, Encoding};
use bytes::Bytes;
use cratefield_auth_client::{AuthClient, VerifyError};
use cratefield_core::{Clock, HttpClient, HttpError};
use p256::ecdsa::signature::Signer;
use p256::ecdsa::{self, Signature};
use serde_json::{Value, json};
use time::OffsetDateTime;

const ISSUER: &str = "https://auth.acme.example";
const CLIENT: &str = "client-kontinuum";
const OTHER_CLIENT: &str = "client-undercover";
const NOW: i64 = 1_800_000_000;

/// A clock frozen at [`NOW`], through the port — no `std::time`.
struct FrozenClock;

impl Clock for FrozenClock {
    fn now(&self) -> OffsetDateTime {
        OffsetDateTime::from_unix_timestamp(NOW).expect("in range")
    }
}

/// An `HttpClient` that answers with one canned JWKS body and counts
/// how many times it was asked.
struct FakeJwks {
    body: RwLock<String>,
    calls: RwLock<usize>,
}

impl FakeJwks {
    fn new(body: String) -> Arc<Self> {
        Arc::new(Self {
            body: RwLock::new(body),
            calls: RwLock::new(0),
        })
    }
    fn calls(&self) -> usize {
        *self.calls.read().expect("uncontended")
    }
}

#[async_trait]
impl HttpClient for FakeJwks {
    async fn send(
        &self,
        _request: http::Request<Bytes>,
    ) -> Result<http::Response<Bytes>, HttpError> {
        *self.calls.write().expect("uncontended") += 1;
        let body = self.body.read().expect("uncontended").clone();
        Ok(http::Response::builder()
            .status(200)
            .body(Bytes::from(body))
            .expect("response"))
    }
}

/// A throwaway P-256 keypair, generated in the test.
fn key(seed: u8) -> (ecdsa::SigningKey, Value) {
    let mut bytes = [seed.max(1); 32];
    bytes[0] = seed.max(1);
    let secret = p256::SecretKey::from_slice(&bytes).expect("scalar");
    let signing = ecdsa::SigningKey::from(&secret);
    // Uncompressed SEC1 is 0x04 || X || Y; the JWK carries X and Y.
    let point = signing.verifying_key().to_sec1_point(false);
    let sec1 = point.as_bytes();
    assert_eq!(sec1.len(), 65, "uncompressed point");
    let jwk = json!({
        "kty": "EC",
        "crv": "P-256",
        "kid": format!("k{seed}"),
        "x": Base64UrlUnpadded::encode_string(&sec1[1..33]),
        "y": Base64UrlUnpadded::encode_string(&sec1[33..65]),
    });
    (signing, jwk)
}

fn b64(bytes: &[u8]) -> String {
    Base64UrlUnpadded::encode_string(bytes)
}

/// Mints a token the way the auth service does.
fn mint(signing: &ecdsa::SigningKey, header: &Value, claims: &Value) -> String {
    let signing_input = format!(
        "{}.{}",
        b64(serde_json::to_string(header).expect("header").as_bytes()),
        b64(serde_json::to_string(claims).expect("claims").as_bytes())
    );
    let signature: Signature = signing.sign(signing_input.as_bytes());
    format!("{signing_input}.{}", b64(&signature.to_bytes()))
}

fn claims(aud: &str, iss: &str, exp: i64) -> Value {
    json!({
        "sub": "user-1", "aud": aud, "iss": iss, "sid": "session-1",
        "exp": exp, "iat": NOW - 10, "email": "a@example.com",
        "email_verified": true, "amr": ["passkey"],
    })
}

fn client(http: Arc<dyn HttpClient>) -> AuthClient {
    AuthClient::new(http, Arc::new(FrozenClock), ISSUER, CLIENT)
}

fn jwks_body(jwks: &[Value]) -> String {
    json!({ "keys": jwks }).to_string()
}

/// The control: a well-formed token for this client verifies, and the
/// claims come back intact. Without this the refusals below could all
/// be passing for the wrong reason.
#[pollster::test]
async fn a_valid_token_verifies_and_yields_its_claims() {
    let (signing, jwk) = key(1);
    let http = FakeJwks::new(jwks_body(&[jwk]));
    let auth = client(http);
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    let verified = auth.verify(&token).await.expect("verifies");
    assert_eq!(verified.sub, "user-1");
    assert_eq!(verified.sid, "session-1");
    assert_eq!(verified.amr, vec!["passkey".to_owned()]);
    // A token minted before issue #627 carries no `sso_connection`, and
    // must still verify rather than fail on the missing claim.
    assert_eq!(verified.sso_connection, None);
    assert!(!verified.signed_in_via_sso("ssoc_1"));
}

/// Issue #627: an enterprise SSO sign-in says which connection it came
/// through, and `signed_in_via_sso` is how a relying party gates on it.
#[pollster::test]
async fn an_sso_token_names_its_connection_and_only_that_one() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let mut payload = claims(CLIENT, ISSUER, NOW + 600);
    payload["sso_connection"] = json!("ssoc_1");
    payload["amr"] = json!(["sso"]);
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &payload,
    );

    let verified = auth.verify(&token).await.expect("verifies");
    assert_eq!(verified.sso_connection.as_deref(), Some("ssoc_1"));
    assert!(verified.signed_in_via_sso("ssoc_1"));
    // A connection id is not a secret, but it is not a bearer either:
    // naming the one this token did not come through is refused.
    assert!(!verified.signed_in_via_sso("ssoc_2"));
    assert!(!verified.signed_in_via_sso(""));
}

/// Both halves are required. A token that names a connection without
/// `sso` in `amr` is not one this crate will treat as an SSO sign-in.
#[pollster::test]
async fn an_sso_connection_without_the_amr_is_not_an_sso_sign_in() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let mut payload = claims(CLIENT, ISSUER, NOW + 600);
    payload["sso_connection"] = json!("ssoc_1");
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &payload,
    );

    let verified = auth.verify(&token).await.expect("verifies");
    assert_eq!(verified.sso_connection.as_deref(), Some("ssoc_1"));
    assert!(!verified.signed_in_via_sso("ssoc_1"));
}

/// The check hand-written verifiers forget. This token is signed by the
/// right issuer with the right key and is entirely valid — for another
/// venture. Accepting it would let any client of the same instance use its own
/// token against every other one.
#[pollster::test]
async fn a_token_for_another_client_is_refused() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(OTHER_CLIENT, ISSUER, NOW + 600),
    );

    assert_eq!(
        auth.verify(&token).await,
        Err(VerifyError::Audience {
            got: OTHER_CLIENT.to_owned(),
            want: CLIENT.to_owned()
        })
    );
}

/// A token from a different auth service entirely.
#[pollster::test]
async fn a_token_from_another_issuer_is_refused() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, "https://evil.example", NOW + 600),
    );

    assert!(matches!(
        auth.verify(&token).await,
        Err(VerifyError::Issuer { .. })
    ));
}

#[pollster::test]
async fn an_expired_token_is_refused() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW - 3600),
    );

    assert_eq!(auth.verify(&token).await, Err(VerifyError::Expired));
}

/// `alg: none` is the oldest JWT attack: strip the signature and claim
/// none was needed. It is refused before a key is even looked up.
#[pollster::test]
async fn the_none_algorithm_is_refused() {
    let (_signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let header = b64(json!({"alg": "none", "kid": "k1"}).to_string().as_bytes());
    let payload = b64(claims(CLIENT, ISSUER, NOW + 600).to_string().as_bytes());
    let token = format!("{header}.{payload}.");

    assert_eq!(
        auth.verify(&token).await,
        Err(VerifyError::Algorithm("none".to_owned()))
    );
}

/// Algorithm confusion: ask us to verify with HMAC so the public key
/// becomes the shared secret. Refused on the header alone.
#[pollster::test]
async fn an_hmac_algorithm_is_refused() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "HS256", "kid": "k1"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    assert_eq!(
        auth.verify(&token).await,
        Err(VerifyError::Algorithm("HS256".to_owned()))
    );
}

/// Signed by a key the issuer does not publish: correct shape, correct
/// claims, wrong signer.
#[pollster::test]
async fn a_token_signed_by_an_unpublished_key_is_refused() {
    let (_published, jwk) = key(1);
    let (attacker, _) = key(9);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    // Names the published kid, but is signed with a different key.
    let token = mint(
        &attacker,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    assert_eq!(auth.verify(&token).await, Err(VerifyError::Signature));
}

/// A tampered payload invalidates the signature over it.
#[pollster::test]
async fn a_tampered_payload_is_refused() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );
    let mut parts: Vec<&str> = token.split('.').collect();
    let swapped = b64(claims("client-elevated", ISSUER, NOW + 600)
        .to_string()
        .as_bytes());
    parts[1] = &swapped;
    let tampered = parts.join(".");

    assert_eq!(auth.verify(&tampered).await, Err(VerifyError::Signature));
}

/// The key set is fetched once and then cached: a busy app must not
/// hammer the auth service on every request.
#[pollster::test]
async fn the_key_set_is_cached_across_verifications() {
    let (signing, jwk) = key(1);
    let http = FakeJwks::new(jwks_body(&[jwk]));
    let auth = client(Arc::clone(&http) as Arc<dyn HttpClient>);
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    for _ in 0..5 {
        auth.verify(&token).await.expect("verifies");
    }
    assert_eq!(http.calls(), 1, "one fetch serves every verification");
}

/// A token naming a key we do not hold triggers exactly one forced
/// refetch — that is what makes rotation invisible — and no more,
/// however many such tokens arrive. Otherwise anyone could use invented
/// key ids to drive traffic at the auth service.
#[pollster::test]
async fn an_unknown_key_forces_one_refetch_and_is_then_rate_limited() {
    let (_signing, jwk) = key(1);
    let (attacker, _) = key(9);
    let http = FakeJwks::new(jwks_body(&[jwk]));
    let auth = client(Arc::clone(&http) as Arc<dyn HttpClient>);
    let token = mint(
        &attacker,
        &json!({"alg": "ES256", "kid": "k-not-published", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    for _ in 0..10 {
        assert!(matches!(
            auth.verify(&token).await,
            Err(VerifyError::UnknownKey(_))
        ));
    }
    assert_eq!(
        http.calls(),
        2,
        "one initial fetch plus one forced refetch, not ten"
    );
}

/// An issuer that mistakenly publishes a private key must not turn that
/// bug into a client vulnerability: the key is skipped, not used.
#[pollster::test]
async fn a_private_key_in_the_published_set_is_ignored() {
    let (signing, mut jwk) = key(1);
    jwk["d"] = json!("dGhpcy1pcy1ub3QtYS1yZWFsLXByaXZhdGUta2V5");
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    assert!(
        matches!(auth.verify(&token).await, Err(VerifyError::UnknownKey(_))),
        "a key carrying `d` is refused, so the token cannot verify"
    );
}

/// An unreachable auth service must not invalidate a running app's
/// sessions: the previously fetched keys keep working.
#[pollster::test]
async fn a_failed_refetch_keeps_the_previous_keys() {
    struct FailsAfterFirst {
        body: String,
        calls: RwLock<usize>,
    }
    #[async_trait]
    impl HttpClient for FailsAfterFirst {
        async fn send(
            &self,
            _request: http::Request<Bytes>,
        ) -> Result<http::Response<Bytes>, HttpError> {
            let mut calls = self.calls.write().expect("uncontended");
            *calls += 1;
            if *calls == 1 {
                Ok(http::Response::builder()
                    .status(200)
                    .body(Bytes::from(self.body.clone()))
                    .expect("response"))
            } else {
                Ok(http::Response::builder()
                    .status(503)
                    .body(Bytes::new())
                    .expect("response"))
            }
        }
    }

    let (signing, jwk) = key(1);
    let http = Arc::new(FailsAfterFirst {
        body: jwks_body(&[jwk]),
        calls: RwLock::new(0),
    });
    let auth = client(Arc::clone(&http) as Arc<dyn HttpClient>);
    let good = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );
    let unknown = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k-missing", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    auth.verify(&good).await.expect("first verification");
    // Forces a refetch, which now fails.
    let _ = auth.verify(&unknown).await;
    // The original key must still verify.
    auth.verify(&good)
        .await
        .expect("a failed refetch keeps the previous keys");
}

/// A cold cache must cost the auth service **one** fetch, however many
/// verifications arrive at once. Every caller that finds the cache stale
/// runs the refresh itself, so a burst of concurrent requests at a cold
/// start (or the instant a TTL lapses under load) sent N fetches for one
/// key set — a thundering herd aimed at the auth service, which is the
/// one thing a consuming app cannot afford to hammer.
#[test]
fn a_cold_cache_race_fetches_the_key_set_once() {
    const THREADS: usize = 8;

    /// Canned body, plus a delay inside `send` so every thread has passed
    /// its freshness check before the first fetch comes back. The delay is
    /// what makes the unguarded version fail every run rather than one in
    /// a hundred (the trick `push-auth`'s own race test uses).
    struct SlowJwks {
        body: String,
        calls: AtomicUsize,
    }
    #[async_trait]
    impl HttpClient for SlowJwks {
        async fn send(
            &self,
            _request: http::Request<Bytes>,
        ) -> Result<http::Response<Bytes>, HttpError> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            std::thread::sleep(std::time::Duration::from_millis(50));
            Ok(http::Response::builder()
                .status(200)
                .body(Bytes::from(self.body.clone()))
                .expect("response"))
        }
    }

    let (signing, jwk) = key(1);
    let http = Arc::new(SlowJwks {
        body: jwks_body(&[jwk]),
        calls: AtomicUsize::new(0),
    });
    let auth = Arc::new(client(Arc::clone(&http) as Arc<dyn HttpClient>));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );

    let gate = Barrier::new(THREADS);
    std::thread::scope(|scope| {
        for _ in 0..THREADS {
            let auth = Arc::clone(&auth);
            let token = token.clone();
            let gate = &gate;
            scope.spawn(move || {
                gate.wait();
                pollster::block_on(auth.verify(&token)).expect("verifies");
            });
        }
    });

    assert_eq!(
        http.calls.load(Ordering::SeqCst),
        1,
        "one key set, one fetch — a cold-cache race must not stampede the auth service"
    );
}

/// Garbage in the header, the segments, or the base64 is refused
/// without panicking — this crate parses attacker-controlled input.
#[pollster::test]
async fn malformed_tokens_are_refused_without_panicking() {
    let (_signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));

    for token in [
        "",
        "not-a-token",
        "a.b",
        "a.b.c.d",
        "!!!.###.$$$",
        "eyJhbGciOiJFUzI1NiJ9",
    ] {
        assert!(
            auth.verify(token).await.is_err(),
            "{token:?} must be refused"
        );
    }
}

/// Issue #912 (review): an ID token is signed by the same key and carries
/// the same audience as an access token, so it is refused by its `typ`
/// before its claims are read as an access token's.
#[pollster::test]
async fn an_id_token_is_refused_as_an_access_token() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "JWT"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );
    assert!(
        matches!(auth.verify(&token).await, Err(VerifyError::Type(ref t)) if t == "JWT"),
        "an ID token must not verify as an access token"
    );
}

/// A token with no `typ` at all is not an access token either.
#[pollster::test]
async fn a_token_without_a_type_is_refused() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );
    assert!(matches!(
        auth.verify(&token).await,
        Err(VerifyError::Type(_))
    ));
}

/// Issue #912: `auth_time` and `roles` are read, and `authenticated_within`
/// says whether the person proved who they are recently enough. Verification
/// alone does not answer that.
#[pollster::test]
async fn auth_time_and_roles_are_read_and_checked_by_the_relying_party() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let mut payload = claims(CLIENT, ISSUER, NOW + 600);
    payload["auth_time"] = json!(NOW - 100);
    payload["roles"] = json!(["owner"]);
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &payload,
    );
    let verified = auth.verify(&token).await.expect("verifies");
    assert_eq!(verified.auth_time, Some(NOW - 100));
    assert_eq!(verified.roles, vec!["owner".to_owned()]);
    assert!(verified.authenticated_within(120, NOW));
    assert!(
        !verified.authenticated_within(60, NOW),
        "100s is older than 60s"
    );
    assert!(
        !verified.authenticated_within(120, NOW + 500),
        "the window has passed"
    );
}

/// A token minted before the claim existed has no `auth_time`, and a relying
/// party that asks for freshness is told it is not fresh.
#[pollster::test]
async fn a_token_without_auth_time_is_never_fresh() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &claims(CLIENT, ISSUER, NOW + 600),
    );
    let verified = auth.verify(&token).await.expect("verifies");
    assert_eq!(verified.auth_time, None);
    assert!(verified.roles.is_empty());
    assert!(!verified.authenticated_within(i64::MAX, NOW));
}

/// Issue #912, second review: a payment gate passes only a passkey or email
/// ceremony that is recent. A federated, SSO or password sign-in does not,
/// even when it is recent, and neither does an old passkey sign-in.
#[pollster::test]
async fn stepped_up_within_requires_a_recent_passkey_or_email() {
    let (signing, jwk) = key(1);
    let auth = client(FakeJwks::new(jwks_body(&[jwk])));
    let mint_with = |amr: Value, auth_time: i64| {
        let mut payload = claims(CLIENT, ISSUER, NOW + 600);
        payload["auth_time"] = json!(auth_time);
        payload["amr"] = amr;
        payload["acr"] = json!("urn:cratefield:stepup");
        mint(
            &signing,
            &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
            &payload,
        )
    };
    let passkey = auth
        .verify(&mint_with(json!(["passkey", "user"]), NOW - 30))
        .await
        .expect("verifies");
    assert!(passkey.stepped_up_within(120, NOW));
    assert_eq!(passkey.acr.as_deref(), Some("urn:cratefield:stepup"));

    let email = auth
        .verify(&mint_with(json!(["email"]), NOW - 30))
        .await
        .expect("verifies");
    assert!(email.stepped_up_within(120, NOW));

    // The same recent email login during the quiet period: no `acr` was
    // issued for it, so it is not a step-up (issue #912, third review).
    let mut plain = claims(CLIENT, ISSUER, NOW + 600);
    plain["auth_time"] = json!(NOW - 30);
    plain["amr"] = json!(["email"]);
    let plain_token = mint(
        &signing,
        &json!({"alg": "ES256", "kid": "k1", "typ": "at+jwt"}),
        &plain,
    );
    let plain = auth.verify(&plain_token).await.expect("verifies");
    assert!(!plain.stepped_up_within(120, NOW), "no acr, no step-up");
    assert!(plain.authenticated_within(120, NOW));

    let federated = auth
        .verify(&mint_with(json!(["federated"]), NOW - 30))
        .await
        .expect("verifies");
    assert!(
        !federated.stepped_up_within(120, NOW),
        "a federated sign-in is not a step-up"
    );
    assert!(
        federated.authenticated_within(120, NOW),
        "it is recent, though"
    );

    let password = auth
        .verify(&mint_with(json!(["pwd"]), NOW - 30))
        .await
        .expect("verifies");
    assert!(!password.stepped_up_within(120, NOW));

    let stale = auth
        .verify(&mint_with(json!(["passkey"]), NOW - 600))
        .await
        .expect("verifies");
    assert!(
        !stale.stepped_up_within(120, NOW),
        "an old passkey sign-in is not recent"
    );
}