ppoppo-token 0.3.0

JWT (RFC 9068, EdDSA) issuance + verification engine for the Ppoppo ecosystem. Single deep module with a small interface (issue, verify) hiding RFC 8725 mitigations M01-M45, JWKS handling, and substrate ports (epoch, session, replay).
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
//! Negative regression tests for the OIDC id_token verification path.
//!
//! Each `#[test]` pins one mitigation row from
//! `0context/STANDARDS_JWT_DETAILS_MITIGATION_PPOPPO.md` §J. Test names
//! mirror the matrix `Test name` column verbatim — renaming a test
//! without flipping the matrix row is a regression.
//!
//! Phase 10.2 covers M66 (nonce binding); 10.3+10.4 add M67/M68
//! (at_hash / c_hash). M69-M73 land in Sessions D-E.

#![allow(clippy::unwrap_used, clippy::expect_used)]

use base64::Engine as _;
use jsonwebtoken::{DecodingKey, EncodingKey, Header};
use ppoppo_token::id_token::{
    verify,
    scopes::{Email, EmailProfile, EmailProfilePhone, EmailProfilePhoneAddress, Openid, Profile},
    AuthError, Nonce, VerifyConfig,
};
use ppoppo_token::KeySet;
use serde_json::json;
use sha2::{Digest, Sha256};

// ── Test keypair (Ed25519) ─────────────────────────────────────────────
//
// Same fixed pair used by `tests/jwt_negative.rs` so id_token verifies
// against the identical KeySet shape. Test-only; no production value.

const TEST_PRIVATE_KEY_PEM: &[u8] = b"-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIG+00IvEd4uv6IWtGFVUEBVdqnXiuI/ESQHu6rmcDvAs
-----END PRIVATE KEY-----
";

const TEST_PUBLIC_KEY_PEM: &[u8] = b"-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAh//e6j3It3xhjghg8Kpn2pM0jMCH/cvemGu4vv7D1Q4=
-----END PUBLIC KEY-----
";

const TEST_KID: &str = "k4.test.0";

const ISSUER: &str = "https://accounts.ppoppo.com";
const AUDIENCE: &str = "rp-client-1234";
const TEST_SUB_ULID: &str = "01HSAB00000000000000000000";

fn test_keyset() -> KeySet {
    let mut ks = KeySet::new();
    let dec = DecodingKey::from_ed_pem(TEST_PUBLIC_KEY_PEM).expect("public PEM");
    ks.insert(TEST_KID, dec);
    ks
}

/// Forge a real Ed25519-signed id_token (`typ="JWT"`) with the test keypair.
fn forge_id_token(payload: &serde_json::Value) -> String {
    let mut header = Header::new(jsonwebtoken::Algorithm::EdDSA);
    header.kid = Some(TEST_KID.to_string());
    header.typ = Some("JWT".to_string());
    let enc = EncodingKey::from_ed_pem(TEST_PRIVATE_KEY_PEM).expect("private PEM");
    jsonwebtoken::encode(&header, payload, &enc).expect("encode")
}

fn cfg(expected_nonce: &str) -> VerifyConfig {
    VerifyConfig::id_token(
        ISSUER,
        AUDIENCE,
        Nonce::new(expected_nonce).expect("non-empty test nonce"),
    )
}

fn base_payload() -> serde_json::Value {
    let now = time::OffsetDateTime::now_utc().unix_timestamp();
    json!({
        "iss": ISSUER,
        "sub": TEST_SUB_ULID,
        "aud": AUDIENCE,
        "exp": now + 600,
        "iat": now,
        // Phase 10.10 — `cat="id"` is mandatory on the id_token wire (M29
        // mirror in `engine::check_id_token_cat`). Every test fixture
        // that exercises a happy-path or M66+ negative MUST carry it;
        // omission would surface as `CatMismatch("")` and mask the
        // intended failure axis. The dedicated `cat_*` tests below
        // override or remove this field deliberately.
        "cat": "id",
    })
}

// ── M29-mirror — cat profile-routing assertion (Phase 10.10) ──────────
//
// Symmetric to access-token's M29 (`cat == "access"` else
// `TokenTypeMismatch`). Fires BEFORE M66 in `id_token::verify`, so a
// wrong-profile token short-circuits before any binding gate. Section
// pinned at the top of the test file to mirror the verify-side execution
// order.

