rainier-crypt 2.0.0

Authenticated encryption and message signing for Rainier.
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
//! JWTs and a JWKS document (feature `jwt`).
//!
//! ```ignore
//! let jwt = Jwt::new(ring).issued_by("https://id.example.com").for_audience("api");
//!
//! let token = jwt.sign(&claims)?;
//! let claims: Claims = jwt.verify(&token)?;
//!
//! // /.well-known/jwks.json
//! Response::json(&jwt.jwks())
//! ```
//!
//! # Why this is here and not left to an application
//!
//! `rainier-crypt` had exactly one asymmetric signer — Ed25519 — and OIDC
//! relying parties expect **RS256**. So the one asymmetric algorithm the
//! framework shipped could not do the one asymmetric job an identity provider
//! has, and every such application wrote key loading, rotation and a JWKS
//! serialiser itself.
//!
//! It is also not only for issuers. Anything that *verifies* a third-party
//! token — a Google ID token, an Apple one, a Kubernetes service-account token
//! — needs the same key ring keyed by `kid`, and the same rule about which
//! keys are still acceptable.
//!
//! # Rotation is an overlap, not a switch
//!
//! Signing keys rotate; tokens already issued keep arriving. So a ring
//! **signs with the newest key and verifies against every key it still
//! holds**, and a key is retired in two steps: stop signing with it, then —
//! once every token it signed has expired — remove it.
//!
//! Publishing the JWKS is what makes that work for somebody else's verifier:
//! it lists every key that can still verify, so a relying party that refreshes
//! its copy keeps accepting tokens across the change. Removing a key from the
//! JWKS the moment it stops signing is the classic mistake, and it invalidates
//! every unexpired token that key issued.
//!
//! # This is not an OAuth server
//!
//! Sign, verify, rotate, publish. Grants, consent, PKCE and the endpoints
//! around them are an application's business — they are where the product is,
//! and a framework that shipped them would be shipping opinions about a
//! product.

use std::sync::Arc;

use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
use base64::Engine as _;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
use rainier_support::{Error, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Value};

/// The signature algorithms this supports.
///
/// Both are asymmetric and both are what relying parties actually ask for.
/// HMAC (`HS256`) is deliberately absent: a symmetric JWT cannot be verified
/// by anyone who cannot also *mint* one, which makes a published JWKS
/// meaningless and is the wrong shape for every use here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JwtAlgorithm {
    /// RSASSA-PKCS1-v1_5 with SHA-256. What OIDC relying parties expect.
    Rs256,
    /// ECDSA over P-256 with SHA-256. Smaller keys and signatures; not every
    /// relying party accepts it.
    Es256,
}

impl JwtAlgorithm {
    fn as_jsonwebtoken(self) -> Algorithm {
        match self {
            Self::Rs256 => Algorithm::RS256,
            Self::Es256 => Algorithm::ES256,
        }
    }

    /// The `alg` value a JWK carries.
    pub fn name(self) -> &'static str {
        match self {
            Self::Rs256 => "RS256",
            Self::Es256 => "ES256",
        }
    }
}

/// One signing key, with the public half a JWKS needs.
pub struct JwtKey {
    kid: String,
    algorithm: JwtAlgorithm,
    encoding: EncodingKey,
    decoding: DecodingKey,
    /// The public JWK, minus the fields the ring fills in.
    jwk: Value,
}

impl JwtKey {
    /// An RS256 key from a PKCS#8 PEM private key.
    ///
    /// The `kid` is yours to choose and travels in every token's header, so it
    /// has to be stable across restarts — a random one per boot means every
    /// token issued before the last deploy stops verifying.
    pub fn rs256_from_pem(kid: impl Into<String>, pem: &str) -> Result<Self> {
        use rsa::pkcs1::DecodeRsaPrivateKey;
        use rsa::pkcs8::DecodePrivateKey;
        use rsa::traits::PublicKeyParts;
        use rsa::RsaPrivateKey;

        // Both spellings are in the wild: `BEGIN PRIVATE KEY` (PKCS#8) and
        // `BEGIN RSA PRIVATE KEY` (PKCS#1). Refusing one of them would be a
        // support question rather than a security property.
        let private = RsaPrivateKey::from_pkcs8_pem(pem)
            .or_else(|_| RsaPrivateKey::from_pkcs1_pem(pem))
            .map_err(|e| Error::internal(format!("could not read the RSA private key: {e}")))?;

        let public = private.to_public_key();
        let jwk = json!({
            "kty": "RSA",
            "n": B64URL.encode(public.n().to_bytes_be()),
            "e": B64URL.encode(public.e().to_bytes_be()),
        });

        Ok(Self {
            kid: kid.into(),
            algorithm: JwtAlgorithm::Rs256,
            encoding: EncodingKey::from_rsa_pem(pem.as_bytes())
                .map_err(|e| Error::internal(format!("could not load the RSA key: {e}")))?,
            decoding: DecodingKey::from_rsa_pem(public_pem(&public)?.as_bytes())
                .map_err(|e| Error::internal(format!("could not load the RSA key: {e}")))?,
            jwk,
        })
    }

