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