entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! JWT encoding (minting) with HMAC signatures per RFC 7519 / RFC 7515.
//!
//! Complements [`verify_jwt`](super::verify_jwt): where that function
//! validates an inbound token, [`JwtEncoder`] mints an outbound one. The
//! two are symmetrical — a token produced here round-trips through
//! `verify_jwt` and yields the same registered and custom claims.
//!
//! # Design
//!
//! * **Builder over the registered claims** — the encoder mirrors the
//!   accessor surface of [`JwtClaims`](super::JwtClaims): `iss`, `sub`,
//!   `aud`, `exp`, `iat`, `nbf`, `jti`, plus a `nonce` convenience (OIDC
//!   core §3.1.3.6) and arbitrary string / boolean / array custom claims.
//! * **`alg=none` is unrepresentable** — signing is parameterised by
//!   [`JwtSigningAlgorithm`], which has no `None` variant. There is no API
//!   path that produces an unsigned token, so the signature-bypass attack
//!   `verify_jwt` defends against cannot be created by this crate in the
//!   first place.
//! * **Storage-free / transport-free** — [`JwtEncoder::sign`] returns the
//!   compact-serialisation `String`; the caller owns transport.
//! * **Manual JSON emission** — the crate's [`JsonValue`](crate::json::JsonValue)
//!   parses but does not serialise, so the header and payload objects are
//!   built directly as RFC 8259 JSON with escaping, mirroring the manual
//!   document construction in `saml::generate_sp_metadata`.
//!
//! # Security
//!
//! * The HMAC key is the shared secret (for OIDC ID tokens, the client
//!   secret — the `client_secret_jwt`-style symmetric signing of OIDC
//!   core §10.1). It is accepted as `&[u8]` and never copied into the
//!   returned token or any error message.
//! * Signature bytes are produced via the crate's own
//!   [`HmacSha256`](crate::crypto::HmacSha256) /
//!   [`HmacSha512`](crate::crypto::HmacSha512), the same primitives
//!   `verify_jwt` checks against.
//!
//! # Example
//!
//! ```
//! use entropy_auth::jwt::{JwtEncoder, JwtSigningAlgorithm};
//! use entropy_auth::verify_jwt;
//!
//! let token = JwtEncoder::new()
//!     .issuer("https://auth.example.com")
//!     .subject("user-123")
//!     .audience("my-client")
//!     .expiration(9_999_999_999)
//!     .issued_at(1_700_000_000)
//!     .custom_claim("roles", ["admin", "user"])
//!     .sign(JwtSigningAlgorithm::Hs256, b"client-secret");
//!
//! let (header, claims) = verify_jwt(&token, b"client-secret").unwrap();
//! assert_eq!(claims.sub(), Some("user-123"));
//! assert_eq!(claims.iss(), Some("https://auth.example.com"));
//! assert!(claims.validate_aud("my-client"));
//! ```

use crate::crypto::{HmacSha256, HmacSha512};
use crate::encoding::base64url_encode;
use crate::json::escape_json_string;
use crate::util::log::debug;

use super::header::JwtAlgorithm;

// ---------------------------------------------------------------------------
// Signing algorithm
// ---------------------------------------------------------------------------

/// The HMAC algorithm used to sign a minted JWT.
///
/// Deliberately distinct from [`JwtAlgorithm`](super::JwtAlgorithm): that
/// enum models *parsing* and therefore carries a `None` variant so an
/// inbound `"alg":"none"` token can be recognised and rejected. This enum
/// models *signing* and has **no** `None` variant — there is no way to ask
/// the encoder to produce an unsigned token.
#[doc(alias = "signing_algorithm")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum JwtSigningAlgorithm {
    /// HMAC using SHA-256 (RFC 7518 §3.2).
    Hs256,
    /// HMAC using SHA-512 (RFC 7518 §3.2).
    Hs512,
}