    /// An ES256 key from a PKCS#8 PEM private key.
    pub fn es256_from_pem(kid: impl Into<String>, pem: &str) -> Result<Self> {
        use p256::elliptic_curve::sec1::ToEncodedPoint;
        use p256::pkcs8::DecodePrivateKey;
        use p256::SecretKey;

        let secret = SecretKey::from_pkcs8_pem(pem)
            .map_err(|e| Error::internal(format!("could not read the P-256 private key: {e}")))?;

        let point = secret.public_key().to_encoded_point(false);
        let jwk = json!({
            "kty": "EC",
            "crv": "P-256",
            "x": B64URL.encode(point.x().ok_or_else(|| Error::internal("no x coordinate"))?),
            "y": B64URL.encode(point.y().ok_or_else(|| Error::internal("no y coordinate"))?),
        });

        let public_pem = {
            use p256::pkcs8::EncodePublicKey;
            secret
                .public_key()
                .to_public_key_pem(Default::default())
                .map_err(|e| Error::internal(format!("could not encode the public key: {e}")))?
        };

        Ok(Self {
            kid: kid.into(),
            algorithm: JwtAlgorithm::Es256,
            encoding: EncodingKey::from_ec_pem(pem.as_bytes())
                .map_err(|e| Error::internal(format!("could not load the P-256 key: {e}")))?,
            decoding: DecodingKey::from_ec_pem(public_pem.as_bytes())
                .map_err(|e| Error::internal(format!("could not load the P-256 key: {e}")))?,
            jwk,
        })
    }

    /// Generate an RS256 key. **For tests and for a first boot.**
    ///
    /// A key generated at boot is a key that changes on restart, so every
    /// token issued before it stops verifying — fine for a test, and a source
    /// of intermittent logouts anywhere else.
    pub fn generate_rs256(kid: impl Into<String>, bits: usize) -> Result<Self> {
        use rsa::pkcs8::{EncodePrivateKey, LineEnding};
        use rsa::RsaPrivateKey;

        let private = RsaPrivateKey::new(&mut rand::thread_rng(), bits)
            .map_err(|e| Error::internal(format!("could not generate an RSA key: {e}")))?;
        let pem = private
            .to_pkcs8_pem(LineEnding::LF)
            .map_err(|e| Error::internal(format!("could not encode the key: {e}")))?;

        Self::rs256_from_pem(kid, &pem)
    }

    /// Generate an ES256 key. **For tests and for a first boot** — see
    /// [`generate_rs256`](Self::generate_rs256).
    pub fn generate_es256(kid: impl Into<String>) -> Result<Self> {
        use p256::pkcs8::{EncodePrivateKey, LineEnding};

        let secret = p256::SecretKey::random(&mut rand::thread_rng());
        let pem = secret
            .to_pkcs8_pem(LineEnding::LF)
            .map_err(|e| Error::internal(format!("could not encode the key: {e}")))?;

        Self::es256_from_pem(kid, &pem)
    }

    /// The key id.
    pub fn kid(&self) -> &str {
        &self.kid
    }

    /// The algorithm.
    pub fn algorithm(&self) -> JwtAlgorithm {
        self.algorithm
    }

    /// The public JWK, as a JWKS entry.
    pub fn to_jwk(&self) -> Value {
        let mut jwk = self.jwk.clone();
        jwk["kid"] = json!(self.kid);
        jwk["alg"] = json!(self.algorithm.name());
        jwk["use"] = json!("sig");
        jwk
    }
}