#[tokio::test]
async fn cat_id_passes_via_base_payload() {
    // Happy path documented as its own test even though every passing
    // M66+ test implicitly exercises it (base_payload sets `cat="id"`).
    // Explicit fixture means a future regression where someone strips
    // `cat` from base_payload doesn't silently weaken every other test.
    const NONCE: &str = "happy-path-nonce";
    let mut payload = base_payload();
    payload
        .as_object_mut()
        .unwrap()
        .insert("nonce".into(), serde_json::Value::String(NONCE.into()));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert!(result.is_ok(), "M29-mirror: cat=\"id\" must round-trip");
}

#[tokio::test]
async fn cat_access_returns_cat_mismatch_substitution_signal() {
    // Headline forgery: an attacker rewrites `cat` to "access" in an
    // attempt to slip the id_token through a verify path that expected
    // an access token. (They can't actually re-sign without the key;
    // this test pins the audit signal when they try.)
    const NONCE: &str = "substitution-test-nonce";
    let mut payload = base_payload();
    payload
        .as_object_mut()
        .unwrap()
        .insert("nonce".into(), serde_json::Value::String(NONCE.into()));
    payload
        .as_object_mut()
        .unwrap()
        .insert("cat".into(), serde_json::Value::String("access".into()));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::CatMismatch("access".into())));
}

#[tokio::test]
async fn cat_absent_returns_cat_mismatch_with_empty_audit() {
    // β1 strict-from-day-1: an id_token without `cat` is refused. The
    // empty-string audit signal distinguishes "stripped / non-PAS issuer"
    // from "wrong value" in operator dashboards.
    const NONCE: &str = "absent-cat-test-nonce";
    let mut payload = base_payload();
    payload
        .as_object_mut()
        .unwrap()
        .insert("nonce".into(), serde_json::Value::String(NONCE.into()));
    payload.as_object_mut().unwrap().remove("cat");
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::CatMismatch(String::new())));
}

#[tokio::test]
async fn cat_check_fires_before_nonce_check() {
    // Order assertion (per verify.rs comment "fires before any typed
    // gate"): a token missing BOTH `cat` and `nonce` returns CatMismatch,
    // not NonceMissing. Pins the execution order so a future refactor
    // that reorders gates doesn't silently change the audit signal.
    let mut payload = base_payload();
    payload.as_object_mut().unwrap().remove("cat");
    // intentionally also no `nonce`
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg("nonce-irrelevant"), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(
        result,
        Err(AuthError::CatMismatch(String::new())),
        "M29-mirror MUST fire before M66 nonce so the audit signal points at \
         the profile-routing failure first"
    );
}

// ── M66 — nonce binding ────────────────────────────────────────────────

#[tokio::test]
async fn nonce_missing_returns_nonce_missing() {
    let mut payload = base_payload();
    // intentionally omit `nonce` from payload
    payload.as_object_mut().unwrap().remove("nonce");
    let token = forge_id_token(&payload);

    let result = verify::<Openid>(&token, &cfg("expected-nonce-abc"), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::NonceMissing));
}

#[tokio::test]
async fn nonce_mismatch_returns_nonce_mismatch() {
    let mut payload = base_payload();
    payload.as_object_mut().unwrap().insert(
        "nonce".into(),
        serde_json::Value::String("token-side-nonce".into()),
    );
    let token = forge_id_token(&payload);

    let result =
        verify::<Openid>(&token, &cfg("rp-stored-nonce-different"), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::NonceMismatch));
}

#[tokio::test]
async fn nonce_present_and_matches_passes() {
    const NONCE: &str = "shared-nonce-value-xyz";
    let mut payload = base_payload();
    payload
        .as_object_mut()
        .unwrap()
        .insert("nonce".into(), serde_json::Value::String(NONCE.into()));
    let token = forge_id_token(&payload);

    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    let claims = result.expect("M66 happy-path must accept");
    assert_eq!(claims.iss, ISSUER);
    assert_eq!(claims.sub, TEST_SUB_ULID);
    assert_eq!(claims.nonce, NONCE);
}

// ── Construction-time invariant: empty Nonce ───────────────────────────

#[test]
fn empty_nonce_construction_returns_nonce_config_empty() {
    let result = Nonce::new("");
    assert_eq!(result.unwrap_err(), AuthError::NonceConfigEmpty);
}