impl JwtSigningAlgorithm {
    /// Returns the `alg` header value for this algorithm (e.g. `"HS256"`).
    #[must_use]
    #[inline]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Hs256 => "HS256",
            Self::Hs512 => "HS512",
        }
    }

    /// Returns the parsing-side [`JwtAlgorithm`] this algorithm corresponds
    /// to, for callers that need to relate the two enums.
    #[must_use]
    #[inline]
    pub fn to_jwt_algorithm(self) -> JwtAlgorithm {
        match self {
            Self::Hs256 => JwtAlgorithm::HS256,
            Self::Hs512 => JwtAlgorithm::HS512,
        }
    }
}

// ---------------------------------------------------------------------------
// Custom claim values
// ---------------------------------------------------------------------------

/// A value for a custom (non-registered) JWT claim.
///
/// Covers the claim shapes an identity provider actually needs to emit:
/// strings (`preferred_username`, `email`), booleans (`email_verified`),
/// unsigned integers (`NumericDate`-style claims), and string arrays
/// (`roles`). Nested-object claims are out of scope — keeping the surface
/// minimal per the crate's no-speculative-API policy.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CustomClaimValue {
    /// A JSON string value.
    Str(String),
    /// A JSON boolean value.
    Bool(bool),
    /// A JSON unsigned-integer value (e.g. a `NumericDate` claim).
    Number(u64),
    /// A JSON array of strings.
    StrArray(Vec<String>),
}

/// Types that can be supplied as a custom claim value to
/// [`JwtEncoder::custom_claim`].
///
/// Implemented for `&str` / `String` (string claims), `bool` (boolean
/// claims), `u64` (unsigned-integer claims), and the common
/// string-collection shapes `Vec<String>`, `Vec<&str>`, `&[&str]`, and
/// `[&str; N]` (string-array claims such as `roles`). The trait is sealed
/// against a private representation, so callers cannot construct
/// unsupported claim shapes.
pub trait IntoCustomClaim {
    /// Converts `self` into the internal claim representation.
    #[doc(hidden)]
    fn into_custom_claim(self) -> CustomClaimValueOpaque;
}

/// Opaque wrapper around the internal custom-claim representation.
///
/// This type is returned by [`IntoCustomClaim`] but carries no public
/// constructors, keeping the underlying representation an implementation
/// detail.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct CustomClaimValueOpaque(CustomClaimValue);

impl IntoCustomClaim for &str {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::Str(self.to_owned()))
    }
}

impl IntoCustomClaim for CustomClaimValueOpaque {
    /// Identity passthrough: lets an already-resolved custom-claim value (e.g.
    /// one carried through a higher-level builder) be handed back to
    /// [`JwtEncoder::custom_claim`] without re-wrapping.
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        self
    }
}

impl IntoCustomClaim for String {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::Str(self))
    }
}

impl IntoCustomClaim for bool {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::Bool(self))
    }
}

impl IntoCustomClaim for u64 {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::Number(self))
    }
}

impl IntoCustomClaim for Vec<String> {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::StrArray(self))
    }
}

impl IntoCustomClaim for Vec<&str> {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::StrArray(
            self.into_iter().map(ToOwned::to_owned).collect(),
        ))
    }
}

impl IntoCustomClaim for &[&str] {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::StrArray(
            self.iter().map(|s| (*s).to_owned()).collect(),
        ))
    }
}

impl<const N: usize> IntoCustomClaim for [&str; N] {
    fn into_custom_claim(self) -> CustomClaimValueOpaque {
        CustomClaimValueOpaque(CustomClaimValue::StrArray(
            self.iter().map(|s| (*s).to_owned()).collect(),
        ))
    }
}

// ---------------------------------------------------------------------------
// Encoder
// ---------------------------------------------------------------------------