impl std::fmt::Debug for JwtKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JwtKey")
            .field("kid", &self.kid)
            .field("algorithm", &self.algorithm)
            .finish()
    }
}

/// The keys this service signs and verifies with.
///
/// Signs with the **first**; verifies against **any**. See the module docs for
/// why retiring one is two steps.
#[derive(Debug, Default)]
pub struct JwtKeyRing {
    keys: Vec<Arc<JwtKey>>,
}

impl JwtKeyRing {
    /// A ring signing with `key`.
    pub fn new(key: JwtKey) -> Self {
        Self { keys: vec![Arc::new(key)] }
    }

    /// Also verify tokens signed by `key`, without signing new ones with it.
    ///
    /// The middle step of a rotation. Keep it here until every token it signed
    /// has expired.
    #[must_use = "this returns a ring with the key added"]
    pub fn with_previous(mut self, key: JwtKey) -> Self {
        self.keys.push(Arc::new(key));
        self
    }

    /// The key new tokens are signed with.
    pub fn current(&self) -> Option<&Arc<JwtKey>> {
        self.keys.first()
    }

    /// The key with this id, if the ring holds it.
    pub fn find(&self, kid: &str) -> Option<&Arc<JwtKey>> {
        self.keys.iter().find(|key| key.kid == kid)
    }

    /// Every key id, current first.
    pub fn ids(&self) -> Vec<&str> {
        self.keys.iter().map(|key| key.kid.as_str()).collect()
    }

    /// The JWKS document.
    ///
    /// Every key that can still verify, which is the whole ring — not just the
    /// signing one. Publishing only the current key invalidates every
    /// unexpired token the previous one issued, which is the classic way to
    /// break a rotation.
    pub fn jwks(&self) -> Value {
        json!({ "keys": self.keys.iter().map(|key| key.to_jwk()).collect::<Vec<_>>() })
    }
}

/// Signs and verifies tokens.
pub struct Jwt {
    ring: JwtKeyRing,
    issuer: Option<String>,
    audience: Vec<String>,
    leeway: u64,
}

impl Jwt {
    /// Sign and verify with `ring`.
    pub fn new(ring: JwtKeyRing) -> Self {
        Self { ring, issuer: None, audience: Vec::new(), leeway: 60 }
    }