// ── M67 helpers ────────────────────────────────────────────────────────
//
// `compute_hash_binding` is a deliberate hand-roll of SHA-256
// leftmost-128-bit base64url-no-pad — independent of `engine::hash_binding::compute`.
// If the test imports the engine's helper, the test becomes tautological:
// engine drift would then move both sides identically and the test would
// pass while interop with other OIDC implementations breaks. Per
// `feedback_audit_grilled_decisions`, the engine and test must converge
// from independent code paths; this duplication is the cost.

const NONCE: &str = "binding-test-nonce";
const ACCESS_TOKEN: &str = "fake.access.token.three.dots";
const AUTH_CODE: &str = "oauth2-authorization-code-test";

fn compute_hash_binding(subject: &[u8]) -> String {
    let digest = Sha256::digest(subject);
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..16])
}

fn payload_with_nonce() -> serde_json::Value {
    let mut p = base_payload();
    p.as_object_mut()
        .unwrap()
        .insert("nonce".into(), serde_json::Value::String(NONCE.into()));
    p
}

// ── M67 — at_hash binding (OIDC Core §3.1.3.8) ─────────────────────────

#[tokio::test]
async fn at_hash_missing_returns_at_hash_missing() {
    // Payload has nonce but NOT at_hash; cfg expects an at_hash.
    let token = forge_id_token(&payload_with_nonce());
    let cfg = cfg(NONCE).with_access_token_binding(ACCESS_TOKEN);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AtHashMissing));
}

#[tokio::test]
async fn at_hash_mismatch_returns_at_hash_mismatch() {
    // Payload's at_hash is computed for a DIFFERENT access_token.
    let mut payload = payload_with_nonce();
    payload.as_object_mut().unwrap().insert(
        "at_hash".into(),
        serde_json::Value::String(compute_hash_binding(b"some-other-access-token")),
    );
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_access_token_binding(ACCESS_TOKEN);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AtHashMismatch));
}

#[tokio::test]
async fn at_hash_present_and_matches_passes() {
    // Canonical happy path: payload.at_hash == hash(ACCESS_TOKEN).
    let mut payload = payload_with_nonce();
    payload.as_object_mut().unwrap().insert(
        "at_hash".into(),
        serde_json::Value::String(compute_hash_binding(ACCESS_TOKEN.as_bytes())),
    );
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_access_token_binding(ACCESS_TOKEN);
    let claims = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("M67 happy path must accept");
    assert_eq!(claims.iss, ISSUER);
    assert_eq!(claims.nonce, NONCE);
}

/// Negative-of-the-negative: when the cfg has NO access_token binding,
/// the engine MUST NOT inspect at_hash even if the payload has a bogus
/// one. Pure code flow consumers (RCW/CTW today) leave the binding unset;
/// imposing at_hash on them would break their flow.
#[tokio::test]
async fn at_hash_ignored_when_binding_unset_even_if_bogus_in_payload() {
    let mut payload = payload_with_nonce();
    payload.as_object_mut().unwrap().insert(
        "at_hash".into(),
        serde_json::Value::String("totally-bogus-not-a-real-hash".into()),
    );
    let token = forge_id_token(&payload);
    // No `with_access_token_binding` — engine is opt-in.
    let cfg = cfg(NONCE);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert!(result.is_ok(), "M67 must skip when binding is unset");
}

// ── M68 — c_hash binding (OIDC Core §3.3.2.11) ─────────────────────────

#[tokio::test]
async fn c_hash_missing_returns_c_hash_missing() {
    let token = forge_id_token(&payload_with_nonce());
    let cfg = cfg(NONCE).with_authorization_code_binding(AUTH_CODE);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::CHashMissing));
}

#[tokio::test]
async fn c_hash_mismatch_returns_c_hash_mismatch() {
    let mut payload = payload_with_nonce();
    payload.as_object_mut().unwrap().insert(
        "c_hash".into(),
        serde_json::Value::String(compute_hash_binding(b"a-different-code")),
    );
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_authorization_code_binding(AUTH_CODE);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::CHashMismatch));
}

#[tokio::test]
async fn c_hash_present_and_matches_passes() {
    let mut payload = payload_with_nonce();
    payload.as_object_mut().unwrap().insert(
        "c_hash".into(),
        serde_json::Value::String(compute_hash_binding(AUTH_CODE.as_bytes())),
    );
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_authorization_code_binding(AUTH_CODE);
    let claims = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("M68 happy path must accept");
    assert_eq!(claims.nonce, NONCE);
}