/// Builder that assembles registered and custom claims, then mints a
/// signed JWT.
///
/// Construct with [`JwtEncoder::new`], chain claim setters, then call
/// [`sign`](JwtEncoder::sign). Every setter is optional; an encoder with
/// no claims set produces a valid JWT with an empty payload object.
///
/// The registered-claim setters mirror the accessors on
/// [`JwtClaims`](super::JwtClaims) so encode and verify are symmetrical.
#[doc(alias = "jwt_builder")]
#[derive(Debug, Clone, Default)]
#[must_use = "an encoder does nothing until `sign` is called"]
pub struct JwtEncoder {
    iss: Option<String>,
    sub: Option<String>,
    aud: Vec<String>,
    exp: Option<u64>,
    nbf: Option<u64>,
    iat: Option<u64>,
    jti: Option<String>,
    nonce: Option<String>,
    kid: Option<String>,
    custom: Vec<(String, CustomClaimValue)>,
}

impl JwtEncoder {
    /// Creates an empty encoder with no claims set.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the issuer (`iss`) claim (RFC 7519 §4.1.1).
    #[inline]
    pub fn issuer(mut self, iss: impl Into<String>) -> Self {
        self.iss = Some(iss.into());
        self
    }

    /// Sets the subject (`sub`) claim (RFC 7519 §4.1.2).
    #[inline]
    pub fn subject(mut self, sub: impl Into<String>) -> Self {
        self.sub = Some(sub.into());
        self
    }

    /// Adds an audience (`aud`) value (RFC 7519 §4.1.3).
    ///
    /// May be called multiple times; the `aud` claim is emitted as a single
    /// string when one value is present and as a JSON array when more than
    /// one is present, matching the normalisation
    /// [`JwtClaims`](super::JwtClaims) applies on the way back in.
    #[inline]
    pub fn audience(mut self, aud: impl Into<String>) -> Self {
        self.aud.push(aud.into());
        self
    }

    /// Sets the expiration time (`exp`) claim as seconds since the Unix
    /// epoch (RFC 7519 §4.1.4).
    #[inline]
    pub fn expiration(mut self, exp: u64) -> Self {
        self.exp = Some(exp);
        self
    }

    /// Sets the not-before time (`nbf`) claim as seconds since the Unix
    /// epoch (RFC 7519 §4.1.5).
    #[inline]
    pub fn not_before(mut self, nbf: u64) -> Self {
        self.nbf = Some(nbf);
        self
    }

    /// Sets the issued-at time (`iat`) claim as seconds since the Unix
    /// epoch (RFC 7519 §4.1.6).
    #[inline]
    pub fn issued_at(mut self, iat: u64) -> Self {
        self.iat = Some(iat);
        self
    }

    /// Sets the JWT ID (`jti`) claim (RFC 7519 §4.1.7).
    #[inline]
    pub fn jwt_id(mut self, jti: impl Into<String>) -> Self {
        self.jti = Some(jti.into());
        self
    }

