Skip to main content

auth_framework/server/security/
fapi.rs

1//! FAPI 2.0 (Financial-grade API) Security Profile Implementation
2//!
3//! This module implements the Financial-grade API (FAPI) 2.0 Security Profile,
4//! which provides enhanced security requirements for high-risk scenarios like
5//! financial services.
6//!
7//! # Security Features
8//!
9//! - **Enhanced Request Security**: JWS request object signing
10//! - **Response Security**: JWS response signing
11//! - **Advanced Client Authentication**: Enhanced mTLS and private key JWT
12//! - **Threat Protection**: JARM, DPoP, PAR mandatory
13//! - **Compliance Validation**: Automated FAPI 2.0 requirement checking
14//! - **Sender-Constrained Tokens**: Resource server validation of token binding
15//! - **Rich Authorization Requests**: RFC 9396 fine-grained authorization
16//! - **Enhanced Logging**: Detailed audit trails
17//!
18//! # FAPI 2.0 Requirements
19//!
20//! - Mutual TLS (mTLS) for client authentication
21//! - JWS request object signing (RFC 9101)
22//! - DPoP for sender constraining (RFC 9449)
23//! - Pushed Authorization Requests (PAR) (RFC 9126)
24//! - JWT Secured Authorization Response Mode (JARM)
25//! - Enhanced threat modeling and protection
26
27use crate::distributed::rate_limiting::{DistributedRateLimiter, RateLimitResult};
28use crate::errors::{AuthError, Result};
29use crate::security::secure_jwt::SecureJwtValidator;
30use crate::server::{DpopManager, MutualTlsManager, PARManager, PrivateKeyJwtManager};
31use chrono::{DateTime, Duration, Utc};
32use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
33use serde::{Deserialize, Serialize};
34use serde_json::{Value, json};
35use std::collections::HashMap;
36use std::sync::Arc;
37use tokio::sync::RwLock;
38use uuid::Uuid;
39
40/// FAPI 2.0 Security Profile Manager
41///
42/// # Rate limiting
43///
44/// `FapiManager` has no rate limiter of its own, and the crate's HTTP router does not serve FAPI routes, so nothing in the crate
45/// limits `validate_authorization_request`, `validate_token_request`, `authenticate_client_jwt` or
46/// `validate_sender_constrained_token`. These do signature work and keep per-request state (a DPoP proof and its replay record)
47/// before the caller is authenticated, so put a limiter in front of the FAPI `/authorize` and `/token` endpoints yourself:
48/// one bucket per caller address, counted before any signature check, and one per authenticated client, counted after
49/// client authentication succeeded, with a separate allowance for each endpoint. If the limiter cannot be consulted, refuse
50/// the request rather than serve it unlimited. See `docs/FAPI_RATE_LIMIT_DESIGN.md`.
51///
52/// To have the manager count for you, give it a limiter with [`FapiManager::with_rate_limiter`] and call
53/// [`FapiManager::validate_authorization_request_from`] and [`FapiManager::validate_token_request_from`] with the caller's address;
54/// the methods without `_from` never consult it.
55#[derive(Clone)]
56pub struct FapiManager {
57    /// DPoP manager for sender constraining
58    dpop_manager: Arc<DpopManager>,
59
60    /// Mutual TLS manager for client authentication
61    mtls_manager: Arc<MutualTlsManager>,
62
63    /// PAR manager for pushed authorization requests
64    par_manager: Arc<PARManager>,
65
66    /// Private key JWT manager
67    private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
68
69    /// JWT validator for request object validation
70    jwt_validator: Arc<SecureJwtValidator>,
71
72    /// FAPI configuration
73    config: FapiConfig,
74
75    /// Active FAPI sessions
76    sessions: Arc<RwLock<HashMap<String, FapiSession>>>,
77
78    /// Optional limiter used by the `_from` entry points (see [`FapiManager::with_rate_limiter`])
79    rate_limiter: Option<Arc<DistributedRateLimiter>>,
80}
81
82impl std::fmt::Debug for FapiManager {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        let mut d = f.debug_struct("FapiManager");
85        d.field("dpop_manager", &self.dpop_manager);
86        d.field("mtls_manager", &self.mtls_manager);
87        d.field("par_manager", &self.par_manager);
88        d.field("private_key_jwt_manager", &self.private_key_jwt_manager);
89        d.field("jwt_validator", &self.jwt_validator);
90        d.field("config", &self.config);
91        d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
92        d.field("rate_limiter", &self.rate_limiter.is_some());
93        d.finish()
94    }
95}
96
97/// FAPI 2.0 Configuration
98#[derive(Clone)]
99pub struct FapiConfig {
100    /// Issuer identifier
101    pub issuer: String,
102
103    /// Request object signing algorithm (required: RS256, PS256, or ES256)
104    pub request_signing_algorithm: Algorithm,
105
106    /// Response signing algorithm
107    pub response_signing_algorithm: Algorithm,
108
109    /// Private key for signing
110    pub private_key: EncodingKey,
111
112    /// Public key for verification
113    pub public_key: DecodingKey,
114
115    /// Maximum request object age (seconds)
116    pub max_request_age: i64,
117
118    /// Require DPoP for all requests
119    pub require_dpop: bool,
120
121    /// Require mTLS for all requests
122    pub require_mtls: bool,
123
124    /// Require PAR for authorization requests
125    pub require_par: bool,
126
127    /// Enable JARM (JWT Secured Authorization Response Mode)
128    pub enable_jarm: bool,
129
130    /// Enhanced audit logging
131    pub enhanced_audit: bool,
132
133    /// Whether the config is running in degraded mode (HMAC placeholder keys
134    /// instead of the required RSA keys). FAPI operations MUST reject requests
135    /// when this flag is true.
136    pub is_degraded: bool,
137}
138
139impl std::fmt::Debug for FapiConfig {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        f.debug_struct("FapiConfig")
142            .field("issuer", &self.issuer)
143            .field("request_signing_algorithm", &self.request_signing_algorithm)
144            .field(
145                "response_signing_algorithm",
146                &self.response_signing_algorithm,
147            )
148            .field("private_key", &"<EncodingKey>")
149            .field("public_key", &"<DecodingKey>")
150            .field("max_request_age", &self.max_request_age)
151            .field("require_dpop", &self.require_dpop)
152            .field("require_mtls", &self.require_mtls)
153            .field("require_par", &self.require_par)
154            .field("enable_jarm", &self.enable_jarm)
155            .field("enhanced_audit", &self.enhanced_audit)
156            .field("is_degraded", &self.is_degraded)
157            .finish()
158    }
159}
160
161impl FapiConfig {
162    /// Create a new FAPI 2.0 configuration builder.
163    ///
164    /// The builder enforces strict FAPI 2.0 compliance by default (DPoP, mTLS, PAR, JARM enabled).
165    pub fn builder(
166        issuer: impl Into<String>,
167        private_key: EncodingKey,
168        public_key: DecodingKey,
169    ) -> FapiConfigBuilder {
170        FapiConfigBuilder {
171            issuer: issuer.into(),
172            request_signing_algorithm: Algorithm::PS256,
173            response_signing_algorithm: Algorithm::PS256,
174            private_key,
175            public_key,
176            max_request_age: 60,
177            require_dpop: true,
178            require_mtls: true,
179            require_par: true,
180            enable_jarm: true,
181            enhanced_audit: true,
182            is_degraded: false,
183        }
184    }
185
186    /// Load configuration from environment variables.
187    #[deprecated(since = "0.5.0", note = "use FapiConfig::from_env() instead")]
188    pub fn load_from_env() -> Self {
189        Self::from_env()
190    }
191
192    /// Create a FAPI configuration from standard environment variables.
193    ///
194    /// Reads `FAPI_ISSUER`, `FAPI_PRIVATE_KEY_PATH`, and `FAPI_PUBLIC_KEY_PATH`.
195    pub fn from_env() -> Self {
196        Self::default()
197    }
198}
199
200/// Builder for FAPI 2.0 Configuration
201pub struct FapiConfigBuilder {
202    issuer: String,
203    request_signing_algorithm: Algorithm,
204    response_signing_algorithm: Algorithm,
205    private_key: EncodingKey,
206    public_key: DecodingKey,
207    max_request_age: i64,
208    require_dpop: bool,
209    require_mtls: bool,
210    require_par: bool,
211    enable_jarm: bool,
212    enhanced_audit: bool,
213    is_degraded: bool,
214}
215
216impl FapiConfigBuilder {
217    /// Set the request signing algorithm (default: PS256).
218    ///
219    /// FAPI 2.0 requires PS256 or ES256.
220    pub fn request_signing_algorithm(mut self, alg: Algorithm) -> Self {
221        self.request_signing_algorithm = alg;
222        self
223    }
224
225    /// Set the response signing algorithm (default: PS256).
226    pub fn response_signing_algorithm(mut self, alg: Algorithm) -> Self {
227        self.response_signing_algorithm = alg;
228        self
229    }
230
231    /// Set the maximum allowed age for request objects in seconds (default: 60).
232    pub fn max_request_age(mut self, age: i64) -> Self {
233        self.max_request_age = age;
234        self
235    }
236
237    /// Set whether DPoP is required (default: true).
238    pub fn require_dpop(mut self, require: bool) -> Self {
239        self.require_dpop = require;
240        self
241    }
242
243    /// Set whether mTLS is required (default: true).
244    pub fn require_mtls(mut self, require: bool) -> Self {
245        self.require_mtls = require;
246        self
247    }
248
249    /// Set whether PAR is required (default: true).
250    pub fn require_par(mut self, require: bool) -> Self {
251        self.require_par = require;
252        self
253    }
254
255    /// Enable or disable JARM (default: true).
256    pub fn enable_jarm(mut self, enable: bool) -> Self {
257        self.enable_jarm = enable;
258        self
259    }
260
261    /// Enable or disable enhanced audit logging (default: true).
262    pub fn enhanced_audit(mut self, enable: bool) -> Self {
263        self.enhanced_audit = enable;
264        self
265    }
266
267    /// Mark this configuration as degraded (for testing/development only).
268    pub fn degraded(mut self) -> Self {
269        self.is_degraded = true;
270        self
271    }
272
273    /// Build the FapiConfig.
274    pub fn build(self) -> FapiConfig {
275        FapiConfig {
276            issuer: self.issuer,
277            request_signing_algorithm: self.request_signing_algorithm,
278            response_signing_algorithm: self.response_signing_algorithm,
279            private_key: self.private_key,
280            public_key: self.public_key,
281            max_request_age: self.max_request_age,
282            require_dpop: self.require_dpop,
283            require_mtls: self.require_mtls,
284            require_par: self.require_par,
285            enable_jarm: self.enable_jarm,
286            enhanced_audit: self.enhanced_audit,
287            is_degraded: self.is_degraded,
288        }
289    }
290}
291
292/// FAPI 2.0 Session
293#[derive(Clone, Serialize, Deserialize)]
294pub struct FapiSession {
295    /// Session ID
296    pub session_id: String,
297
298    /// Client ID
299    pub client_id: String,
300
301    /// User ID
302    pub user_id: String,
303
304    /// Session creation time
305    pub created_at: DateTime<Utc>,
306
307    /// Session expiration time
308    pub expires_at: DateTime<Utc>,
309
310    /// DPoP proof token
311    pub dpop_proof: Option<String>,
312
313    /// Client certificate thumbprint
314    pub cert_thumbprint: Option<String>,
315
316    /// Request object JTI (to prevent replay)
317    pub request_jti: Option<String>,
318
319    /// Authorized scopes
320    pub scopes: Vec<String>,
321
322    /// Session metadata
323    pub metadata: HashMap<String, Value>,
324}
325
326impl std::fmt::Debug for FapiSession {
327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328        let mut d = f.debug_struct("FapiSession");
329        d.field(
330            "session_id",
331            &crate::utils::redact::redacted(&self.session_id),
332        );
333        d.field("client_id", &self.client_id);
334        d.field("user_id", &self.user_id);
335        d.field("created_at", &self.created_at);
336        d.field("expires_at", &self.expires_at);
337        d.field(
338            "dpop_proof",
339            &crate::utils::redact::redacted(&self.dpop_proof),
340        );
341        d.field("cert_thumbprint", &self.cert_thumbprint);
342        d.field("request_jti", &self.request_jti);
343        d.field("scopes", &self.scopes);
344        d.field("metadata", &self.metadata);
345        d.finish()
346    }
347}
348
349impl FapiSession {
350    /// Create a new builder for a FAPI 2.0 Session.
351    pub fn builder(
352        session_id: impl Into<String>,
353        client_id: impl Into<String>,
354        user_id: impl Into<String>,
355        expires_in: Duration,
356    ) -> FapiSessionBuilder {
357        let now = Utc::now();
358        FapiSessionBuilder {
359            session_id: session_id.into(),
360            client_id: client_id.into(),
361            user_id: user_id.into(),
362            created_at: now,
363            expires_at: now + expires_in,
364            dpop_proof: None,
365            cert_thumbprint: None,
366            request_jti: None,
367            scopes: Vec::new(),
368            metadata: HashMap::new(),
369        }
370    }
371}
372
373/// Builder for FAPI 2.0 Session
374pub struct FapiSessionBuilder {
375    session_id: String,
376    client_id: String,
377    user_id: String,
378    created_at: DateTime<Utc>,
379    expires_at: DateTime<Utc>,
380    dpop_proof: Option<String>,
381    cert_thumbprint: Option<String>,
382    request_jti: Option<String>,
383    scopes: Vec<String>,
384    metadata: HashMap<String, Value>,
385}
386
387impl FapiSessionBuilder {
388    /// Set the DPoP proof token.
389    pub fn dpop_proof(mut self, proof: impl Into<String>) -> Self {
390        self.dpop_proof = Some(proof.into());
391        self
392    }
393
394    /// Set the client certificate thumbprint for mTLS.
395    pub fn cert_thumbprint(mut self, thumbprint: impl Into<String>) -> Self {
396        self.cert_thumbprint = Some(thumbprint.into());
397        self
398    }
399
400    /// Set the request object JTI to prevent replay.
401    pub fn request_jti(mut self, jti: impl Into<String>) -> Self {
402        self.request_jti = Some(jti.into());
403        self
404    }
405
406    /// Add an authorized scope.
407    pub fn add_scope(mut self, scope: impl Into<String>) -> Self {
408        self.scopes.push(scope.into());
409        self
410    }
411
412    /// Add multiple authorized scopes.
413    pub fn add_scopes<I, S>(mut self, scopes: I) -> Self
414    where
415        I: IntoIterator<Item = S>,
416        S: Into<String>,
417    {
418        self.scopes.extend(scopes.into_iter().map(Into::into));
419        self
420    }
421
422    /// Add custom metadata to the session.
423    pub fn add_metadata(mut self, key: impl Into<String>, value: Value) -> Self {
424        self.metadata.insert(key.into(), value);
425        self
426    }
427
428    /// Build the FapiSession.
429    pub fn build(self) -> FapiSession {
430        FapiSession {
431            session_id: self.session_id,
432            client_id: self.client_id,
433            user_id: self.user_id,
434            created_at: self.created_at,
435            expires_at: self.expires_at,
436            dpop_proof: self.dpop_proof,
437            cert_thumbprint: self.cert_thumbprint,
438            request_jti: self.request_jti,
439            scopes: self.scopes,
440            metadata: self.metadata,
441        }
442    }
443}
444
445/// FAPI 2.0 Request Object Claims
446#[derive(Debug, Clone, Serialize, Deserialize)]
447pub struct FapiRequestObject {
448    /// Issuer (client_id)
449    pub iss: String,
450
451    /// Audience (authorization server)
452    pub aud: String,
453
454    /// Issued at time
455    pub iat: i64,
456
457    /// Expiration time
458    pub exp: i64,
459
460    /// Not before time
461    pub nbf: Option<i64>,
462
463    /// JWT ID (unique identifier)
464    pub jti: String,
465
466    /// Response type
467    pub response_type: String,
468
469    /// Client ID
470    pub client_id: String,
471
472    /// Redirect URI
473    pub redirect_uri: String,
474
475    /// Scope
476    pub scope: String,
477
478    /// State
479    pub state: Option<String>,
480
481    /// Nonce (for OIDC)
482    pub nonce: Option<String>,
483
484    /// Code challenge (for PKCE)
485    pub code_challenge: Option<String>,
486
487    /// Code challenge method
488    pub code_challenge_method: Option<String>,
489
490    /// Additional claims
491    #[serde(flatten)]
492    pub additional_claims: HashMap<String, Value>,
493}
494
495/// FAPI 2.0 Authorization Response (JARM)
496#[derive(Clone, Serialize, Deserialize)]
497pub struct FapiAuthorizationResponse {
498    /// Issuer (authorization server)
499    pub iss: String,
500
501    /// Audience (client_id)
502    pub aud: String,
503
504    /// Issued at time
505    pub iat: i64,
506
507    /// Expiration time
508    pub exp: i64,
509
510    /// Authorization code (if successful)
511    pub code: Option<String>,
512
513    /// State parameter
514    pub state: Option<String>,
515
516    /// Error code (if failed)
517    pub error: Option<String>,
518
519    /// Error description
520    pub error_description: Option<String>,
521
522    /// Additional response parameters
523    #[serde(flatten)]
524    pub additional_params: HashMap<String, Value>,
525}
526
527impl std::fmt::Debug for FapiAuthorizationResponse {
528    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
529        let mut d = f.debug_struct("FapiAuthorizationResponse");
530        d.field("iss", &self.iss);
531        d.field("aud", &self.aud);
532        d.field("iat", &self.iat);
533        d.field("exp", &self.exp);
534        d.field("code", &crate::utils::redact::redacted(&self.code));
535        d.field("state", &self.state);
536        d.field("error", &self.error);
537        d.field("error_description", &self.error_description);
538        d.field(
539            "additional_params",
540            &crate::utils::redact::redacted(&self.additional_params),
541        );
542        d.finish()
543    }
544}
545
546/// FAPI 2.0 Token Response
547#[derive(Clone, Serialize, Deserialize)]
548pub struct FapiTokenResponse {
549    /// Access token
550    pub access_token: String,
551
552    /// Token type (always "DPoP" for FAPI 2.0)
553    pub token_type: String,
554
555    /// Expires in (seconds)
556    pub expires_in: i64,
557
558    /// Refresh token
559    pub refresh_token: Option<String>,
560
561    /// Scope
562    pub scope: Option<String>,
563
564    /// ID token (for OIDC)
565    pub id_token: Option<String>,
566
567    /// Certificate thumbprint confirmation
568    pub cnf: Option<Value>,
569}
570
571impl std::fmt::Debug for FapiTokenResponse {
572    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
573        let mut d = f.debug_struct("FapiTokenResponse");
574        d.field(
575            "access_token",
576            &crate::utils::redact::redacted(&self.access_token),
577        );
578        d.field("token_type", &self.token_type);
579        d.field("expires_in", &self.expires_in);
580        d.field(
581            "refresh_token",
582            &crate::utils::redact::redacted(&self.refresh_token),
583        );
584        d.field("scope", &self.scope);
585        d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
586        d.field("cnf", &self.cnf);
587        d.finish()
588    }
589}
590
591/// Is a request object issued at `iat` older than `max_age` seconds at `now`?
592fn request_object_too_old(now: i64, iat: i64, max_age: i64) -> bool {
593    now.checked_sub(iat).is_none_or(|age| age > max_age)
594}
595
596impl FapiManager {
597    /// Create a new FAPI manager
598    pub fn new(
599        config: FapiConfig,
600        dpop_manager: Arc<DpopManager>,
601        mtls_manager: Arc<MutualTlsManager>,
602        par_manager: Arc<PARManager>,
603        private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
604        jwt_validator: Arc<SecureJwtValidator>,
605    ) -> Self {
606        Self {
607            dpop_manager,
608            mtls_manager,
609            par_manager,
610            private_key_jwt_manager,
611            jwt_validator,
612            config,
613            sessions: Arc::new(RwLock::new(HashMap::new())),
614            rate_limiter: None,
615        }
616    }
617
618    /// Count requests made through [`validate_authorization_request_from`](Self::validate_authorization_request_from)
619    /// and [`validate_token_request_from`](Self::validate_token_request_from) against `limiter`.
620    ///
621    /// Two kinds of bucket live in the limiter: `fapi:<authorize|token>:<peer>` per caller address, counted before any
622    /// signature work, and `fapi_client:<client id>` per authenticated client, counted only after the client proved who it is,
623    /// so a third party cannot spend a client's allowance by naming it. The limiter's configuration sets the allowance. A limiter
624    /// that cannot be consulted refuses the request. The methods without `_from` never consult it.
625    #[must_use]
626    pub fn with_rate_limiter(mut self, limiter: Arc<DistributedRateLimiter>) -> Self {
627        self.rate_limiter = Some(limiter);
628        self
629    }
630
631    /// Map a limiter outcome to a request outcome: only `Allowed` serves the request.
632    fn limiter_outcome(what: &str, outcome: Result<RateLimitResult>) -> Result<()> {
633        match outcome {
634            Ok(RateLimitResult::Allowed { .. }) => Ok(()),
635            Ok(RateLimitResult::Denied { retry_after, .. }) => {
636                tracing::warn!(bucket = %what, "FAPI rate limit exceeded");
637                Err(AuthError::rate_limit(format!(
638                    "Rate limit exceeded; retry after {} seconds",
639                    retry_after.as_secs().max(1)
640                )))
641            }
642            Ok(RateLimitResult::Blocked { unblock_at, .. }) => {
643                tracing::warn!(bucket = %what, "FAPI rate limit: caller blocked");
644                let secs = unblock_at
645                    .checked_duration_since(std::time::Instant::now())
646                    .map_or(1, |d| d.as_secs().max(1));
647                Err(AuthError::rate_limit(format!(
648                    "Rate limit exceeded; retry after {secs} seconds"
649                )))
650            }
651            Err(e) => {
652                tracing::error!(error = %e, bucket = %what, "FAPI rate limiter error");
653                Err(AuthError::internal("Rate limiter unavailable"))
654            }
655        }
656    }
657
658    /// Count one request against `key`; with no limiter configured nothing is counted.
659    async fn count(&self, key: String) -> Result<()> {
660        match &self.rate_limiter {
661            Some(limiter) => Self::limiter_outcome(&key, limiter.check_rate_limit(&key).await),
662            None => Ok(()),
663        }
664    }
665
666    /// Like [`validate_authorization_request`](Self::validate_authorization_request), counting the request against the
667    /// caller address `peer` first and, once the request object is valid, against its client.
668    pub async fn validate_authorization_request_from(
669        &self,
670        peer: &str,
671        request_object: &str,
672        client_cert: Option<&str>,
673        dpop_proof: Option<&str>,
674        request_uri: Option<&str>,
675    ) -> Result<FapiRequestObject> {
676        self.count(format!("fapi:authorize:{peer}")).await?;
677        let request = self
678            .validate_authorization_request(request_object, client_cert, dpop_proof, request_uri)
679            .await?;
680        self.count(format!("fapi_client:{}", request.client_id))
681            .await?;
682        Ok(request)
683    }
684
685    /// Validate FAPI 2.0 authorization request
686    pub async fn validate_authorization_request(
687        &self,
688        request_object: &str,
689        client_cert: Option<&str>,
690        dpop_proof: Option<&str>,
691        request_uri: Option<&str>,
692    ) -> Result<FapiRequestObject> {
693        let claims = if let Some(uri) = request_uri {
694            // PAR workflow - validate request_uri and retrieve the request
695            if self.config.require_par {
696                // Use PAR manager to consume the pushed request
697                let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
698                    AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
699                })?;
700
701                tracing::info!(
702                    "FAPI PAR request consumed successfully for client: {}",
703                    par_request.client_id
704                );
705
706                // Convert PAR request to FAPI request object
707                let nonce = par_request.additional_params.get("nonce").cloned();
708                FapiRequestObject {
709                    iss: par_request.client_id.clone(),
710                    aud: self.config.issuer.clone(),
711                    iat: Utc::now().timestamp(),
712                    exp: Utc::now().timestamp() + 300, // 5 minutes
713                    nbf: Some(Utc::now().timestamp()),
714                    jti: uuid::Uuid::new_v4().to_string(),
715                    response_type: par_request.response_type,
716                    client_id: par_request.client_id,
717                    redirect_uri: par_request.redirect_uri,
718                    scope: par_request.scope.unwrap_or_default(),
719                    state: par_request.state,
720                    nonce,
721                    code_challenge: par_request.code_challenge,
722                    code_challenge_method: par_request.code_challenge_method,
723                    additional_claims: par_request
724                        .additional_params
725                        .into_iter()
726                        .map(|(k, v)| (k, serde_json::Value::String(v)))
727                        .collect(),
728                }
729            } else {
730                return Err(AuthError::InvalidRequest(
731                    "request_uri provided but PAR not required".to_string(),
732                ));
733            }
734        } else {
735            // Standard request object validation
736            if self.config.require_par {
737                return Err(AuthError::InvalidRequest(
738                    "PAR is required but no request_uri provided".to_string(),
739                ));
740            }
741
742            // Validate request object JWT using enhanced validation
743            self.validate_request_object(request_object).await?
744        };
745
746        // Validate mTLS if required
747        if self.config.require_mtls {
748            let cert = client_cert.ok_or_else(|| {
749                AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
750            })?;
751            let cert_bytes = decode_client_certificate(cert)?;
752            self.mtls_manager
753                .validate_client_certificate(&cert_bytes, &claims.client_id)
754                .await?;
755        }
756
757        // Validate DPoP if required; the proof is recorded only once the request has been accepted.
758        let pending_proof = if self.config.require_dpop {
759            let proof = dpop_proof.ok_or_else(|| {
760                AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0")
761            })?;
762            Some(
763                self.dpop_manager
764                    .verify_dpop_proof(
765                        proof,
766                        "POST",
767                        &format!("{}/authorize", self.config.issuer),
768                        None,
769                        None,
770                        None,
771                    )
772                    .await?,
773            )
774        } else {
775            None
776        };
777
778        // Validate request object claims
779        self.validate_request_claims(&claims).await?;
780
781        if let Some(pending) = pending_proof {
782            self.dpop_manager.commit_dpop_proof(pending).await?;
783        }
784
785        Ok(claims)
786    }
787
788    /// Validate request object JWT
789    async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
790        // Use the SecureJwtValidator for enhanced security validation
791        let decoding_key = &self.config.public_key;
792
793        // Validate using SecureJwtValidator with enhanced security features
794        match self
795            .jwt_validator
796            .validate_token(request_object, decoding_key)
797        {
798            Ok(secure_claims) => {
799                // Decode JWT header to get algorithm
800                let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
801                    AuthError::token(format!("Invalid request object header: {}", e))
802                })?;
803
804                // Validate algorithm requirement for FAPI
805                if !matches!(
806                    header.alg,
807                    Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
808                ) {
809                    return Err(AuthError::token(
810                        "Request object must use RS256, PS256, or ES256".to_string(),
811                    ));
812                }
813
814                // Set up validation with the same algorithm for FAPI-specific claims
815                let mut validation = Validation::new(header.alg);
816                validation.set_audience(&[&self.config.issuer]);
817                validation.validate_exp = true;
818                validation.validate_nbf = true;
819
820                // Decode the FAPI request object structure
821                let token_data = jsonwebtoken::decode::<FapiRequestObject>(
822                    request_object,
823                    &self.config.public_key,
824                    &validation,
825                )
826                .map_err(|e| {
827                    AuthError::token(format!("Request object validation failed: {}", e))
828                })?;
829
830                let fapi_claims = token_data.claims;
831
832                // Use the validated secure claims for enhanced security checks
833                // Ensure the subject matches between secure validation and FAPI claims
834                if secure_claims.sub != fapi_claims.client_id {
835                    return Err(AuthError::token(
836                        "Subject mismatch between secure validation and FAPI claims".to_string(),
837                    ));
838                }
839
840                // Use secure claims issuer for additional validation
841                if secure_claims.iss != fapi_claims.iss {
842                    return Err(AuthError::token(
843                        "Issuer mismatch between secure validation and FAPI claims".to_string(),
844                    ));
845                }
846
847                // Validate expiry consistency
848                if secure_claims.exp != fapi_claims.exp {
849                    return Err(AuthError::token(
850                        "Expiry mismatch between secure validation and FAPI claims".to_string(),
851                    ));
852                }
853
854                // Additional FAPI validations using the validated claims
855                let now = Utc::now().timestamp();
856
857                // Check request object age
858                if request_object_too_old(now, fapi_claims.iat, self.config.max_request_age) {
859                    return Err(AuthError::token("Request object too old".to_string()));
860                }
861
862                // Validate required claims
863                if fapi_claims.client_id.is_empty() {
864                    return Err(AuthError::token(
865                        "client_id required in request object".to_string(),
866                    ));
867                }
868
869                if fapi_claims.redirect_uri.is_empty() {
870                    return Err(AuthError::token(
871                        "redirect_uri required in request object".to_string(),
872                    ));
873                }
874
875                if fapi_claims.response_type.is_empty() {
876                    return Err(AuthError::token(
877                        "response_type required in request object".to_string(),
878                    ));
879                }
880
881                tracing::info!(
882                    "FAPI request object validated successfully with SecureJwtValidator for client: {}",
883                    fapi_claims.client_id
884                );
885
886                Ok(fapi_claims)
887            }
888            Err(e) => {
889                tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
890                Err(AuthError::token(format!(
891                    "Enhanced JWT validation failed: {}",
892                    e
893                )))
894            }
895        }
896    }
897
898    /// Validate request object claims against FAPI requirements
899    async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
900        // Validate response_type for FAPI 2.0
901        if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
902            return Err(AuthError::InvalidRequest(
903                "FAPI 2.0 requires code or code id_token response type".to_string(),
904            ));
905        }
906
907        // Validate PKCE for public clients
908        if claims.code_challenge.is_none() {
909            return Err(AuthError::InvalidRequest(
910                "PKCE required for FAPI 2.0".to_string(),
911            ));
912        }
913
914        if let Some(method) = &claims.code_challenge_method {
915            if method != "S256" {
916                return Err(AuthError::InvalidRequest(
917                    "FAPI 2.0 requires S256 code challenge method".to_string(),
918                ));
919            }
920        } else {
921            return Err(AuthError::InvalidRequest(
922                "code_challenge_method required for FAPI 2.0".to_string(),
923            ));
924        }
925
926        Ok(())
927    }
928
929    /// Authenticate client using private key JWT (RFC 7523)
930    ///
931    /// The caller learns only that authentication failed: the detailed reasons (unknown client,
932    /// bad signature, wrong audience, replay, ...) are logged, never returned.
933    pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
934        const REFUSED: &str = "Client authentication failed";
935
936        // Use the private key JWT manager for authentication
937        let auth_result = match self
938            .private_key_jwt_manager
939            .authenticate_client(client_assertion)
940            .await
941        {
942            Ok(result) => result,
943            Err(e) => {
944                tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
945                return Err(AuthError::auth_method("private_key_jwt", REFUSED));
946            }
947        };
948
949        if auth_result.authenticated {
950            tracing::info!(
951                "FAPI client authenticated successfully using private key JWT: {}",
952                auth_result.client_id
953            );
954            Ok(auth_result.client_id)
955        } else {
956            tracing::warn!(
957                "FAPI private key JWT authentication failed: {}",
958                auth_result.errors.join("; ")
959            );
960            Err(AuthError::auth_method("private_key_jwt", REFUSED))
961        }
962    }
963
964    /// Validate FAPI token request with enhanced security
965    pub async fn validate_token_request(
966        &self,
967        client_assertion: Option<&str>,
968        client_cert: Option<&str>,
969        dpop_proof: Option<&str>,
970        _authorization_code: &str,
971    ) -> Result<String> {
972        let client_id = self
973            .authenticate_token_client(client_assertion, client_cert)
974            .await?;
975        self.check_token_dpop(dpop_proof).await?;
976        Ok(client_id)
977    }
978
979    /// Like [`validate_token_request`](Self::validate_token_request), counting the request against the caller address `peer`
980    /// before any signature work, and against the client's own bucket once the client has authenticated (before the DPoP check).
981    pub async fn validate_token_request_from(
982        &self,
983        peer: &str,
984        client_assertion: Option<&str>,
985        client_cert: Option<&str>,
986        dpop_proof: Option<&str>,
987        _authorization_code: &str,
988    ) -> Result<String> {
989        self.count(format!("fapi:token:{peer}")).await?;
990        let client_id = self
991            .authenticate_token_client(client_assertion, client_cert)
992            .await?;
993        self.count(format!("fapi_client:{client_id}")).await?;
994        self.check_token_dpop(dpop_proof).await?;
995        Ok(client_id)
996    }
997
998    /// Authenticate the client of a token request: private key JWT, or mTLS when required.
999    async fn authenticate_token_client(
1000        &self,
1001        client_assertion: Option<&str>,
1002        client_cert: Option<&str>,
1003    ) -> Result<String> {
1004        // Client authentication - prefer private key JWT for FAPI 2.0
1005        let client_id = if let Some(assertion) = client_assertion {
1006            self.authenticate_client_jwt(assertion).await?
1007        } else if self.config.require_mtls {
1008            if let Some(cert) = client_cert {
1009                let cert_bytes = decode_client_certificate(cert)?;
1010
1011                // Look the client up by the identity the certificate carries; the manager then
1012                // verifies the chain AND that this certificate is bound to that client.
1013                let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
1014
1015                self.mtls_manager
1016                    .validate_client_certificate(&cert_bytes, &client_id)
1017                    .await?;
1018
1019                client_id.to_string()
1020            } else {
1021                return Err(AuthError::auth_method(
1022                    "mtls",
1023                    "Client certificate required for FAPI 2.0 token request",
1024                ));
1025            }
1026        } else {
1027            return Err(AuthError::auth_method(
1028                "fapi",
1029                "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
1030            ));
1031        };
1032        Ok(client_id)
1033    }
1034
1035    /// Validate the DPoP proof of a token request when the configuration requires one.
1036    async fn check_token_dpop(&self, dpop_proof: Option<&str>) -> Result<()> {
1037        // Validate DPoP if required
1038        if self.config.require_dpop {
1039            let proof = dpop_proof.ok_or_else(|| {
1040                AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0 token request")
1041            })?;
1042            self.dpop_manager
1043                .validate_dpop_proof(
1044                    proof,
1045                    "POST",
1046                    &format!("{}/token", self.config.issuer),
1047                    None, // an authorization code is not an access token: no `ath` at this endpoint
1048                    None,
1049                )
1050                .await?;
1051        }
1052        Ok(())
1053    }
1054
1055    /// Generate FAPI 2.0 authorization response (JARM)
1056    pub async fn generate_authorization_response(
1057        &self,
1058        client_id: &str,
1059        code: Option<&str>,
1060        state: Option<&str>,
1061        error: Option<&str>,
1062        error_description: Option<&str>,
1063    ) -> Result<String> {
1064        if !self.config.enable_jarm {
1065            return Err(AuthError::Configuration {
1066                message: "JARM not enabled".to_string(),
1067                help: Some("Enable JARM in your configuration to use this feature".to_string()),
1068                docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
1069                source: None,
1070                suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
1071            });
1072        }
1073
1074        let now = Utc::now();
1075        let exp = now + Duration::minutes(5); // Response expires in 5 minutes
1076
1077        let response = FapiAuthorizationResponse {
1078            iss: self.config.issuer.clone(),
1079            aud: client_id.to_string(),
1080            iat: now.timestamp(),
1081            exp: exp.timestamp(),
1082            code: code.map(|c| c.to_string()),
1083            state: state.map(|s| s.to_string()),
1084            error: error.map(|e| e.to_string()),
1085            error_description: error_description.map(|d| d.to_string()),
1086            additional_params: HashMap::new(),
1087        };
1088
1089        // Create JWT header
1090        let header = Header::new(self.config.response_signing_algorithm);
1091
1092        // Sign the response
1093        let token =
1094            jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
1095                AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
1096            })?;
1097
1098        Ok(token)
1099    }
1100
1101    /// Generate FAPI 2.0 token response
1102    pub async fn generate_token_response(
1103        &self,
1104        client_id: &str,
1105        user_id: &str,
1106        scopes: Vec<String>,
1107        cert_thumbprint: Option<String>,
1108        dpop_jkt: Option<String>,
1109    ) -> Result<FapiTokenResponse> {
1110        // Generate access token
1111        let access_token = self
1112            .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
1113            .await?;
1114
1115        // Generate refresh token
1116        let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
1117
1118        // Build confirmation claim
1119        let mut cnf = json!({});
1120
1121        if let Some(thumbprint) = cert_thumbprint {
1122            cnf["x5t#S256"] = Value::String(thumbprint);
1123        }
1124
1125        if let Some(jkt) = dpop_jkt {
1126            cnf["jkt"] = Value::String(jkt);
1127        }
1128
1129        let response = FapiTokenResponse {
1130            access_token,
1131            token_type: "DPoP".to_string(), // Always DPoP for FAPI 2.0
1132            expires_in: 3600,               // 1 hour
1133            refresh_token: Some(refresh_token),
1134            scope: Some(scopes.join(" ")),
1135            id_token: None, // ID token generated by OIDC layer when openid scope present
1136            cnf: if cnf.as_object().is_none_or(|o| o.is_empty()) {
1137                None
1138            } else {
1139                Some(cnf)
1140            },
1141        };
1142
1143        Ok(response)
1144    }
1145
1146    /// Generate access token
1147    async fn generate_access_token(
1148        &self,
1149        client_id: &str,
1150        user_id: &str,
1151        scopes: &[String],
1152        cert_thumbprint: &Option<String>,
1153        dpop_jkt: &Option<String>,
1154    ) -> Result<String> {
1155        let claims =
1156            self.access_token_claims(client_id, user_id, scopes, cert_thumbprint, dpop_jkt);
1157
1158        // Create JWT header
1159        let header = Header::new(Algorithm::RS256);
1160
1161        // Sign the token
1162        let token =
1163            jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1164                AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
1165            })?;
1166
1167        Ok(token)
1168    }
1169
1170    /// The claims of a FAPI access token.
1171    fn access_token_claims(
1172        &self,
1173        client_id: &str,
1174        user_id: &str,
1175        scopes: &[String],
1176        cert_thumbprint: &Option<String>,
1177        dpop_jkt: &Option<String>,
1178    ) -> Value {
1179        let now = Utc::now();
1180        let exp = now + Duration::hours(1);
1181
1182        let mut claims = json!({
1183            "iss": self.config.issuer,
1184            // This server is the audience the resource check accepts; the client is `client_id`.
1185            "aud": self.config.issuer,
1186            "client_id": client_id,
1187            "sub": user_id,
1188            "iat": now.timestamp(),
1189            "nbf": now.timestamp(),
1190            "exp": exp.timestamp(),
1191            "scope": scopes.join(" "),
1192            "jti": Uuid::new_v4().to_string(),
1193            "typ": "access",
1194        });
1195
1196        // Add confirmation claims
1197        let mut cnf = json!({});
1198
1199        if let Some(thumbprint) = cert_thumbprint {
1200            cnf["x5t#S256"] = Value::String(thumbprint.clone());
1201        }
1202
1203        if let Some(jkt) = dpop_jkt {
1204            cnf["jkt"] = Value::String(jkt.clone());
1205        }
1206
1207        if !cnf.as_object().is_none_or(|o| o.is_empty()) {
1208            claims["cnf"] = cnf;
1209        }
1210
1211        claims
1212    }
1213
1214    /// Generate refresh token
1215    async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
1216        let now = Utc::now();
1217        let exp = now + Duration::days(30); // 30 day expiry
1218
1219        let claims = json!({
1220            "iss": self.config.issuer,
1221            "aud": client_id,
1222            "sub": user_id,
1223            "iat": now.timestamp(),
1224            "exp": exp.timestamp(),
1225            "typ": crate::security::secure_jwt::TYP_REFRESH_TOKEN,
1226            "jti": Uuid::new_v4().to_string(),
1227        });
1228
1229        // Create JWT header
1230        let header = Header::new(Algorithm::RS256);
1231
1232        // Sign the token
1233        let token =
1234            jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1235                AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
1236            })?;
1237
1238        Ok(token)
1239    }
1240
1241    /// Create FAPI session
1242    pub async fn create_session(
1243        &self,
1244        client_id: &str,
1245        user_id: &str,
1246        scopes: Vec<String>,
1247        dpop_proof: Option<String>,
1248        cert_thumbprint: Option<String>,
1249        request_jti: Option<String>,
1250    ) -> Result<String> {
1251        let session_id = Uuid::new_v4().to_string();
1252        let now = Utc::now();
1253        let expires_at = now + Duration::hours(24); // 24 hour session
1254
1255        let session = FapiSession {
1256            session_id: session_id.clone(),
1257            client_id: client_id.to_string(),
1258            user_id: user_id.to_string(),
1259            created_at: now,
1260            expires_at,
1261            dpop_proof,
1262            cert_thumbprint,
1263            request_jti,
1264            scopes,
1265            metadata: HashMap::new(),
1266        };
1267
1268        let mut sessions = self.sessions.write().await;
1269        sessions.insert(session_id.clone(), session);
1270
1271        Ok(session_id)
1272    }
1273
1274    /// Get FAPI session
1275    pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
1276        let sessions = self.sessions.read().await;
1277        Ok(sessions.get(session_id).cloned())
1278    }
1279
1280    /// Validate FAPI session
1281    pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
1282        let session = self
1283            .get_session(session_id)
1284            .await?
1285            .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
1286
1287        // Check expiration
1288        if Utc::now() > session.expires_at {
1289            return Err(AuthError::validation("Session expired".to_string()));
1290        }
1291
1292        Ok(session)
1293    }
1294
1295    /// Remove FAPI session
1296    pub async fn remove_session(&self, session_id: &str) -> Result<()> {
1297        let mut sessions = self.sessions.write().await;
1298        sessions.remove(session_id);
1299        Ok(())
1300    }
1301
1302    /// Audit log entry for FAPI compliance
1303    pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
1304        if self.config.enhanced_audit {
1305            // Implement proper audit logging for FAPI compliance
1306            // This should log to secure, tamper-evident storage
1307            // Format: ISO 8601 timestamp, event type, client details, user context
1308            let timestamp = chrono::Utc::now().to_rfc3339();
1309            let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
1310
1311            // In production, write to secure audit log storage
1312            tracing::info!("{}", audit_entry);
1313        }
1314        Ok(())
1315    }
1316
1317    /// Extract client ID from certificate
1318    async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
1319        client_id_from_certificate(cert_bytes)
1320    }
1321
1322    /// Validate FAPI 2.0 compliance of the current configuration.
1323    ///
1324    /// Returns a list of compliance violations. An empty list means the
1325    /// configuration is fully FAPI 2.0 compliant.
1326    pub fn check_compliance(&self) -> Vec<FapiComplianceViolation> {
1327        let mut violations = Vec::new();
1328
1329        if self.config.is_degraded {
1330            violations.push(FapiComplianceViolation {
1331                requirement: "crypto-keys".to_string(),
1332                severity: FapiViolationSeverity::Critical,
1333                message: "RSA key pair not properly configured; all FAPI operations will fail"
1334                    .to_string(),
1335            });
1336        }
1337
1338        if !self.config.require_par {
1339            violations.push(FapiComplianceViolation {
1340                requirement: "par".to_string(),
1341                severity: FapiViolationSeverity::Critical,
1342                message: "FAPI 2.0 Security Profile requires Pushed Authorization Requests"
1343                    .to_string(),
1344            });
1345        }
1346
1347        if !self.config.require_dpop {
1348            violations.push(FapiComplianceViolation {
1349                requirement: "sender-constraint".to_string(),
1350                severity: FapiViolationSeverity::Warning,
1351                message: "DPoP is recommended for sender-constrained tokens".to_string(),
1352            });
1353        }
1354
1355        if !self.config.require_mtls {
1356            violations.push(FapiComplianceViolation {
1357                requirement: "sender-constraint".to_string(),
1358                severity: FapiViolationSeverity::Warning,
1359                message: "mTLS is recommended for client authentication and token binding"
1360                    .to_string(),
1361            });
1362        }
1363
1364        if !self.config.require_dpop && !self.config.require_mtls {
1365            violations.push(FapiComplianceViolation {
1366                requirement: "sender-constraint".to_string(),
1367                severity: FapiViolationSeverity::Critical,
1368                message:
1369                    "FAPI 2.0 requires at least one sender-constraining mechanism (DPoP or mTLS)"
1370                        .to_string(),
1371            });
1372        }
1373
1374        if !self.config.enable_jarm {
1375            violations.push(FapiComplianceViolation {
1376                requirement: "jarm".to_string(),
1377                severity: FapiViolationSeverity::Warning,
1378                message: "JARM is recommended for authorization response integrity".to_string(),
1379            });
1380        }
1381
1382        if !self.config.enhanced_audit {
1383            violations.push(FapiComplianceViolation {
1384                requirement: "audit".to_string(),
1385                severity: FapiViolationSeverity::Warning,
1386                message: "Enhanced audit logging is recommended for FAPI compliance".to_string(),
1387            });
1388        }
1389
1390        if !matches!(
1391            self.config.request_signing_algorithm,
1392            Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
1393        ) {
1394            violations.push(FapiComplianceViolation {
1395                requirement: "algorithm".to_string(),
1396                severity: FapiViolationSeverity::Critical,
1397                message: "Request signing must use RS256, PS256, or ES256".to_string(),
1398            });
1399        }
1400
1401        if self.config.max_request_age > 600 {
1402            violations.push(FapiComplianceViolation {
1403                requirement: "request-lifetime".to_string(),
1404                severity: FapiViolationSeverity::Warning,
1405                message: "Max request age exceeds recommended 10 minutes".to_string(),
1406            });
1407        }
1408
1409        violations
1410    }
1411
1412    /// Returns true if the configuration is fully FAPI 2.0 compliant (no critical violations).
1413    pub fn is_compliant(&self) -> bool {
1414        !self
1415            .check_compliance()
1416            .iter()
1417            .any(|v| matches!(v.severity, FapiViolationSeverity::Critical))
1418    }
1419
1420    /// Validate a sender-constrained access token at a resource server.
1421    ///
1422    /// Verifies that the token's `cnf` claim matches the presented proof
1423    /// (DPoP proof JKT or mTLS certificate thumbprint).
1424    pub async fn validate_sender_constrained_token(
1425        &self,
1426        access_token: &str,
1427        dpop_proof: Option<&str>,
1428        client_cert: Option<&str>,
1429        http_method: &str,
1430        http_uri: &str,
1431    ) -> Result<serde_json::Value> {
1432        // Validate the token's signature and standard claims via SecureJwtValidator
1433        let token_data = self
1434            .jwt_validator
1435            .validate_token(access_token, &self.config.public_key)?;
1436
1437        // Decode the raw JWT payload to access the cnf claim which is not in SecureJwtClaims
1438        let header = jsonwebtoken::decode_header(access_token)
1439            .map_err(|e| AuthError::token(format!("Invalid token header: {}", e)))?;
1440        let mut validation = Validation::new(header.alg);
1441        validation.set_audience(&[&self.config.issuer]);
1442        validation.validate_exp = true;
1443        let raw_claims = jsonwebtoken::decode::<serde_json::Value>(
1444            access_token,
1445            &self.config.public_key,
1446            &validation,
1447        )
1448        .map_err(|e| AuthError::token(format!("Token decode failed: {}", e)))?;
1449
1450        // Extract cnf claim from the raw payload
1451        let cnf = raw_claims.claims.get("cnf").ok_or_else(|| {
1452            AuthError::token("Token is not sender-constrained (missing cnf claim)".to_string())
1453        })?;
1454
1455        // A `cnf` that names no binding we can check, or names one of the wrong type, is not a
1456        // binding: refuse it rather than skip the checks below.
1457        let jkt_member = cnf.get("jkt");
1458        let x5t_member = cnf.get("x5t#S256");
1459        for (name, member) in [("jkt", jkt_member), ("x5t#S256", x5t_member)] {
1460            if member.is_some_and(|v| !v.is_string()) {
1461                return Err(AuthError::token(format!(
1462                    "Token's cnf.{name} is not a string"
1463                )));
1464            }
1465        }
1466        if jkt_member.is_none() && x5t_member.is_none() {
1467            return Err(AuthError::token(
1468                "Token's cnf claim names no supported key binding".to_string(),
1469            ));
1470        }
1471
1472        // Validate DPoP binding if cnf contains jkt. The proof is verified here and recorded
1473        // only after the certificate binding below has passed too.
1474        let pending_proof = if let Some(expected_jkt) = cnf.get("jkt").and_then(|v| v.as_str()) {
1475            let proof = dpop_proof.ok_or_else(|| {
1476                AuthError::token(
1477                    "Token is DPoP-bound but no DPoP proof header provided".to_string(),
1478                )
1479            })?;
1480            Some(
1481                self.dpop_manager
1482                    .verify_dpop_proof(
1483                        proof,
1484                        http_method,
1485                        http_uri,
1486                        Some(access_token),
1487                        None,
1488                        Some(expected_jkt),
1489                    )
1490                    .await?,
1491            )
1492        } else {
1493            None
1494        };
1495
1496        // Validate mTLS certificate binding if cnf contains x5t#S256
1497        if let Some(expected_thumbprint) = cnf.get("x5t#S256").and_then(|v| v.as_str()) {
1498            let cert = client_cert.ok_or_else(|| {
1499                AuthError::token(
1500                    "Token is certificate-bound but no client certificate provided".to_string(),
1501                )
1502            })?;
1503            // RFC 8705 x5t#S256: SHA-256 over the DER encoding of the presented certificate
1504            use base64::Engine;
1505            use sha2::{Digest, Sha256};
1506            let cert_der = decode_client_certificate(cert)?;
1507            let presented_thumbprint =
1508                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(&cert_der));
1509            if !bool::from(subtle::ConstantTimeEq::ct_eq(
1510                presented_thumbprint.as_bytes(),
1511                expected_thumbprint.as_bytes(),
1512            )) {
1513                return Err(AuthError::token(
1514                    "Certificate thumbprint does not match token binding".to_string(),
1515                ));
1516            }
1517        }
1518
1519        if let Some(pending) = pending_proof {
1520            self.dpop_manager.commit_dpop_proof(pending).await?;
1521        }
1522
1523        // Return the validated token claims
1524        Ok(serde_json::json!({
1525            "sub": token_data.sub,
1526            "iss": token_data.iss,
1527            "exp": token_data.exp,
1528            "scope": token_data.scope,
1529        }))
1530    }
1531
1532    /// Validate a Rich Authorization Request (RFC 9396) authorization_details parameter.
1533    pub fn validate_authorization_details(
1534        &self,
1535        authorization_details: &[AuthorizationDetail],
1536    ) -> Result<()> {
1537        if authorization_details.is_empty() {
1538            return Err(AuthError::InvalidRequest(
1539                "authorization_details must not be empty".to_string(),
1540            ));
1541        }
1542
1543        for (i, detail) in authorization_details.iter().enumerate() {
1544            if detail.r#type.is_empty() {
1545                return Err(AuthError::InvalidRequest(format!(
1546                    "authorization_details[{}]: type is required",
1547                    i
1548                )));
1549            }
1550
1551            // Validate locations if present
1552            for location in &detail.locations {
1553                if !location.starts_with("https://") {
1554                    return Err(AuthError::InvalidRequest(format!(
1555                        "authorization_details[{}]: location must use HTTPS: {}",
1556                        i, location
1557                    )));
1558                }
1559            }
1560
1561            // Validate actions are non-empty strings
1562            for action in &detail.actions {
1563                if action.is_empty() {
1564                    return Err(AuthError::InvalidRequest(format!(
1565                        "authorization_details[{}]: empty action not allowed",
1566                        i
1567                    )));
1568                }
1569            }
1570        }
1571
1572        Ok(())
1573    }
1574}
1575
1576/// FAPI 2.0 compliance violation
1577#[derive(Debug, Clone)]
1578pub struct FapiComplianceViolation {
1579    /// Which FAPI requirement is violated
1580    pub requirement: String,
1581    /// Severity of the violation
1582    pub severity: FapiViolationSeverity,
1583    /// Human-readable description
1584    pub message: String,
1585}
1586
1587/// Severity of a compliance violation
1588#[derive(Debug, Clone, PartialEq, Eq)]
1589pub enum FapiViolationSeverity {
1590    /// Must be fixed for FAPI 2.0 compliance
1591    Critical,
1592    /// Recommended but not strictly required
1593    Warning,
1594}
1595
1596/// Rich Authorization Request detail (RFC 9396)
1597#[derive(Debug, Clone, Serialize, Deserialize)]
1598pub struct AuthorizationDetail {
1599    /// Type of authorization (e.g. "payment_initiation", "account_information")
1600    pub r#type: String,
1601
1602    /// Resource server locations this authorization applies to
1603    #[serde(default)]
1604    pub locations: Vec<String>,
1605
1606    /// Permitted actions (e.g. "read", "write", "execute")
1607    #[serde(default)]
1608    pub actions: Vec<String>,
1609
1610    /// Data types the client wants to access
1611    #[serde(default)]
1612    pub datatypes: Vec<String>,
1613
1614    /// Unique identifier for the authorization detail
1615    #[serde(skip_serializing_if = "Option::is_none")]
1616    pub identifier: Option<String>,
1617
1618    /// Additional fields specific to the authorization type
1619    #[serde(flatten)]
1620    pub additional_fields: HashMap<String, Value>,
1621}
1622
1623impl Default for FapiConfig {
1624    fn default() -> Self {
1625        // Load configuration from environment variables or use secure defaults
1626        let issuer =
1627            std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
1628
1629        let mut is_degraded = false;
1630
1631        // Load private key from environment — FAPI *requires* asymmetric keys.
1632        // There is intentionally no insecure fallback; callers must either set
1633        // FAPI_PRIVATE_KEY_PATH or construct FapiConfig manually.
1634        let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
1635            std::fs::read(&key_path)
1636                .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
1637                .and_then(|bytes| {
1638                    EncodingKey::from_rsa_pem(&bytes)
1639                        .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
1640                })
1641                .unwrap_or_else(|_| {
1642                    tracing::error!(
1643                        "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH is set but the key could not \
1644                         be loaded. FAPI REQUIRES an RSA private key for request/response signing. \
1645                         Using an ephemeral HMAC placeholder — ALL FAPI OPERATIONS WILL BE REJECTED \
1646                         until a valid RSA key is provided. Set FAPI_PRIVATE_KEY_PATH to a valid \
1647                         PEM-encoded RSA private key file."
1648                    );
1649                    is_degraded = true;
1650                    use ring::rand::{SecureRandom, SystemRandom};
1651                    let rng = SystemRandom::new();
1652                    let mut bytes = [0u8; 32];
1653                    rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1654                    EncodingKey::from_secret(&bytes)
1655                })
1656        } else {
1657            tracing::error!(
1658                "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH not set. FAPI REQUIRES an RSA \
1659                 private key for request and response signing. Using an ephemeral HMAC \
1660                 placeholder — ALL FAPI OPERATIONS WILL BE REJECTED until a valid RSA key \
1661                 is provided. Set FAPI_PRIVATE_KEY_PATH to a PEM-encoded RSA private key file."
1662            );
1663            is_degraded = true;
1664            use ring::rand::{SecureRandom, SystemRandom};
1665            let rng = SystemRandom::new();
1666            let mut bytes = [0u8; 32];
1667            rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1668            EncodingKey::from_secret(&bytes)
1669        };
1670
1671        // Same treatment for the public key.
1672        let public_key = if let Ok(key_path) = std::env::var("FAPI_PUBLIC_KEY_PATH") {
1673            std::fs::read(&key_path)
1674                .map_err(|e| tracing::warn!("Failed to load public key from {}: {}", key_path, e))
1675                .and_then(|bytes| {
1676                    DecodingKey::from_rsa_pem(&bytes)
1677                        .map_err(|e| tracing::warn!("Invalid RSA public key format: {}", e))
1678                })
1679                .unwrap_or_else(|_| {
1680                    tracing::error!(
1681                        "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH is set but the key could not \
1682                         be loaded. FAPI verification will not work correctly."
1683                    );
1684                    is_degraded = true;
1685                    use ring::rand::{SecureRandom, SystemRandom};
1686                    let rng = SystemRandom::new();
1687                    let mut secret = [0u8; 32];
1688                    rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1689                    DecodingKey::from_secret(&secret)
1690                })
1691        } else {
1692            tracing::error!(
1693                "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH not set. FAPI verification will \
1694                 not work correctly. Set FAPI_PUBLIC_KEY_PATH to a PEM-encoded RSA public key file."
1695            );
1696            is_degraded = true;
1697            use ring::rand::{SecureRandom, SystemRandom};
1698            let rng = SystemRandom::new();
1699            let mut secret = [0u8; 32];
1700            rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1701            DecodingKey::from_secret(&secret)
1702        };
1703
1704        Self {
1705            issuer,
1706            request_signing_algorithm: Algorithm::RS256,
1707            response_signing_algorithm: Algorithm::RS256,
1708            private_key,
1709            public_key,
1710            max_request_age: 300, // 5 minutes
1711            require_dpop: true,
1712            require_mtls: true,
1713            require_par: true,
1714            enable_jarm: true,
1715            enhanced_audit: true,
1716            is_degraded,
1717        }
1718    }
1719}
1720
1721/// Decode a client certificate passed as text: PEM (`-----BEGIN CERTIFICATE-----`) or bare
1722/// base64 of the DER encoding. The text must come from the TLS handshake (or a proxy that
1723/// strips client-supplied copies), never from a header or body the client chooses. DER is binary, so the `&str` entry points of this module can
1724/// only ever receive an encoded form; hashing or parsing the text bytes themselves is wrong.
1725fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
1726    use base64::Engine;
1727    use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
1728
1729    const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
1730    const END: &str = "-----END CERTIFICATE-----";
1731    let bad = || {
1732        AuthError::auth_method(
1733            "mtls",
1734            "Client certificate must be PEM or base64-encoded DER",
1735        )
1736    };
1737
1738    let trimmed = input.trim();
1739    let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
1740        let end = rest.find(END).ok_or_else(bad)?;
1741        // Exactly one certificate: nothing but whitespace may follow the END line.
1742        if !rest[end + END.len()..].trim().is_empty() {
1743            return Err(bad());
1744        }
1745        &rest[..end]
1746    } else {
1747        trimmed
1748    };
1749    let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
1750    if compact.is_empty() {
1751        return Err(bad());
1752    }
1753    STANDARD
1754        .decode(&compact)
1755        .or_else(|_| STANDARD_NO_PAD.decode(&compact))
1756        .or_else(|_| URL_SAFE.decode(&compact))
1757        .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
1758        .map_err(|_| bad())
1759}
1760
1761/// The client identity a certificate carries: its single subject CN, otherwise its single
1762/// DNS/URI subjectAltName. Parsed from the DER, never searched for as text in the raw bytes.
1763fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
1764    use x509_parser::extensions::GeneralName;
1765
1766    let cert = match x509_parser::parse_x509_certificate(cert_der) {
1767        Ok(([], cert)) => cert,
1768        _ => {
1769            return Err(AuthError::auth_method(
1770                "mtls",
1771                "Invalid client certificate format",
1772            ));
1773        }
1774    };
1775
1776    let common_names: Vec<String> = cert
1777        .subject()
1778        .iter_common_name()
1779        .filter_map(|cn| cn.as_str().ok().map(str::to_string))
1780        .collect();
1781    if common_names.len() == 1 && !common_names[0].is_empty() {
1782        return Ok(common_names[0].clone());
1783    }
1784
1785    if let Ok(Some(san)) = cert.subject_alternative_name() {
1786        let names: Vec<String> = san
1787            .value
1788            .general_names
1789            .iter()
1790            .filter_map(|name| match name {
1791                GeneralName::DNSName(dns) => Some(dns.to_string()),
1792                GeneralName::URI(uri) => Some(uri.to_string()),
1793                _ => None,
1794            })
1795            .collect();
1796        if names.len() == 1 {
1797            return Ok(names[0].clone());
1798        }
1799    }
1800
1801    Err(AuthError::auth_method(
1802        "mtls",
1803        "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
1804    ))
1805}
1806
1807#[cfg(test)]
1808mod tests {
1809    use super::*;
1810
1811    #[test]
1812    fn test_fapi_config_builder() {
1813        use ring::rand::{SecureRandom, SystemRandom};
1814        let rng = SystemRandom::new();
1815        let mut bytes = [0u8; 32];
1816        rng.fill(&mut bytes).unwrap();
1817        let private_key = EncodingKey::from_secret(&bytes);
1818        let public_key = DecodingKey::from_secret(&bytes);
1819
1820        let config = FapiConfig::builder("https://fapi.example.com", private_key, public_key)
1821            .request_signing_algorithm(Algorithm::ES256)
1822            .max_request_age(120)
1823            .require_dpop(false)
1824            .degraded()
1825            .build();
1826
1827        assert_eq!(config.issuer, "https://fapi.example.com");
1828        assert_eq!(config.request_signing_algorithm, Algorithm::ES256);
1829        assert_eq!(config.max_request_age, 120);
1830        assert!(!config.require_dpop);
1831        assert!(config.require_mtls); // default is true
1832        assert!(config.is_degraded);
1833    }
1834
1835    #[test]
1836    fn test_fapi_session_builder() {
1837        let session = FapiSession::builder(
1838            "sess_123",
1839            "client_456",
1840            "user_789",
1841            Duration::try_hours(1).unwrap(),
1842        )
1843        .dpop_proof("proof_abc")
1844        .add_scope("openid")
1845        .add_scopes(vec!["profile", "email"])
1846        .add_metadata("custom_flag", json!(true))
1847        .build();
1848
1849        assert_eq!(session.session_id, "sess_123");
1850        assert_eq!(session.client_id, "client_456");
1851        assert_eq!(session.user_id, "user_789");
1852        assert_eq!(session.dpop_proof.as_deref(), Some("proof_abc"));
1853        assert_eq!(session.scopes, vec!["openid", "profile", "email"]);
1854        assert_eq!(session.metadata["custom_flag"], true);
1855    }
1856
1857    #[tokio::test]
1858    async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
1859        use crate::security::secure_jwt::SecureJwtConfig;
1860        use crate::server::jwt::private_key_jwt::ClientJwtConfig;
1861        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1862
1863        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
1864        let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1865        let manager = FapiManager::new(
1866            FapiConfig::default(),
1867            Arc::new(DpopManager::new(validator())),
1868            Arc::new(MutualTlsManager::new()),
1869            Arc::new(PARManager::new(Arc::new(
1870                crate::storage::MemoryStorage::new(),
1871            ))),
1872            assertions.clone(),
1873            Arc::new(validator()),
1874        );
1875
1876        // A registered client with a real key.
1877        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1878        let raw = key.public_key_raw();
1879        let point = &raw[raw.len() - 65..];
1880        let jwk = json!({
1881            "kty": "EC", "crv": "P-256",
1882            "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1883            "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1884        });
1885        assertions
1886            .register_client(
1887                ClientJwtConfig::builder("fapi-client", jwk)
1888                    .algorithms(vec![Algorithm::ES256])
1889                    .audience("https://auth.example.com/token")
1890                    .build(),
1891            )
1892            .await
1893            .unwrap();
1894        let encoding_key = EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap();
1895
1896        // Genuine assertion: authenticated.
1897        let good = assertions
1898            .create_client_assertion(
1899                "fapi-client",
1900                "https://auth.example.com/token",
1901                &encoding_key,
1902                Algorithm::ES256,
1903            )
1904            .unwrap();
1905        assert_eq!(
1906            manager.authenticate_client_jwt(&good).await.unwrap(),
1907            "fapi-client"
1908        );
1909
1910        // Each way to fail gives the same bare message: unknown client, wrong audience from the
1911        // real client (a reason that is only known after the signature verified), replay, junk.
1912        let wrong_audience = assertions
1913            .create_client_assertion(
1914                "fapi-client",
1915                "https://elsewhere.example/token",
1916                &encoding_key,
1917                Algorithm::ES256,
1918            )
1919            .unwrap();
1920        let unknown = assertions
1921            .create_client_assertion(
1922                "ghost",
1923                "https://auth.example.com/token",
1924                &encoding_key,
1925                Algorithm::ES256,
1926            )
1927            .unwrap();
1928        for (why, assertion) in [
1929            ("wrong audience", wrong_audience.as_str()),
1930            ("unknown client", unknown.as_str()),
1931            ("replay", good.as_str()),
1932            ("junk", "not-a-jwt"),
1933        ] {
1934            let message = manager
1935                .authenticate_client_jwt(assertion)
1936                .await
1937                .expect_err(why)
1938                .to_string();
1939            assert!(
1940                message.contains("Client authentication failed"),
1941                "{why}: {message}"
1942            );
1943            for leak in [
1944                "udience",
1945                "registered",
1946                "ignature",
1947                "replay",
1948                "JTI",
1949                "Algorithm",
1950                "expired",
1951            ] {
1952                assert!(
1953                    !message.contains(leak),
1954                    "{why}: {message:?} mentions {leak:?}"
1955                );
1956            }
1957        }
1958    }
1959
1960    #[tokio::test]
1961    async fn test_fapi_manager_creation() {
1962        // Comprehensive FAPI configuration validation
1963        let config = FapiConfig::default();
1964
1965        // Verify FAPI security requirements are enabled by default
1966        assert_eq!(config.issuer, "https://auth.example.com"); // Corrected expected value
1967        assert!(config.require_dpop);
1968        assert!(config.require_mtls);
1969        assert!(config.require_par);
1970        assert!(config.enable_jarm);
1971        assert!(config.enhanced_audit);
1972    }
1973
1974    #[tokio::test]
1975    async fn test_fapi_request_validation() {
1976        // Test request object validation according to FAPI requirements
1977        // This should validate JWT request objects, signatures, and claims
1978        let config = FapiConfig::default();
1979
1980        // Mock request object with required FAPI claims
1981        let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1982
1983        // SECURITY CRITICAL: Perform comprehensive JWT validation
1984        let validation_result = validate_fapi_request_object(request_object, &config);
1985        assert!(
1986            validation_result.is_ok(),
1987            "FAPI request object validation failed"
1988        );
1989
1990        // Ensure basic structure is valid but NEVER skip signature verification in production
1991        assert!(!request_object.is_empty());
1992    }
1993
1994    /// Validate FAPI request object with proper JWT verification
1995    fn validate_fapi_request_object(
1996        request_object: &str,
1997        _config: &FapiConfig,
1998    ) -> Result<(), String> {
1999        // Parse JSON structure
2000        let parsed: serde_json::Value = serde_json::from_str(request_object)
2001            .map_err(|_| "Invalid JSON structure in request object")?;
2002
2003        // Validate required FAPI claims
2004        let required_claims = ["iss", "aud", "exp", "iat", "jti"];
2005        for claim in &required_claims {
2006            if parsed.get(claim).is_none() {
2007                return Err(format!("Missing required FAPI claim: {}", claim));
2008            }
2009        }
2010
2011        // Validate expiration
2012        if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
2013            let now = chrono::Utc::now().timestamp();
2014            if exp <= now {
2015                return Err("Request object has expired".to_string());
2016            }
2017        }
2018
2019        // In production: Verify JWT signature against client's public key
2020        // For testing: Accept if structure is valid
2021        Ok(())
2022    }
2023
2024    #[tokio::test]
2025    async fn test_fapi_response_generation() {
2026        // Test JARM (JWT Secured Authorization Response Mode) generation
2027        // This should create signed JWT responses for authorization responses
2028        let config = FapiConfig::default();
2029
2030        // Mock authorization response
2031        let auth_response = serde_json::json!({
2032            "code": "auth_code_123",
2033            "state": "client_state",
2034            "iss": config.issuer,
2035            "aud": "client_id",
2036            "exp": 9999999999i64
2037        });
2038
2039        // In real implementation, sign the response as a JWT
2040        assert!(auth_response["code"].is_string());
2041    }
2042
2043    #[tokio::test]
2044    async fn test_fapi_token_generation() {
2045        // Test FAPI-compliant token generation with DPoP and mTLS
2046        let config = FapiConfig::default();
2047
2048        // Mock FAPI token request with required security features
2049        let scopes = ["accounts".to_string(), "payments".to_string()];
2050        let client_id = "fapi_client_123";
2051        let user_id = "user_456";
2052        let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
2053
2054        // Verify FAPI-specific requirements would be enforced
2055        assert!(config.require_dpop);
2056        assert!(config.require_mtls);
2057        assert!(!scopes.is_empty());
2058        assert!(!client_id.is_empty());
2059        assert!(!user_id.is_empty());
2060        assert!(cert_thumbprint.is_some());
2061    }
2062
2063    #[tokio::test]
2064    async fn test_fapi_session_management() {
2065        // Test FAPI session management and security requirements
2066        let config = FapiConfig::default();
2067
2068        // Mock FAPI session with enhanced security
2069        let session_data = serde_json::json!({
2070            "client_id": "fapi_client",
2071            "user_id": "fapi_user",
2072            "scopes": ["accounts", "payments"],
2073            "mtls_cert": "client_certificate",
2074            "dpop_key": "client_dpop_key"
2075        });
2076
2077        // Verify session includes FAPI security elements
2078        assert!(session_data["mtls_cert"].is_string());
2079        assert!(session_data["dpop_key"].is_string());
2080        assert!(config.enhanced_audit);
2081    }
2082
2083    // ---- certificate input decoding and client-id derivation ----
2084
2085    fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
2086        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2087        let mut dn = rcgen::DistinguishedName::new();
2088        dn.push(rcgen::DnType::CommonName, cn);
2089        if let Some(org) = org {
2090            dn.push(rcgen::DnType::OrganizationName, org);
2091        }
2092        params.distinguished_name = dn;
2093        let key = rcgen::KeyPair::generate().unwrap();
2094        params.self_signed(&key).unwrap()
2095    }
2096
2097    #[test]
2098    fn decode_client_certificate_accepts_pem_and_base64_der() {
2099        use base64::Engine;
2100        let cert = test_cert("client-a", None);
2101        let der = cert.der().to_vec();
2102
2103        assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
2104        let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
2105        assert_eq!(decode_client_certificate(&b64).unwrap(), der);
2106        let wrapped = format!("  {}\n{}  \n", &b64[..20], &b64[20..]);
2107        assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
2108    }
2109
2110    #[test]
2111    fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
2112        let a = test_cert("client-a", None).pem();
2113        let b = test_cert("client-b", None).pem();
2114        assert!(decode_client_certificate("").is_err());
2115        assert!(decode_client_certificate("!!! not base64 !!!").is_err());
2116        assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
2117        // Two certificates in one value: refuse rather than silently using the first.
2118        assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
2119    }
2120
2121    #[test]
2122    fn client_id_comes_from_the_parsed_subject_cn() {
2123        let cert = test_cert("client-a", None);
2124        assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
2125    }
2126
2127    #[test]
2128    fn client_id_is_not_found_by_searching_the_raw_bytes() {
2129        // Text that merely looks like "CN=..." inside another attribute (here Organization) is
2130        // not an identity: the id comes from the parsed subject.
2131        let cert = test_cert("real-client", Some("CN=victim-client,"));
2132        assert_eq!(
2133            client_id_from_certificate(cert.der()).unwrap(),
2134            "real-client"
2135        );
2136    }
2137
2138    #[test]
2139    fn client_id_needs_a_unique_identity() {
2140        // No CN and no SAN: there is nothing to derive, so no id is invented.
2141        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2142        params.distinguished_name = rcgen::DistinguishedName::new(); // rcgen defaults to a CN
2143        let key = rcgen::KeyPair::generate().unwrap();
2144        let nameless = params.self_signed(&key).unwrap();
2145        assert!(client_id_from_certificate(nameless.der()).is_err());
2146        assert!(client_id_from_certificate(b"not a certificate").is_err());
2147    }
2148}
2149
2150#[cfg(test)]
2151mod request_object_age {
2152    use super::*;
2153    use crate::security::secure_jwt::SecureJwtConfig;
2154
2155    const ISS: &str = "https://fapi.example.com";
2156    const CLIENT: &str = "client-1";
2157
2158    fn request_object(enc: &EncodingKey, iat: i64) -> String {
2159        let now = Utc::now().timestamp();
2160        let claims = json!({
2161            "iss": CLIENT, "sub": CLIENT, "aud": ISS, "exp": now + 300, "nbf": now - 1,
2162            "iat": iat, "jti": Uuid::new_v4().to_string(), "scope": "read", "typ": "access",
2163            "response_type": "code", "client_id": CLIENT,
2164            "redirect_uri": "https://client.example/cb",
2165            "code_challenge": "abc", "code_challenge_method": "S256",
2166        });
2167        jsonwebtoken::encode(&Header::new(Algorithm::ES256), &claims, enc).unwrap()
2168    }
2169
2170    #[tokio::test]
2171    async fn the_age_of_a_request_object_cannot_wrap() {
2172        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2173        let pem = key.serialize_pem();
2174        let enc = EncodingKey::from_ec_pem(pem.as_bytes()).unwrap();
2175        let config = FapiConfig {
2176            issuer: ISS.to_string(),
2177            private_key: EncodingKey::from_ec_pem(pem.as_bytes()).unwrap(),
2178            public_key: DecodingKey::from_ec_der(key.public_key_raw()),
2179            ..FapiConfig::default()
2180        };
2181        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2182        let secure = SecureJwtValidator::new(SecureJwtConfig {
2183            allowed_algorithms: vec![Algorithm::ES256],
2184            required_issuers: [CLIENT.to_string()].into_iter().collect(),
2185            ec_public_key_pem: Some(key.public_key_pem()),
2186            require_secure_transport: false,
2187            ..SecureJwtConfig::default()
2188        })
2189        .unwrap();
2190        let m = FapiManager::new(
2191            config,
2192            Arc::new(DpopManager::new(validator())),
2193            Arc::new(MutualTlsManager::new()),
2194            Arc::new(PARManager::new(Arc::new(
2195                crate::storage::MemoryStorage::new(),
2196            ))),
2197            Arc::new(PrivateKeyJwtManager::new(validator())),
2198            Arc::new(secure),
2199        );
2200        let now = Utc::now().timestamp();
2201        m.validate_request_object(&request_object(&enc, now))
2202            .await
2203            .expect("a fresh request object is accepted");
2204        // Old enough to be refused for its age, young enough for the token checks before it.
2205        match m
2206            .validate_request_object(&request_object(&enc, now - 3000))
2207            .await
2208        {
2209            Ok(_) => panic!("a request object 50 minutes old: ACCEPTED"),
2210            Err(e) => assert!(e.to_string().contains("too old"), "refused with {e:?}"),
2211        }
2212        // An iat that cannot be a request object's, whatever stops it first.
2213        assert!(
2214            m.validate_request_object(&request_object(&enc, i64::MIN))
2215                .await
2216                .is_err()
2217        );
2218    }
2219
2220    #[test]
2221    fn an_age_that_cannot_be_represented_is_too_old() {
2222        let now = Utc::now().timestamp();
2223        assert!(!request_object_too_old(now, now, 60));
2224        assert!(!request_object_too_old(now, now - 60, 60));
2225        assert!(request_object_too_old(now, now - 61, 60));
2226        // now - iat overflows: it must read as too old, not wrap (or panic).
2227        assert!(request_object_too_old(now, i64::MIN, 60));
2228        assert!(request_object_too_old(now, i64::MIN + 1, 60));
2229        assert!(request_object_too_old(i64::MAX, -1, 60));
2230    }
2231}
2232
2233#[cfg(test)]
2234mod dpop_regression {
2235    //! DPoP proofs at the FAPI resource check: every way a proof can be wrong is refused, with its
2236    //! own reason, and a correct proof is accepted. Each refusal is paired with the accepted case
2237    //! built the same way, so a test cannot pass because every proof fails for one shared reason.
2238    use super::*;
2239    use crate::security::secure_jwt::SecureJwtConfig;
2240    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as B64};
2241    use sha2::{Digest, Sha256};
2242
2243    const ISS: &str = "https://fapi.example.com";
2244    const URI: &str = "https://rs.example.com/resource";
2245
2246    fn ec_key() -> (EncodingKey, serde_json::Value) {
2247        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2248        let raw = key.public_key_raw();
2249        let point = &raw[raw.len() - 65..];
2250        let jwk = json!({
2251            "kty": "EC", "crv": "P-256",
2252            "x": B64.encode(&point[1..33]),
2253            "y": B64.encode(&point[33..65]),
2254        });
2255        (
2256            EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2257            jwk,
2258        )
2259    }
2260
2261    fn ath_of(token: &str) -> String {
2262        B64.encode(Sha256::digest(token.as_bytes()))
2263    }
2264
2265    /// How to build a proof: everything a correct one has, each field overridable.
2266    struct Proof<'a> {
2267        key: &'a (EncodingKey, serde_json::Value),
2268        htm: &'a str,
2269        htu: &'a str,
2270        iat: i64,
2271        jti: &'a str,
2272        ath: Option<String>,
2273        der: bool,
2274        jwk_extra: Option<(&'a str, &'a str)>,
2275    }
2276
2277    impl Proof<'_> {
2278        fn build(&self) -> String {
2279            let mut jwk = self.key.1.clone();
2280            if let Some((k, v)) = self.jwk_extra {
2281                jwk[k] = json!(v);
2282            }
2283            let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
2284            let mut claims =
2285                json!({"jti": self.jti, "htm": self.htm, "htu": self.htu, "iat": self.iat});
2286            if let Some(a) = &self.ath {
2287                claims["ath"] = json!(a);
2288            }
2289            let si = format!(
2290                "{}.{}",
2291                B64.encode(header.to_string()),
2292                B64.encode(claims.to_string())
2293            );
2294            // jsonwebtoken signs in the JWS form: r || s.
2295            let sig =
2296                jsonwebtoken::crypto::sign(si.as_bytes(), &self.key.0, Algorithm::ES256).unwrap();
2297            if !self.der {
2298                return format!("{si}.{sig}");
2299            }
2300            let raw = B64.decode(sig).unwrap();
2301            let int = |v: &[u8]| {
2302                let mut v: Vec<u8> = v.iter().copied().skip_while(|&x| x == 0).collect();
2303                if v.is_empty() || v[0] & 0x80 != 0 {
2304                    v.insert(0, 0);
2305                }
2306                let mut o = vec![0x02, v.len() as u8];
2307                o.extend(v);
2308                o
2309            };
2310            let mut body = int(&raw[..32]);
2311            body.extend(int(&raw[32..]));
2312            let mut der = vec![0x30, body.len() as u8];
2313            der.extend(body);
2314            format!("{si}.{}", B64.encode(der))
2315        }
2316    }
2317
2318    fn manager() -> (FapiManager, Arc<DpopManager>, Vec<u8>) {
2319        let secret = b"0123456789abcdef0123456789abcdef".to_vec();
2320        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2321        let dpop = Arc::new(DpopManager::new(validator()));
2322        let config = FapiConfig::builder(
2323            ISS,
2324            EncodingKey::from_secret(&secret),
2325            DecodingKey::from_secret(&secret),
2326        )
2327        .build();
2328        let m = FapiManager::new(
2329            config,
2330            dpop.clone(),
2331            Arc::new(MutualTlsManager::new()),
2332            Arc::new(PARManager::new(Arc::new(
2333                crate::storage::MemoryStorage::new(),
2334            ))),
2335            Arc::new(PrivateKeyJwtManager::new(validator())),
2336            Arc::new(
2337                SecureJwtValidator::new(SecureJwtConfig {
2338                    required_issuers: [ISS.to_string()].into_iter().collect(),
2339                    require_secure_transport: false,
2340                    ..SecureJwtConfig::default()
2341                })
2342                .unwrap(),
2343            ),
2344        );
2345        (m, dpop, secret)
2346    }
2347
2348    fn sign_hs256(secret: &[u8], claims: &serde_json::Value) -> String {
2349        jsonwebtoken::encode(
2350            &Header::new(Algorithm::HS256),
2351            claims,
2352            &EncodingKey::from_secret(secret),
2353        )
2354        .unwrap()
2355    }
2356
2357    /// A bound access token written out by hand, so the proof cases do not depend on how the
2358    /// manager mints tokens (that has its own test below).
2359    fn token_for(secret: &[u8], jkt: &str) -> String {
2360        let now = Utc::now().timestamp();
2361        sign_hs256(
2362            secret,
2363            &json!({
2364                "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2365                "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2366                "typ": "access", "cnf": {"jkt": jkt},
2367            }),
2368        )
2369    }
2370
2371    async fn check(m: &FapiManager, tok: &str, proof: Option<&str>, method: &str) -> Result<()> {
2372        m.validate_sender_constrained_token(tok, proof, None, method, URI)
2373            .await
2374            .map(|_| ())
2375    }
2376
2377    fn refused(r: Result<()>, reason: &str, what: &str) {
2378        match r {
2379            Ok(()) => panic!("{what}: ACCEPTED"),
2380            Err(e) => assert!(
2381                e.to_string().contains(reason),
2382                "{what}: refused with {e:?}, expected a reason containing {reason:?}"
2383            ),
2384        }
2385    }
2386
2387    /// One bound token, the key it is bound to, and another key.
2388    struct Fixture {
2389        m: FapiManager,
2390        tok: String,
2391        key_a: (EncodingKey, serde_json::Value),
2392        key_b: (EncodingKey, serde_json::Value),
2393        now: i64,
2394    }
2395
2396    impl Fixture {
2397        fn new() -> Self {
2398            let (m, dpop, secret) = manager();
2399            let key_a = ec_key();
2400            let key_b = ec_key();
2401            let jkt = dpop.create_dpop_confirmation(&key_a.1).unwrap().jkt;
2402            let tok = token_for(&secret, &jkt);
2403            Fixture {
2404                m,
2405                tok,
2406                key_a,
2407                key_b,
2408                now: Utc::now().timestamp(),
2409            }
2410        }
2411
2412        /// The correct proof for the bound key; tests override one field.
2413        fn good<'a>(&'a self, jti: &'a str) -> Proof<'a> {
2414            Proof {
2415                key: &self.key_a,
2416                htm: "GET",
2417                htu: URI,
2418                iat: self.now,
2419                jti,
2420                ath: Some(ath_of(&self.tok)),
2421                der: false,
2422                jwk_extra: None,
2423            }
2424        }
2425
2426        async fn present(&self, proof: &str) -> Result<()> {
2427            check(&self.m, &self.tok, Some(proof), "GET").await
2428        }
2429    }
2430
2431    #[tokio::test]
2432    async fn a_correct_proof_from_the_bound_key_is_accepted() {
2433        let f = Fixture::new();
2434        f.present(&f.good("j-ok").build())
2435            .await
2436            .expect("a correct proof from the bound key is accepted");
2437    }
2438
2439    #[tokio::test]
2440    async fn a_proof_from_another_key_is_refused_though_otherwise_correct() {
2441        let f = Fixture::new();
2442        let p = Proof {
2443            key: &f.key_b,
2444            ..f.good("j-other")
2445        }
2446        .build();
2447        refused(f.present(&p).await, "key binding", "other key");
2448    }
2449
2450    #[tokio::test]
2451    async fn a_proof_for_another_method_url_or_time_is_refused() {
2452        let f = Fixture::new();
2453        let p = Proof {
2454            htm: "DELETE",
2455            ..f.good("j-htm")
2456        }
2457        .build();
2458        refused(f.present(&p).await, "HTTP method", "wrong htm");
2459        let p = Proof {
2460            htu: "https://evil.example/x",
2461            ..f.good("j-htu")
2462        }
2463        .build();
2464        refused(f.present(&p).await, "HTTP URI", "wrong htu");
2465        let p = Proof {
2466            iat: f.now - 86_400,
2467            ..f.good("j-old")
2468        }
2469        .build();
2470        refused(f.present(&p).await, "too old", "one-day-old iat");
2471        let p = Proof {
2472            iat: f.now + 86_400,
2473            ..f.good("j-future")
2474        }
2475        .build();
2476        refused(f.present(&p).await, "in the future", "future iat");
2477    }
2478
2479    #[tokio::test]
2480    async fn a_proof_used_twice_is_refused_the_second_time() {
2481        let f = Fixture::new();
2482        let once = f.good("j-replay").build();
2483        f.present(&once).await.expect("first use");
2484        refused(f.present(&once).await, "already used", "replayed proof");
2485    }
2486
2487    #[tokio::test]
2488    async fn no_proof_is_refused_for_a_bound_token() {
2489        let f = Fixture::new();
2490        refused(
2491            check(&f.m, &f.tok, None, "GET").await,
2492            "no DPoP proof header",
2493            "no proof",
2494        );
2495    }
2496
2497    #[tokio::test]
2498    async fn a_proof_must_name_this_access_token() {
2499        let f = Fixture::new();
2500        let p = Proof {
2501            ath: None,
2502            ..f.good("j-no-ath")
2503        }
2504        .build();
2505        refused(f.present(&p).await, "'ath'", "no ath");
2506        let p = Proof {
2507            ath: Some(ath_of("another-token")),
2508            ..f.good("j-bad-ath")
2509        }
2510        .build();
2511        refused(f.present(&p).await, "access token hash", "wrong ath");
2512    }
2513
2514    #[tokio::test]
2515    async fn a_der_signature_or_a_private_key_in_the_header_is_refused() {
2516        let f = Fixture::new();
2517        let p = Proof {
2518            der: true,
2519            ..f.good("j-der")
2520        }
2521        .build();
2522        refused(f.present(&p).await, "r||s", "DER-encoded ES256 signature");
2523        let p = Proof {
2524            jwk_extra: Some(("d", "AAAA")),
2525            ..f.good("j-priv")
2526        }
2527        .build();
2528        refused(f.present(&p).await, "private key", "private key in jwk");
2529    }
2530
2531    #[tokio::test]
2532    async fn a_token_minted_by_the_manager_passes_its_own_resource_check() {
2533        let (m, dpop, secret) = manager();
2534        let key = ec_key();
2535        let jkt = dpop.create_dpop_confirmation(&key.1).unwrap().jkt;
2536        // generate_access_token signs with the configured RSA key; here the claims it signs are
2537        // signed with the test's HMAC secret, which is what the resource check reads them with.
2538        let claims =
2539            m.access_token_claims("client-1", "user-1", &["read".into()], &None, &Some(jkt));
2540        for field in ["typ", "nbf", "client_id"] {
2541            assert!(claims.get(field).is_some(), "minted claims lack {field}");
2542        }
2543        assert_eq!(claims["aud"], json!(ISS));
2544        let tok = sign_hs256(&secret, &claims);
2545        let proof = Proof {
2546            key: &key,
2547            htm: "GET",
2548            htu: URI,
2549            iat: Utc::now().timestamp(),
2550            jti: "j-minted",
2551            ath: Some(ath_of(&tok)),
2552            der: false,
2553            jwk_extra: None,
2554        }
2555        .build();
2556        check(&m, &tok, Some(&proof), "GET")
2557            .await
2558            .expect("a token built from the manager's own claims is accepted");
2559    }
2560
2561    #[tokio::test]
2562    async fn a_cnf_that_names_no_checkable_binding_is_refused() {
2563        let (m, _dpop, secret) = manager();
2564        let now = Utc::now().timestamp();
2565        for (cnf, what) in [
2566            (json!({}), "empty cnf"),
2567            (json!({"foo": "bar"}), "unknown member only"),
2568            (json!({"jkt": 5}), "jkt that is not a string"),
2569        ] {
2570            let tok = sign_hs256(
2571                &secret,
2572                &json!({
2573                    "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2574                    "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2575                    "typ": "access", "cnf": cnf,
2576                }),
2577            );
2578            refused(check(&m, &tok, None, "GET").await, "cnf", what);
2579        }
2580    }
2581
2582    #[tokio::test]
2583    async fn a_proof_from_the_wrong_key_leaves_no_replay_record() {
2584        let f = Fixture::new();
2585        let p = Proof {
2586            key: &f.key_b,
2587            ..f.good("j-wrong-key")
2588        }
2589        .build();
2590        refused(f.present(&p).await, "key binding", "other key");
2591        assert_eq!(
2592            f.m.dpop_manager.replay_record_count().await,
2593            0,
2594            "a proof refused for its key must not take a cache slot"
2595        );
2596        f.present(&f.good("j-right-key").build())
2597            .await
2598            .expect("the bound key");
2599        assert_eq!(f.m.dpop_manager.replay_record_count().await, 1);
2600    }
2601
2602    #[tokio::test]
2603    async fn an_rs256_token_minted_by_the_manager_passes_the_resource_check() {
2604        // Production signs access tokens with RS256 and an RSA key.
2605        let key =
2606            rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
2607                .unwrap();
2608        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2609        let dpop = Arc::new(DpopManager::new(validator()));
2610        let config = FapiConfig::builder(
2611            ISS,
2612            EncodingKey::from_rsa_pem(key.serialize_pem().as_bytes()).unwrap(),
2613            DecodingKey::from_rsa_der(key.public_key_raw()),
2614        )
2615        .build();
2616        let m = FapiManager::new(
2617            config,
2618            dpop.clone(),
2619            Arc::new(MutualTlsManager::new()),
2620            Arc::new(PARManager::new(Arc::new(
2621                crate::storage::MemoryStorage::new(),
2622            ))),
2623            Arc::new(PrivateKeyJwtManager::new(validator())),
2624            Arc::new(
2625                SecureJwtValidator::new(SecureJwtConfig {
2626                    allowed_algorithms: vec![Algorithm::RS256],
2627                    required_issuers: [ISS.to_string()].into_iter().collect(),
2628                    rsa_public_key_pem: Some(key.public_key_pem()),
2629                    require_secure_transport: false,
2630                    ..SecureJwtConfig::default()
2631                })
2632                .unwrap(),
2633            ),
2634        );
2635        let client = ec_key();
2636        let jkt = dpop.create_dpop_confirmation(&client.1).unwrap().jkt;
2637        let tok = m
2638            .generate_access_token("client-1", "user-1", &["read".into()], &None, &Some(jkt))
2639            .await
2640            .unwrap();
2641        let proof = Proof {
2642            key: &client,
2643            htm: "GET",
2644            htu: URI,
2645            iat: Utc::now().timestamp(),
2646            jti: "j-rs256",
2647            ath: Some(ath_of(&tok)),
2648            der: false,
2649            jwk_extra: None,
2650        }
2651        .build();
2652        check(&m, &tok, Some(&proof), "GET")
2653            .await
2654            .expect("an RS256 token minted by the manager is accepted");
2655    }
2656
2657    #[tokio::test]
2658    async fn a_wrong_certificate_does_not_use_up_the_proof() {
2659        let (m, dpop, secret) = manager();
2660        let key_a = ec_key();
2661        let jkt = dpop.create_dpop_confirmation(&key_a.1).unwrap().jkt;
2662        let cert = rcgen::CertificateParams::default()
2663            .self_signed(&rcgen::KeyPair::generate().unwrap())
2664            .unwrap();
2665        let other = rcgen::CertificateParams::default()
2666            .self_signed(&rcgen::KeyPair::generate().unwrap())
2667            .unwrap();
2668        let x5t = B64.encode(Sha256::digest(cert.der().as_ref()));
2669        let now = Utc::now().timestamp();
2670        // A token bound to both a key and a certificate.
2671        let tok = sign_hs256(
2672            &secret,
2673            &json!({
2674                "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2675                "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2676                "typ": "access", "cnf": {"jkt": jkt, "x5t#S256": x5t},
2677            }),
2678        );
2679        let proof = Proof {
2680            key: &key_a,
2681            htm: "GET",
2682            htu: URI,
2683            iat: now,
2684            jti: "j-both",
2685            ath: Some(ath_of(&tok)),
2686            der: false,
2687            jwk_extra: None,
2688        }
2689        .build();
2690        let wrong = m
2691            .validate_sender_constrained_token(&tok, Some(&proof), Some(&other.pem()), "GET", URI)
2692            .await
2693            .map(|_| ());
2694        refused(wrong, "Certificate thumbprint", "wrong certificate");
2695        assert_eq!(
2696            m.dpop_manager.replay_record_count().await,
2697            0,
2698            "a proof was recorded although the certificate was refused"
2699        );
2700        m.validate_sender_constrained_token(&tok, Some(&proof), Some(&cert.pem()), "GET", URI)
2701            .await
2702            .expect("both bindings satisfied");
2703        assert_eq!(m.dpop_manager.replay_record_count().await, 1);
2704    }
2705
2706    // ---- optional rate limiter on the `_from` entry points (ROADMAP A16 slice 3) ----
2707
2708    struct Limited {
2709        manager: FapiManager,
2710        assertions: Arc<PrivateKeyJwtManager>,
2711        key: EncodingKey,
2712    }
2713
2714    impl Limited {
2715        /// A manager for one registered client `fapi-client`; `max` requests per bucket, or no limiter at all.
2716        async fn new(max: Option<u32>) -> Self {
2717            use crate::distributed::rate_limiting::{RateLimitConfig, RateLimitStrategy};
2718            use crate::security::secure_jwt::SecureJwtConfig;
2719            use crate::server::jwt::private_key_jwt::ClientJwtConfig;
2720            use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
2721
2722            let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2723            let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
2724            let mut manager = FapiManager::new(
2725                FapiConfig {
2726                    require_dpop: false,
2727                    ..FapiConfig::default()
2728                },
2729                Arc::new(DpopManager::new(validator())),
2730                Arc::new(MutualTlsManager::new()),
2731                Arc::new(PARManager::new(Arc::new(
2732                    crate::storage::MemoryStorage::new(),
2733                ))),
2734                assertions.clone(),
2735                Arc::new(validator()),
2736            );
2737            if let Some(max_requests) = max {
2738                let limiter = DistributedRateLimiter::new(RateLimitConfig {
2739                    max_requests,
2740                    window_duration: std::time::Duration::from_secs(600),
2741                    strategy: RateLimitStrategy::FixedWindow,
2742                    distributed: false,
2743                    redis_url: None,
2744                    burst_allowance: None,
2745                    adaptive: false,
2746                    penalty_duration: None,
2747                })
2748                .await
2749                .unwrap();
2750                manager = manager.with_rate_limiter(Arc::new(limiter));
2751            }
2752            let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2753            let raw = key.public_key_raw();
2754            let point = &raw[raw.len() - 65..];
2755            let jwk = json!({
2756                "kty": "EC", "crv": "P-256",
2757                "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
2758                "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
2759            });
2760            assertions
2761                .register_client(
2762                    ClientJwtConfig::builder("fapi-client", jwk)
2763                        .algorithms(vec![Algorithm::ES256])
2764                        .audience("https://auth.example.com/token")
2765                        .build(),
2766                )
2767                .await
2768                .unwrap();
2769            Self {
2770                manager,
2771                assertions,
2772                key: EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2773            }
2774        }
2775
2776        /// A fresh, genuine assertion (each is single-use).
2777        fn assertion(&self) -> String {
2778            self.assertions
2779                .create_client_assertion(
2780                    "fapi-client",
2781                    "https://auth.example.com/token",
2782                    &self.key,
2783                    Algorithm::ES256,
2784                )
2785                .unwrap()
2786        }
2787
2788        /// The right client naming itself with the wrong audience: authentication fails.
2789        fn unauthenticated_assertion(&self) -> String {
2790            self.assertions
2791                .create_client_assertion(
2792                    "fapi-client",
2793                    "https://elsewhere.example/token",
2794                    &self.key,
2795                    Algorithm::ES256,
2796                )
2797                .unwrap()
2798        }
2799
2800        async fn token_from(&self, peer: &str, assertion: &str) -> Result<String> {
2801            self.manager
2802                .validate_token_request_from(peer, Some(assertion), None, None, "code")
2803                .await
2804        }
2805    }
2806
2807    fn is_rate_limited<T>(r: &Result<T>) -> bool {
2808        matches!(r, Err(AuthError::RateLimit { .. }))
2809    }
2810
2811    #[tokio::test]
2812    async fn the_address_bucket_refuses_before_any_signature_work() {
2813        let t = Limited::new(Some(2)).await;
2814        // Under the limit (control): accepted.
2815        assert_eq!(
2816            t.token_from("203.0.113.1", &t.assertion()).await.unwrap(),
2817            "fapi-client"
2818        );
2819        // Two more from the same peer exhaust nothing else; junk is counted too.
2820        assert!(!is_rate_limited(&t.token_from("203.0.113.1", "junk").await));
2821        // Over the address limit: refused...
2822        let genuine = t.assertion();
2823        let over = t.token_from("203.0.113.1", &genuine).await;
2824        assert!(
2825            is_rate_limited(&over),
2826            "expected a rate-limit refusal, got {over:?}"
2827        );
2828        // ...and before the assertion was checked: it still works from another address (a replay
2829        // record would have refused it), which also shows the address bucket is per peer.
2830        assert_eq!(
2831            t.token_from("203.0.113.2", &genuine).await.unwrap(),
2832            "fapi-client"
2833        );
2834    }
2835
2836    #[tokio::test]
2837    async fn the_client_bucket_is_not_escaped_by_changing_address() {
2838        let t = Limited::new(Some(2)).await;
2839        for peer in ["198.51.100.1", "198.51.100.2"] {
2840            assert_eq!(
2841                t.token_from(peer, &t.assertion()).await.unwrap(),
2842                "fapi-client"
2843            );
2844        }
2845        let over = t.token_from("198.51.100.3", &t.assertion()).await;
2846        assert!(
2847            is_rate_limited(&over),
2848            "expected a rate-limit refusal, got {over:?}"
2849        );
2850    }
2851
2852    #[tokio::test]
2853    async fn an_unauthenticated_request_naming_a_client_does_not_spend_its_bucket() {
2854        let t = Limited::new(Some(2)).await;
2855        for i in 0..6 {
2856            let r = t
2857                .token_from(&format!("192.0.2.{i}"), &t.unauthenticated_assertion())
2858                .await;
2859            assert!(r.is_err() && !is_rate_limited(&r), "round {i}: {r:?}");
2860        }
2861        // The client's own allowance is intact: two genuine requests still pass.
2862        for peer in ["192.0.2.100", "192.0.2.101"] {
2863            assert_eq!(
2864                t.token_from(peer, &t.assertion()).await.unwrap(),
2865                "fapi-client"
2866            );
2867        }
2868    }
2869
2870    #[tokio::test]
2871    async fn authorize_and_token_do_not_share_an_address_allowance() {
2872        let t = Limited::new(Some(1)).await;
2873        assert_eq!(
2874            t.token_from("203.0.113.9", &t.assertion()).await.unwrap(),
2875            "fapi-client"
2876        );
2877        let r = t
2878            .manager
2879            .validate_authorization_request_from("203.0.113.9", "junk", None, None, None)
2880            .await;
2881        assert!(
2882            r.is_err() && !is_rate_limited(&r),
2883            "authorize bucket was spent by token: {r:?}"
2884        );
2885        let again = t
2886            .manager
2887            .validate_authorization_request_from("203.0.113.9", "junk", None, None, None)
2888            .await;
2889        assert!(
2890            is_rate_limited(&again),
2891            "second authorize from one peer: {again:?}"
2892        );
2893    }
2894
2895    #[test]
2896    fn a_limiter_that_cannot_be_consulted_refuses() {
2897        let unavailable = FapiManager::limiter_outcome("k", Err(AuthError::internal("down")));
2898        assert!(unavailable.is_err() && !is_rate_limited(&unavailable));
2899        let blocked = FapiManager::limiter_outcome(
2900            "k",
2901            Ok(RateLimitResult::Blocked {
2902                unblock_at: std::time::Instant::now() + std::time::Duration::from_secs(30),
2903                reason: "test".to_string(),
2904            }),
2905        );
2906        assert!(is_rate_limited(&blocked));
2907    }
2908
2909    #[tokio::test]
2910    async fn without_a_limiter_the_from_entry_points_count_nothing() {
2911        let t = Limited::new(None).await;
2912        for _ in 0..5 {
2913            assert_eq!(
2914                t.token_from("203.0.113.5", &t.assertion()).await.unwrap(),
2915                "fapi-client"
2916            );
2917        }
2918    }
2919}