    /// Set the `iss` this service claims, and require it when verifying.
    #[must_use = "this returns a configured signer rather than configuring in place"]
    pub fn issued_by(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Require this `aud` when verifying.
    ///
    /// Worth setting. A token minted for one audience being accepted by
    /// another is how a token issued for an analytics API turns into one that
    /// works against the admin API.
    #[must_use = "this returns a configured signer rather than configuring in place"]
    pub fn for_audience(mut self, audience: impl Into<String>) -> Self {
        self.audience.push(audience.into());
        self
    }

    /// How much clock skew to tolerate on `exp` and `nbf`, in seconds.
    ///
    /// Sixty by default. Zero means a verifier whose clock is a second behind
    /// the issuer's rejects freshly minted tokens, which is a bug that only
    /// appears on somebody else's machine.
    #[must_use = "this returns a configured signer rather than configuring in place"]
    pub fn leeway(mut self, seconds: u64) -> Self {
        self.leeway = seconds;
        self
    }

    /// The key ring.
    pub fn ring(&self) -> &JwtKeyRing {
        &self.ring
    }

    /// The JWKS document — see [`JwtKeyRing::jwks`].
    pub fn jwks(&self) -> Value {
        self.ring.jwks()
    }

    /// Sign `claims` with the current key.
    ///
    /// The header carries the `kid`, which is what lets a verifier pick the
    /// right key out of a JWKS instead of trying all of them.
    pub fn sign<C: Serialize>(&self, claims: &C) -> Result<String> {
        let key = self.ring.current().ok_or_else(|| {
            Error::internal("the JWT key ring is empty, so nothing can be signed")
        })?;

        let mut header = Header::new(key.algorithm.as_jsonwebtoken());
        header.kid = Some(key.kid.clone());

        jsonwebtoken::encode(&header, claims, &key.encoding)
            .map_err(|e| Error::internal(format!("could not sign the token: {e}")))
    }

    /// Verify `token` and return its claims.
    ///
    /// Checks the signature, `exp`, `nbf`, and — when configured — `iss` and
    /// `aud`.
    ///
    /// # Errors
    ///
    /// A `401` for anything wrong with the token, with the reason in the
    /// message: an unknown `kid`, a bad signature, an expired token, the wrong
    /// issuer.
    pub fn verify<C: DeserializeOwned>(&self, token: &str) -> Result<C> {
        let header = jsonwebtoken::decode_header(token)
            .map_err(|_| Error::unauthenticated("This token is not readable."))?;

        let kid = header.kid.ok_or_else(|| Error::unauthenticated("This token names no key."))?;

        // By id, rather than trying every key. A token that names a key this
        // service does not hold is not a token worth spending CPU on, and
        // trying them all would make an unknown-key token cost the same as a
        // real one.
        let key = self.ring.find(&kid).ok_or_else(|| {
            Error::unauthenticated("This token names a key this service does not hold.")
        })?;

        // The algorithm from the **key**, never from the token's header. A
        // verifier that trusts the header's `alg` is the classic JWT
        // vulnerability: a forged header saying `none`, or saying `HS256` over
        // a public key everybody has.
        let mut validation = Validation::new(key.algorithm.as_jsonwebtoken());
        validation.leeway = self.leeway;

        if let Some(issuer) = &self.issuer {
            validation.set_issuer(&[issuer]);
        }
        if !self.audience.is_empty() {
            validation.set_audience(&self.audience);
        } else {
            // Otherwise `jsonwebtoken` refuses a token carrying an `aud` this
            // service did not ask about, which is not what "no audience
            // configured" should mean.
            validation.validate_aud = false;
        }

        jsonwebtoken::decode::<C>(token, &key.decoding, &validation)
            .map(|data| data.claims)
            .map_err(|e| Error::unauthenticated(format!("This token is not valid: {e}")))
    }

    /// The `kid` a token names, without verifying it.
    ///
    /// For deciding whether a JWKS needs refreshing before rejecting the
    /// token — which is the difference between a rotation that costs nothing
    /// and one that rejects traffic for a cache lifetime.
    pub fn kid_of(token: &str) -> Option<String> {
        jsonwebtoken::decode_header(token).ok()?.kid
    }
}

impl std::fmt::Debug for Jwt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Jwt")
            .field("keys", &self.ring.ids())
            .field("issuer", &self.issuer)
            .field("audience", &self.audience)
            .finish()
    }
}