    /// Sets the OIDC `nonce` claim (`OpenID` Connect Core §3.1.3.6).
    ///
    /// The nonce binds an ID token to the authorization request that
    /// produced it; the relying party compares it against the value it
    /// sent.
    #[inline]
    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
        self.nonce = Some(nonce.into());
        self
    }

    /// Sets the `kid` (key ID) JOSE header parameter (RFC 7515 §4.1.4).
    ///
    /// The `kid` lets a verifier select the right key from a JWKS. It is
    /// usually set automatically by [`sign_asymmetric`](Self::sign_asymmetric)
    /// from the signing key's own `kid`; this setter exists for callers that
    /// mint HMAC tokens but still want to advertise a key identifier, or that
    /// want to override the signing key's `kid`.
    #[inline]
    pub fn key_id(mut self, kid: impl Into<String>) -> Self {
        self.kid = Some(kid.into());
        self
    }

    /// Adds a custom (non-registered) claim.
    ///
    /// Accepts string, boolean, and string-array values via
    /// [`IntoCustomClaim`] — for example a `preferred_username` string, an
    /// `email_verified` boolean, or a `roles` array.
    ///
    /// The first occurrence of a name wins: a custom name that duplicates an
    /// earlier custom claim, or a registered claim set via a dedicated setter
    /// (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`, `nonce`), is dropped
    /// rather than emitted as a second JSON key. This keeps the payload free
    /// of duplicate keys, which are ambiguous across parsers and rejected by
    /// this crate's own decoder. Prefer the dedicated setters for registered
    /// claims.
    #[inline]
    pub fn custom_claim(mut self, name: impl Into<String>, value: impl IntoCustomClaim) -> Self {
        self.custom.push((name.into(), value.into_custom_claim().0));
        self
    }

    /// Signs the assembled claims and returns the compact-serialisation
    /// JWT string `base64url(header).base64url(payload).base64url(signature)`.
    ///
    /// # Security
    ///
    /// The `key` is the shared HMAC secret and is never embedded in the
    /// returned token or logged. For OIDC ID tokens this is the relying
    /// party's `client_secret` (OIDC core §10.1, `client_secret_jwt`).
    ///
    /// The caller MUST supply a key at least as long as the algorithm's hash
    /// output — 32 bytes for `HS256`, 64 bytes for `HS512` (RFC 7518 §3.2).
    /// A shorter key reduces the brute-force resistance of the signature; this
    /// method does not reject one, so generate keys with
    /// [`crypto::fill_random`](crate::crypto::fill_random) (or a comparably
    /// strong source) sized to the algorithm.
    #[must_use = "this returns the signed JWT string"]
    pub fn sign(&self, alg: JwtSigningAlgorithm, key: &[u8]) -> String {
        let signing_input = self.signing_input(alg.as_str(), self.kid.as_deref());

        let signature_b64 = match alg {
            JwtSigningAlgorithm::Hs256 => {
                base64url_encode(&HmacSha256::mac(key, signing_input.as_bytes()))
            }
            JwtSigningAlgorithm::Hs512 => {
                base64url_encode(&HmacSha512::mac(key, signing_input.as_bytes()))
            }
        };

        // SECURITY: Never log the signing key or the signature value.
        debug!(alg = %alg.as_str(), "jwt: token minted");

        let mut token = signing_input;
        token.push('.');
        token.push_str(&signature_b64);
        token
    }

    /// Signs the assembled claims with an asymmetric key (`EdDSA` / ES256) and
    /// returns the compact-serialisation JWT.
    ///
    /// The `kid` header parameter is taken from the signing key
    /// ([`AsymmetricSigningKey::kid`](crate::jwt::AsymmetricSigningKey::kid))
    /// unless overridden via [`key_id`](Self::key_id), so a verifier holding
    /// the matching JWKS can select the right key. The produced token
    /// round-trips through
    /// [`verify_jwt_asymmetric`](crate::jwt::verify_jwt_asymmetric).
    ///
    /// # Security
    ///
    /// The private key never leaves the [`AsymmetricSigningKey`](crate::jwt::AsymmetricSigningKey) and is never
    /// logged. As with [`sign`](Self::sign), `alg=none` is unrepresentable —
    /// the key carries a concrete [`AsymmetricAlgorithm`](crate::jwt::AsymmetricAlgorithm).
    #[cfg(feature = "asym-jwt")]
    #[must_use = "this returns the signed JWT string"]
    pub fn sign_asymmetric(&self, key: &crate::jwt::AsymmetricSigningKey) -> String {
        let kid = self.kid.as_deref().unwrap_or_else(|| key.kid());
        let alg = key.algorithm().as_str();
        let signing_input = self.signing_input(alg, Some(kid));

        let signature_b64 = base64url_encode(&key.sign(signing_input.as_bytes()));

        // SECURITY: never log the private key or the signature value.
        debug!(alg = %alg, "jwt: token minted (asymmetric)");

        let mut token = signing_input;
        token.push('.');
        token.push_str(&signature_b64);
        token
    }

    /// Builds the `base64url(header).base64url(payload)` signing input
    /// (RFC 7515 §5.1). `typ` is fixed to `"JWT"` (RFC 7519 §5.1); `kid` is
    /// emitted when present (RFC 7515 §4.1.4).
    fn signing_input(&self, alg: &str, kid: Option<&str>) -> String {
        let header_json = match kid {
            Some(kid) => format!(
                r#"{{"alg":"{alg}","typ":"JWT","kid":{}}}"#,
                escape_json_string(kid),
            ),
            None => format!(r#"{{"alg":"{alg}","typ":"JWT"}}"#),
        };
        let header_b64 = base64url_encode(header_json.as_bytes());

        let payload_json = self.build_payload_json();
        let payload_b64 = base64url_encode(payload_json.as_bytes());

        super::signature::signing_input(&header_b64, &payload_b64)
    }

    /// Builds the RFC 8259 JSON payload object from the configured claims.
    ///
    /// Registered claims are emitted in a fixed, RFC-order layout followed
    /// by custom claims in insertion order. Numeric claims are written as
    /// integers (no fractional part), matching how
    /// [`JwtClaims`](super::JwtClaims) reads them back as `u64`.
    fn build_payload_json(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        // Names already emitted, so a custom claim cannot produce a duplicate
        // JSON key. Duplicate keys are ambiguous across parsers (first vs last
        // wins) and this crate's own decoder rejects them outright, so a token
        // minted with a colliding custom name would fail its own round-trip.
        let mut seen: Vec<&str> = Vec::new();

        if let Some(iss) = &self.iss {
            parts.push(format!(r#""iss":{}"#, escape_json_string(iss)));
            seen.push("iss");
        }
        if let Some(sub) = &self.sub {
            parts.push(format!(r#""sub":{}"#, escape_json_string(sub)));
            seen.push("sub");
        }
        match self.aud.as_slice() {
            [] => {}
            [single] => {
                parts.push(format!(r#""aud":{}"#, escape_json_string(single)));
                seen.push("aud");
            }
            multiple => {
                let items: Vec<String> = multiple.iter().map(|a| escape_json_string(a)).collect();
                parts.push(format!(r#""aud":[{}]"#, items.join(",")));
                seen.push("aud");
            }
        }
        if let Some(exp) = self.exp {
            parts.push(format!(r#""exp":{exp}"#));
            seen.push("exp");
        }
        if let Some(nbf) = self.nbf {
            parts.push(format!(r#""nbf":{nbf}"#));
            seen.push("nbf");
        }
        if let Some(iat) = self.iat {
            parts.push(format!(r#""iat":{iat}"#));
            seen.push("iat");
        }
        if let Some(jti) = &self.jti {
            parts.push(format!(r#""jti":{}"#, escape_json_string(jti)));
            seen.push("jti");
        }
        if let Some(nonce) = &self.nonce {
            parts.push(format!(r#""nonce":{}"#, escape_json_string(nonce)));
            seen.push("nonce");
        }

        for (name, value) in &self.custom {
            // First occurrence wins: skip a custom name that collides with a
            // registered claim already emitted, or an earlier custom claim.
            if seen.contains(&name.as_str()) {
                continue;
            }
            seen.push(name);
            let rendered = match value {
                CustomClaimValue::Str(s) => escape_json_string(s),
                CustomClaimValue::Bool(b) => b.to_string(),
                CustomClaimValue::Number(n) => n.to_string(),
                CustomClaimValue::StrArray(items) => {
                    let rendered: Vec<String> =
                        items.iter().map(|s| escape_json_string(s)).collect();
                    format!("[{}]", rendered.join(","))
                }
            };
            parts.push(format!("{}:{rendered}", escape_json_string(name)));
        }

        format!("{{{}}}", parts.join(","))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jwt::{JwtAlgorithm, verify_jwt};

    const KEY: &[u8] = b"super-secret-key-for-testing-only";

    // --- Structure ---

    #[test]
    fn minted_token_has_three_segments() {
        let token = JwtEncoder::new().sign(JwtSigningAlgorithm::Hs256, KEY);
        assert_eq!(token.split('.').count(), 3);
    }

    #[test]
    fn empty_encoder_produces_empty_payload_object() {
        let token = JwtEncoder::new().sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(claims.iss(), None);
        assert_eq!(claims.sub(), None);
        assert!(claims.aud().is_empty());
    }

    #[test]
    fn custom_claim_colliding_with_registered_is_dropped() {
        // A custom "sub" must not emit a second "sub" JSON key: the registered
        // setter wins, and the token round-trips through the crate's own
        // decoder (which rejects duplicate keys). A repeated custom name keeps
        // its first value.
        let token = JwtEncoder::new()
            .subject("real-subject")
            .custom_claim("sub", "attacker")
            .custom_claim("role", "admin")
            .custom_claim("role", "user")
            .sign(JwtSigningAlgorithm::Hs256, KEY);

        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(claims.sub(), Some("real-subject"));
        assert_eq!(
            claims.get_claim("role").and_then(|v| v.as_str()),
            Some("admin"),
            "first custom occurrence wins",
        );
    }

    // --- Round-trip against verify_jwt ---

    #[test]
    fn round_trip_hs256() {
        let token = JwtEncoder::new()
            .issuer("https://auth.example.com")
            .subject("user-123")
            .audience("my-client")
            .expiration(9_999_999_999)
            .not_before(1_000)
            .issued_at(1_700_000_000)
            .jwt_id("token-abc")
            .sign(JwtSigningAlgorithm::Hs256, KEY);

        let (header, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(header.alg(), JwtAlgorithm::HS256);
        assert_eq!(header.typ(), Some("JWT"));
        assert_eq!(claims.iss(), Some("https://auth.example.com"));
        assert_eq!(claims.sub(), Some("user-123"));
        assert_eq!(claims.aud(), &["my-client"]);
        assert_eq!(claims.exp(), Some(9_999_999_999));
        assert_eq!(claims.nbf(), Some(1_000));
        assert_eq!(claims.iat(), Some(1_700_000_000));
        assert_eq!(claims.jti(), Some("token-abc"));
    }

    #[test]
    fn round_trip_hs512() {
        let token = JwtEncoder::new()
            .subject("user-9")
            .sign(JwtSigningAlgorithm::Hs512, KEY);
        let (header, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(header.alg(), JwtAlgorithm::HS512);
        assert_eq!(claims.sub(), Some("user-9"));
    }

    #[test]
    fn wrong_key_fails_verification() {
        let token = JwtEncoder::new()
            .subject("user-1")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        assert!(verify_jwt(&token, b"wrong-key").is_err());
    }

    // --- Audience normalisation ---

    #[test]
    fn single_audience_is_emitted_as_string() {
        let token = JwtEncoder::new()
            .audience("only-client")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        // Decode payload directly to confirm it is a JSON string, not array.
        let payload = token.split('.').nth(1).unwrap();
        let bytes = crate::encoding::base64url_decode(payload).unwrap();
        let json = std::str::from_utf8(&bytes).unwrap();
        assert!(json.contains(r#""aud":"only-client""#), "got: {json}");
    }

    #[test]
    fn multiple_audiences_are_emitted_as_array() {
        let token = JwtEncoder::new()
            .audience("client-a")
            .audience("client-b")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(claims.aud(), &["client-a", "client-b"]);
        let payload = token.split('.').nth(1).unwrap();
        let bytes = crate::encoding::base64url_decode(payload).unwrap();
        let json = std::str::from_utf8(&bytes).unwrap();
        assert!(
            json.contains(r#""aud":["client-a","client-b"]"#),
            "got: {json}"
        );
    }

    // --- Custom claims ---

    #[test]
    fn custom_string_claim() {
        let token = JwtEncoder::new()
            .custom_claim("preferred_username", "frodo")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            claims
                .get_claim("preferred_username")
                .and_then(|v| v.as_str()),
            Some("frodo"),
        );
    }

    #[test]
    fn custom_bool_claim() {
        let token = JwtEncoder::new()
            .custom_claim("email_verified", true)
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            claims
                .get_claim("email_verified")
                .and_then(crate::json::JsonValue::as_bool),
            Some(true),
        );
    }

    #[test]
    fn custom_string_array_claim() {
        let token = JwtEncoder::new()
            .custom_claim("roles", ["admin", "developer"])
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        let roles = claims
            .get_claim("roles")
            .and_then(|v| v.as_array())
            .unwrap();
        let names: Vec<&str> = roles.iter().filter_map(|v| v.as_str()).collect();
        assert_eq!(names, ["admin", "developer"]);
    }

    #[test]
    fn custom_claim_accepts_owned_string_and_vec() {
        let token = JwtEncoder::new()
            .custom_claim("tenant".to_string(), String::from("entropy"))
            .custom_claim("groups", vec!["a".to_string(), "b".to_string()])
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            claims.get_claim("tenant").and_then(|v| v.as_str()),
            Some("entropy")
        );
        assert_eq!(
            claims
                .get_claim("groups")
                .and_then(|v| v.as_array())
                .unwrap()
                .len(),
            2
        );
    }

    #[test]
    fn nonce_claim_round_trips() {
        let token = JwtEncoder::new()
            .nonce("n-0S6_WzA2Mj")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            claims.get_claim("nonce").and_then(|v| v.as_str()),
            Some("n-0S6_WzA2Mj")
        );
    }

    // --- JSON escaping ---

    #[test]
    fn escapes_special_characters_in_string_claims() {
        let token = JwtEncoder::new()
            .subject("a\"b\\c\nd")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(claims.sub(), Some("a\"b\\c\nd"));
    }

    #[test]
    fn escapes_control_characters() {
        let token = JwtEncoder::new()
            .subject("tab\there")
            .custom_claim("x", "\u{1}\u{1f}")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        // Must still parse — escaping kept the JSON well-formed.
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(claims.sub(), Some("tab\there"));
        assert_eq!(
            claims.get_claim("x").and_then(|v| v.as_str()),
            Some("\u{1}\u{1f}")
        );
    }

    #[test]
    fn preserves_non_ascii_unicode() {
        let token = JwtEncoder::new()
            .custom_claim("name", "Sméagol 🧙")
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            claims.get_claim("name").and_then(|v| v.as_str()),
            Some("Sméagol 🧙")
        );
    }

    // --- Algorithm enum ---

    #[test]
    fn signing_algorithm_as_str() {
        assert_eq!(JwtSigningAlgorithm::Hs256.as_str(), "HS256");
        assert_eq!(JwtSigningAlgorithm::Hs512.as_str(), "HS512");
    }

    #[test]
    fn signing_algorithm_maps_to_jwt_algorithm() {
        assert_eq!(
            JwtSigningAlgorithm::Hs256.to_jwt_algorithm(),
            JwtAlgorithm::HS256
        );
        assert_eq!(
            JwtSigningAlgorithm::Hs512.to_jwt_algorithm(),
            JwtAlgorithm::HS512
        );
    }

    // --- RFC 7515 Appendix A.1 known structure ---

    #[test]
    fn header_segment_matches_expected_for_hs256() {
        // The fixed header {"alg":"HS256","typ":"JWT"} base64url-encodes to
        // a stable value; verifying it pins the encoder's header layout.
        let token = JwtEncoder::new().sign(JwtSigningAlgorithm::Hs256, KEY);
        let header_b64 = token.split('.').next().unwrap();
        let decoded = crate::encoding::base64url_decode(header_b64).unwrap();
        assert_eq!(
            std::str::from_utf8(&decoded).unwrap(),
            r#"{"alg":"HS256","typ":"JWT"}"#,
        );
    }
}