rs-identity-model 0.8.2

Production-grade, RFC-compliant OIDC/OAuth2 client library for Rust
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
//! Resource-server side DPoP proof verification (RFC 9449 §4.3).

use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use jsonwebtoken::jwk::{AlgorithmParameters, Jwk, ThumbprintHash};
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
use serde_json::Value;
use subtle::ConstantTimeEq;

use super::key::curve_name;
use super::proof::{DPOP_PROOF_TYP, ath, normalize_htu};
use crate::jwks::JsonWebKey;
use crate::{IdentityError, Result};

/// How far a proof's `iat` may sit from the current time before it is rejected
/// (RFC 9449 §4.3 requires `iat` within an acceptable window). Matches
/// `go/pkg/dpop`'s `defaultMaxIATAge`.
const DEFAULT_MAX_IAT_AGE: Duration = Duration::from_secs(60);

/// The JWS algorithms a DPoP proof may be signed with.
///
/// Only asymmetric algorithms appear: RFC 9449 §4.2 forbids symmetric ones,
/// because a shared secret lets anyone holding it mint proofs and the token stops
/// being sender-constrained at all. `none` cannot appear here either — a proof
/// claiming it fails to parse before this list is consulted.
///
/// Two deliberate omissions, both matching `go/pkg/dpop`'s allowlist or the
/// crate's existing [`crate::DEFAULT_ALLOWED_ALGORITHMS`]:
///
/// - `ES512`, because the underlying `jsonwebtoken` verifier has no P-521
///   support, so allowing it here would only turn a clear rejection into a
///   confusing signature failure.
/// - `EdDSA`, which `go/pkg/dpop` also omits. Widening both languages is
///   tracked by [#579](https://github.com/jamescrowley321/identity-model/issues/579).
const PROOF_ALGORITHMS: &[Algorithm] = &[
    Algorithm::ES256,
    Algorithm::ES384,
    Algorithm::RS256,
    Algorithm::RS384,
    Algorithm::RS512,
    Algorithm::PS256,
    Algorithm::PS384,
    Algorithm::PS512,
];

/// JWK members that carry private key material (RFC 7518 §6.2.2, §6.3.2, §6.4).
/// A proof's embedded `jwk` must be the public key alone (RFC 9449 §4.2), so any
/// of these appearing is a rejection.
const PRIVATE_JWK_MEMBERS: &[&str] = &["d", "p", "q", "dp", "dq", "qi", "k"];

/// A DPoP proof whose signature and claims have been verified (RFC 9449 §4.2).
///
/// A verified proof only shows that *some* key signed it — the embedded `jwk` is
/// supplied by whoever made the proof. The sender-constraint check is that
/// [`DpopProof::thumbprint`] equals the presented token's `cnf.jkt`
/// (RFC 9449 §6, DPOP-005). [`verify_bound_proof`] performs it, together with the
/// `ath` binding; [`verify_proof`] performs it only when
/// [`DpopVerifyOptions::jkt`] is set.
#[derive(Clone, Debug)]
pub struct DpopProof {
    /// The `typ` header, always [`DPOP_PROOF_TYP`].
    pub typ: String,
    /// The JWA name of the algorithm the proof was signed with.
    pub algorithm: String,
    /// The public key embedded in the proof header.
    pub public_jwk: JsonWebKey,
    /// The RFC 7638 SHA-256 thumbprint of [`DpopProof::public_jwk`], the value to
    /// compare against a bound token's `cnf.jkt`.
    pub thumbprint: String,
    /// The proof's unique identifier, for replay detection.
    pub jti: String,
    /// The HTTP method the proof was issued for.
    pub htm: String,
    /// The normalized request URI the proof was issued for.
    pub htu: String,
    /// When the proof was created, in seconds since the Unix epoch.
    pub iat: i64,
    /// The access-token hash, on a resource-request proof (RFC 9449 §7).
    pub ath: Option<String>,
    /// The server-supplied nonce, when the proof answers a challenge (§8).
    pub nonce: Option<String>,
}