// ── M69 — azp (authorized party) binding (OIDC Core §2) ───────────────
//
// β1 strictness: when azp is present in payload, it MUST equal client_id
// regardless of aud cardinality. When absent, only multi-aud refuses.

#[tokio::test]
async fn azp_missing_when_aud_multi_returns_azp_missing() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("aud".into(), json!([AUDIENCE, "sibling-client-9999"]));
    // Intentionally no `azp` claim.
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AzpMissing));
}

#[tokio::test]
async fn azp_mismatch_when_aud_multi_returns_azp_mismatch() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("aud".into(), json!([AUDIENCE, "sibling-client-9999"]));
    payload
        .as_object_mut()
        .unwrap()
        .insert("azp".into(), json!("not-the-rp-client-id"));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AzpMismatch));
}

#[tokio::test]
async fn azp_present_and_matches_client_id_passes() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("aud".into(), json!([AUDIENCE, "sibling-client-9999"]));
    payload
        .as_object_mut()
        .unwrap()
        .insert("azp".into(), json!(AUDIENCE));
    let token = forge_id_token(&payload);
    let claims = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("M69 happy path must accept");
    assert_eq!(claims.azp.as_deref(), Some(AUDIENCE));
}

/// β1 pin: single-aud + azp absent passes (§2 silent on mandate when
/// single-aud). This test prevents future drift toward "always require azp".
#[tokio::test]
async fn azp_absent_when_aud_single_passes() {
    // base_payload sets aud as a single string; no azp claim.
    let token = forge_id_token(&payload_with_nonce());
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert!(
        result.is_ok(),
        "M69 must permit single-aud token without azp (§2 silent)"
    );
}

/// β1 pin: single-aud + bogus azp must REFUSE (§2 "MUST contain Client ID"
/// is unconditional when azp present). Catches the substitution case
/// where a forged single-aud token carries a sibling client's azp.
#[tokio::test]
async fn azp_mismatch_when_aud_single_returns_azp_mismatch() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("azp".into(), json!("sibling-client-9999"));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AzpMismatch));
}

// ── M70 — auth_time freshness (OIDC Core §3.1.3.7) ────────────────────
//
// Opt-in via `cfg.with_max_age(n)`. Once opted in, missing auth_time is
// a hard refusal; stale tokens (now - auth_time > n) yield AuthTimeStale.

#[tokio::test]
async fn auth_time_stale_returns_auth_time_stale() {
    let mut payload = payload_with_nonce();
    let now = time::OffsetDateTime::now_utc().unix_timestamp();
    // auth_time was 10 minutes ago; max_age window is 5 minutes.
    payload
        .as_object_mut()
        .unwrap()
        .insert("auth_time".into(), json!(now - 600));
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_max_age(300);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AuthTimeStale));
}

#[tokio::test]
async fn auth_time_missing_when_max_age_set_returns_auth_time_missing() {
    // Payload has nonce but NO auth_time; cfg requires max_age window.
    let token = forge_id_token(&payload_with_nonce());
    let cfg = cfg(NONCE).with_max_age(300);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AuthTimeMissing));
}

#[tokio::test]
async fn auth_time_within_window_passes() {
    let mut payload = payload_with_nonce();
    let now = time::OffsetDateTime::now_utc().unix_timestamp();
    payload
        .as_object_mut()
        .unwrap()
        .insert("auth_time".into(), json!(now - 60));
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_max_age(300);
    let claims = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("M70 happy path must accept fresh auth_time");
    assert_eq!(claims.auth_time, Some(now - 60));
}

/// Opt-in invariant: when `cfg.max_age` is unset, the engine MUST NOT
/// impose freshness — even if the payload omits auth_time. RPs that
/// did not request the gate are not penalized.
#[tokio::test]
async fn auth_time_ignored_when_max_age_unset() {
    // Payload has no auth_time. cfg has no max_age window. Must pass.
    let token = forge_id_token(&payload_with_nonce());
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert!(
        result.is_ok(),
        "M70 must skip freshness check when max_age is unset"
    );
}