/// An RSA public key as PEM, which is what `DecodingKey` wants.
fn public_pem(public: &rsa::RsaPublicKey) -> Result<String> {
    use rsa::pkcs8::{EncodePublicKey, LineEnding};

    public
        .to_public_key_pem(LineEnding::LF)
        .map_err(|e| Error::internal(format!("could not encode the public key: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct Claims {
        sub: String,
        exp: i64,
        #[serde(skip_serializing_if = "Option::is_none")]
        iss: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        aud: Option<String>,
    }

    fn in_an_hour() -> i64 {
        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64
            + 3600
    }

    fn claims() -> Claims {
        Claims { sub: "user-42".into(), exp: in_an_hour(), iss: None, aud: None }
    }

    /// 2048 bits, generated once per test binary: RSA key generation is slow
    /// enough that doing it per test doubles the suite's runtime.
    fn rsa_key() -> &'static JwtKey {
        use std::sync::OnceLock;
        static KEY: OnceLock<JwtKey> = OnceLock::new();
        KEY.get_or_init(|| JwtKey::generate_rs256("test-rsa", 2048).expect("generate"))
    }

    fn rsa_jwt() -> Jwt {
        Jwt::new(JwtKeyRing::new(JwtKey::rs256_from_pem("test-rsa", &rsa_pem()).expect("from pem")))
    }

    /// The same key material as `rsa_key`, re-encoded — so two `Jwt`s in one
    /// test share a key without generating two.
    fn rsa_pem() -> String {
        use rsa::pkcs8::{EncodePrivateKey, LineEnding};
        use std::sync::OnceLock;
        static PEM: OnceLock<String> = OnceLock::new();

        PEM.get_or_init(|| {
            let private = rsa::RsaPrivateKey::new(&mut rand::thread_rng(), 2048).expect("generate");
            private.to_pkcs8_pem(LineEnding::LF).expect("encode").to_string()
        })
        .clone()
    }

    #[test]
    fn an_rs256_token_round_trips() {
        let jwt = rsa_jwt();
        let token = jwt.sign(&claims()).unwrap();

        assert_eq!(jwt.verify::<Claims>(&token).unwrap().sub, "user-42");
    }

    #[test]
    fn an_es256_token_round_trips() {
        let jwt = Jwt::new(JwtKeyRing::new(JwtKey::generate_es256("test-ec").unwrap()));
        let token = jwt.sign(&claims()).unwrap();

        assert_eq!(jwt.verify::<Claims>(&token).unwrap().sub, "user-42");
    }

    #[test]
    fn the_header_names_the_key() {
        // Which is what lets a verifier pick one out of a JWKS rather than
        // trying all of them.
        let token = rsa_jwt().sign(&claims()).unwrap();

        assert_eq!(Jwt::kid_of(&token).as_deref(), Some("test-rsa"));
    }

    #[test]
    fn a_tampered_token_does_not_verify() {
        let jwt = rsa_jwt();
        let token = jwt.sign(&claims()).unwrap();

        // Flip a character in the payload segment.
        let mut parts: Vec<&str> = token.split('.').collect();
        let payload = parts[1].to_string();
        let tampered_payload = format!("{}A", &payload[..payload.len() - 1]);
        parts[1] = &tampered_payload;

        assert!(jwt.verify::<Claims>(&parts.join(".")).is_err());
    }

    #[test]
    fn an_expired_token_does_not_verify() {
        let jwt = rsa_jwt();
        let expired = Claims { exp: 1, ..claims() };

        let token = jwt.sign(&expired).unwrap();

        assert!(jwt.verify::<Claims>(&token).is_err());
    }

    #[test]
    fn a_token_from_another_key_does_not_verify() {
        let token = rsa_jwt().sign(&claims()).unwrap();

        let stranger = Jwt::new(JwtKeyRing::new(
            JwtKey::rs256_from_pem("test-rsa", &other_pem()).expect("from pem"),
        ));

        assert!(stranger.verify::<Claims>(&token).is_err());
    }

    fn other_pem() -> String {
        use rsa::pkcs8::{EncodePrivateKey, LineEnding};
        use std::sync::OnceLock;
        static PEM: OnceLock<String> = OnceLock::new();

        PEM.get_or_init(|| {
            let private = rsa::RsaPrivateKey::new(&mut rand::thread_rng(), 2048).expect("generate");
            private.to_pkcs8_pem(LineEnding::LF).expect("encode").to_string()
        })
        .clone()
    }

    #[test]
    fn an_unknown_kid_is_refused_without_trying_every_key() {
        let jwt = rsa_jwt();
        let token = jwt.sign(&claims()).unwrap();

        // Re-sign under a ring that does not hold this kid.
        let other = Jwt::new(JwtKeyRing::new(JwtKey::generate_es256("somebody-else").unwrap()));

        let error = other.verify::<Claims>(&token).unwrap_err();
        assert!(error.message().contains("does not hold"), "{}", error.message());
    }

    #[test]
    fn a_rotation_keeps_verifying_the_previous_keys_tokens() {
        // The whole point of an overlap. A token signed before the rotation
        // has to keep working until it expires.
        let old = JwtKey::rs256_from_pem("old", &rsa_pem()).unwrap();
        let signed_before = Jwt::new(JwtKeyRing::new(old)).sign(&claims()).unwrap();

        let rotated = Jwt::new(
            JwtKeyRing::new(JwtKey::generate_es256("new").unwrap())
                .with_previous(JwtKey::rs256_from_pem("old", &rsa_pem()).unwrap()),
        );

        assert!(rotated.verify::<Claims>(&signed_before).is_ok());

        // And new tokens use the new key.
        let signed_after = rotated.sign(&claims()).unwrap();
        assert_eq!(Jwt::kid_of(&signed_after).as_deref(), Some("new"));
    }

    #[test]
    fn the_jwks_lists_every_key_that_can_still_verify() {
        // Publishing only the signing key invalidates every unexpired token
        // the previous one issued — the classic way to break a rotation.
        let ring = JwtKeyRing::new(JwtKey::generate_es256("new").unwrap())
            .with_previous(JwtKey::rs256_from_pem("old", &rsa_pem()).unwrap());

        let jwks = ring.jwks();
        let keys = jwks["keys"].as_array().unwrap();

        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0]["kid"], "new");
        assert_eq!(keys[1]["kid"], "old");
    }

    #[test]
    fn a_jwks_entry_is_the_shape_a_relying_party_reads() {
        let jwks = JwtKeyRing::new(JwtKey::rs256_from_pem("k1", &rsa_pem()).unwrap()).jwks();
        let key = &jwks["keys"][0];

        assert_eq!(key["kty"], "RSA");
        assert_eq!(key["alg"], "RS256");
        assert_eq!(key["use"], "sig");
        assert_eq!(key["kid"], "k1");
        // The modulus and exponent, base64url with no padding.
        assert!(key["n"].as_str().unwrap().len() > 300);
        assert_eq!(key["e"].as_str().unwrap(), "AQAB", "65537, as every RSA key uses");
        assert!(!key["n"].as_str().unwrap().contains('='), "base64url is unpadded");
    }

    #[test]
    fn an_ec_jwks_entry_carries_its_curve_and_point() {
        let jwks = JwtKeyRing::new(JwtKey::generate_es256("k1").unwrap()).jwks();
        let key = &jwks["keys"][0];

        assert_eq!(key["kty"], "EC");
        assert_eq!(key["crv"], "P-256");
        assert_eq!(key["alg"], "ES256");
        // P-256 coordinates are 32 bytes, so 43 base64url characters.
        assert_eq!(key["x"].as_str().unwrap().len(), 43);
        assert_eq!(key["y"].as_str().unwrap().len(), 43);
    }

    #[test]
    fn the_issuer_is_checked_when_it_is_configured() {
        let signer = rsa_jwt().issued_by("https://id.example.com");
        let token = signer
            .sign(&Claims { iss: Some("https://id.example.com".into()), ..claims() })
            .unwrap();

        assert!(signer.verify::<Claims>(&token).is_ok());

        // A token from somewhere else, signed with the same key, is refused.
        let impostor = signer
            .sign(&Claims { iss: Some("https://evil.example.com".into()), ..claims() })
            .unwrap();
        assert!(signer.verify::<Claims>(&impostor).is_err());
    }

    #[test]
    fn the_audience_is_checked_when_it_is_configured() {
        // A token minted for one audience being accepted by another is how a
        // token for an analytics API turns into one for the admin API.
        let signer = rsa_jwt().for_audience("api");

        let right = signer.sign(&Claims { aud: Some("api".into()), ..claims() }).unwrap();
        assert!(signer.verify::<Claims>(&right).is_ok());

        let wrong = signer.sign(&Claims { aud: Some("analytics".into()), ..claims() }).unwrap();
        assert!(signer.verify::<Claims>(&wrong).is_err());
    }

    #[test]
    fn a_token_with_an_audience_verifies_when_none_is_configured() {
        // "No audience configured" must mean "do not check", not "refuse
        // anything that has one".
        let jwt = rsa_jwt();
        let token = jwt.sign(&Claims { aud: Some("api".into()), ..claims() }).unwrap();

        assert!(jwt.verify::<Claims>(&token).is_ok());
    }

    #[test]
    fn nonsense_is_refused_without_panicking() {
        let jwt = rsa_jwt();

        for token in ["", "not.a.token", "a.b", &"x".repeat(5000)] {
            assert!(jwt.verify::<Claims>(token).is_err(), "{token:?}");
        }
    }

    #[test]
    fn an_empty_ring_cannot_sign() {
        let jwt = Jwt::new(JwtKeyRing::default());

        let error = jwt.sign(&claims()).unwrap_err();
        assert!(error.message().contains("empty"), "{}", error.message());
    }

    #[test]
    fn a_generated_key_can_be_read_back_from_its_own_pem() {
        // The path an application takes on a first boot: generate, save, load.
        let key = rsa_key();

        assert_eq!(key.kid(), "test-rsa");
        assert_eq!(key.algorithm(), JwtAlgorithm::Rs256);
        assert_eq!(key.to_jwk()["kty"], "RSA");
    }
}