/// Settings for [`verify_proof`].
///
/// The defaults check everything RFC 9449 §4.3 makes mandatory — signature,
/// algorithm, `typ`, the embedded public `jwk`, `jti` presence, `htm`/`htu`
/// match, and an `iat` within 60 seconds. The `ath`, `jkt`, and `nonce` checks
/// need values only the caller has — the presented token, its `cnf.jkt`, the
/// issued nonce — so they are set here. [`verify_bound_proof`] requires the first
/// two.
#[derive(Clone, Debug)]
pub struct DpopVerifyOptions {
    max_iat_age: Duration,
    expected_ath: Option<String>,
    expected_jkt: Option<String>,
    expected_nonce: Option<String>,
    /// Overrides the verification clock. Internal test seam.
    pub(crate) now: Option<i64>,
}

impl Default for DpopVerifyOptions {
    fn default() -> Self {
        Self {
            max_iat_age: DEFAULT_MAX_IAT_AGE,
            expected_ath: None,
            expected_jkt: None,
            expected_nonce: None,
            now: None,
        }
    }
}

impl DpopVerifyOptions {
    /// Returns the default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets how far the proof's `iat` may sit from now, in either direction. The
    /// default is 60 seconds.
    #[must_use]
    pub const fn max_iat_age(mut self, max_iat_age: Duration) -> Self {
        self.max_iat_age = max_iat_age;
        self
    }

    /// Requires the proof's `ath` to be the hash of `access_token`, binding the
    /// proof to the token presented alongside it (RFC 9449 §7).
    ///
    /// Set this on every protected-resource request. Without it a proof minted
    /// for one token is accepted alongside another.
    #[must_use]
    pub fn access_token(mut self, access_token: &str) -> Self {
        self.expected_ath = Some(ath(access_token));
        self
    }

    /// Requires the proof to be signed by the key whose RFC 7638 thumbprint is
    /// `jkt` — the presented token's `cnf.jkt` (RFC 9449 §6). This is the
    /// sender-constraint check: without it, a proof signed with any key the
    /// caller generated verifies.
    #[must_use]
    pub fn jkt(mut self, jkt: impl Into<String>) -> Self {
        self.expected_jkt = Some(jkt.into());
        self
    }

    /// Requires the proof's `nonce` to equal `nonce` (RFC 9449 §8).
    #[must_use]
    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
        self.expected_nonce = Some(nonce.into());
        self
    }
}

/// Reads an optional string claim. A member that is present with another JSON
/// type is rejected by name rather than ignored.
fn string_claim(claims: &Value, name: &str) -> Result<Option<String>> {
    match claims.get(name) {
        None => Ok(None),
        Some(Value::String(value)) => Ok(Some(value.clone())),
        Some(other) => Err(reject(
            name,
            format!("{name} claim must be a string, got {}", json_type(other)),
        )),
    }
}

/// Names a JSON value's type for an error message.
const fn json_type(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Array(_) => "an array",
        Value::Object(_) => "an object",
    }
}

/// Verifies a DPoP proof presented with a DPoP-bound access token on a
/// protected-resource request (RFC 9449 §7).
///
/// This is the complete resource-server check: [`verify_proof`] with the proof's
/// `ath` required to be the hash of `access_token`, and its key required to be
/// the one `jkt` — the token's `cnf.jkt` — names. Use it rather than
/// [`verify_proof`] wherever a bound token is presented, so neither binding can
/// be left out.
///
/// Replay detection still needs a `jti` store; see [`verify_proof`].
///
/// # Errors
///
/// [`IdentityError::DpopVerification`] for every rejection [`verify_proof`]
/// lists, and for an `ath` or `jkt` that does not match.
pub fn verify_bound_proof(
    proof: &str,
    expected_htm: &str,
    expected_htu: &str,
    access_token: &str,
    jkt: &str,
    options: &DpopVerifyOptions,
) -> Result<DpopProof> {
    let options = options.clone().access_token(access_token).jkt(jkt);
    verify_proof(proof, expected_htm, expected_htu, &options)
}