// ── M71 — acr step-up assertion (OIDC Core §3.1.3.7, §5.5.1.1) ────────
//
// Opt-in via `cfg.with_acr_values(values)`. Once opted in, missing acr
// is a hard refusal; acr-not-in-allowlist yields AcrNotAllowed.
// Comparison is case-sensitive — see check_acr.rs.

const ACR_SILVER: &str = "urn:mace:incommon:iap:silver";
const ACR_BRONZE: &str = "urn:mace:incommon:iap:bronze";

#[tokio::test]
async fn acr_not_in_values_returns_acr_not_allowed() {
    let mut payload = payload_with_nonce();
    // Token asserts bronze, but RP requires silver.
    payload
        .as_object_mut()
        .unwrap()
        .insert("acr".into(), json!(ACR_BRONZE));
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_acr_values(vec![ACR_SILVER.to_string()]);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AcrNotAllowed));
}

#[tokio::test]
async fn acr_missing_when_values_set_returns_acr_missing() {
    // Payload has no acr; cfg requires acr_values.
    let token = forge_id_token(&payload_with_nonce());
    let cfg = cfg(NONCE).with_acr_values(vec![ACR_SILVER.to_string()]);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::AcrMissing));
}

#[tokio::test]
async fn acr_in_values_passes() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("acr".into(), json!(ACR_SILVER));
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_acr_values(vec![
        ACR_SILVER.to_string(),
        ACR_BRONZE.to_string(),
    ]);
    let claims = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("M71 happy path must accept allowed acr");
    assert_eq!(claims.acr.as_deref(), Some(ACR_SILVER));
}

/// Opt-in invariant: when `cfg.acr_values` is unset, the engine MUST NOT
/// impose the step-up gate — even if the payload carries an acr value.
/// RPs that did not request step-up are not penalized by IdPs that
/// volunteer an acr claim.
#[tokio::test]
async fn acr_ignored_when_values_unset_even_if_payload_carries_one() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("acr".into(), json!("some-arbitrary-acr-value"));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert!(
        result.is_ok(),
        "M71 must skip step-up check when acr_values is unset"
    );
}

/// Case-sensitivity pin: RP allowlist of "...silver" (lowercase URN)
/// must REFUSE a token asserting "...SILVER" (uppercase). The §5.5.1.1
/// URN convention is case-sensitive; case-folding would silently admit
/// step-up downgrades. This test is the regression guard against
/// `eq_ignore_ascii_case` creeping in.
#[tokio::test]
async fn acr_case_sensitive_uppercase_rejected_against_lowercase_allowlist() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("acr".into(), json!("URN:MACE:INCOMMON:IAP:SILVER"));
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE).with_acr_values(vec![ACR_SILVER.to_string()]);
    let result = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(
        result,
        Err(AuthError::AcrNotAllowed),
        "case-folding would silently admit a downgrade — must compare with =="
    );
}

// ── M72 — per-scope PII allowlist (OIDC Core §5.4) ─────────────────────

/// Token carries `email`; scope `Openid` does not permit it. M72 must
/// refuse with `UnknownClaim("email")`. The compile-time accessor narrowing
/// already prevents reads (`Claims<Openid>::email()` is a compile error);
/// this test pins the wire-side gate that prevents the field from
/// populating in the first place.
#[tokio::test]
async fn unknown_claim_at_openid_scope_returns_unknown_claim() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("email".into(), json!("victim@example.com"));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(result, Err(AuthError::UnknownClaim("email".into())));
}

/// Same token shape as above but verified at scope `Email` — `email` is
/// in `Email::names()` so M72 admits it. Proves the gate is *narrowing*,
/// not flat-rejecting.
#[tokio::test]
async fn email_claim_at_email_scope_passes() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("email".into(), json!("user@example.com"));
    payload
        .as_object_mut()
        .unwrap()
        .insert("email_verified".into(), json!(true));
    let token = forge_id_token(&payload);
    let claims = verify::<Email>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("Email scope must admit email + email_verified");
    assert_eq!(claims.email(), "user@example.com");
    assert_eq!(claims.email_verified(), Some(true));
}

/// Synthetic claim name an attacker might inject hoping a future
/// downstream consumer learns to read it. β1 strict-refuse: any
/// non-allowlisted name is rejected with the carried name surfacing in
/// the audit log. This is the regression guard against a lenient-strip
/// path silently sneaking back into the deserializer.
#[tokio::test]
async fn unknown_synthetic_claim_returns_unknown_claim() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("attacker_injected_field".into(), json!("payload"));
    let token = forge_id_token(&payload);
    let result = verify::<Openid>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await;
    assert_eq!(
        result,
        Err(AuthError::UnknownClaim("attacker_injected_field".into())),
    );
}

