Skip to main content

auth_framework/server/jwt/
private_key_jwt.rs

1//! RFC 7523: JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants
2//!
3//! This module implements private key JWT client authentication, allowing clients
4//! to authenticate using JWTs signed with their private keys.
5//!
6//! ## Security properties
7//!
8//! - **Real public-key verification**: the registered JWK is turned into a genuine
9//!   RSA / EC / Ed25519 verification key. Symmetric (`HS*`) algorithms are refused at
10//!   registration, and the algorithm used for verification is the one in the
11//!   assertion's header, accepted only if it is on the client's allow-list *and*
12//!   belongs to the registered key's family.
13//! - **Audience**: every client must be registered with the audience value(s) it may
14//!   present (the token endpoint URL(s)); an assertion is accepted only if its `aud`
15//!   is one of them.
16//! - **Verified claims only**: the client is looked up from the unverified `iss`
17//!   solely to find its key; every decision afterwards uses the claims returned by
18//!   signature verification.
19//! - **Replay protection**: a `jti` is claimed atomically, per client, and only after
20//!   everything else has passed; it is remembered until the assertion can no longer be
21//!   accepted (`exp` plus the clock skew), whatever the cleanup interval. Revoked `jti`s are
22//!   refused.
23//! - **No client enumeration by answer**: an unknown client and an assertion whose signature
24//!   does not verify get the same answer. Detailed reasons are given only once the key has
25//!   proved the assertion genuine. (The unknown-client path does not parse a key or verify a
26//!   signature, so it is faster; a `client_id` is not a secret, and rate limiting belongs at
27//!   the edge.)
28//! - **Bounded memory**: at most 5,000 unexpired `jti`s per client
29//!   (default 5,000) and 100,000 in all, so one client cannot lock the others out.
30//!
31//! ## Things to know
32//!
33//! - Replay protection and `jti` revocation are in memory, per manager instance. Revoked
34//!   assertion `jti`s are kept in their own namespace (`private_key_jwt:` prefix) of the
35//!   validator's revocation list, so they never collide with access-token `jti`s.
36//! - `iat` is optional (RFC 7523 does not require it). With it, `exp - iat` is bounded by the
37//!   client's maximum lifetime; without it, `exp` may not be further ahead than that maximum
38//!   plus the clock skew.
39//! - There is no `kid` handling or key rotation: one JWK per client; replace it by registering
40//!   the client again. A JWK's own `alg` member is not consulted (the allow-list decides, which
41//!   is the safe direction).
42//!
43//! ## Usage Example
44//!
45//! ```rust,no_run
46//! use auth_framework::server::jwt::private_key_jwt::{PrivateKeyJwtManager, ClientJwtConfig};
47//! use auth_framework::{SecureJwtValidator, SecureJwtConfig};
48//! use chrono::Duration;
49//! use jsonwebtoken::Algorithm;
50//!
51//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
52//! // `Default` generates a fresh random secret per instance.
53//! // Pass an explicit `jwt_secret` when running multiple nodes that share a key.
54//! let jwt_config = SecureJwtConfig {
55//!     jwt_secret: std::env::var("JWT_SECRET").expect("JWT_SECRET must be set").into(),
56//!     ..SecureJwtConfig::default()
57//! };
58//! let jwt_validator = SecureJwtValidator::new(jwt_config);
59//!
60//! // Create manager with custom cleanup interval
61//! let manager = PrivateKeyJwtManager::new(jwt_validator)
62//!     .with_cleanup_interval(Duration::minutes(30));
63//!
64//! // Configure client for JWT authentication
65//! let config = ClientJwtConfig::builder(
66//!     "example_client",
67//!     serde_json::json!({"kty": "RSA", "n": "...", "e": "AQAB"}),
68//! )
69//! .rs256_only()
70//! .audience("https://api.example.com")
71//! .build();
72//!
73//! manager.register_client(config).await?;
74//!
75//! // Authenticate client with JWT assertion
76//! let client_assertion = "eyJ..."; // JWT assertion from client
77//! let auth_result = manager.authenticate_client(client_assertion).await?;
78//!
79//! if auth_result.authenticated {
80//!     println!("Client authenticated successfully");
81//!     // Process authenticated client...
82//! }
83//!
84//! // Perform scheduled cleanup
85//! manager.schedule_automatic_cleanup().await;
86//! # Ok(())
87//! # }
88//! ```
89
90use crate::errors::{AuthError, Result};
91use crate::security::secure_jwt::SecureJwtValidator;
92use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
93use chrono::{DateTime, Duration, Utc};
94use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
95use serde::{Deserialize, Serialize};
96use std::collections::HashMap;
97
98/// Smallest RSA modulus (in bits) accepted for a registered client key.
99const MIN_RSA_MODULUS_BITS: usize = 2048;
100
101/// Largest assertion (bytes) that is looked at at all.
102const MAX_ASSERTION_BYTES: usize = 8 * 1024;
103
104/// Longest `jti` accepted.
105const MAX_JTI_BYTES: usize = 256;
106
107/// Longest `client_id` accepted at registration.
108const MAX_CLIENT_ID_BYTES: usize = 256;
109
110/// Most unexpired `jti`s remembered in all; beyond this new assertions are refused (fail closed).
111const MAX_TRACKED_JTIS: usize = 100_000;
112
113/// Most unexpired assertions (distinct `jti`s) remembered per client; further ones are refused
114/// until older ones expire, so one client cannot use up the room of the others.
115const DEFAULT_MAX_OUTSTANDING_ASSERTIONS: usize = 5_000;
116
117/// Above this many remembered `jti`s, expired ones are dropped on a claim...
118const JTI_SWEEP_THRESHOLD: usize = 1024;
119
120/// ...but at most this often (seconds): a sweep scans the whole map under the write lock.
121const JTI_SWEEP_INTERVAL_SECS: i64 = 5;
122
123/// Namespace of assertion `jti`s in the validator's revocation list.
124const REVOCATION_NAMESPACE: &str = "private_key_jwt:";
125
126/// What is said about an unknown client or an assertion that is not proven genuine.
127const GENERIC_REJECTION: &str = "Client authentication failed";
128
129/// JWK members that only a private or symmetric key carries. A registered
130/// client key must be a public key.
131const PRIVATE_JWK_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "oth", "k"];
132
133/// Private Key JWT claims for client authentication
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct PrivateKeyJwtClaims {
136    /// Issuer - must equal the client_id
137    pub iss: String,
138
139    /// Subject - must equal the client_id
140    pub sub: String,
141
142    /// Audience - authorization server token endpoint
143    pub aud: String,
144
145    /// JWT ID for replay protection
146    pub jti: String,
147
148    /// Expiration time
149    pub exp: i64,
150
151    /// Issued at time. RFC 7523 does not require it: an assertion without one is read as `0`,
152    /// which is treated as "absent" (the lifetime is then bounded through `exp` alone).
153    #[serde(default)]
154    pub iat: i64,
155
156    /// Not before time (optional)
157    pub nbf: Option<i64>,
158}
159
160/// Client JWT configuration for private key authentication
161#[derive(Debug, Clone)]
162pub struct ClientJwtConfig {
163    /// Client identifier
164    pub client_id: String,
165
166    /// Public key for JWT verification (JWK format)
167    pub public_key_jwk: serde_json::Value,
168
169    /// Allowed signing algorithms (asymmetric only; `HS*` is refused at registration)
170    pub allowed_algorithms: Vec<Algorithm>,
171
172    /// Maximum JWT lifetime (default: 5 minutes)
173    pub max_jwt_lifetime: Duration,
174
175    /// Clock skew tolerance (default: 60 seconds)
176    pub clock_skew: Duration,
177
178    /// Audience values (token endpoint URLs) an assertion may be addressed to.
179    /// Registration requires at least one.
180    pub expected_audiences: Vec<String>,
181}
182
183impl ClientJwtConfig {
184    /// Create a builder for private key JWT client configuration.
185    pub fn builder(
186        client_id: impl Into<String>,
187        public_key_jwk: serde_json::Value,
188    ) -> ClientJwtConfigBuilder {
189        ClientJwtConfigBuilder {
190            client_id: client_id.into(),
191            public_key_jwk,
192            allowed_algorithms: vec![Algorithm::RS256, Algorithm::ES256],
193            max_jwt_lifetime: Duration::minutes(5),
194            clock_skew: Duration::seconds(60),
195            expected_audiences: Vec::new(),
196        }
197    }
198}
199
200/// Builder for private key JWT client configuration.
201pub struct ClientJwtConfigBuilder {
202    client_id: String,
203    public_key_jwk: serde_json::Value,
204    allowed_algorithms: Vec<Algorithm>,
205    max_jwt_lifetime: Duration,
206    clock_skew: Duration,
207    expected_audiences: Vec<String>,
208}
209
210impl ClientJwtConfigBuilder {
211    /// Restrict signing to RS256 only.
212    pub fn rs256_only(mut self) -> Self {
213        self.allowed_algorithms = vec![Algorithm::RS256];
214        self
215    }
216
217    /// Replace the allowed algorithm list.
218    pub fn algorithms(mut self, algorithms: Vec<Algorithm>) -> Self {
219        self.allowed_algorithms = algorithms;
220        self
221    }
222
223    /// Set the maximum JWT lifetime.
224    pub fn max_jwt_lifetime(mut self, max_jwt_lifetime: Duration) -> Self {
225        self.max_jwt_lifetime = max_jwt_lifetime;
226        self
227    }
228
229    /// Set the clock skew tolerance.
230    pub fn clock_skew(mut self, clock_skew: Duration) -> Self {
231        self.clock_skew = clock_skew;
232        self
233    }
234
235    /// Add one expected audience.
236    pub fn audience(mut self, audience: impl Into<String>) -> Self {
237        self.expected_audiences.push(audience.into());
238        self
239    }
240
241    /// Replace the expected audience list.
242    pub fn audiences<I, S>(mut self, audiences: I) -> Self
243    where
244        I: IntoIterator<Item = S>,
245        S: Into<String>,
246    {
247        self.expected_audiences = audiences.into_iter().map(Into::into).collect();
248        self
249    }
250
251    /// Build the client JWT configuration.
252    pub fn build(self) -> ClientJwtConfig {
253        ClientJwtConfig {
254            client_id: self.client_id,
255            public_key_jwk: self.public_key_jwk,
256            allowed_algorithms: self.allowed_algorithms,
257            max_jwt_lifetime: self.max_jwt_lifetime,
258            clock_skew: self.clock_skew,
259            expected_audiences: self.expected_audiences,
260        }
261    }
262}
263
264/// JWT authentication result
265#[derive(Debug, Clone)]
266pub struct JwtAuthResult {
267    /// Client identifier
268    pub client_id: String,
269
270    /// Whether authentication was successful
271    pub authenticated: bool,
272
273    /// JWT claims if valid
274    pub claims: Option<PrivateKeyJwtClaims>,
275
276    /// Validation errors
277    pub errors: Vec<String>,
278
279    /// JWT ID for tracking (only set for a verified assertion)
280    pub jti: Option<String>,
281}
282
283/// The claims as they arrive: `aud` may be a string or an array (RFC 7519, 4.1.3).
284#[derive(Deserialize)]
285struct ReceivedClaims {
286    iss: String,
287    sub: String,
288    aud: ReceivedAudience,
289    jti: String,
290    exp: i64,
291    iat: Option<i64>,
292    nbf: Option<i64>,
293}
294
295#[derive(Deserialize)]
296#[serde(untagged)]
297enum ReceivedAudience {
298    One(String),
299    Many(Vec<String>),
300}
301
302impl ReceivedAudience {
303    /// The first audience value, if any (used when no audience is configured).
304    fn first(&self) -> Option<String> {
305        match self {
306            ReceivedAudience::One(one) => Some(one.clone()),
307            ReceivedAudience::Many(many) => many.first().cloned(),
308        }
309    }
310
311    /// The configured audience this assertion is addressed to, if any: exact membership.
312    fn matching(&self, configured: &[String]) -> Option<String> {
313        let listed: &[String] = match self {
314            ReceivedAudience::One(one) => std::slice::from_ref(one),
315            ReceivedAudience::Many(many) => many,
316        };
317        listed.iter().find(|a| configured.contains(a)).cloned()
318    }
319}
320
321/// The remembered `jti`s: key -> deadline, with a per-client count for the quota.
322#[derive(Default)]
323struct JtiStore {
324    entries: HashMap<String, DateTime<Utc>>,
325    per_client: HashMap<String, usize>,
326    last_sweep: Option<DateTime<Utc>>,
327}
328
329impl std::fmt::Debug for JtiStore {
330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331        let mut d = f.debug_struct("JtiStore");
332        d.field("entries", &crate::utils::redact::redacted(&self.entries));
333        d.field("per_client", &self.per_client);
334        d.field("last_sweep", &self.last_sweep);
335        d.finish()
336    }
337}
338
339impl std::ops::Deref for JtiStore {
340    type Target = HashMap<String, DateTime<Utc>>;
341    fn deref(&self) -> &Self::Target {
342        &self.entries
343    }
344}
345
346impl std::ops::DerefMut for JtiStore {
347    fn deref_mut(&mut self) -> &mut Self::Target {
348        &mut self.entries
349    }
350}
351
352impl JtiStore {
353    /// Drop the entries whose deadline has passed and recount the clients.
354    fn sweep(&mut self, now: DateTime<Utc>) {
355        self.entries.retain(|_, deadline| *deadline > now);
356        self.per_client.clear();
357        for key in self.entries.keys() {
358            *self
359                .per_client
360                .entry(client_of_key(key).to_string())
361                .or_default() += 1;
362        }
363        self.last_sweep = Some(now);
364    }
365}
366
367/// The client id inside a key made by `PrivateKeyJwtManager::jti_key` ("len:client:jti").
368fn client_of_key(key: &str) -> &str {
369    key.split_once(':')
370        .and_then(|(len, rest)| len.parse::<usize>().ok().and_then(|n| rest.get(..n)))
371        .unwrap_or("")
372}
373
374/// Why verification failed, split by whether the client's key vouched for the assertion.
375enum Rejection {
376    /// Nothing is proven: the answer must not depend on the client or on why.
377    Unproven(String),
378    /// The signature verified; the reason may be told to the (genuine) caller.
379    Proven(String),
380}
381
382/// The kind of public key a JWK describes.
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384enum KeyKind {
385    Rsa,
386    EcP256,
387    EcP384,
388    Ed25519,
389}
390
391impl KeyKind {
392    /// Whether `algorithm` is a signature algorithm for this kind of key.
393    fn supports(self, algorithm: Algorithm) -> bool {
394        match self {
395            KeyKind::Rsa => matches!(
396                algorithm,
397                Algorithm::RS256
398                    | Algorithm::RS384
399                    | Algorithm::RS512
400                    | Algorithm::PS256
401                    | Algorithm::PS384
402                    | Algorithm::PS512
403            ),
404            KeyKind::EcP256 => algorithm == Algorithm::ES256,
405            KeyKind::EcP384 => algorithm == Algorithm::ES384,
406            KeyKind::Ed25519 => algorithm == Algorithm::EdDSA,
407        }
408    }
409}
410
411/// `true` for the HMAC family, whose "public" key would be a shared secret.
412fn is_symmetric(algorithm: Algorithm) -> bool {
413    matches!(
414        algorithm,
415        Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512
416    )
417}
418
419/// Private Key JWT Manager
420#[derive(Debug)]
421pub struct PrivateKeyJwtManager {
422    /// Client configurations indexed by client_id
423    client_configs: tokio::sync::RwLock<HashMap<String, ClientJwtConfig>>,
424
425    /// Used JTIs (scoped per client) for replay protection, each with the time after which the
426    /// assertion could no longer be accepted anyway (`exp` plus the clock skew)
427    used_jtis: tokio::sync::RwLock<JtiStore>,
428
429    /// Holds the `jti` revocation list
430    jwt_validator: SecureJwtValidator,
431
432    /// How long revoked-`jti` records are kept by `schedule_automatic_cleanup`; never less
433    /// than the longest time an assertion of a registered client can stay acceptable
434    cleanup_interval: Duration,
435
436    /// Whether registration refuses a client without an expected audience (opt-in).
437    require_audiences: bool,
438
439    /// Most unexpired `jti`s remembered per client.
440    max_outstanding_assertions: usize,
441}
442
443impl PrivateKeyJwtManager {
444    /// Create a new Private Key JWT Manager
445    pub fn new(jwt_validator: SecureJwtValidator) -> Self {
446        Self {
447            client_configs: tokio::sync::RwLock::new(HashMap::new()),
448            used_jtis: tokio::sync::RwLock::new(JtiStore::default()),
449            jwt_validator,
450            cleanup_interval: Duration::hours(1),
451            require_audiences: false,
452            max_outstanding_assertions: DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
453        }
454    }
455
456    /// Make registration refuse a client that configures no expected audience.
457    ///
458    /// Without an audience an assertion cannot be bound to this server, so a genuine assertion
459    /// captured elsewhere could be presented here. It is off by default so that a patch release
460    /// does not start refusing existing registrations; a registration without an audience logs
461    /// a warning. Turn it on once every client has its token endpoint configured.
462    pub fn require_audiences(mut self, require: bool) -> Self {
463        self.require_audiences = require;
464        self
465    }
466
467    #[cfg(test)]
468    fn with_max_outstanding_assertions(mut self, max: usize) -> Self {
469        self.max_outstanding_assertions = max;
470        self
471    }
472
473    /// Register a client for private key JWT authentication
474    ///
475    /// Registration fails unless the key is a well-formed public RSA / EC (P-256,
476    /// P-384) / Ed25519 JWK, no symmetric algorithm is allowed, and at least one allowed
477    /// algorithm fits the key. A client without an expected audience is accepted with a
478    /// warning unless [`require_audiences`](Self::require_audiences) is on.
479    pub async fn register_client(&self, config: ClientJwtConfig) -> Result<()> {
480        self.validate_client_config(&config)?;
481
482        let mut configs = self.client_configs.write().await;
483        configs.insert(config.client_id.clone(), config);
484
485        Ok(())
486    }
487
488    /// Authenticate a client using private key JWT
489    ///
490    /// Returns `Err` only for input that is not an assertion at all (oversized, not a JWT).
491    /// An unknown client and an assertion that does not verify both return `Ok` with
492    /// `authenticated == false` and the same single message; a refusal after the signature has
493    /// verified (wrong audience, expired, replayed, ...) names its reason.
494    pub async fn authenticate_client(&self, client_assertion: &str) -> Result<JwtAuthResult> {
495        if client_assertion.len() > MAX_ASSERTION_BYTES {
496            return Err(AuthError::auth_method(
497                "private_key_jwt",
498                "Client assertion is too large",
499            ));
500        }
501        let header = self.parse_jwt_header(client_assertion)?;
502
503        // The unverified `iss` is used only to find which key to verify with.
504        let claimed_client_id = self.extract_claimed_client_id(client_assertion)?;
505        let rejected = |errors: Vec<String>| JwtAuthResult {
506            client_id: claimed_client_id.clone(),
507            authenticated: false,
508            claims: None,
509            errors,
510            jti: None,
511        };
512        let config = {
513            let configs = self.client_configs.read().await;
514            configs.get(&claimed_client_id).cloned()
515        };
516        let Some(config) = config else {
517            tracing::debug!("private_key_jwt: assertion for an unregistered client");
518            return Ok(rejected(vec![GENERIC_REJECTION.to_string()]));
519        };
520
521        // Everything below uses the claims that signature verification returned.
522        let claims = match self.verify_jwt_signature(client_assertion, &header, &config) {
523            Ok(claims) => claims,
524            Err(Rejection::Unproven(reason)) => {
525                tracing::debug!("private_key_jwt: assertion not verified: {}", reason);
526                return Ok(rejected(vec![GENERIC_REJECTION.to_string()]));
527            }
528            Err(Rejection::Proven(reason)) => return Ok(rejected(vec![reason])),
529        };
530
531        let mut errors = Vec::new();
532        self.validate_jwt_structure(&claims, &config, &mut errors);
533        self.validate_jwt_timing(&claims, &config, &mut errors);
534
535        match self
536            .jwt_validator
537            .is_token_revoked(&Self::revocation_id(&claims.jti))
538        {
539            Ok(false) => {}
540            Ok(true) => errors.push("JWT has been revoked".to_string()),
541            Err(e) => errors.push(format!("Revocation check failed: {}", e)),
542        }
543
544        // Claim the JTI last, so an assertion that fails any check above does not
545        // consume it, and check-and-record is a single step. It is remembered until the
546        // assertion could no longer be accepted.
547        if errors.is_empty() {
548            let deadline = claims
549                .exp
550                .saturating_add(config.clock_skew.num_seconds())
551                .saturating_add(1);
552            let deadline =
553                DateTime::from_timestamp(deadline, 0).unwrap_or(DateTime::<Utc>::MAX_UTC);
554            if let Err(e) = self
555                .claim_jti(
556                    &config.client_id,
557                    &claims.jti,
558                    deadline,
559                    self.max_outstanding_assertions,
560                )
561                .await
562            {
563                errors.push(format!("JTI rejected: {}", e));
564            }
565        }
566
567        if !errors.is_empty() {
568            return Ok(rejected(errors));
569        }
570
571        let jti = claims.jti.clone();
572        Ok(JwtAuthResult {
573            client_id: config.client_id,
574            authenticated: true,
575            claims: Some(claims),
576            errors,
577            jti: Some(jti),
578        })
579    }
580
581    /// Create a client assertion JWT (for testing/client-side use).
582    ///
583    /// # Key encoding by algorithm
584    /// - **HS256/384/512**: `signing_key` is the raw HMAC secret bytes (such an assertion is
585    ///   refused by `authenticate_client`: symmetric algorithms cannot be registered).
586    /// - **RS256/384/512, PS256/384/512**: a PEM-encoded RSA private key.
587    /// - **ES256/384**: a PEM-encoded EC private key.
588    /// - **EdDSA**: a PEM-encoded Ed25519 private key.
589    pub fn create_client_assertion(
590        &self,
591        client_id: &str,
592        audience: &str,
593        signing_key: &[u8],
594        algorithm: Algorithm,
595    ) -> Result<String> {
596        let now = Utc::now();
597        let claims = PrivateKeyJwtClaims {
598            iss: client_id.to_string(),
599            sub: client_id.to_string(),
600            aud: audience.to_string(),
601            jti: uuid::Uuid::new_v4().to_string(),
602            exp: (now + Duration::minutes(5)).timestamp(),
603            iat: now.timestamp(),
604            nbf: Some(now.timestamp()),
605        };
606
607        let bad_key = |e: jsonwebtoken::errors::Error| {
608            AuthError::auth_method(
609                "private_key_jwt",
610                format!("Invalid signing key for {:?}: {}", algorithm, e),
611            )
612        };
613        let encoding_key = match algorithm {
614            Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
615                EncodingKey::from_secret(signing_key)
616            }
617            Algorithm::RS256
618            | Algorithm::RS384
619            | Algorithm::RS512
620            | Algorithm::PS256
621            | Algorithm::PS384
622            | Algorithm::PS512 => EncodingKey::from_rsa_pem(signing_key).map_err(bad_key)?,
623            Algorithm::ES256 | Algorithm::ES384 => {
624                EncodingKey::from_ec_pem(signing_key).map_err(bad_key)?
625            }
626            Algorithm::EdDSA => EncodingKey::from_ed_pem(signing_key).map_err(bad_key)?,
627        };
628
629        let header = Header::new(algorithm);
630        encode(&header, &claims, &encoding_key).map_err(|e| {
631            AuthError::auth_method("private_key_jwt", format!("Failed to encode JWT: {}", e))
632        })
633    }
634
635    /// Drop the remembered JTIs whose assertions could no longer be accepted anyway. A JTI is
636    /// kept until its own deadline (`exp` plus the client's clock skew), never for a fixed
637    /// interval, so cleanup cannot reopen a replay window.
638    pub async fn cleanup_expired_jtis(&self) {
639        self.used_jtis.write().await.sweep(Utc::now());
640    }
641
642    /// Set the cleanup interval for JTI management
643    pub fn with_cleanup_interval(mut self, interval: Duration) -> Self {
644        self.cleanup_interval = interval;
645        self
646    }
647
648    /// Get the current cleanup interval
649    pub fn get_cleanup_interval(&self) -> Duration {
650        self.cleanup_interval
651    }
652
653    /// Update the cleanup interval
654    pub fn update_cleanup_interval(&mut self, interval: Duration) {
655        self.cleanup_interval = interval;
656    }
657
658    /// Revoke a JWT by its JTI using the enhanced validator
659    pub fn revoke_jwt_token(&self, jti: &str) -> Result<()> {
660        self.jwt_validator.revoke_token(&Self::revocation_id(jti))
661    }
662
663    /// Check if a JWT is revoked using the enhanced validator
664    pub fn is_jwt_token_revoked(&self, jti: &str) -> Result<bool> {
665        self.jwt_validator
666            .is_token_revoked(&Self::revocation_id(jti))
667    }
668
669    /// Clean up expired JTIs, and revocation records older than the cleanup interval. The
670    /// interval is raised to the longest time an assertion of a registered client can stay
671    /// acceptable (`max_jwt_lifetime + 2 * clock_skew`), so a revoked `jti` is never forgotten
672    /// while an assertion carrying it could still be presented.
673    pub async fn schedule_automatic_cleanup(&self) {
674        // In a production system, this would run on a background task
675        // For now, we'll perform the cleanup immediately
676        self.cleanup_expired_jtis().await;
677
678        let longest_acceptance = self
679            .client_configs
680            .read()
681            .await
682            .values()
683            .map(|c| c.max_jwt_lifetime + c.clock_skew + c.clock_skew)
684            .max()
685            .unwrap_or_else(Duration::zero);
686        let retention = self.cleanup_interval.max(longest_acceptance);
687
688        // Clean up expired revoked tokens from the validator as well
689        let expired_cutoff = std::time::SystemTime::now()
690            .checked_sub(retention.to_std().unwrap_or_default())
691            .unwrap_or_else(std::time::SystemTime::now);
692
693        // Clean up expired tokens, ignoring cleanup errors
694        let _ = self.jwt_validator.cleanup_revoked_tokens(expired_cutoff);
695    }
696
697    /// Parse JWT header without verification
698    fn parse_jwt_header(&self, jwt: &str) -> Result<Header> {
699        jsonwebtoken::decode_header(jwt).map_err(|e| {
700            AuthError::auth_method("private_key_jwt", format!("Invalid JWT header: {}", e))
701        })
702    }
703
704    /// Read the claimed `iss` without verifying anything. The result may only be
705    /// used to choose which registered key to verify with.
706    fn extract_claimed_client_id(&self, jwt: &str) -> Result<String> {
707        #[derive(Deserialize)]
708        struct Unverified {
709            iss: String,
710        }
711
712        let parts: Vec<&str> = jwt.split('.').collect();
713        if parts.len() != 3 {
714            return Err(AuthError::auth_method(
715                "private_key_jwt",
716                "Invalid JWT format",
717            ));
718        }
719
720        let claims_bytes = URL_SAFE_NO_PAD.decode(parts[1]).map_err(|_| {
721            AuthError::auth_method("private_key_jwt", "Invalid JWT claims encoding")
722        })?;
723
724        let claims: Unverified = serde_json::from_slice(&claims_bytes)
725            .map_err(|_| AuthError::auth_method("private_key_jwt", "Invalid JWT claims format"))?;
726
727        Ok(claims.iss)
728    }
729
730    /// Validate the claims of a verified assertion.
731    fn validate_jwt_structure(
732        &self,
733        claims: &PrivateKeyJwtClaims,
734        config: &ClientJwtConfig,
735        errors: &mut Vec<String>,
736    ) {
737        // Check issuer equals subject and client_id
738        if claims.iss != claims.sub {
739            errors.push("Issuer must equal subject".to_string());
740        }
741
742        if claims.iss != config.client_id {
743            errors.push("Issuer must equal client_id".to_string());
744        }
745
746        // Check audience (unless the client was registered without one: see `require_audiences`)
747        if !config.expected_audiences.is_empty() && !config.expected_audiences.contains(&claims.aud)
748        {
749            errors.push(format!("Audience '{}' not allowed", claims.aud));
750        }
751
752        // Check JTI is present and of sensible size
753        if claims.jti.trim().is_empty() {
754            errors.push("JTI (JWT ID) is required".to_string());
755        }
756        if claims.jti.len() > MAX_JTI_BYTES {
757            errors.push(format!("JTI is longer than {} bytes", MAX_JTI_BYTES));
758        }
759    }
760
761    /// Verify the assertion's signature with the client's registered public key and
762    /// return the verified claims.
763    ///
764    /// The algorithm is the one in the (signed-over) header, accepted only if it is
765    /// on the client's allow-list and fits the registered key. `iss`, `aud`, `exp`
766    /// and `nbf` are checked here against the configuration, independent of any
767    /// issuer pinned on the authorization server's own token validator. `aud` may be a
768    /// string or an array; one of its values must be a configured audience, exactly.
769    fn verify_jwt_signature(
770        &self,
771        jwt: &str,
772        header: &Header,
773        config: &ClientJwtConfig,
774    ) -> std::result::Result<PrivateKeyJwtClaims, Rejection> {
775        let algorithm = header.alg;
776        if !config.allowed_algorithms.contains(&algorithm) {
777            return Err(Rejection::Unproven(format!(
778                "Algorithm {:?} not allowed",
779                algorithm
780            )));
781        }
782
783        let (decoding_key, kind) = self
784            .jwk_to_decoding_key(&config.public_key_jwk)
785            .map_err(|e| Rejection::Unproven(e.to_string()))?;
786        if is_symmetric(algorithm) || !kind.supports(algorithm) {
787            return Err(Rejection::Unproven(format!(
788                "Algorithm {:?} does not match the registered {:?} key",
789                algorithm, kind
790            )));
791        }
792
793        let mut validation = Validation::new(algorithm);
794        if config.expected_audiences.is_empty() {
795            // Registered without an audience (see `require_audiences`): the `aud` claim must be
796            // present but cannot be matched against anything.
797            validation.validate_aud = false;
798        } else {
799            validation.set_audience(&config.expected_audiences);
800        }
801        validation.set_issuer(&[&config.client_id]);
802        validation.set_required_spec_claims(&["exp", "aud", "iss", "sub"]);
803        validation.validate_nbf = true;
804        validation.leeway = config.clock_skew.num_seconds().max(0) as u64;
805
806        let token_data =
807            decode::<ReceivedClaims>(jwt, &decoding_key, &validation).map_err(|e| {
808                use jsonwebtoken::errors::ErrorKind as K;
809                // jsonwebtoken checks the signature before any claim, so these kinds can only
810                // occur once it has verified; anything else (including kinds added later) is
811                // treated as "not proven".
812                match e.kind() {
813                    K::ExpiredSignature
814                    | K::ImmatureSignature
815                    | K::InvalidIssuer
816                    | K::InvalidAudience
817                    | K::InvalidSubject
818                    | K::MissingRequiredClaim(_) => {
819                        Rejection::Proven(format!("Invalid assertion: {}", e))
820                    }
821                    // A claim of the wrong shape: say so without echoing the parser's text.
822                    K::Json(_) => Rejection::Proven("Invalid assertion claims".to_string()),
823                    _ => Rejection::Unproven(format!("JWT verification failed: {}", e)),
824                }
825            })?;
826
827        let received = token_data.claims;
828        let aud = if config.expected_audiences.is_empty() {
829            received
830                .aud
831                .first()
832                .ok_or_else(|| Rejection::Proven("Audience missing".to_string()))?
833        } else {
834            received
835                .aud
836                .matching(&config.expected_audiences)
837                .ok_or_else(|| Rejection::Proven("Audience not allowed".to_string()))?
838        };
839        Ok(PrivateKeyJwtClaims {
840            iss: received.iss,
841            sub: received.sub,
842            aud,
843            jti: received.jti,
844            exp: received.exp,
845            iat: received.iat.unwrap_or(0),
846            nbf: received.nbf,
847        })
848    }
849
850    /// Convert a public JWK into a real verification key.
851    ///
852    /// Supports RSA (modulus of at least 2048 bits), EC P-256 / P-384 and OKP
853    /// Ed25519. Anything that carries private or symmetric key material is refused.
854    fn jwk_to_decoding_key(&self, jwk: &serde_json::Value) -> Result<(DecodingKey, KeyKind)> {
855        let fail = |message: String| AuthError::auth_method("private_key_jwt", message);
856        let text = |name: &str| -> Result<&str> {
857            jwk.get(name)
858                .and_then(|v| v.as_str())
859                .ok_or_else(|| fail(format!("Missing '{}' in JWK", name)))
860        };
861        let bytes = |name: &str| -> Result<Vec<u8>> {
862            URL_SAFE_NO_PAD
863                .decode(text(name)?.as_bytes())
864                .map_err(|_| fail(format!("Invalid base64url '{}' parameter", name)))
865        };
866
867        if !jwk.is_object() {
868            return Err(fail("JWK must be a JSON object".to_string()));
869        }
870        if let Some(member) = PRIVATE_JWK_MEMBERS
871            .iter()
872            .find(|member| jwk.get(**member).is_some())
873        {
874            return Err(fail(format!(
875                "JWK contains private or symmetric key parameter '{}'; register the public key only",
876                member
877            )));
878        }
879        if let Some(usage) = jwk.get("use")
880            && usage.as_str() != Some("sig")
881        {
882            return Err(fail("JWK 'use' must be 'sig'".to_string()));
883        }
884
885        match text("kty")? {
886            "RSA" => {
887                let n = bytes("n")?;
888                let e = bytes("e")?;
889                let first = n.iter().position(|b| *b != 0).unwrap_or(n.len());
890                let significant = &n[first..];
891                let bits = match significant.first() {
892                    Some(top) => (significant.len() - 1) * 8 + (8 - top.leading_zeros() as usize),
893                    None => 0,
894                };
895                if bits < MIN_RSA_MODULUS_BITS {
896                    return Err(fail(format!(
897                        "RSA modulus of {} bits is below the {}-bit minimum",
898                        bits, MIN_RSA_MODULUS_BITS
899                    )));
900                }
901                let exponent: Vec<u8> = e.iter().copied().skip_while(|b| *b == 0).collect();
902                if exponent.len() < 2 && exponent.first().is_none_or(|b| *b < 3) {
903                    return Err(fail(
904                        "RSA public exponent must be greater than 1".to_string(),
905                    ));
906                }
907                if exponent.last().is_some_and(|b| b % 2 == 0) {
908                    return Err(fail("RSA public exponent must be odd".to_string()));
909                }
910                let key = DecodingKey::from_rsa_components(text("n")?, text("e")?)
911                    .map_err(|e| fail(format!("Invalid RSA JWK: {}", e)))?;
912                Ok((key, KeyKind::Rsa))
913            }
914            "EC" => {
915                let (kind, len) = match text("crv")? {
916                    "P-256" => (KeyKind::EcP256, 32),
917                    "P-384" => (KeyKind::EcP384, 48),
918                    other => {
919                        return Err(fail(format!("Unsupported EC curve: {}", other)));
920                    }
921                };
922                if bytes("x")?.len() != len || bytes("y")?.len() != len {
923                    return Err(fail(format!(
924                        "EC coordinates must be {} bytes for this curve",
925                        len
926                    )));
927                }
928                let key = DecodingKey::from_ec_components(text("x")?, text("y")?)
929                    .map_err(|e| fail(format!("Invalid EC JWK: {}", e)))?;
930                Ok((key, kind))
931            }
932            "OKP" => {
933                if text("crv")? != "Ed25519" {
934                    return Err(fail("Unsupported OKP curve (only Ed25519)".to_string()));
935                }
936                if bytes("x")?.len() != 32 {
937                    return Err(fail("Ed25519 public key must be 32 bytes".to_string()));
938                }
939                let key = DecodingKey::from_ed_components(text("x")?)
940                    .map_err(|e| fail(format!("Invalid OKP JWK: {}", e)))?;
941                Ok((key, KeyKind::Ed25519))
942            }
943            other => Err(fail(format!("Unsupported key type: {}", other))),
944        }
945    }
946
947    /// Name of an assertion `jti` in the validator's revocation list, which also holds
948    /// access-token `jti`s: the prefix keeps the two apart.
949    fn revocation_id(jti: &str) -> String {
950        format!("{}{}", REVOCATION_NAMESPACE, jti)
951    }
952
953    /// Key under which a client's JTI is remembered: length-prefixed, so no (client, jti) pair
954    /// can collide with another whatever characters either contains.
955    fn jti_key(client_id: &str, jti: &str) -> String {
956        format!("{}:{}:{}", client_id.len(), client_id, jti)
957    }
958
959    /// Atomically check that a client's JTI is unused and record it until `deadline`.
960    ///
961    /// Expired entries are swept when the map is large, but at most every few seconds (a sweep
962    /// scans the whole map under the write lock). A full map refuses new claims, and so does a
963    /// client that already has `quota` unexpired ones, so one client cannot use up the room of
964    /// the others.
965    async fn claim_jti(
966        &self,
967        client_id: &str,
968        jti: &str,
969        deadline: DateTime<Utc>,
970        quota: usize,
971    ) -> Result<()> {
972        let mut guard = self.used_jtis.write().await;
973        let store = &mut *guard;
974        let now = Utc::now();
975        if store.entries.len() >= JTI_SWEEP_THRESHOLD
976            && store
977                .last_sweep
978                .is_none_or(|at| now - at >= Duration::seconds(JTI_SWEEP_INTERVAL_SECS))
979        {
980            store.sweep(now);
981        }
982        if store.entries.len() >= MAX_TRACKED_JTIS {
983            return Err(AuthError::auth_method(
984                "private_key_jwt",
985                "Too many unexpired assertions are being tracked",
986            ));
987        }
988        if store.per_client.get(client_id).copied().unwrap_or(0) >= quota {
989            return Err(AuthError::auth_method(
990                "private_key_jwt",
991                "Too many unexpired assertions for this client",
992            ));
993        }
994        match store.entries.entry(Self::jti_key(client_id, jti)) {
995            std::collections::hash_map::Entry::Occupied(_) => Err(AuthError::auth_method(
996                "private_key_jwt",
997                "JTI already used: replay detected",
998            )),
999            std::collections::hash_map::Entry::Vacant(slot) => {
1000                slot.insert(deadline);
1001                *store.per_client.entry(client_id.to_string()).or_default() += 1;
1002                Ok(())
1003            }
1004        }
1005    }
1006
1007    /// Validate JWT timing constraints (all arithmetic is checked or saturating: the claims
1008    /// are attacker-chosen integers)
1009    fn validate_jwt_timing(
1010        &self,
1011        claims: &PrivateKeyJwtClaims,
1012        config: &ClientJwtConfig,
1013        errors: &mut Vec<String>,
1014    ) {
1015        let now = Utc::now().timestamp();
1016        let skew = config.clock_skew.num_seconds();
1017
1018        // Check expiration
1019        if claims.exp <= now.saturating_sub(skew) {
1020            errors.push("JWT has expired".to_string());
1021        }
1022
1023        // Check not before
1024        if let Some(nbf) = claims.nbf
1025            && nbf > now.saturating_add(skew)
1026        {
1027            errors.push("JWT not yet valid".to_string());
1028        }
1029
1030        let max_lifetime = config.max_jwt_lifetime.num_seconds();
1031        let iat = (claims.iat != 0).then_some(claims.iat);
1032        match iat {
1033            Some(iat) => {
1034                // Issued at, and the maximum lifetime measured from it
1035                if iat > now.saturating_add(skew) {
1036                    errors.push("JWT issued in the future".to_string());
1037                }
1038                match claims.exp.checked_sub(iat) {
1039                    Some(lifetime) if lifetime <= 0 => {
1040                        errors.push("JWT expiry is not after its issue time".to_string());
1041                    }
1042                    Some(lifetime) if lifetime > max_lifetime => {
1043                        errors.push(format!(
1044                            "JWT lifetime {} exceeds maximum {}",
1045                            lifetime, max_lifetime
1046                        ));
1047                    }
1048                    Some(_) => {}
1049                    None => errors.push("JWT lifetime is out of range".to_string()),
1050                }
1051            }
1052            None => {
1053                // No `iat` (RFC 7523 does not require one): the lifetime cannot be measured
1054                // from it, so `exp` may not lie further ahead than a fresh assertion's would.
1055                let horizon = now.saturating_add(max_lifetime).saturating_add(skew);
1056                if claims.exp > horizon {
1057                    errors.push(
1058                        "JWT expiry is further ahead than the maximum lifetime allows".to_string(),
1059                    );
1060                }
1061            }
1062        }
1063    }
1064
1065    /// Validate client configuration
1066    fn validate_client_config(&self, config: &ClientJwtConfig) -> Result<()> {
1067        let fail = |message: &str| AuthError::auth_method("private_key_jwt", message);
1068
1069        if config.client_id.trim().is_empty() {
1070            return Err(fail("Client ID cannot be empty"));
1071        }
1072        if config.client_id.len() > MAX_CLIENT_ID_BYTES
1073            || config.client_id.chars().any(char::is_control)
1074        {
1075            return Err(fail(
1076                "Client ID must be at most 256 bytes without control characters",
1077            ));
1078        }
1079
1080        if config.allowed_algorithms.is_empty() {
1081            return Err(fail("At least one algorithm must be allowed"));
1082        }
1083
1084        if config.allowed_algorithms.iter().any(|a| is_symmetric(*a)) {
1085            return Err(fail(
1086                "Symmetric (HS*) algorithms cannot be used with private_key_jwt",
1087            ));
1088        }
1089
1090        if config
1091            .expected_audiences
1092            .iter()
1093            .any(|a| a.trim().is_empty())
1094        {
1095            return Err(fail("An expected audience must not be empty"));
1096        }
1097        if config.expected_audiences.is_empty() {
1098            if self.require_audiences {
1099                return Err(fail(
1100                    "At least one audience (token endpoint) must be configured",
1101                ));
1102            }
1103            tracing::warn!(
1104                client_id = %config.client_id,
1105                "private_key_jwt client registered without an expected audience: its assertions \
1106                 are not bound to this server (see PrivateKeyJwtManager::require_audiences)"
1107            );
1108        }
1109
1110        if config.clock_skew < Duration::zero() || config.max_jwt_lifetime <= Duration::zero() {
1111            return Err(fail(
1112                "clock_skew must not be negative and max_jwt_lifetime must be positive",
1113            ));
1114        }
1115        if config.clock_skew > Duration::minutes(10)
1116            || config.max_jwt_lifetime > Duration::hours(24)
1117        {
1118            return Err(fail(
1119                "clock_skew must be at most 10 minutes and max_jwt_lifetime at most 24 hours",
1120            ));
1121        }
1122
1123        // The key must really be usable, and at least one allowed algorithm must fit it.
1124        let (_, kind) = self.jwk_to_decoding_key(&config.public_key_jwk)?;
1125        if !config.allowed_algorithms.iter().any(|a| kind.supports(*a)) {
1126            return Err(fail(
1127                "None of the allowed algorithms can be verified with the registered key",
1128            ));
1129        }
1130
1131        Ok(())
1132    }
1133}
1134
1135impl Default for ClientJwtConfig {
1136    fn default() -> Self {
1137        Self {
1138            client_id: String::new(),
1139            public_key_jwk: serde_json::json!({}),
1140            allowed_algorithms: vec![Algorithm::RS256, Algorithm::ES256],
1141            max_jwt_lifetime: Duration::minutes(5),
1142            clock_skew: Duration::seconds(60),
1143            expected_audiences: Vec::new(),
1144        }
1145    }
1146}
1147
1148#[cfg(test)]
1149mod tests {
1150    use super::*;
1151    use rcgen::{
1152        KeyPair, PKCS_ECDSA_P256_SHA256, PKCS_ECDSA_P384_SHA384, PKCS_ED25519, PKCS_RSA_SHA256,
1153        RsaKeySize,
1154    };
1155    use serde_json::{Value, json};
1156    use std::sync::{Arc, OnceLock};
1157
1158    const TOKEN_ENDPOINT: &str = "https://auth.example.com/token";
1159
1160    fn create_test_manager() -> PrivateKeyJwtManager {
1161        let jwt_config = crate::security::secure_jwt::SecureJwtConfig::default();
1162        let jwt_validator = SecureJwtValidator::new(jwt_config);
1163        PrivateKeyJwtManager::new(jwt_validator)
1164    }
1165
1166    /// A manager whose validator pins no issuer, as a deployer might set up.
1167    fn create_unpinned_manager() -> PrivateKeyJwtManager {
1168        let mut jwt_config = crate::security::secure_jwt::SecureJwtConfig::default();
1169        jwt_config.required_issuers.clear();
1170        let jwt_validator = SecureJwtValidator::new(jwt_config);
1171        PrivateKeyJwtManager::new(jwt_validator)
1172    }
1173
1174    /// A real generated key: signing half, public JWK, and the algorithm it signs with.
1175    #[derive(Clone)]
1176    struct TestKey {
1177        encoding_key: Arc<EncodingKey>,
1178        pem: String,
1179        jwk: Value,
1180        algorithm: Algorithm,
1181    }
1182
1183    fn b64(bytes: &[u8]) -> String {
1184        URL_SAFE_NO_PAD.encode(bytes)
1185    }
1186
1187    fn ec_key(alg: &'static rcgen::SignatureAlgorithm, point_len: usize, crv: &str) -> TestKey {
1188        let key = KeyPair::generate_for(alg).unwrap();
1189        let raw = key.public_key_raw();
1190        let point = &raw[raw.len() - point_len..];
1191        assert_eq!(point[0], 4, "uncompressed point");
1192        let half = (point_len - 1) / 2;
1193        TestKey {
1194            encoding_key: Arc::new(
1195                EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
1196            ),
1197            pem: key.serialize_pem(),
1198            jwk: json!({"kty": "EC", "crv": crv, "x": b64(&point[1..1 + half]), "y": b64(&point[1 + half..])}),
1199            algorithm: if crv == "P-256" {
1200                Algorithm::ES256
1201            } else {
1202                Algorithm::ES384
1203            },
1204        }
1205    }
1206
1207    fn p256_key() -> TestKey {
1208        ec_key(&PKCS_ECDSA_P256_SHA256, 65, "P-256")
1209    }
1210
1211    fn p384_key() -> TestKey {
1212        ec_key(&PKCS_ECDSA_P384_SHA384, 97, "P-384")
1213    }
1214
1215    fn ed25519_key() -> TestKey {
1216        let key = KeyPair::generate_for(&PKCS_ED25519).unwrap();
1217        TestKey {
1218            encoding_key: Arc::new(
1219                EncodingKey::from_ed_pem(key.serialize_pem().as_bytes()).unwrap(),
1220            ),
1221            pem: key.serialize_pem(),
1222            jwk: json!({"kty": "OKP", "crv": "Ed25519", "x": b64(key.public_key_raw())}),
1223            algorithm: Algorithm::EdDSA,
1224        }
1225    }
1226
1227    /// Read one DER INTEGER (tag, length, content) and return its content and the rest.
1228    fn der_integer(input: &[u8]) -> (&[u8], &[u8]) {
1229        assert_eq!(input[0], 0x02);
1230        let (len, header) = if input[1] & 0x80 == 0 {
1231            (input[1] as usize, 2)
1232        } else {
1233            let n = (input[1] & 0x7f) as usize;
1234            let len = input[2..2 + n]
1235                .iter()
1236                .fold(0usize, |a, b| (a << 8) | *b as usize);
1237            (len, 2 + n)
1238        };
1239        (&input[header..header + len], &input[header + len..])
1240    }
1241
1242    /// One shared RSA-2048 key; generating it is slow.
1243    fn rsa_key() -> TestKey {
1244        static KEY: OnceLock<TestKey> = OnceLock::new();
1245        KEY.get_or_init(|| {
1246            let key = KeyPair::generate_rsa_for(&PKCS_RSA_SHA256, RsaKeySize::_2048).unwrap();
1247            // public_key_raw() is the DER RSAPublicKey: SEQUENCE { n INTEGER, e INTEGER }.
1248            let raw = key.public_key_raw();
1249            assert_eq!(raw[0], 0x30);
1250            let body = if raw[1] & 0x80 == 0 {
1251                &raw[2..]
1252            } else {
1253                &raw[2 + (raw[1] & 0x7f) as usize..]
1254            };
1255            let (n, rest) = der_integer(body);
1256            let (e, _) = der_integer(rest);
1257            let n = n.strip_prefix(&[0]).unwrap_or(n);
1258            TestKey {
1259                encoding_key: Arc::new(
1260                    EncodingKey::from_rsa_pem(key.serialize_pem().as_bytes()).unwrap(),
1261                ),
1262                pem: key.serialize_pem(),
1263                jwk: json!({"kty": "RSA", "n": b64(n), "e": b64(e)}),
1264                algorithm: Algorithm::RS256,
1265            }
1266        })
1267        .clone()
1268    }
1269
1270    /// Claims for an assertion by `client`, addressed to the token endpoint.
1271    fn claims(client: &str, jti: &str) -> Value {
1272        let now = Utc::now().timestamp();
1273        json!({
1274            "iss": client, "sub": client, "aud": TOKEN_ENDPOINT, "jti": jti,
1275            "exp": now + 120, "iat": now, "nbf": now
1276        })
1277    }
1278
1279    fn sign(key: &TestKey, algorithm: Algorithm, claims: &Value) -> String {
1280        encode(&Header::new(algorithm), claims, &key.encoding_key).unwrap()
1281    }
1282
1283    fn config(client: &str, key: &TestKey) -> ClientJwtConfig {
1284        ClientJwtConfig::builder(client, key.jwk.clone())
1285            .algorithms(vec![key.algorithm])
1286            .audience(TOKEN_ENDPOINT)
1287            .build()
1288    }
1289
1290    async fn registered(client: &str, key: &TestKey) -> PrivateKeyJwtManager {
1291        let manager = create_test_manager();
1292        manager.register_client(config(client, key)).await.unwrap();
1293        manager
1294    }
1295
1296    /// The assertion must be answered with "not authenticated"; an `Err` (which means "not an
1297    /// assertion at all") or an unrelated failure does not count. Returns the reasons given.
1298    async fn assert_rejected(
1299        manager: &PrivateKeyJwtManager,
1300        assertion: &str,
1301        why: &str,
1302    ) -> Vec<String> {
1303        let result = manager
1304            .authenticate_client(assertion)
1305            .await
1306            .unwrap_or_else(|e| panic!("{why}: expected a verdict, got an error: {e}"));
1307        assert!(
1308            !result.authenticated,
1309            "{why}: the assertion must not authenticate"
1310        );
1311        assert!(!result.errors.is_empty(), "{why}: a reason is required");
1312        result.errors
1313    }
1314
1315    // ----- genuine assertions authenticate -----
1316
1317    #[tokio::test]
1318    async fn genuine_es256_assertion_authenticates() {
1319        let key = p256_key();
1320        let manager = registered("c", &key).await;
1321        let result = manager
1322            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "j1")))
1323            .await
1324            .unwrap();
1325        assert!(result.authenticated, "{:?}", result.errors);
1326        assert_eq!(result.client_id, "c");
1327        assert_eq!(result.jti.as_deref(), Some("j1"));
1328    }
1329
1330    #[tokio::test]
1331    async fn genuine_es384_assertion_authenticates() {
1332        let key = p384_key();
1333        let manager = registered("c", &key).await;
1334        let result = manager
1335            .authenticate_client(&sign(&key, Algorithm::ES384, &claims("c", "j1")))
1336            .await
1337            .unwrap();
1338        assert!(result.authenticated, "{:?}", result.errors);
1339    }
1340
1341    #[tokio::test]
1342    async fn genuine_eddsa_assertion_authenticates() {
1343        let key = ed25519_key();
1344        let manager = registered("c", &key).await;
1345        let result = manager
1346            .authenticate_client(&sign(&key, Algorithm::EdDSA, &claims("c", "j1")))
1347            .await
1348            .unwrap();
1349        assert!(result.authenticated, "{:?}", result.errors);
1350    }
1351
1352    #[tokio::test]
1353    async fn genuine_rs256_and_ps256_assertions_authenticate() {
1354        let key = rsa_key();
1355        let manager = create_test_manager();
1356        manager
1357            .register_client(
1358                ClientJwtConfig::builder("c", key.jwk.clone())
1359                    .algorithms(vec![Algorithm::RS256, Algorithm::PS256])
1360                    .audience(TOKEN_ENDPOINT)
1361                    .build(),
1362            )
1363            .await
1364            .unwrap();
1365        for (alg, jti) in [(Algorithm::RS256, "j-rs"), (Algorithm::PS256, "j-ps")] {
1366            let result = manager
1367                .authenticate_client(&sign(&key, alg, &claims("c", jti)))
1368                .await
1369                .unwrap();
1370            assert!(result.authenticated, "{alg:?}: {:?}", result.errors);
1371        }
1372    }
1373
1374    #[tokio::test]
1375    async fn authentication_does_not_depend_on_the_servers_issuer_pin() {
1376        // The validator is configured for the authorization server's own tokens.
1377        // Client assertions must verify the same way whether or not it pins an issuer.
1378        let key = p256_key();
1379        for manager in [create_test_manager(), create_unpinned_manager()] {
1380            manager.register_client(config("c", &key)).await.unwrap();
1381            let result = manager
1382                .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "j1")))
1383                .await
1384                .unwrap();
1385            assert!(result.authenticated, "{:?}", result.errors);
1386        }
1387    }
1388
1389    // ----- forgery: a signature made without the private key -----
1390
1391    #[tokio::test]
1392    async fn assertion_forged_with_a_key_derived_from_the_public_jwk_is_rejected() {
1393        let key = p256_key();
1394        let x = key.jwk["x"].as_str().unwrap();
1395        let y = key.jwk["y"].as_str().unwrap();
1396        // What the earlier implementation used as its "verification key".
1397        let derived = format!("ec_private_key_jwt_crv:{}_x:{}_y:{}", "P-256", x, y);
1398        let forged = encode(
1399            &Header::new(Algorithm::HS256),
1400            &claims("c", "forged"),
1401            &EncodingKey::from_secret(derived.as_bytes()),
1402        )
1403        .unwrap();
1404
1405        // Default algorithms (HS256 is not on the list)...
1406        let manager = registered("c", &key).await;
1407        assert_rejected(&manager, &forged, "HS256 not allowed").await;
1408
1409        // ...and a client that asks for HS256 cannot even be registered.
1410        let manager = create_test_manager();
1411        let hs_config = ClientJwtConfig::builder("c", key.jwk.clone())
1412            .algorithms(vec![Algorithm::HS256])
1413            .audience(TOKEN_ENDPOINT)
1414            .build();
1415        assert!(manager.register_client(hs_config).await.is_err());
1416        assert_rejected(&manager, &forged, "client never registered").await;
1417
1418        // The same through a validator that pins no issuer.
1419        let manager = create_unpinned_manager();
1420        manager.register_client(config("c", &key)).await.unwrap();
1421        assert_rejected(&manager, &forged, "unpinned validator").await;
1422    }
1423
1424    #[tokio::test]
1425    async fn assertion_forged_for_an_rsa_client_with_a_public_derived_secret_is_rejected() {
1426        let key = rsa_key();
1427        let n = key.jwk["n"].as_str().unwrap();
1428        let e = key.jwk["e"].as_str().unwrap();
1429        let derived = format!("rsa_private_key_jwt_n:{}_e:{}", n, e);
1430        let forged = encode(
1431            &Header::new(Algorithm::HS256),
1432            &claims("c", "forged"),
1433            &EncodingKey::from_secret(derived.as_bytes()),
1434        )
1435        .unwrap();
1436        let manager = registered("c", &key).await;
1437        assert_rejected(&manager, &forged, "HS256 against an RSA client").await;
1438    }
1439
1440    #[tokio::test]
1441    async fn assertion_signed_by_another_key_is_rejected() {
1442        let registered_key = p256_key();
1443        let attacker_key = p256_key();
1444        let manager = registered("c", &registered_key).await;
1445        assert_rejected(
1446            &manager,
1447            &sign(&attacker_key, Algorithm::ES256, &claims("c", "j1")),
1448            "signed by a different key",
1449        )
1450        .await;
1451    }
1452
1453    #[tokio::test]
1454    async fn assertion_with_a_tampered_payload_is_rejected() {
1455        let key = p256_key();
1456        let manager = registered("c", &key).await;
1457        let genuine = sign(&key, Algorithm::ES256, &claims("c", "j1"));
1458        let mut parts: Vec<String> = genuine.split('.').map(str::to_string).collect();
1459        parts[1] = b64(claims("c", "j2").to_string().as_bytes());
1460        assert_rejected(&manager, &parts.join("."), "payload changed after signing").await;
1461    }
1462
1463    #[tokio::test]
1464    async fn header_algorithm_outside_the_allow_list_is_rejected() {
1465        let key = rsa_key();
1466        let manager = registered("c", &key).await; // allows RS256 only
1467        assert_rejected(
1468            &manager,
1469            &sign(&key, Algorithm::PS256, &claims("c", "j1")),
1470            "PS256 is not on the allow-list",
1471        )
1472        .await;
1473    }
1474
1475    #[tokio::test]
1476    async fn header_algorithm_of_the_wrong_key_family_is_rejected() {
1477        // An EC key whose allow-list also (uselessly) names RS256: an RS256 header
1478        // must not be verified against the EC key, nor panic.
1479        let key = p256_key();
1480        let manager = create_test_manager();
1481        manager
1482            .register_client(
1483                ClientJwtConfig::builder("c", key.jwk.clone())
1484                    .algorithms(vec![Algorithm::ES256, Algorithm::RS256])
1485                    .audience(TOKEN_ENDPOINT)
1486                    .build(),
1487            )
1488            .await
1489            .unwrap();
1490        let rsa = rsa_key();
1491        assert_rejected(
1492            &manager,
1493            &sign(&rsa, Algorithm::RS256, &claims("c", "j1")),
1494            "RS256 token against an EC key",
1495        )
1496        .await;
1497        // The EC key still works.
1498        let result = manager
1499            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "j2")))
1500            .await
1501            .unwrap();
1502        assert!(result.authenticated, "{:?}", result.errors);
1503    }
1504
1505    // ----- claims -----
1506
1507    async fn assert_claim_rejected(mutate: impl FnOnce(&mut Value), why: &str) {
1508        let key = p256_key();
1509        let manager = registered("c", &key).await;
1510        let mut c = claims("c", "j1");
1511        mutate(&mut c);
1512        assert_rejected(&manager, &sign(&key, Algorithm::ES256, &c), why).await;
1513    }
1514
1515    #[tokio::test]
1516    async fn audience_must_be_a_configured_token_endpoint() {
1517        assert_claim_rejected(
1518            |c| c["aud"] = json!("https://evil.example/token"),
1519            "foreign aud",
1520        )
1521        .await;
1522        // The earlier code required aud == client_id; that is not a token endpoint.
1523        assert_claim_rejected(|c| c["aud"] = json!("c"), "aud = client_id").await;
1524        assert_claim_rejected(
1525            |c| {
1526                c.as_object_mut().unwrap().remove("aud");
1527            },
1528            "no aud",
1529        )
1530        .await;
1531    }
1532
1533    #[tokio::test]
1534    async fn any_configured_audience_is_accepted() {
1535        let key = p256_key();
1536        let manager = create_test_manager();
1537        manager
1538            .register_client(
1539                ClientJwtConfig::builder("c", key.jwk.clone())
1540                    .algorithms(vec![Algorithm::ES256])
1541                    .audiences([TOKEN_ENDPOINT, "https://auth.example.com/par"])
1542                    .build(),
1543            )
1544            .await
1545            .unwrap();
1546        let mut c = claims("c", "j1");
1547        c["aud"] = json!("https://auth.example.com/par");
1548        let result = manager
1549            .authenticate_client(&sign(&key, Algorithm::ES256, &c))
1550            .await
1551            .unwrap();
1552        assert!(result.authenticated, "{:?}", result.errors);
1553    }
1554
1555    #[tokio::test]
1556    async fn issuer_and_subject_must_both_be_the_client() {
1557        assert_claim_rejected(|c| c["sub"] = json!("someone-else"), "sub != iss").await;
1558        assert_claim_rejected(
1559            |c| {
1560                c.as_object_mut().unwrap().remove("sub");
1561            },
1562            "no sub",
1563        )
1564        .await;
1565    }
1566
1567    #[tokio::test]
1568    async fn assertion_for_an_unregistered_client_is_rejected() {
1569        let key = p256_key();
1570        let manager = registered("c", &key).await;
1571        let errors = assert_rejected(
1572            &manager,
1573            &sign(&key, Algorithm::ES256, &claims("other", "j1")),
1574            "unregistered client",
1575        )
1576        .await;
1577        assert_eq!(errors, vec![GENERIC_REJECTION.to_string()]);
1578    }
1579
1580    #[tokio::test]
1581    async fn assertion_must_name_a_registered_client_not_borrow_anothers_key() {
1582        // Two clients, two keys: client b's assertion signed with a's key but claiming b.
1583        let (ka, kb) = (p256_key(), p256_key());
1584        let manager = create_test_manager();
1585        manager.register_client(config("a", &ka)).await.unwrap();
1586        manager.register_client(config("b", &kb)).await.unwrap();
1587        assert_rejected(
1588            &manager,
1589            &sign(&ka, Algorithm::ES256, &claims("b", "j1")),
1590            "a's key used to claim b",
1591        )
1592        .await;
1593    }
1594
1595    #[tokio::test]
1596    async fn expired_not_yet_valid_and_overlong_assertions_are_rejected() {
1597        let now = Utc::now().timestamp();
1598        assert_claim_rejected(
1599            |c| {
1600                c["exp"] = json!(now - 3600);
1601                c["iat"] = json!(now - 3700);
1602                c["nbf"] = json!(now - 3700);
1603            },
1604            "expired",
1605        )
1606        .await;
1607        assert_claim_rejected(|c| c["nbf"] = json!(now + 3600), "nbf in the future").await;
1608        assert_claim_rejected(|c| c["iat"] = json!(now + 3600), "iat in the future").await;
1609        assert_claim_rejected(
1610            |c| c["exp"] = json!(now + 86_400),
1611            "lifetime far above the maximum",
1612        )
1613        .await;
1614        assert_claim_rejected(
1615            |c| {
1616                c.as_object_mut().unwrap().remove("exp");
1617            },
1618            "no exp",
1619        )
1620        .await;
1621    }
1622
1623    #[tokio::test]
1624    async fn jti_is_required() {
1625        assert_claim_rejected(|c| c["jti"] = json!(""), "empty jti").await;
1626        assert_claim_rejected(|c| c["jti"] = json!("   "), "blank jti").await;
1627        assert_claim_rejected(
1628            |c| {
1629                c.as_object_mut().unwrap().remove("jti");
1630            },
1631            "no jti",
1632        )
1633        .await;
1634    }
1635
1636    // ----- replay and revocation -----
1637
1638    #[tokio::test]
1639    async fn an_assertion_cannot_be_replayed() {
1640        let key = p256_key();
1641        let manager = registered("c", &key).await;
1642        let assertion = sign(&key, Algorithm::ES256, &claims("c", "once"));
1643        assert!(
1644            manager
1645                .authenticate_client(&assertion)
1646                .await
1647                .unwrap()
1648                .authenticated
1649        );
1650        let second = manager.authenticate_client(&assertion).await.unwrap();
1651        assert!(!second.authenticated);
1652        assert!(
1653            second.errors.iter().any(|e| e.contains("replay")),
1654            "{:?}",
1655            second.errors
1656        );
1657    }
1658
1659    #[tokio::test]
1660    async fn jtis_are_scoped_to_the_client() {
1661        let (ka, kb) = (p256_key(), p256_key());
1662        let manager = create_test_manager();
1663        manager.register_client(config("a", &ka)).await.unwrap();
1664        manager.register_client(config("b", &kb)).await.unwrap();
1665        for (client, key) in [("a", &ka), ("b", &kb)] {
1666            let result = manager
1667                .authenticate_client(&sign(key, Algorithm::ES256, &claims(client, "shared-jti")))
1668                .await
1669                .unwrap();
1670            assert!(result.authenticated, "{client}: {:?}", result.errors);
1671        }
1672    }
1673
1674    #[tokio::test]
1675    async fn a_rejected_assertion_does_not_consume_its_jti() {
1676        let (key, attacker) = (p256_key(), p256_key());
1677        let manager = registered("c", &key).await;
1678        assert_rejected(
1679            &manager,
1680            &sign(&attacker, Algorithm::ES256, &claims("c", "burn")),
1681            "forged",
1682        )
1683        .await;
1684        let result = manager
1685            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "burn")))
1686            .await
1687            .unwrap();
1688        assert!(result.authenticated, "{:?}", result.errors);
1689    }
1690
1691    #[tokio::test]
1692    async fn an_assertion_that_fails_a_later_check_does_not_consume_its_jti() {
1693        // Validly signed, but its lifetime is above the maximum: refused after verification.
1694        let key = p256_key();
1695        let manager = registered("c", &key).await;
1696        let mut too_long = claims("c", "kept");
1697        too_long["exp"] = json!(Utc::now().timestamp() + 86_400);
1698        assert_rejected(
1699            &manager,
1700            &sign(&key, Algorithm::ES256, &too_long),
1701            "lifetime",
1702        )
1703        .await;
1704        let result = manager
1705            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "kept")))
1706            .await
1707            .unwrap();
1708        assert!(result.authenticated, "{:?}", result.errors);
1709    }
1710
1711    #[tokio::test]
1712    async fn concurrent_presentations_of_one_assertion_succeed_exactly_once() {
1713        let key = p256_key();
1714        let manager = Arc::new(registered("c", &key).await);
1715        let assertion = Arc::new(sign(&key, Algorithm::ES256, &claims("c", "race")));
1716        let mut tasks = Vec::new();
1717        for _ in 0..16 {
1718            let (manager, assertion) = (manager.clone(), assertion.clone());
1719            tasks.push(tokio::spawn(async move {
1720                manager
1721                    .authenticate_client(&assertion)
1722                    .await
1723                    .unwrap()
1724                    .authenticated
1725            }));
1726        }
1727        let mut successes = 0;
1728        for task in tasks {
1729            if task.await.unwrap() {
1730                successes += 1;
1731            }
1732        }
1733        assert_eq!(successes, 1);
1734    }
1735
1736    #[tokio::test]
1737    async fn a_revoked_jti_is_rejected() {
1738        let key = p256_key();
1739        let manager = registered("c", &key).await;
1740        manager.revoke_jwt_token("revoked").unwrap();
1741        assert_rejected(
1742            &manager,
1743            &sign(&key, Algorithm::ES256, &claims("c", "revoked")),
1744            "revoked jti",
1745        )
1746        .await;
1747    }
1748
1749    // ----- registration -----
1750
1751    #[tokio::test]
1752    async fn registration_refuses_symmetric_algorithms() {
1753        let key = p256_key();
1754        for alg in [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512] {
1755            let manager = create_test_manager();
1756            let cfg = ClientJwtConfig::builder("c", key.jwk.clone())
1757                .algorithms(vec![Algorithm::ES256, alg])
1758                .audience(TOKEN_ENDPOINT)
1759                .build();
1760            assert!(manager.register_client(cfg).await.is_err(), "{alg:?}");
1761        }
1762    }
1763
1764    #[tokio::test]
1765    async fn an_audience_is_optional_by_default_and_required_on_request() {
1766        let key = p256_key();
1767
1768        // Default (patch-release compatible): a client without an audience registers, and its
1769        // signature is still verified; any `aud` value is then accepted.
1770        let lenient = create_test_manager();
1771        let none = ClientJwtConfig::builder("c", key.jwk.clone())
1772            .algorithms(vec![Algorithm::ES256])
1773            .build();
1774        lenient.register_client(none).await.unwrap();
1775        let ok = lenient
1776            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "no-aud-1")))
1777            .await
1778            .unwrap();
1779        assert!(ok.authenticated, "{:?}", ok.errors);
1780        // ... but the signature is still checked: another key's assertion is refused.
1781        let other = p256_key();
1782        let forged = lenient
1783            .authenticate_client(&sign(&other, Algorithm::ES256, &claims("c", "no-aud-2")))
1784            .await
1785            .unwrap();
1786        assert!(!forged.authenticated);
1787
1788        // Opt in: no audience, no registration.
1789        let strict = create_test_manager().require_audiences(true);
1790        let none = ClientJwtConfig::builder("c", key.jwk.clone()).build();
1791        assert!(strict.register_client(none).await.is_err());
1792
1793        // A blank audience is refused either way.
1794        for manager in [
1795            create_test_manager(),
1796            create_test_manager().require_audiences(true),
1797        ] {
1798            let blank = ClientJwtConfig::builder("c", key.jwk.clone())
1799                .audience("  ")
1800                .build();
1801            assert!(manager.register_client(blank).await.is_err());
1802        }
1803    }
1804
1805    #[tokio::test]
1806    async fn registration_refuses_private_or_symmetric_key_material() {
1807        let manager = create_test_manager();
1808        for member in ["d", "p", "q", "dp", "dq", "qi", "k"] {
1809            let mut jwk = p256_key().jwk;
1810            jwk[member] = json!("AQAB");
1811            let cfg = ClientJwtConfig::builder("c", jwk)
1812                .audience(TOKEN_ENDPOINT)
1813                .build();
1814            assert!(manager.register_client(cfg).await.is_err(), "{member}");
1815        }
1816        let oct = json!({"kty": "oct", "k": "c2VjcmV0"});
1817        let cfg = ClientJwtConfig::builder("c", oct)
1818            .audience(TOKEN_ENDPOINT)
1819            .build();
1820        assert!(manager.register_client(cfg).await.is_err());
1821    }
1822
1823    #[tokio::test]
1824    async fn registration_refuses_unusable_keys() {
1825        let manager = create_test_manager();
1826        let good = p256_key().jwk;
1827
1828        let mut cases: Vec<(&str, Value)> = vec![
1829            ("empty object", json!({})),
1830            ("not an object", json!("RSA")),
1831            ("unknown kty", json!({"kty": "XYZ"})),
1832            (
1833                "P-521 has no supported algorithm",
1834                json!({"kty": "EC", "crv": "P-521", "x": good["x"], "y": good["y"]}),
1835            ),
1836            (
1837                "short EC coordinate",
1838                json!({"kty": "EC", "crv": "P-256", "x": b64(&[1u8; 8]), "y": good["y"]}),
1839            ),
1840            (
1841                "bad base64",
1842                json!({"kty": "EC", "crv": "P-256", "x": "***", "y": good["y"]}),
1843            ),
1844            ("wrong use", {
1845                let mut j = good.clone();
1846                j["use"] = json!("enc");
1847                j
1848            }),
1849            (
1850                "1024-bit RSA",
1851                json!({"kty": "RSA", "n": b64(&[0xC3u8; 128]), "e": "AQAB"}),
1852            ),
1853            (
1854                "empty RSA modulus",
1855                json!({"kty": "RSA", "n": "", "e": "AQAB"}),
1856            ),
1857        ];
1858        let rsa = rsa_key().jwk;
1859        cases.push((
1860            "RSA exponent 1",
1861            json!({"kty": "RSA", "n": rsa["n"], "e": "AQ"}),
1862        ));
1863        cases.push((
1864            "RSA zero exponent",
1865            json!({"kty": "RSA", "n": rsa["n"], "e": "AA"}),
1866        ));
1867        cases.push((
1868            "RSA even exponent",
1869            json!({"kty": "RSA", "n": rsa["n"], "e": "BA"}),
1870        ));
1871        for (name, jwk) in cases {
1872            let cfg = ClientJwtConfig::builder("c", jwk)
1873                .audience(TOKEN_ENDPOINT)
1874                .build();
1875            assert!(manager.register_client(cfg).await.is_err(), "{name}");
1876        }
1877    }
1878
1879    #[tokio::test]
1880    async fn registration_requires_an_algorithm_that_fits_the_key() {
1881        let manager = create_test_manager();
1882        let cfg = ClientJwtConfig::builder("c", p256_key().jwk)
1883            .algorithms(vec![Algorithm::RS256])
1884            .audience(TOKEN_ENDPOINT)
1885            .build();
1886        assert!(manager.register_client(cfg).await.is_err());
1887        let cfg = ClientJwtConfig::builder("c", p256_key().jwk)
1888            .algorithms(vec![])
1889            .audience(TOKEN_ENDPOINT)
1890            .build();
1891        assert!(manager.register_client(cfg).await.is_err());
1892        let cfg = ClientJwtConfig::builder("  ", p256_key().jwk)
1893            .audience(TOKEN_ENDPOINT)
1894            .build();
1895        assert!(manager.register_client(cfg).await.is_err());
1896    }
1897
1898    #[tokio::test]
1899    async fn registration_refuses_nonsensical_time_settings() {
1900        let key = p256_key();
1901        let manager = create_test_manager();
1902        let negative_skew = ClientJwtConfig::builder("c", key.jwk.clone())
1903            .audience(TOKEN_ENDPOINT)
1904            .clock_skew(Duration::seconds(-5))
1905            .build();
1906        assert!(manager.register_client(negative_skew).await.is_err());
1907        let zero_lifetime = ClientJwtConfig::builder("c", key.jwk.clone())
1908            .audience(TOKEN_ENDPOINT)
1909            .max_jwt_lifetime(Duration::zero())
1910            .build();
1911        assert!(manager.register_client(zero_lifetime).await.is_err());
1912    }
1913
1914    // ----- client-side helper and housekeeping (unchanged behaviour) -----
1915
1916    #[test]
1917    fn test_create_client_assertion() {
1918        let manager = create_test_manager();
1919
1920        // HS256 uses a raw secret.
1921        let assertion = manager
1922            .create_client_assertion(
1923                "test_client",
1924                "https://auth.example.com/token",
1925                b"super-secret-key-for-testing-purposes",
1926                Algorithm::HS256,
1927            )
1928            .unwrap();
1929
1930        // Should have JWT format: header.payload.signature
1931        let parts: Vec<&str> = assertion.split('.').collect();
1932        assert_eq!(parts.len(), 3);
1933        // Each part must be non-empty (real base64url)
1934        assert!(!parts[0].is_empty());
1935        assert!(!parts[1].is_empty());
1936        assert!(!parts[2].is_empty());
1937    }
1938
1939    #[test]
1940    fn test_create_client_assertion_rejects_a_key_that_does_not_fit_the_algorithm() {
1941        // Key bytes that are not a PEM key of the algorithm's family are refused, never
1942        // silently signed under a different declared `alg`.
1943        let manager = create_test_manager();
1944        for algorithm in [Algorithm::ES256, Algorithm::RS256, Algorithm::EdDSA] {
1945            let result = manager.create_client_assertion(
1946                "test_client",
1947                "https://auth.example.com/token",
1948                b"super-secret-key-for-testing-purposes",
1949                algorithm,
1950            );
1951            assert!(
1952                result.is_err(),
1953                "{algorithm:?}: a key/algorithm mismatch must be rejected, not silently signed"
1954            );
1955        }
1956    }
1957
1958    #[tokio::test]
1959    async fn a_client_built_assertion_authenticates() {
1960        let key = p256_key();
1961        let manager = registered("c", &key).await;
1962        let assertion = manager
1963            .create_client_assertion("c", TOKEN_ENDPOINT, key.pem.as_bytes(), Algorithm::ES256)
1964            .unwrap();
1965        let result = manager.authenticate_client(&assertion).await.unwrap();
1966        assert!(result.authenticated, "{:?}", result.errors);
1967    }
1968
1969    #[tokio::test]
1970    async fn test_jti_replay_protection() {
1971        let manager = create_test_manager();
1972
1973        // First use is allowed, the second is not.
1974        assert!(
1975            manager
1976                .claim_jti(
1977                    "c",
1978                    "test_jti_123",
1979                    in_an_hour(),
1980                    DEFAULT_MAX_OUTSTANDING_ASSERTIONS
1981                )
1982                .await
1983                .is_ok()
1984        );
1985        assert!(
1986            manager
1987                .claim_jti(
1988                    "c",
1989                    "test_jti_123",
1990                    in_an_hour(),
1991                    DEFAULT_MAX_OUTSTANDING_ASSERTIONS
1992                )
1993                .await
1994                .is_err()
1995        );
1996        // Another client may use the same value.
1997        assert!(
1998            manager
1999                .claim_jti(
2000                    "d",
2001                    "test_jti_123",
2002                    in_an_hour(),
2003                    DEFAULT_MAX_OUTSTANDING_ASSERTIONS
2004                )
2005                .await
2006                .is_ok()
2007        );
2008    }
2009
2010    #[test]
2011    fn test_jwt_timing_validation() {
2012        let manager = create_test_manager();
2013        let config = ClientJwtConfig::default();
2014        let mut errors = Vec::new();
2015
2016        let now = Utc::now().timestamp();
2017
2018        // Test expired JWT
2019        let expired_claims = PrivateKeyJwtClaims {
2020            iss: "test".to_string(),
2021            sub: "test".to_string(),
2022            aud: "test".to_string(),
2023            jti: "test".to_string(),
2024            exp: now - 3600, // Expired 1 hour ago
2025            iat: now - 3660,
2026            nbf: Some(now - 3660),
2027        };
2028
2029        manager.validate_jwt_timing(&expired_claims, &config, &mut errors);
2030        assert!(!errors.is_empty());
2031        assert!(errors.iter().any(|e| e.contains("expired")));
2032    }
2033
2034    #[tokio::test]
2035    async fn test_cleanup_expired_jtis() {
2036        let manager = create_test_manager();
2037
2038        manager
2039            .claim_jti(
2040                "c",
2041                "old_jti",
2042                in_an_hour(),
2043                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2044            )
2045            .await
2046            .unwrap();
2047        manager
2048            .claim_jti(
2049                "c",
2050                "new_jti",
2051                in_an_hour(),
2052                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2053            )
2054            .await
2055            .unwrap();
2056
2057        // Manually set old timestamp
2058        {
2059            let mut jtis = manager.used_jtis.write().await;
2060            jtis.insert(
2061                PrivateKeyJwtManager::jti_key("c", "old_jti"),
2062                Utc::now() - Duration::days(2),
2063            );
2064        }
2065
2066        // Cleanup should remove old JTI
2067        manager.cleanup_expired_jtis().await;
2068
2069        let jtis = manager.used_jtis.read().await;
2070        assert!(!jtis.contains_key(&PrivateKeyJwtManager::jti_key("c", "old_jti")));
2071        assert!(jtis.contains_key(&PrivateKeyJwtManager::jti_key("c", "new_jti")));
2072    }
2073
2074    #[test]
2075    fn test_client_jwt_config_builder() {
2076        let config = ClientJwtConfig::builder("builder_client", p256_key().jwk)
2077            .algorithms(vec![Algorithm::RS256])
2078            .max_jwt_lifetime(Duration::minutes(10))
2079            .clock_skew(Duration::seconds(30))
2080            .audiences([
2081                "https://auth.example.com/token",
2082                "https://auth.example.com/par",
2083            ])
2084            .build();
2085
2086        assert_eq!(config.client_id, "builder_client");
2087        assert_eq!(config.allowed_algorithms, vec![Algorithm::RS256]);
2088        assert_eq!(config.max_jwt_lifetime, Duration::minutes(10));
2089        assert_eq!(config.clock_skew, Duration::seconds(30));
2090        assert_eq!(config.expected_audiences.len(), 2);
2091    }
2092
2093    #[test]
2094    fn test_cleanup_interval_configuration() {
2095        let jwt_config = crate::security::secure_jwt::SecureJwtConfig::default();
2096        let jwt_validator = SecureJwtValidator::new(jwt_config);
2097        let manager =
2098            PrivateKeyJwtManager::new(jwt_validator).with_cleanup_interval(Duration::minutes(30));
2099
2100        assert_eq!(manager.get_cleanup_interval(), Duration::minutes(30));
2101    }
2102
2103    #[test]
2104    fn test_cleanup_interval_update() {
2105        let mut manager = create_test_manager();
2106
2107        // Check default value
2108        assert_eq!(manager.get_cleanup_interval(), Duration::hours(1));
2109
2110        // Update cleanup interval
2111        manager.update_cleanup_interval(Duration::minutes(15));
2112        assert_eq!(manager.get_cleanup_interval(), Duration::minutes(15));
2113    }
2114
2115    #[tokio::test]
2116    async fn test_jwt_token_revocation_integration() {
2117        let manager = create_test_manager();
2118
2119        let jti = "test_revoke_jti_456";
2120
2121        // Token should not be revoked initially
2122        let is_revoked_before = manager.is_jwt_token_revoked(jti).unwrap_or(false);
2123        assert!(!is_revoked_before);
2124
2125        // Revoke the token
2126        manager.revoke_jwt_token(jti).unwrap();
2127
2128        // Token should now be revoked
2129        let is_revoked_after = manager.is_jwt_token_revoked(jti).unwrap_or(false);
2130        assert!(is_revoked_after);
2131    }
2132
2133    #[tokio::test]
2134    async fn test_scheduled_cleanup_integration() {
2135        let mut manager = create_test_manager();
2136
2137        // Set a shorter cleanup interval for testing
2138        manager.update_cleanup_interval(Duration::minutes(1));
2139
2140        // Add some test JTIs and revoked tokens
2141        manager
2142            .claim_jti(
2143                "c",
2144                "test_jti_1",
2145                in_an_hour(),
2146                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2147            )
2148            .await
2149            .unwrap();
2150        manager.revoke_jwt_token("revoked_jti_1").unwrap();
2151
2152        // Run scheduled cleanup
2153        manager.schedule_automatic_cleanup().await;
2154
2155        // Verify cleanup was executed (this mainly tests that the method runs without errors)
2156        assert_eq!(manager.get_cleanup_interval(), Duration::minutes(1));
2157    }
2158
2159    #[tokio::test]
2160    async fn test_cleanup_interval_used_in_cleanup_method() {
2161        let mut manager = create_test_manager();
2162
2163        // Set custom cleanup interval
2164        manager.update_cleanup_interval(Duration::minutes(30));
2165
2166        manager
2167            .claim_jti(
2168                "c",
2169                "recent_jti",
2170                in_an_hour(),
2171                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2172            )
2173            .await
2174            .unwrap();
2175        manager
2176            .claim_jti(
2177                "c",
2178                "old_jti",
2179                in_an_hour(),
2180                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2181            )
2182            .await
2183            .unwrap();
2184
2185        // Manually set timestamps to test cleanup interval usage
2186        {
2187            let mut jtis = manager.used_jtis.write().await;
2188            jtis.insert(
2189                PrivateKeyJwtManager::jti_key("c", "recent_jti"),
2190                Utc::now() + Duration::minutes(15), // deadline still ahead: kept
2191            );
2192            jtis.insert(
2193                PrivateKeyJwtManager::jti_key("c", "old_jti"),
2194                Utc::now() - Duration::minutes(45), // deadline passed: dropped
2195            );
2196        }
2197
2198        // Run cleanup - should remove old_jti but keep recent_jti
2199        manager.cleanup_expired_jtis().await;
2200
2201        let jtis = manager.used_jtis.read().await;
2202        assert!(
2203            jtis.contains_key(&PrivateKeyJwtManager::jti_key("c", "recent_jti")),
2204            "Recent JTI should be retained"
2205        );
2206        assert!(
2207            !jtis.contains_key(&PrivateKeyJwtManager::jti_key("c", "old_jti")),
2208            "Old JTI should be removed"
2209        );
2210    }
2211
2212    // ----- review round -----
2213
2214    fn in_an_hour() -> DateTime<Utc> {
2215        Utc::now() + Duration::hours(1)
2216    }
2217
2218    #[tokio::test]
2219    async fn unknown_clients_and_unproven_assertions_get_the_same_answer() {
2220        let (key, attacker) = (p256_key(), p256_key());
2221        let manager = registered("c", &key).await;
2222
2223        let unknown = manager
2224            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("nobody", "j1")))
2225            .await
2226            .unwrap();
2227        let forged = manager
2228            .authenticate_client(&sign(&attacker, Algorithm::ES256, &claims("c", "j2")))
2229            .await
2230            .unwrap();
2231        let wrong_alg = manager
2232            .authenticate_client(&sign(&rsa_key(), Algorithm::RS256, &claims("c", "j3")))
2233            .await;
2234        for result in [&unknown, &forged] {
2235            assert!(!result.authenticated);
2236            assert_eq!(result.errors, vec![GENERIC_REJECTION.to_string()]);
2237            assert!(result.claims.is_none() && result.jti.is_none());
2238        }
2239        // A disallowed algorithm is not told apart from a bad signature either.
2240        let result = wrong_alg.unwrap();
2241        assert_eq!(result.errors, vec![GENERIC_REJECTION.to_string()]);
2242    }
2243
2244    #[tokio::test]
2245    async fn reasons_are_given_only_once_the_key_has_vouched_for_the_assertion() {
2246        let key = p256_key();
2247        let manager = registered("c", &key).await;
2248        let reasons = |claims: Value| {
2249            let manager = &manager;
2250            let key = &key;
2251            async move {
2252                manager
2253                    .authenticate_client(&sign(key, Algorithm::ES256, &claims))
2254                    .await
2255                    .unwrap()
2256                    .errors
2257                    .join("; ")
2258                    .to_lowercase()
2259            }
2260        };
2261        let mut wrong_aud = claims("c", "r1");
2262        wrong_aud["aud"] = json!("https://evil.example/token");
2263        assert!(reasons(wrong_aud).await.contains("audience"));
2264        let mut expired = claims("c", "r2");
2265        let now = Utc::now().timestamp();
2266        expired["exp"] = json!(now - 3600);
2267        expired["iat"] = json!(now - 3700);
2268        expired["nbf"] = json!(now - 3700);
2269        assert!(reasons(expired).await.contains("expired"));
2270        let mut other_sub = claims("c", "r3");
2271        other_sub["sub"] = json!("someone-else");
2272        assert!(reasons(other_sub).await.contains("subject"));
2273        // None of those messages says anything about "signature".
2274        let mut blank_jti = claims("c", "r4");
2275        blank_jti["jti"] = json!(" ");
2276        assert!(!reasons(blank_jti).await.contains("signature"));
2277    }
2278
2279    #[tokio::test]
2280    async fn the_key_family_check_rejects_a_header_that_does_not_fit_the_key() {
2281        let manager = create_test_manager();
2282        let (p256, p384, rsa) = (p256_key(), p384_key(), rsa_key());
2283        let everything = vec![
2284            Algorithm::ES256,
2285            Algorithm::ES384,
2286            Algorithm::RS256,
2287            Algorithm::EdDSA,
2288        ];
2289        let config_for = |key: &TestKey| {
2290            ClientJwtConfig::builder("c", key.jwk.clone())
2291                .algorithms(everything.clone())
2292                .audience(TOKEN_ENDPOINT)
2293                .build()
2294        };
2295        // (key registered, algorithm in the header)
2296        for (key, algorithm) in [
2297            (&p384, Algorithm::ES256),
2298            (&p256, Algorithm::ES384),
2299            (&p256, Algorithm::RS256),
2300            (&rsa, Algorithm::ES256),
2301            (&p384, Algorithm::EdDSA),
2302        ] {
2303            let config = config_for(key);
2304            let outcome = manager.verify_jwt_signature("a.b.c", &Header::new(algorithm), &config);
2305            match outcome {
2306                Err(Rejection::Unproven(reason)) => assert!(
2307                    reason.contains("does not match"),
2308                    "{algorithm:?} against {:?}: {reason}",
2309                    key.algorithm
2310                ),
2311                other => panic!(
2312                    "{algorithm:?} against a {:?} key must be refused by the family check, got {}",
2313                    key.algorithm,
2314                    match other {
2315                        Ok(_) => "success".to_string(),
2316                        Err(Rejection::Unproven(r)) | Err(Rejection::Proven(r)) => r,
2317                    }
2318                ),
2319            }
2320        }
2321    }
2322
2323    #[tokio::test]
2324    async fn aud_may_be_an_array_with_one_configured_audience() {
2325        let key = p256_key();
2326        let manager = registered("c", &key).await;
2327        let mut listed = claims("c", "a1");
2328        listed["aud"] = json!(["https://other.example", TOKEN_ENDPOINT]);
2329        let result = manager
2330            .authenticate_client(&sign(&key, Algorithm::ES256, &listed))
2331            .await
2332            .unwrap();
2333        assert!(result.authenticated, "{:?}", result.errors);
2334        assert_eq!(result.claims.unwrap().aud, TOKEN_ENDPOINT);
2335
2336        let mut foreign = claims("c", "a2");
2337        foreign["aud"] = json!(["https://other.example", "https://more.example"]);
2338        assert_rejected(
2339            &manager,
2340            &sign(&key, Algorithm::ES256, &foreign),
2341            "no configured audience",
2342        )
2343        .await;
2344        let mut prefix = claims("c", "a3");
2345        prefix["aud"] = json!([format!("{TOKEN_ENDPOINT}/extra")]);
2346        assert_rejected(
2347            &manager,
2348            &sign(&key, Algorithm::ES256, &prefix),
2349            "audience is not a prefix match",
2350        )
2351        .await;
2352        let mut empty = claims("c", "a4");
2353        empty["aud"] = json!([]);
2354        assert_rejected(
2355            &manager,
2356            &sign(&key, Algorithm::ES256, &empty),
2357            "empty audience array",
2358        )
2359        .await;
2360    }
2361
2362    #[tokio::test]
2363    async fn cleanup_cannot_reopen_the_replay_window() {
2364        let key = p256_key();
2365        let mut manager = registered("c", &key).await;
2366        // An interval far shorter than the assertion's remaining life.
2367        manager.update_cleanup_interval(Duration::milliseconds(1));
2368        let assertion = sign(&key, Algorithm::ES256, &claims("c", "window"));
2369        assert!(
2370            manager
2371                .authenticate_client(&assertion)
2372                .await
2373                .unwrap()
2374                .authenticated
2375        );
2376        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
2377        manager.cleanup_expired_jtis().await;
2378        manager.schedule_automatic_cleanup().await;
2379        let replay = manager.authenticate_client(&assertion).await.unwrap();
2380        assert!(!replay.authenticated, "replayed after cleanup");
2381
2382        // The entry goes once its own deadline (exp + skew) has passed.
2383        {
2384            let mut jtis = manager.used_jtis.write().await;
2385            for deadline in jtis.values_mut() {
2386                *deadline = Utc::now() - Duration::seconds(1);
2387            }
2388        }
2389        manager.cleanup_expired_jtis().await;
2390        assert!(manager.used_jtis.read().await.is_empty());
2391    }
2392
2393    #[tokio::test]
2394    async fn a_revoked_jti_is_not_forgotten_while_an_assertion_could_still_use_it() {
2395        let key = p256_key();
2396        let mut manager = registered("c", &key).await;
2397        manager.update_cleanup_interval(Duration::milliseconds(1));
2398        manager.revoke_jwt_token("revoked-early").unwrap();
2399        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
2400        manager.schedule_automatic_cleanup().await;
2401        assert!(manager.is_jwt_token_revoked("revoked-early").unwrap());
2402        assert_rejected(
2403            &manager,
2404            &sign(&key, Algorithm::ES256, &claims("c", "revoked-early")),
2405            "revocation outlived by cleanup",
2406        )
2407        .await;
2408    }
2409
2410    #[tokio::test]
2411    async fn extreme_timestamps_are_refused_without_overflow() {
2412        let key = p256_key();
2413        let manager = registered("c", &key).await;
2414        let cases = [
2415            (i64::MIN + 1000, i64::MAX - 1000),
2416            (i64::MIN, i64::MAX),
2417            (0, i64::MAX),
2418            (i64::MAX, i64::MIN),
2419            (i64::MAX - 5, i64::MAX),
2420        ];
2421        for (n, (iat, exp)) in cases.into_iter().enumerate() {
2422            let mut c = claims("c", &format!("big{n}"));
2423            c["iat"] = json!(iat);
2424            c["exp"] = json!(exp);
2425            c["nbf"] = json!(iat);
2426            assert_rejected(
2427                &manager,
2428                &sign(&key, Algorithm::ES256, &c),
2429                &format!("{iat}..{exp}"),
2430            )
2431            .await;
2432        }
2433        // The timing check itself, called directly with the extremes.
2434        let mut errors = Vec::new();
2435        let config = ClientJwtConfig::default();
2436        let extreme = PrivateKeyJwtClaims {
2437            iss: "c".into(),
2438            sub: "c".into(),
2439            aud: "a".into(),
2440            jti: "j".into(),
2441            exp: i64::MAX - 1000,
2442            iat: i64::MIN + 1000,
2443            nbf: Some(i64::MIN),
2444        };
2445        manager.validate_jwt_timing(&extreme, &config, &mut errors);
2446        assert!(!errors.is_empty());
2447    }
2448
2449    #[tokio::test]
2450    async fn client_ids_cannot_be_used_to_collide_jti_keys() {
2451        let manager = create_test_manager();
2452        let key = p256_key();
2453        for bad in ["a\0b", "line\nbreak", "tab\there", &"x".repeat(257)] {
2454            let cfg = ClientJwtConfig::builder(bad, key.jwk.clone())
2455                .audience(TOKEN_ENDPOINT)
2456                .build();
2457            assert!(manager.register_client(cfg).await.is_err(), "{bad:?}");
2458        }
2459        // Even if such ids existed, their (client, jti) keys do not collide.
2460        manager
2461            .claim_jti(
2462                "a",
2463                "b\0c",
2464                in_an_hour(),
2465                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2466            )
2467            .await
2468            .unwrap();
2469        manager
2470            .claim_jti(
2471                "a\0b",
2472                "c",
2473                in_an_hour(),
2474                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2475            )
2476            .await
2477            .unwrap();
2478    }
2479
2480    #[tokio::test]
2481    async fn registration_bounds_the_clock_skew_and_lifetime() {
2482        let manager = create_test_manager();
2483        let key = p256_key();
2484        let build = |skew, lifetime| {
2485            ClientJwtConfig::builder("c", key.jwk.clone())
2486                .audience(TOKEN_ENDPOINT)
2487                .clock_skew(skew)
2488                .max_jwt_lifetime(lifetime)
2489                .build()
2490        };
2491        assert!(
2492            manager
2493                .register_client(build(Duration::minutes(11), Duration::minutes(5)))
2494                .await
2495                .is_err()
2496        );
2497        assert!(
2498            manager
2499                .register_client(build(Duration::seconds(60), Duration::hours(25)))
2500                .await
2501                .is_err()
2502        );
2503        manager
2504            .register_client(build(Duration::minutes(10), Duration::hours(24)))
2505            .await
2506            .unwrap();
2507    }
2508
2509    #[tokio::test]
2510    async fn oversized_assertions_and_jtis_are_refused() {
2511        let key = p256_key();
2512        let manager = registered("c", &key).await;
2513        // Genuinely signed and otherwise valid, but padded past the size limit.
2514        let mut padded = claims("c", "padded");
2515        padded["pad"] = json!("x".repeat(9000));
2516        let huge = sign(&key, Algorithm::ES256, &padded);
2517        assert!(huge.len() > MAX_ASSERTION_BYTES);
2518        assert!(manager.authenticate_client(&huge).await.is_err());
2519        // The same assertion within the limit is fine.
2520        let mut small = claims("c", "not-padded");
2521        small["pad"] = json!("x".repeat(100));
2522        assert!(
2523            manager
2524                .authenticate_client(&sign(&key, Algorithm::ES256, &small))
2525                .await
2526                .unwrap()
2527                .authenticated
2528        );
2529
2530        let mut long_jti = claims("c", &"j".repeat(300));
2531        long_jti["jti"] = json!("j".repeat(300));
2532        let result = manager
2533            .authenticate_client(&sign(&key, Algorithm::ES256, &long_jti))
2534            .await
2535            .unwrap();
2536        assert!(!result.authenticated);
2537        assert!(
2538            result.errors.join(";").contains("JTI"),
2539            "{:?}",
2540            result.errors
2541        );
2542    }
2543
2544    #[tokio::test]
2545    async fn the_replay_map_is_bounded() {
2546        let manager = create_test_manager();
2547        // Expired entries are swept as the map grows.
2548        {
2549            let mut jtis = manager.used_jtis.write().await;
2550            for i in 0..2000 {
2551                jtis.insert(format!("old{i}"), Utc::now() - Duration::hours(1));
2552            }
2553        }
2554        manager
2555            .claim_jti(
2556                "c",
2557                "fresh",
2558                in_an_hour(),
2559                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2560            )
2561            .await
2562            .unwrap();
2563        assert!(manager.used_jtis.read().await.len() < 10);
2564
2565        // A map full of live entries refuses more rather than growing.
2566        {
2567            let mut jtis = manager.used_jtis.write().await;
2568            for i in 0..MAX_TRACKED_JTIS {
2569                jtis.insert(format!("live{i}"), in_an_hour());
2570            }
2571        }
2572        assert!(
2573            manager
2574                .claim_jti(
2575                    "c",
2576                    "one-too-many",
2577                    in_an_hour(),
2578                    DEFAULT_MAX_OUTSTANDING_ASSERTIONS
2579                )
2580                .await
2581                .is_err()
2582        );
2583    }
2584
2585    #[tokio::test]
2586    async fn an_assertion_that_is_not_a_jwt_is_an_error_not_a_verdict() {
2587        let manager = create_test_manager();
2588        for junk in ["", "a.b", "not a jwt", "a.b.c"] {
2589            assert!(manager.authenticate_client(junk).await.is_err(), "{junk:?}");
2590        }
2591    }
2592
2593    // ----- review round 3 -----
2594
2595    #[tokio::test]
2596    async fn one_client_cannot_use_up_the_room_of_the_others() {
2597        let manager = create_test_manager();
2598        let hour = in_an_hour();
2599        for i in 0..3 {
2600            manager
2601                .claim_jti("a", &format!("j{i}"), hour, 3)
2602                .await
2603                .unwrap();
2604        }
2605        assert!(manager.claim_jti("a", "j3", hour, 3).await.is_err());
2606        // Another client is untouched, and so is a's quota once its entries expire.
2607        manager.claim_jti("b", "j0", hour, 3).await.unwrap();
2608        {
2609            let mut jtis = manager.used_jtis.write().await;
2610            for deadline in jtis.values_mut() {
2611                *deadline = Utc::now() - Duration::seconds(1);
2612            }
2613        }
2614        manager.cleanup_expired_jtis().await;
2615        manager.claim_jti("a", "j3", hour, 3).await.unwrap();
2616    }
2617
2618    #[tokio::test]
2619    async fn the_quota_applies_to_real_assertions_and_is_per_client() {
2620        let (ka, kb) = (p256_key(), p256_key());
2621        let manager = create_test_manager().with_max_outstanding_assertions(2);
2622        manager
2623            .register_client(
2624                ClientJwtConfig::builder("a", ka.jwk.clone())
2625                    .algorithms(vec![Algorithm::ES256])
2626                    .audience(TOKEN_ENDPOINT)
2627                    .build(),
2628            )
2629            .await
2630            .unwrap();
2631        manager.register_client(config("b", &kb)).await.unwrap();
2632        for i in 0..2 {
2633            let r = manager
2634                .authenticate_client(&sign(&ka, Algorithm::ES256, &claims("a", &format!("q{i}"))))
2635                .await
2636                .unwrap();
2637            assert!(r.authenticated, "{:?}", r.errors);
2638        }
2639        let third = assert_rejected(
2640            &manager,
2641            &sign(&ka, Algorithm::ES256, &claims("a", "q2")),
2642            "third outstanding assertion",
2643        )
2644        .await;
2645        assert!(third.join(";").contains("Too many"), "{third:?}");
2646        assert!(
2647            manager
2648                .authenticate_client(&sign(&kb, Algorithm::ES256, &claims("b", "q0")))
2649                .await
2650                .unwrap()
2651                .authenticated
2652        );
2653    }
2654
2655    #[tokio::test]
2656    async fn the_sweep_is_throttled() {
2657        let manager = create_test_manager();
2658        let old = || Utc::now() - Duration::hours(1);
2659        let fill = |n: usize| {
2660            let manager = &manager;
2661            async move {
2662                let mut jtis = manager.used_jtis.write().await;
2663                for i in 0..n {
2664                    jtis.insert(format!("old{i}"), old());
2665                }
2666            }
2667        };
2668        fill(2000).await;
2669        manager
2670            .claim_jti(
2671                "c",
2672                "first",
2673                in_an_hour(),
2674                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2675            )
2676            .await
2677            .unwrap();
2678        assert!(
2679            manager.used_jtis.read().await.len() < 10,
2680            "first claim sweeps"
2681        );
2682
2683        // Right after a sweep, a large map of expired entries is left alone...
2684        fill(2000).await;
2685        manager
2686            .claim_jti(
2687                "c",
2688                "second",
2689                in_an_hour(),
2690                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2691            )
2692            .await
2693            .unwrap();
2694        assert!(
2695            manager.used_jtis.read().await.len() >= 2000,
2696            "no second full scan so soon"
2697        );
2698
2699        // ...until the interval has passed.
2700        manager.used_jtis.write().await.last_sweep =
2701            Some(Utc::now() - Duration::seconds(JTI_SWEEP_INTERVAL_SECS + 1));
2702        manager
2703            .claim_jti(
2704                "c",
2705                "third",
2706                in_an_hour(),
2707                DEFAULT_MAX_OUTSTANDING_ASSERTIONS,
2708            )
2709            .await
2710            .unwrap();
2711        assert!(manager.used_jtis.read().await.len() < 10);
2712    }
2713
2714    #[tokio::test]
2715    async fn iat_is_optional_and_expiry_is_then_bounded_directly() {
2716        let key = p256_key();
2717        let manager = registered("c", &key).await;
2718        let now = Utc::now().timestamp();
2719        let without_iat = |jti: &str, exp: i64| {
2720            let mut c = claims("c", jti);
2721            c.as_object_mut().unwrap().remove("iat");
2722            c["exp"] = json!(exp);
2723            sign(&key, Algorithm::ES256, &c)
2724        };
2725        let ok = manager
2726            .authenticate_client(&without_iat("n1", now + 120))
2727            .await
2728            .unwrap();
2729        assert!(ok.authenticated, "{:?}", ok.errors);
2730        assert_eq!(ok.claims.unwrap().iat, 0);
2731
2732        let far = assert_rejected(
2733            &manager,
2734            &without_iat("n2", now + 3600),
2735            "exp far ahead, no iat",
2736        )
2737        .await;
2738        assert!(far.join(";").contains("further ahead"), "{far:?}");
2739        assert_rejected(&manager, &without_iat("n3", now - 3600), "expired, no iat").await;
2740        // With iat the old rule still applies.
2741        let mut long = claims("c", "n4");
2742        long["exp"] = json!(now + 3600);
2743        assert_rejected(
2744            &manager,
2745            &sign(&key, Algorithm::ES256, &long),
2746            "lifetime from iat",
2747        )
2748        .await;
2749    }
2750
2751    #[tokio::test]
2752    async fn malformed_claims_do_not_echo_the_parser() {
2753        let key = p256_key();
2754        let manager = registered("c", &key).await;
2755        let mut wrong_type = claims("c", "w1");
2756        wrong_type["jti"] = json!(12345);
2757        let mut missing = claims("c", "w2");
2758        missing.as_object_mut().unwrap().remove("jti");
2759        for c in [wrong_type, missing] {
2760            let errors = assert_rejected(
2761                &manager,
2762                &sign(&key, Algorithm::ES256, &c),
2763                "bad claim shape",
2764            )
2765            .await;
2766            let text = errors.join(";");
2767            assert_eq!(text, "Invalid assertion claims", "{text}");
2768        }
2769    }
2770
2771    #[tokio::test]
2772    async fn assertion_jtis_have_their_own_revocation_namespace() {
2773        let key = p256_key();
2774        let manager = registered("c", &key).await;
2775        // An access-token jti revoked in the shared validator does not block an assertion...
2776        manager.jwt_validator.revoke_token("shared-name").unwrap();
2777        let r = manager
2778            .authenticate_client(&sign(&key, Algorithm::ES256, &claims("c", "shared-name")))
2779            .await
2780            .unwrap();
2781        assert!(r.authenticated, "{:?}", r.errors);
2782        // ...and revoking an assertion jti does not revoke an access token of that name.
2783        manager.revoke_jwt_token("other-name").unwrap();
2784        assert!(manager.is_jwt_token_revoked("other-name").unwrap());
2785        assert!(
2786            !manager
2787                .jwt_validator
2788                .is_token_revoked("other-name")
2789                .unwrap()
2790        );
2791        assert_rejected(
2792            &manager,
2793            &sign(&key, Algorithm::ES256, &claims("c", "other-name")),
2794            "revoked assertion jti",
2795        )
2796        .await;
2797    }
2798}