/// Verifies a DPoP proof JWT for a request with method `expected_htm` and URI
/// `expected_htu` (RFC 9449 §4.3, DPOP-006).
///
/// Rejects a proof that: is signed with a symmetric algorithm, `none`, or
/// anything outside the asymmetric allowlist; omits the embedded `jwk`, or embeds
/// private key material, or embeds a non-asymmetric key; is not
/// `typ=dpop+jwt`; fails signature verification against its own embedded key;
/// omits a required claim or carries one with the wrong JSON type; or whose
/// `htm`, `htu`, `iat`, `ath`, `nonce`, or key thumbprint (`jkt`) does not
/// match. Every rejection is an [`IdentityError::DpopVerification`] naming the
/// offending member. `htu` is compared after both sides are normalized
/// ([`crate::dpop_normalize_htu`]).
///
/// On a protected-resource request, prefer [`verify_bound_proof`]: without
/// [`DpopVerifyOptions::jkt`] this function accepts a proof signed by any key.
///
/// # Replay detection is the caller's job
///
/// RFC 9449 §4.3 also expects a server to reject a proof whose `jti` it has
/// already seen inside the `iat` window. That needs state this function does not
/// have: dedupe [`DpopProof::jti`] against a short-lived store — one that only
/// needs to retain entries for [`DpopVerifyOptions::max_iat_age`], since an older
/// proof is rejected on `iat` anyway.
///
/// # Errors
///
/// [`IdentityError::DpopVerification`] for every rejection listed above.
///
/// # Examples
///
/// ```
/// use rs_identity_model::{
///     DpopAlgorithm, DpopKey, DpopProofOptions, DpopVerifyOptions, verify_proof,
/// };
///
/// # fn main() -> rs_identity_model::Result<()> {
/// let key = DpopKey::generate(DpopAlgorithm::Es256)?;
/// let token = "the-access-token";
/// let proof = key.proof(
///     "GET",
///     "https://resource.example.com/userinfo",
///     &DpopProofOptions::new().access_token(token),
/// )?;
///
/// // The `cnf.jkt` claim of the presented token.
/// let jkt = key.thumbprint()?;
/// let verified = verify_proof(
///     &proof,
///     "GET",
///     "https://resource.example.com/userinfo",
///     &DpopVerifyOptions::new().access_token(token).jkt(&jkt),
/// )?;
/// assert_eq!(verified.thumbprint, jkt);
/// # Ok(())
/// # }
/// ```
pub fn verify_proof(
    proof: &str,
    expected_htm: &str,
    expected_htu: &str,
    options: &DpopVerifyOptions,
) -> Result<DpopProof> {
    // An `alg` outside jsonwebtoken's vocabulary — `none` above all — dies here,
    // before any key is touched.
    let header = decode_header(proof).map_err(|e| {
        reject(
            "alg",
            format!("not a DPoP proof signed with a supported asymmetric algorithm: {e}"),
        )
    })?;

    // Check the algorithm BEFORE building a key from the embedded jwk. An
    // attacker who picks HS256 and embeds an `oct` key would otherwise get their
    // own HMAC verified as a valid proof.
    if !PROOF_ALGORITHMS.contains(&header.alg) {
        return Err(reject(
            "alg",
            format!(
                "algorithm {:?} is not allowed for DPoP proofs: RFC 9449 §4.2 requires an \
                 asymmetric algorithm",
                format!("{:?}", header.alg)
            ),
        ));
    }

    if header.typ.as_deref() != Some(DPOP_PROOF_TYP) {
        return Err(reject(
            "typ",
            format!("header typ must be {DPOP_PROOF_TYP:?}"),
        ));
    }

    let jwk = header.jwk.as_ref().ok_or_else(|| {
        reject(
            "jwk",
            "proof header is missing the embedded jwk".to_string(),
        )
    })?;

    // jsonwebtoken's Jwk type cannot represent private members, so it drops them
    // silently on parse and there is nothing left here to inspect. Read the raw
    // protected header to catch a proof that tried to hand over its private key.
    reject_private_jwk_members(proof)?;

    // The embedded key must be asymmetric. A symmetric `oct` key would pair with
    // an HS* alg the allowlist above already refuses, but an explicit check keeps
    // the two from drifting apart.
    match &jwk.algorithm {
        AlgorithmParameters::EllipticCurve(_) | AlgorithmParameters::RSA(_) => {}
        _ => {
            return Err(reject(
                "jwk",
                "embedded jwk is not an asymmetric key".to_string(),
            ));
        }
    }

    let key = DecodingKey::from_jwk(jwk).map_err(|e| {
        reject(
            "jwk",
            format!("embedded jwk is not a usable public key: {e}"),
        )
    })?;

    // A proof carries none of the claims jsonwebtoken validates by default: no
    // exp, no aud, no sub. Turn all of that off and pin the algorithm to the one
    // the allowlist just approved, so the signature check is the only thing this
    // call performs.
    let mut validation = Validation::new(header.alg);
    validation.required_spec_claims.clear();
    validation.validate_exp = false;
    validation.validate_nbf = false;
    validation.validate_aud = false;

    // Decode into a generic value: a typed struct would turn a mistyped claim
    // into a decode error indistinguishable from a bad signature.
    let claims = decode::<Value>(proof, &key, &validation)
        .map_err(|e| reject("signature", e.to_string()))?
        .claims;

    let jti = string_claim(&claims, "jti")?
        .filter(|j| !j.is_empty())
        .ok_or_else(|| reject("jti", "missing required jti claim".to_string()))?;

    let htm = string_claim(&claims, "htm")?
        .ok_or_else(|| reject("htm", "missing required htm claim".to_string()))?;
    if htm != expected_htm {
        return Err(reject(
            "htm",
            "proof htm does not match the request method".to_string(),
        ));
    }

    let htu = string_claim(&claims, "htu")?
        .ok_or_else(|| reject("htu", "missing required htu claim".to_string()))?;
    // Normalize both sides, so a proof from a client that writes the same URI
    // differently (an explicit default port, an uppercase host) still matches.
    let htu = normalize_htu(&htu)
        .map_err(|e| reject("htu", format!("proof htu is not a valid URI: {e}")))?;
    let want_htu = normalize_htu(expected_htu)
        .map_err(|e| reject("htu", format!("invalid expected request URI: {e}")))?;
    if htu != want_htu {
        return Err(reject(
            "htu",
            "proof htu does not match the request URI".to_string(),
        ));
    }

    let iat = match claims.get("iat") {
        None => return Err(reject("iat", "missing required iat claim".to_string())),
        Some(value) => value.as_i64().ok_or_else(|| {
            reject(
                "iat",
                format!("iat claim must be an integer NumericDate, got {value}"),
            )
        })?,
    };
    let ath = string_claim(&claims, "ath")?;
    let nonce = string_claim(&claims, "nonce")?;
    let now = match options.now {
        Some(now) => now,
        None => now_unix()?,
    };
    // `iat` is attacker-controlled and unauthenticated at this point, so the
    // distance must be computed with arithmetic that is total over i64:
    // `now - iat` overflows for an `iat` near i64::MIN and panics under
    // overflow checks. `abs_diff` returns the distance as a u64 and cannot
    // trap, which also removes the `as i64` cast on the window.
    let max_age = options.max_iat_age.as_secs();
    if now.abs_diff(iat) > max_age {
        return Err(reject(
            "iat",
            format!("proof iat is outside the acceptable {max_age}s window"),
        ));
    }

    if let Some(expected) = &options.expected_ath {
        match &ath {
            Some(actual) if ct_eq(actual, expected) => {}
            _ => {
                return Err(reject(
                    "ath",
                    "proof ath does not match the access token hash".to_string(),
                ));
            }
        }
    }

    if let Some(expected) = &options.expected_nonce {
        match &nonce {
            Some(actual) if ct_eq(actual, expected) => {}
            _ => {
                return Err(reject(
                    "nonce",
                    "proof nonce does not match the expected nonce".to_string(),
                ));
            }
        }
    }

    let thumbprint = jwk
        .thumbprint(ThumbprintHash::SHA256)
        .map_err(|e| reject("jwk", format!("cannot compute thumbprint: {e}")))?;

    if let Some(expected) = &options.expected_jkt
        && !ct_eq(&thumbprint, expected)
    {
        return Err(reject(
            "jkt",
            "proof is signed by a key other than the one the token is bound to (cnf.jkt)"
                .to_string(),
        ));
    }

    Ok(DpopProof {
        typ: DPOP_PROOF_TYP.to_string(),
        algorithm: format!("{:?}", header.alg),
        public_jwk: public_jwk_of(jwk),
        thumbprint,
        jti,
        htm,
        htu,
        iat,
        ath,
        nonce,
    })
}