/// Audit-pass guard from `feedback_audit_grilled_decisions`: a fabricated
/// "backdoor" claim must be refused at EVERY scope variant. Catches a
/// silent-pass regression where one variant's `NAMES_*` accidentally
/// admits arbitrary names (e.g. via a star pattern that crept in during
/// a refactor).
#[tokio::test]
async fn fabricated_backdoor_claim_rejected_at_every_scope() {
    let mut payload = payload_with_nonce();
    payload
        .as_object_mut()
        .unwrap()
        .insert("backdoor".into(), json!("attacker-controlled"));
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE);
    let expected = AuthError::UnknownClaim("backdoor".into());

    assert_eq!(
        verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await,
        Err(expected.clone()),
        "Openid scope must refuse backdoor",
    );
    assert_eq!(
        verify::<Email>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await,
        Err(expected.clone()),
        "Email scope must refuse backdoor",
    );
    assert_eq!(
        verify::<Profile>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await,
        Err(expected.clone()),
        "Profile scope must refuse backdoor",
    );
    assert_eq!(
        verify::<EmailProfile>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await,
        Err(expected.clone()),
        "EmailProfile scope must refuse backdoor",
    );
    assert_eq!(
        verify::<EmailProfilePhone>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await,
        Err(expected.clone()),
        "EmailProfilePhone scope must refuse backdoor",
    );
    assert_eq!(
        verify::<EmailProfilePhoneAddress>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp()).await,
        Err(expected),
        "EmailProfilePhoneAddress scope must refuse backdoor",
    );
}

/// Maximal-scope happy path: every PII claim populated, verified at
/// `EmailProfilePhoneAddress`. Proves the maximal allowlist actually
/// permits the union and the deserializer surfaces every accessor.
#[tokio::test]
async fn maximal_scope_with_all_pii_passes() {
    let mut payload = payload_with_nonce();
    let obj = payload.as_object_mut().unwrap();
    obj.insert("email".into(), json!("u@example.com"));
    obj.insert("email_verified".into(), json!(true));
    obj.insert("name".into(), json!("Test User"));
    obj.insert("given_name".into(), json!("Test"));
    obj.insert("family_name".into(), json!("User"));
    obj.insert("phone_number".into(), json!("+15555555555"));
    obj.insert("phone_number_verified".into(), json!(false));
    obj.insert(
        "address".into(),
        json!({"locality": "Seoul", "country": "KR"}),
    );
    let token = forge_id_token(&payload);
    let claims = verify::<EmailProfilePhoneAddress>(&token, &cfg(NONCE), &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("maximal scope must admit full PII bundle");
    assert_eq!(claims.email(), "u@example.com");
    assert_eq!(claims.name(), Some("Test User"));
    assert_eq!(claims.phone_number(), Some("+15555555555"));
    assert_eq!(
        claims.address().and_then(|a| a.country.as_deref()),
        Some("KR"),
    );
}

/// Hybrid-flow happy path: BOTH at_hash and c_hash present + matching,
/// both bindings configured. Demonstrates ordering invariance
/// (verify must succeed regardless of which check the engine runs first).
#[tokio::test]
async fn hybrid_flow_at_hash_and_c_hash_both_pass() {
    let mut payload = payload_with_nonce();
    payload.as_object_mut().unwrap().insert(
        "at_hash".into(),
        serde_json::Value::String(compute_hash_binding(ACCESS_TOKEN.as_bytes())),
    );
    payload.as_object_mut().unwrap().insert(
        "c_hash".into(),
        serde_json::Value::String(compute_hash_binding(AUTH_CODE.as_bytes())),
    );
    let token = forge_id_token(&payload);
    let cfg = cfg(NONCE)
        .with_access_token_binding(ACCESS_TOKEN)
        .with_authorization_code_binding(AUTH_CODE);
    let claims = verify::<Openid>(&token, &cfg, &test_keyset(), time::OffsetDateTime::now_utc().unix_timestamp())
        .await
        .expect("hybrid flow must accept when both hashes match");
    assert_eq!(claims.nonce, NONCE);
}