/// Builds the [`IdentityError::DpopVerification`] for a rejected member.
fn reject(field: &str, reason: String) -> IdentityError {
    IdentityError::DpopVerification {
        field: Some(field.to_string()),
        reason,
    }
}

/// Rejects a proof whose embedded `jwk` carries private key material
/// (RFC 9449 §4.2, DPOP-001).
///
/// Reads the raw protected header rather than the parsed [`Jwk`], which drops
/// unknown members. Cryptographically the private half is ignored either way —
/// verification uses `n`/`e` or `x`/`y` — but a client that leaks its private key
/// into a proof has a serious bug, and accepting the proof would hide it.
fn reject_private_jwk_members(proof: &str) -> Result<()> {
    let encoded = proof.split('.').next().unwrap_or_default();
    let decoded = URL_SAFE_NO_PAD
        .decode(encoded)
        .map_err(|e| reject("jwk", format!("proof header is not valid base64url: {e}")))?;
    let header: Value = serde_json::from_slice(&decoded)
        .map_err(|e| reject("jwk", format!("proof header is not valid JSON: {e}")))?;
    let Some(members) = header.get("jwk").and_then(Value::as_object) else {
        // A missing or non-object jwk is reported by the caller's own check.
        return Ok(());
    };
    for private in PRIVATE_JWK_MEMBERS {
        if members.contains_key(*private) {
            return Err(reject(
                "jwk",
                format!(
                    "embedded jwk must contain only the public key, but carries the private \
                     member {private:?}"
                ),
            ));
        }
    }
    Ok(())
}

/// Converts a verified proof's embedded key to the crate's public JWK type, so
/// `jsonwebtoken` types stay out of the public surface.
fn public_jwk_of(jwk: &Jwk) -> JsonWebKey {
    let mut key = JsonWebKey {
        kty: String::new(),
        kid: jwk.common.key_id.clone().unwrap_or_default(),
        use_: String::new(),
        alg: String::new(),
        n: String::new(),
        e: String::new(),
        crv: String::new(),
        x: String::new(),
        y: String::new(),
        extra: std::collections::HashMap::new(),
    };
    match &jwk.algorithm {
        AlgorithmParameters::EllipticCurve(ec) => {
            key.kty = "EC".to_string();
            key.crv = curve_name(&ec.curve);
            key.x = ec.x.clone();
            key.y = ec.y.clone();
        }
        AlgorithmParameters::RSA(rsa) => {
            key.kty = "RSA".to_string();
            key.n = rsa.n.clone();
            key.e = rsa.e.clone();
        }
        // Unreachable: verify_proof rejects a non-asymmetric key before here.
        _ => {}
    }
    key
}

/// Constant-time equality of two ASCII claim strings, matching how the ID-Token
/// profile compares `nonce`/`at_hash`/`c_hash`.
fn ct_eq(a: &str, b: &str) -> bool {
    a.as_bytes().ct_eq(b.as_bytes()).into()
}

/// Seconds since the Unix epoch, for the `iat` window check.
fn now_unix() -> Result<i64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .map_err(|e| IdentityError::DpopVerification {
            field: None,
            reason: format!("cannot read the system clock to check the proof iat: {e}"),
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dpop::key::{DpopAlgorithm, DpopKey};
    use crate::dpop::proof::DpopProofOptions;

    /// A proof minted at `iat`, using the crate-internal clock seam.
    fn proof_at(key: &DpopKey, iat: i64) -> String {
        let mut options = DpopProofOptions::new();
        options.issued_at = Some(iat);
        key.proof("POST", "https://server.example.com/token", &options)
            .expect("build proof")
    }

    fn verify_at(proof: &str, now: i64, max_age: Duration) -> Result<DpopProof> {
        let mut options = DpopVerifyOptions::new().max_iat_age(max_age);
        options.now = Some(now);
        verify_proof(proof, "POST", "https://server.example.com/token", &options)
    }

    fn field_of(err: &IdentityError) -> Option<&str> {
        match err {
            IdentityError::DpopVerification { field, .. } => field.as_deref(),
            _ => None,
        }
    }

    /// DPOP-006: `iat` is rejected outside the window in **both** directions. A
    /// one-sided check would accept a proof minted far in the future, which lets a
    /// client pre-mint proofs and defeats the freshness requirement.
    #[test]
    fn iat_window_is_enforced_in_both_directions() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        let window = Duration::from_secs(60);
        let proof = proof_at(&key, now);

        // Inside the window: the boundary itself is accepted, matching go/pkg/dpop.
        for offset in [0, 59, 60, -59, -60] {
            verify_at(&proof, now + offset, window)
                .unwrap_or_else(|e| panic!("offset {offset}s should verify: {e}"));
        }

        // Outside it, on both sides.
        for offset in [61, 3600, -61, -3600] {
            let err = verify_at(&proof, now + offset, window)
                .expect_err(&format!("offset {offset}s must be rejected"));
            assert_eq!(field_of(&err), Some("iat"), "offset {offset}s");
        }
    }

    /// An `iat` at the extremes of `i64` is rejected, not trapped on.
    ///
    /// `iat` is attacker-controlled — it arrives in an unauthenticated proof —
    /// and the window check subtracts it from the current time. A plain
    /// `now - iat` overflows for `i64::MIN`, which panics in any
    /// overflow-checked build (the default `dev` profile, and any release
    /// profile setting `overflow-checks`). That is a pre-authentication denial
    /// of service reachable by anyone who can reach the resource server, so the
    /// arithmetic has to be total over the whole domain.
    #[test]
    fn an_extreme_iat_is_rejected_rather_than_overflowing() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;

        for iat in [i64::MIN, i64::MIN + 1, i64::MAX, i64::MAX - 1] {
            let proof = proof_at(&key, iat);
            let err = verify_at(&proof, now, DEFAULT_MAX_IAT_AGE)
                .expect_err("an iat at the i64 boundary is far outside any window");
            assert_eq!(field_of(&err), Some("iat"), "iat {iat}");
        }
    }

    /// A stale proof is rejected even when everything else about it is perfect —
    /// this is the replay window, so it must not depend on any other check.
    #[test]
    fn a_stale_proof_is_rejected_on_iat_alone() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        let proof = proof_at(&key, now - 86_400);
        let err = verify_at(&proof, now, DEFAULT_MAX_IAT_AGE).expect_err("a day-old proof");
        assert_eq!(field_of(&err), Some("iat"));
    }

    /// A proof missing a required claim is rejected by name, not as a blanket
    /// parse failure — a caller distinguishing `htu` from `jti` needs the name.
    #[test]
    fn missing_required_claims_are_reported_by_name() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        let proof = proof_at(&key, now);
        let parts: Vec<&str> = proof.split('.').collect();
        let header = parts[0];

        // Re-sign a payload with one claim dropped each time, so the signature
        // stays valid and the missing claim is the only fault.
        for (claim, field) in [
            ("jti", "jti"),
            ("htm", "htm"),
            ("htu", "htu"),
            ("iat", "iat"),
        ] {
            let mut payload: Value = serde_json::from_slice(
                &URL_SAFE_NO_PAD.decode(parts[1]).expect("payload base64url"),
            )
            .expect("payload JSON");
            payload.as_object_mut().expect("object").remove(claim);
            let resigned = jsonwebtoken::encode(
                &{
                    let mut h = jsonwebtoken::Header::new(Algorithm::ES256);
                    h.typ = Some(DPOP_PROOF_TYP.to_string());
                    h.jwk = Some(key.embedded_jwk().clone());
                    h
                },
                &payload,
                key.encoding_key(),
            )
            .expect("re-sign");
            let _ = header;

            let err = verify_at(&resigned, now, DEFAULT_MAX_IAT_AGE)
                .expect_err(&format!("a proof without {claim:?} must be rejected"));
            assert_eq!(field_of(&err), Some(field), "missing {claim:?}");
        }
    }

    /// An empty `jti` is as useless for replay detection as a missing one, so it is
    /// rejected the same way.
    #[test]
    fn an_empty_jti_is_rejected() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        let mut header = jsonwebtoken::Header::new(Algorithm::ES256);
        header.typ = Some(DPOP_PROOF_TYP.to_string());
        header.jwk = Some(key.embedded_jwk().clone());
        let payload = serde_json::json!({
            "jti": "",
            "htm": "POST",
            "htu": "https://server.example.com/token",
            "iat": now,
        });
        let proof =
            jsonwebtoken::encode(&header, &payload, key.encoding_key()).expect("sign proof");
        let err = verify_at(&proof, now, DEFAULT_MAX_IAT_AGE).expect_err("empty jti");
        assert_eq!(field_of(&err), Some("jti"));
    }

    /// Signs `payload` as a well-formed proof header for `key`, so the payload is
    /// the only thing under test.
    fn sign(key: &DpopKey, payload: &Value) -> String {
        let mut header = jsonwebtoken::Header::new(Algorithm::ES256);
        header.typ = Some(DPOP_PROOF_TYP.to_string());
        header.jwk = Some(key.embedded_jwk().clone());
        jsonwebtoken::encode(&header, payload, key.encoding_key()).expect("sign proof")
    }

    /// A claim with the wrong JSON type is rejected by name, not reported as a
    /// signature failure — a float `iat` from `time.time()` is a malformed proof,
    /// not a forgery.
    #[test]
    fn mistyped_claims_are_reported_by_name() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        for (claim, value, named) in [
            (
                "iat",
                serde_json::json!(1_700_000_000.5),
                "integer NumericDate",
            ),
            (
                "iat",
                serde_json::json!("1700000000"),
                "integer NumericDate",
            ),
            ("jti", serde_json::json!(5), "got a number"),
            ("htm", serde_json::json!(null), "got null"),
            ("htu", serde_json::json!(true), "got a boolean"),
            ("ath", serde_json::json!({}), "got an object"),
            ("nonce", serde_json::json!([]), "got an array"),
        ] {
            let mut payload = serde_json::json!({
                "jti": "j-1",
                "htm": "POST",
                "htu": "https://server.example.com/token",
                "iat": now,
            });
            payload[claim] = value.clone();
            let err = verify_at(&sign(&key, &payload), now, DEFAULT_MAX_IAT_AGE)
                .expect_err(&format!("{claim} = {value} must be rejected"));
            assert_eq!(field_of(&err), Some(claim), "{claim} = {value}");
            assert!(err.to_string().contains(named), "{claim} = {value}: {err}");
        }
    }

    /// The proof's own `htu` is normalized too, so a client that writes the
    /// default port or an uppercase host still matches; one that is not a URI
    /// at all is rejected against `htu`.
    #[test]
    fn proof_htu_is_normalized_before_comparison() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        let proof_with = |htu: &str| {
            sign(
                &key,
                &serde_json::json!({"jti": "j-1", "htm": "GET", "htu": htu, "iat": now}),
            )
        };
        let mut verify = DpopVerifyOptions::new();
        verify.now = Some(now);

        for written in [
            "https://rs.example.com:443/resource",
            "https://RS.Example.COM/resource",
        ] {
            let verified = verify_proof(
                &proof_with(written),
                "GET",
                "https://rs.example.com/resource",
                &verify,
            )
            .unwrap_or_else(|e| panic!("{written} should normalize to a match: {e}"));
            assert_eq!(verified.htu, "https://rs.example.com/resource");
        }

        let err = verify_proof(
            &proof_with("not a uri"),
            "GET",
            "https://rs.example.com/resource",
            &verify,
        )
        .expect_err("non-URI htu");
        assert_eq!(field_of(&err), Some("htu"));
    }

    /// The `jkt` option is the sender-constraint check: a proof signed by any
    /// other key is rejected, however valid it is otherwise.
    #[test]
    fn jkt_rejects_a_proof_signed_by_another_key() {
        let holder = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let attacker = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let jkt = holder.thumbprint().expect("thumbprint");
        let now = 1_700_000_000;
        let mut verify = DpopVerifyOptions::new().jkt(&jkt);
        verify.now = Some(now);

        verify_proof(
            &proof_at(&holder, now),
            "POST",
            "https://server.example.com/token",
            &verify,
        )
        .expect("the bound key's proof verifies");
        let err = verify_proof(
            &proof_at(&attacker, now),
            "POST",
            "https://server.example.com/token",
            &verify,
        )
        .expect_err("another key's proof");
        assert_eq!(field_of(&err), Some("jkt"));
    }

    /// `verify_bound_proof` enforces both bindings: a proof without the token's
    /// `ath` (a token-request proof replayed at a resource) and a proof from a
    /// key `cnf.jkt` does not name are each rejected.
    #[test]
    fn verify_bound_proof_requires_ath_and_jkt() {
        let holder = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let attacker = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let jkt = holder.thumbprint().expect("thumbprint");
        let (token, uri, now) = (
            "bound-token",
            "https://rs.example.com/resource",
            1_700_000_000,
        );
        let resource_proof = |key: &DpopKey, token: Option<&str>| {
            let mut options = DpopProofOptions::new();
            options.issued_at = Some(now);
            if let Some(token) = token {
                options = options.access_token(token);
            }
            key.proof("GET", uri, &options).expect("build proof")
        };
        let mut verify = DpopVerifyOptions::new();
        verify.now = Some(now);

        verify_bound_proof(
            &resource_proof(&holder, Some(token)),
            "GET",
            uri,
            token,
            &jkt,
            &verify,
        )
        .expect("the holder's resource proof verifies");

        let err = verify_bound_proof(
            &resource_proof(&holder, None),
            "GET",
            uri,
            token,
            &jkt,
            &verify,
        )
        .expect_err("a proof without ath");
        assert_eq!(field_of(&err), Some("ath"));

        let err = verify_bound_proof(
            &resource_proof(&attacker, Some(token)),
            "GET",
            uri,
            token,
            &jkt,
            &verify,
        )
        .expect_err("a proof from another key");
        assert_eq!(field_of(&err), Some("jkt"));
    }

    /// The expected-URI argument is normalized before comparison, so a caller may
    /// pass the raw request URI — query string, fragment, and userinfo included —
    /// and still match a proof built from the same request.
    #[test]
    fn expected_htu_is_normalized_before_comparison() {
        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
        let now = 1_700_000_000;
        let mut options = DpopProofOptions::new();
        options.issued_at = Some(now);
        let proof = key
            .proof("GET", "https://rs.example.com/resource", &options)
            .expect("build proof");

        for equivalent in [
            "https://rs.example.com/resource",
            "https://rs.example.com/resource?include=all",
            "https://rs.example.com/resource#section",
            "https://user:pass@rs.example.com/resource",
        ] {
            let mut verify = DpopVerifyOptions::new();
            verify.now = Some(now);
            verify_proof(&proof, "GET", equivalent, &verify)
                .unwrap_or_else(|e| panic!("{equivalent} should normalize to a match: {e}"));
        }

        // A non-absolute expected URI is a caller error reported against htu.
        let mut verify = DpopVerifyOptions::new();
        verify.now = Some(now);
        let err = verify_proof(&proof, "GET", "/resource", &verify).expect_err("relative URI");
        assert_eq!(field_of(&err), Some("htu"));
    }

    /// The allowlist must not contain a symmetric algorithm or `none`. A
    /// regression here silently un-sender-constrains every token in the system,
    /// so it is asserted directly rather than only through a forged proof.
    #[test]
    fn the_algorithm_allowlist_is_asymmetric_only() {
        for symmetric in [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512] {
            assert!(
                !PROOF_ALGORITHMS.contains(&symmetric),
                "{symmetric:?} must never be allowed for a DPoP proof"
            );
        }
        assert!(!PROOF_ALGORITHMS.is_empty());
    }

    /// A header that is not valid base64url or not JSON is rejected rather than
    /// panicking — the private-member scan reads the raw header, so it is the one
    /// place that touches unparsed attacker input.
    #[test]
    fn a_malformed_header_is_rejected_not_panicked_on() {
        for malformed in ["", "!!!.x.y", "e30.x.y"] {
            let err = verify_proof(
                malformed,
                "POST",
                "https://server.example.com/token",
                &DpopVerifyOptions::new(),
            )
            .expect_err("malformed proof");
            assert!(
                matches!(err, IdentityError::DpopVerification { .. }),
                "{malformed:?} produced {err:?}"
            );
        }
    }
}