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::errors::{AuthError, Result};
28use crate::security::secure_jwt::SecureJwtValidator;
29use crate::server::{DpopManager, MutualTlsManager, PARManager, PrivateKeyJwtManager};
30use chrono::{DateTime, Duration, Utc};
31use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
32use serde::{Deserialize, Serialize};
33use serde_json::{Value, json};
34use std::collections::HashMap;
35use std::sync::Arc;
36use tokio::sync::RwLock;
37use uuid::Uuid;
38
39/// FAPI 2.0 Security Profile Manager
40#[derive(Debug, Clone)]
41pub struct FapiManager {
42    /// DPoP manager for sender constraining
43    dpop_manager: Arc<DpopManager>,
44
45    /// Mutual TLS manager for client authentication
46    mtls_manager: Arc<MutualTlsManager>,
47
48    /// PAR manager for pushed authorization requests
49    par_manager: Arc<PARManager>,
50
51    /// Private key JWT manager
52    private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
53
54    /// JWT validator for request object validation
55    jwt_validator: Arc<SecureJwtValidator>,
56
57    /// FAPI configuration
58    config: FapiConfig,
59
60    /// Active FAPI sessions
61    sessions: Arc<RwLock<HashMap<String, FapiSession>>>,
62}
63
64/// FAPI 2.0 Configuration
65#[derive(Clone)]
66pub struct FapiConfig {
67    /// Issuer identifier
68    pub issuer: String,
69
70    /// Request object signing algorithm (required: RS256, PS256, or ES256)
71    pub request_signing_algorithm: Algorithm,
72
73    /// Response signing algorithm
74    pub response_signing_algorithm: Algorithm,
75
76    /// Private key for signing
77    pub private_key: EncodingKey,
78
79    /// Public key for verification
80    pub public_key: DecodingKey,
81
82    /// Maximum request object age (seconds)
83    pub max_request_age: i64,
84
85    /// Require DPoP for all requests
86    pub require_dpop: bool,
87
88    /// Require mTLS for all requests
89    pub require_mtls: bool,
90
91    /// Require PAR for authorization requests
92    pub require_par: bool,
93
94    /// Enable JARM (JWT Secured Authorization Response Mode)
95    pub enable_jarm: bool,
96
97    /// Enhanced audit logging
98    pub enhanced_audit: bool,
99
100    /// Whether the config is running in degraded mode (HMAC placeholder keys
101    /// instead of the required RSA keys). FAPI operations MUST reject requests
102    /// when this flag is true.
103    pub is_degraded: bool,
104}
105
106impl std::fmt::Debug for FapiConfig {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        f.debug_struct("FapiConfig")
109            .field("issuer", &self.issuer)
110            .field("request_signing_algorithm", &self.request_signing_algorithm)
111            .field(
112                "response_signing_algorithm",
113                &self.response_signing_algorithm,
114            )
115            .field("private_key", &"<EncodingKey>")
116            .field("public_key", &"<DecodingKey>")
117            .field("max_request_age", &self.max_request_age)
118            .field("require_dpop", &self.require_dpop)
119            .field("require_mtls", &self.require_mtls)
120            .field("require_par", &self.require_par)
121            .field("enable_jarm", &self.enable_jarm)
122            .field("enhanced_audit", &self.enhanced_audit)
123            .field("is_degraded", &self.is_degraded)
124            .finish()
125    }
126}
127
128impl FapiConfig {
129    /// Create a new FAPI 2.0 configuration builder.
130    ///
131    /// The builder enforces strict FAPI 2.0 compliance by default (DPoP, mTLS, PAR, JARM enabled).
132    pub fn builder(
133        issuer: impl Into<String>,
134        private_key: EncodingKey,
135        public_key: DecodingKey,
136    ) -> FapiConfigBuilder {
137        FapiConfigBuilder {
138            issuer: issuer.into(),
139            request_signing_algorithm: Algorithm::PS256,
140            response_signing_algorithm: Algorithm::PS256,
141            private_key,
142            public_key,
143            max_request_age: 60,
144            require_dpop: true,
145            require_mtls: true,
146            require_par: true,
147            enable_jarm: true,
148            enhanced_audit: true,
149            is_degraded: false,
150        }
151    }
152
153    /// Load configuration from environment variables.
154    #[deprecated(since = "0.5.0", note = "use FapiConfig::from_env() instead")]
155    pub fn load_from_env() -> Self {
156        Self::from_env()
157    }
158
159    /// Create a FAPI configuration from standard environment variables.
160    ///
161    /// Reads `FAPI_ISSUER`, `FAPI_PRIVATE_KEY_PATH`, and `FAPI_PUBLIC_KEY_PATH`.
162    pub fn from_env() -> Self {
163        Self::default()
164    }
165}
166
167/// Builder for FAPI 2.0 Configuration
168pub struct FapiConfigBuilder {
169    issuer: String,
170    request_signing_algorithm: Algorithm,
171    response_signing_algorithm: Algorithm,
172    private_key: EncodingKey,
173    public_key: DecodingKey,
174    max_request_age: i64,
175    require_dpop: bool,
176    require_mtls: bool,
177    require_par: bool,
178    enable_jarm: bool,
179    enhanced_audit: bool,
180    is_degraded: bool,
181}
182
183impl FapiConfigBuilder {
184    /// Set the request signing algorithm (default: PS256).
185    ///
186    /// FAPI 2.0 requires PS256 or ES256.
187    pub fn request_signing_algorithm(mut self, alg: Algorithm) -> Self {
188        self.request_signing_algorithm = alg;
189        self
190    }
191
192    /// Set the response signing algorithm (default: PS256).
193    pub fn response_signing_algorithm(mut self, alg: Algorithm) -> Self {
194        self.response_signing_algorithm = alg;
195        self
196    }
197
198    /// Set the maximum allowed age for request objects in seconds (default: 60).
199    pub fn max_request_age(mut self, age: i64) -> Self {
200        self.max_request_age = age;
201        self
202    }
203
204    /// Set whether DPoP is required (default: true).
205    pub fn require_dpop(mut self, require: bool) -> Self {
206        self.require_dpop = require;
207        self
208    }
209
210    /// Set whether mTLS is required (default: true).
211    pub fn require_mtls(mut self, require: bool) -> Self {
212        self.require_mtls = require;
213        self
214    }
215
216    /// Set whether PAR is required (default: true).
217    pub fn require_par(mut self, require: bool) -> Self {
218        self.require_par = require;
219        self
220    }
221
222    /// Enable or disable JARM (default: true).
223    pub fn enable_jarm(mut self, enable: bool) -> Self {
224        self.enable_jarm = enable;
225        self
226    }
227
228    /// Enable or disable enhanced audit logging (default: true).
229    pub fn enhanced_audit(mut self, enable: bool) -> Self {
230        self.enhanced_audit = enable;
231        self
232    }
233
234    /// Mark this configuration as degraded (for testing/development only).
235    pub fn degraded(mut self) -> Self {
236        self.is_degraded = true;
237        self
238    }
239
240    /// Build the FapiConfig.
241    pub fn build(self) -> FapiConfig {
242        FapiConfig {
243            issuer: self.issuer,
244            request_signing_algorithm: self.request_signing_algorithm,
245            response_signing_algorithm: self.response_signing_algorithm,
246            private_key: self.private_key,
247            public_key: self.public_key,
248            max_request_age: self.max_request_age,
249            require_dpop: self.require_dpop,
250            require_mtls: self.require_mtls,
251            require_par: self.require_par,
252            enable_jarm: self.enable_jarm,
253            enhanced_audit: self.enhanced_audit,
254            is_degraded: self.is_degraded,
255        }
256    }
257}
258
259/// FAPI 2.0 Session
260#[derive(Clone, Serialize, Deserialize)]
261pub struct FapiSession {
262    /// Session ID
263    pub session_id: String,
264
265    /// Client ID
266    pub client_id: String,
267
268    /// User ID
269    pub user_id: String,
270
271    /// Session creation time
272    pub created_at: DateTime<Utc>,
273
274    /// Session expiration time
275    pub expires_at: DateTime<Utc>,
276
277    /// DPoP proof token
278    pub dpop_proof: Option<String>,
279
280    /// Client certificate thumbprint
281    pub cert_thumbprint: Option<String>,
282
283    /// Request object JTI (to prevent replay)
284    pub request_jti: Option<String>,
285
286    /// Authorized scopes
287    pub scopes: Vec<String>,
288
289    /// Session metadata
290    pub metadata: HashMap<String, Value>,
291}
292
293impl std::fmt::Debug for FapiSession {
294    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295        let mut d = f.debug_struct("FapiSession");
296        d.field(
297            "session_id",
298            &crate::utils::redact::redacted(&self.session_id),
299        );
300        d.field("client_id", &self.client_id);
301        d.field("user_id", &self.user_id);
302        d.field("created_at", &self.created_at);
303        d.field("expires_at", &self.expires_at);
304        d.field(
305            "dpop_proof",
306            &crate::utils::redact::redacted(&self.dpop_proof),
307        );
308        d.field("cert_thumbprint", &self.cert_thumbprint);
309        d.field("request_jti", &self.request_jti);
310        d.field("scopes", &self.scopes);
311        d.field("metadata", &self.metadata);
312        d.finish()
313    }
314}
315
316impl FapiSession {
317    /// Create a new builder for a FAPI 2.0 Session.
318    pub fn builder(
319        session_id: impl Into<String>,
320        client_id: impl Into<String>,
321        user_id: impl Into<String>,
322        expires_in: Duration,
323    ) -> FapiSessionBuilder {
324        let now = Utc::now();
325        FapiSessionBuilder {
326            session_id: session_id.into(),
327            client_id: client_id.into(),
328            user_id: user_id.into(),
329            created_at: now,
330            expires_at: now + expires_in,
331            dpop_proof: None,
332            cert_thumbprint: None,
333            request_jti: None,
334            scopes: Vec::new(),
335            metadata: HashMap::new(),
336        }
337    }
338}
339
340/// Builder for FAPI 2.0 Session
341pub struct FapiSessionBuilder {
342    session_id: String,
343    client_id: String,
344    user_id: String,
345    created_at: DateTime<Utc>,
346    expires_at: DateTime<Utc>,
347    dpop_proof: Option<String>,
348    cert_thumbprint: Option<String>,
349    request_jti: Option<String>,
350    scopes: Vec<String>,
351    metadata: HashMap<String, Value>,
352}
353
354impl FapiSessionBuilder {
355    /// Set the DPoP proof token.
356    pub fn dpop_proof(mut self, proof: impl Into<String>) -> Self {
357        self.dpop_proof = Some(proof.into());
358        self
359    }
360
361    /// Set the client certificate thumbprint for mTLS.
362    pub fn cert_thumbprint(mut self, thumbprint: impl Into<String>) -> Self {
363        self.cert_thumbprint = Some(thumbprint.into());
364        self
365    }
366
367    /// Set the request object JTI to prevent replay.
368    pub fn request_jti(mut self, jti: impl Into<String>) -> Self {
369        self.request_jti = Some(jti.into());
370        self
371    }
372
373    /// Add an authorized scope.
374    pub fn add_scope(mut self, scope: impl Into<String>) -> Self {
375        self.scopes.push(scope.into());
376        self
377    }
378
379    /// Add multiple authorized scopes.
380    pub fn add_scopes<I, S>(mut self, scopes: I) -> Self
381    where
382        I: IntoIterator<Item = S>,
383        S: Into<String>,
384    {
385        self.scopes.extend(scopes.into_iter().map(Into::into));
386        self
387    }
388
389    /// Add custom metadata to the session.
390    pub fn add_metadata(mut self, key: impl Into<String>, value: Value) -> Self {
391        self.metadata.insert(key.into(), value);
392        self
393    }
394
395    /// Build the FapiSession.
396    pub fn build(self) -> FapiSession {
397        FapiSession {
398            session_id: self.session_id,
399            client_id: self.client_id,
400            user_id: self.user_id,
401            created_at: self.created_at,
402            expires_at: self.expires_at,
403            dpop_proof: self.dpop_proof,
404            cert_thumbprint: self.cert_thumbprint,
405            request_jti: self.request_jti,
406            scopes: self.scopes,
407            metadata: self.metadata,
408        }
409    }
410}
411
412/// FAPI 2.0 Request Object Claims
413#[derive(Debug, Clone, Serialize, Deserialize)]
414pub struct FapiRequestObject {
415    /// Issuer (client_id)
416    pub iss: String,
417
418    /// Audience (authorization server)
419    pub aud: String,
420
421    /// Issued at time
422    pub iat: i64,
423
424    /// Expiration time
425    pub exp: i64,
426
427    /// Not before time
428    pub nbf: Option<i64>,
429
430    /// JWT ID (unique identifier)
431    pub jti: String,
432
433    /// Response type
434    pub response_type: String,
435
436    /// Client ID
437    pub client_id: String,
438
439    /// Redirect URI
440    pub redirect_uri: String,
441
442    /// Scope
443    pub scope: String,
444
445    /// State
446    pub state: Option<String>,
447
448    /// Nonce (for OIDC)
449    pub nonce: Option<String>,
450
451    /// Code challenge (for PKCE)
452    pub code_challenge: Option<String>,
453
454    /// Code challenge method
455    pub code_challenge_method: Option<String>,
456
457    /// Additional claims
458    #[serde(flatten)]
459    pub additional_claims: HashMap<String, Value>,
460}
461
462/// FAPI 2.0 Authorization Response (JARM)
463#[derive(Clone, Serialize, Deserialize)]
464pub struct FapiAuthorizationResponse {
465    /// Issuer (authorization server)
466    pub iss: String,
467
468    /// Audience (client_id)
469    pub aud: String,
470
471    /// Issued at time
472    pub iat: i64,
473
474    /// Expiration time
475    pub exp: i64,
476
477    /// Authorization code (if successful)
478    pub code: Option<String>,
479
480    /// State parameter
481    pub state: Option<String>,
482
483    /// Error code (if failed)
484    pub error: Option<String>,
485
486    /// Error description
487    pub error_description: Option<String>,
488
489    /// Additional response parameters
490    #[serde(flatten)]
491    pub additional_params: HashMap<String, Value>,
492}
493
494impl std::fmt::Debug for FapiAuthorizationResponse {
495    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496        let mut d = f.debug_struct("FapiAuthorizationResponse");
497        d.field("iss", &self.iss);
498        d.field("aud", &self.aud);
499        d.field("iat", &self.iat);
500        d.field("exp", &self.exp);
501        d.field("code", &crate::utils::redact::redacted(&self.code));
502        d.field("state", &self.state);
503        d.field("error", &self.error);
504        d.field("error_description", &self.error_description);
505        d.field("additional_params", &self.additional_params);
506        d.finish()
507    }
508}
509
510/// FAPI 2.0 Token Response
511#[derive(Clone, Serialize, Deserialize)]
512pub struct FapiTokenResponse {
513    /// Access token
514    pub access_token: String,
515
516    /// Token type (always "DPoP" for FAPI 2.0)
517    pub token_type: String,
518
519    /// Expires in (seconds)
520    pub expires_in: i64,
521
522    /// Refresh token
523    pub refresh_token: Option<String>,
524
525    /// Scope
526    pub scope: Option<String>,
527
528    /// ID token (for OIDC)
529    pub id_token: Option<String>,
530
531    /// Certificate thumbprint confirmation
532    pub cnf: Option<Value>,
533}
534
535impl std::fmt::Debug for FapiTokenResponse {
536    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537        let mut d = f.debug_struct("FapiTokenResponse");
538        d.field(
539            "access_token",
540            &crate::utils::redact::redacted(&self.access_token),
541        );
542        d.field("token_type", &self.token_type);
543        d.field("expires_in", &self.expires_in);
544        d.field(
545            "refresh_token",
546            &crate::utils::redact::redacted(&self.refresh_token),
547        );
548        d.field("scope", &self.scope);
549        d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
550        d.field("cnf", &self.cnf);
551        d.finish()
552    }
553}
554
555impl FapiManager {
556    /// Create a new FAPI manager
557    pub fn new(
558        config: FapiConfig,
559        dpop_manager: Arc<DpopManager>,
560        mtls_manager: Arc<MutualTlsManager>,
561        par_manager: Arc<PARManager>,
562        private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
563        jwt_validator: Arc<SecureJwtValidator>,
564    ) -> Self {
565        Self {
566            dpop_manager,
567            mtls_manager,
568            par_manager,
569            private_key_jwt_manager,
570            jwt_validator,
571            config,
572            sessions: Arc::new(RwLock::new(HashMap::new())),
573        }
574    }
575
576    /// Validate FAPI 2.0 authorization request
577    pub async fn validate_authorization_request(
578        &self,
579        request_object: &str,
580        client_cert: Option<&str>,
581        dpop_proof: Option<&str>,
582        request_uri: Option<&str>,
583    ) -> Result<FapiRequestObject> {
584        let claims = if let Some(uri) = request_uri {
585            // PAR workflow - validate request_uri and retrieve the request
586            if self.config.require_par {
587                // Use PAR manager to consume the pushed request
588                let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
589                    AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
590                })?;
591
592                tracing::info!(
593                    "FAPI PAR request consumed successfully for client: {}",
594                    par_request.client_id
595                );
596
597                // Convert PAR request to FAPI request object
598                let nonce = par_request.additional_params.get("nonce").cloned();
599                FapiRequestObject {
600                    iss: par_request.client_id.clone(),
601                    aud: self.config.issuer.clone(),
602                    iat: Utc::now().timestamp(),
603                    exp: Utc::now().timestamp() + 300, // 5 minutes
604                    nbf: Some(Utc::now().timestamp()),
605                    jti: uuid::Uuid::new_v4().to_string(),
606                    response_type: par_request.response_type,
607                    client_id: par_request.client_id,
608                    redirect_uri: par_request.redirect_uri,
609                    scope: par_request.scope.unwrap_or_default(),
610                    state: par_request.state,
611                    nonce,
612                    code_challenge: par_request.code_challenge,
613                    code_challenge_method: par_request.code_challenge_method,
614                    additional_claims: par_request
615                        .additional_params
616                        .into_iter()
617                        .map(|(k, v)| (k, serde_json::Value::String(v)))
618                        .collect(),
619                }
620            } else {
621                return Err(AuthError::InvalidRequest(
622                    "request_uri provided but PAR not required".to_string(),
623                ));
624            }
625        } else {
626            // Standard request object validation
627            if self.config.require_par {
628                return Err(AuthError::InvalidRequest(
629                    "PAR is required but no request_uri provided".to_string(),
630                ));
631            }
632
633            // Validate request object JWT using enhanced validation
634            self.validate_request_object(request_object).await?
635        };
636
637        // Validate mTLS if required
638        if self.config.require_mtls {
639            let cert = client_cert.ok_or_else(|| {
640                AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
641            })?;
642            let cert_bytes = decode_client_certificate(cert)?;
643            self.mtls_manager
644                .validate_client_certificate(&cert_bytes, &claims.client_id)
645                .await?;
646        }
647
648        // Validate DPoP if required
649        if self.config.require_dpop {
650            let proof = dpop_proof.ok_or_else(|| {
651                AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0")
652            })?;
653            self.dpop_manager
654                .validate_dpop_proof(
655                    proof,
656                    "POST",
657                    &format!("{}/authorize", self.config.issuer),
658                    None,
659                    None,
660                )
661                .await?;
662        }
663
664        // Validate request object claims
665        self.validate_request_claims(&claims).await?;
666
667        Ok(claims)
668    }
669
670    /// Validate request object JWT
671    async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
672        // Use the SecureJwtValidator for enhanced security validation
673        let decoding_key = &self.config.public_key;
674
675        // Validate using SecureJwtValidator with enhanced security features
676        match self
677            .jwt_validator
678            .validate_token(request_object, decoding_key)
679        {
680            Ok(secure_claims) => {
681                // Decode JWT header to get algorithm
682                let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
683                    AuthError::token(format!("Invalid request object header: {}", e))
684                })?;
685
686                // Validate algorithm requirement for FAPI
687                if !matches!(
688                    header.alg,
689                    Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
690                ) {
691                    return Err(AuthError::token(
692                        "Request object must use RS256, PS256, or ES256".to_string(),
693                    ));
694                }
695
696                // Set up validation with the same algorithm for FAPI-specific claims
697                let mut validation = Validation::new(header.alg);
698                validation.set_audience(&[&self.config.issuer]);
699                validation.validate_exp = true;
700                validation.validate_nbf = true;
701
702                // Decode the FAPI request object structure
703                let token_data = jsonwebtoken::decode::<FapiRequestObject>(
704                    request_object,
705                    &self.config.public_key,
706                    &validation,
707                )
708                .map_err(|e| {
709                    AuthError::token(format!("Request object validation failed: {}", e))
710                })?;
711
712                let fapi_claims = token_data.claims;
713
714                // Use the validated secure claims for enhanced security checks
715                // Ensure the subject matches between secure validation and FAPI claims
716                if secure_claims.sub != fapi_claims.client_id {
717                    return Err(AuthError::token(
718                        "Subject mismatch between secure validation and FAPI claims".to_string(),
719                    ));
720                }
721
722                // Use secure claims issuer for additional validation
723                if secure_claims.iss != fapi_claims.iss {
724                    return Err(AuthError::token(
725                        "Issuer mismatch between secure validation and FAPI claims".to_string(),
726                    ));
727                }
728
729                // Validate expiry consistency
730                if secure_claims.exp != fapi_claims.exp {
731                    return Err(AuthError::token(
732                        "Expiry mismatch between secure validation and FAPI claims".to_string(),
733                    ));
734                }
735
736                // Additional FAPI validations using the validated claims
737                let now = Utc::now().timestamp();
738
739                // Check request object age
740                if now - fapi_claims.iat > self.config.max_request_age {
741                    return Err(AuthError::token("Request object too old".to_string()));
742                }
743
744                // Validate required claims
745                if fapi_claims.client_id.is_empty() {
746                    return Err(AuthError::token(
747                        "client_id required in request object".to_string(),
748                    ));
749                }
750
751                if fapi_claims.redirect_uri.is_empty() {
752                    return Err(AuthError::token(
753                        "redirect_uri required in request object".to_string(),
754                    ));
755                }
756
757                if fapi_claims.response_type.is_empty() {
758                    return Err(AuthError::token(
759                        "response_type required in request object".to_string(),
760                    ));
761                }
762
763                tracing::info!(
764                    "FAPI request object validated successfully with SecureJwtValidator for client: {}",
765                    fapi_claims.client_id
766                );
767
768                Ok(fapi_claims)
769            }
770            Err(e) => {
771                tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
772                Err(AuthError::token(format!(
773                    "Enhanced JWT validation failed: {}",
774                    e
775                )))
776            }
777        }
778    }
779
780    /// Validate request object claims against FAPI requirements
781    async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
782        // Validate response_type for FAPI 2.0
783        if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
784            return Err(AuthError::InvalidRequest(
785                "FAPI 2.0 requires code or code id_token response type".to_string(),
786            ));
787        }
788
789        // Validate PKCE for public clients
790        if claims.code_challenge.is_none() {
791            return Err(AuthError::InvalidRequest(
792                "PKCE required for FAPI 2.0".to_string(),
793            ));
794        }
795
796        if let Some(method) = &claims.code_challenge_method {
797            if method != "S256" {
798                return Err(AuthError::InvalidRequest(
799                    "FAPI 2.0 requires S256 code challenge method".to_string(),
800                ));
801            }
802        } else {
803            return Err(AuthError::InvalidRequest(
804                "code_challenge_method required for FAPI 2.0".to_string(),
805            ));
806        }
807
808        Ok(())
809    }
810
811    /// Authenticate client using private key JWT (RFC 7523)
812    ///
813    /// The caller learns only that authentication failed: the detailed reasons (unknown client,
814    /// bad signature, wrong audience, replay, ...) are logged, never returned.
815    pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
816        const REFUSED: &str = "Client authentication failed";
817
818        // Use the private key JWT manager for authentication
819        let auth_result = match self
820            .private_key_jwt_manager
821            .authenticate_client(client_assertion)
822            .await
823        {
824            Ok(result) => result,
825            Err(e) => {
826                tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
827                return Err(AuthError::auth_method("private_key_jwt", REFUSED));
828            }
829        };
830
831        if auth_result.authenticated {
832            tracing::info!(
833                "FAPI client authenticated successfully using private key JWT: {}",
834                auth_result.client_id
835            );
836            Ok(auth_result.client_id)
837        } else {
838            tracing::warn!(
839                "FAPI private key JWT authentication failed: {}",
840                auth_result.errors.join("; ")
841            );
842            Err(AuthError::auth_method("private_key_jwt", REFUSED))
843        }
844    }
845
846    /// Validate FAPI token request with enhanced security
847    pub async fn validate_token_request(
848        &self,
849        client_assertion: Option<&str>,
850        client_cert: Option<&str>,
851        dpop_proof: Option<&str>,
852        authorization_code: &str,
853    ) -> Result<String> {
854        // Client authentication - prefer private key JWT for FAPI 2.0
855        let client_id = if let Some(assertion) = client_assertion {
856            self.authenticate_client_jwt(assertion).await?
857        } else if self.config.require_mtls {
858            if let Some(cert) = client_cert {
859                let cert_bytes = decode_client_certificate(cert)?;
860
861                // Look the client up by the identity the certificate carries; the manager then
862                // verifies the chain AND that this certificate is bound to that client.
863                let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
864
865                self.mtls_manager
866                    .validate_client_certificate(&cert_bytes, &client_id)
867                    .await?;
868
869                client_id.to_string()
870            } else {
871                return Err(AuthError::auth_method(
872                    "mtls",
873                    "Client certificate required for FAPI 2.0 token request",
874                ));
875            }
876        } else {
877            return Err(AuthError::auth_method(
878                "fapi",
879                "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
880            ));
881        };
882
883        // Validate DPoP if required
884        if self.config.require_dpop {
885            let proof = dpop_proof.ok_or_else(|| {
886                AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0 token request")
887            })?;
888            self.dpop_manager
889                .validate_dpop_proof(
890                    proof,
891                    "POST",
892                    &format!("{}/token", self.config.issuer),
893                    Some(authorization_code), // Include authorization code in DPoP validation
894                    None,
895                )
896                .await?;
897        }
898
899        Ok(client_id)
900    }
901
902    /// Generate FAPI 2.0 authorization response (JARM)
903    pub async fn generate_authorization_response(
904        &self,
905        client_id: &str,
906        code: Option<&str>,
907        state: Option<&str>,
908        error: Option<&str>,
909        error_description: Option<&str>,
910    ) -> Result<String> {
911        if !self.config.enable_jarm {
912            return Err(AuthError::Configuration {
913                message: "JARM not enabled".to_string(),
914                help: Some("Enable JARM in your configuration to use this feature".to_string()),
915                docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
916                source: None,
917                suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
918            });
919        }
920
921        let now = Utc::now();
922        let exp = now + Duration::minutes(5); // Response expires in 5 minutes
923
924        let response = FapiAuthorizationResponse {
925            iss: self.config.issuer.clone(),
926            aud: client_id.to_string(),
927            iat: now.timestamp(),
928            exp: exp.timestamp(),
929            code: code.map(|c| c.to_string()),
930            state: state.map(|s| s.to_string()),
931            error: error.map(|e| e.to_string()),
932            error_description: error_description.map(|d| d.to_string()),
933            additional_params: HashMap::new(),
934        };
935
936        // Create JWT header
937        let header = Header::new(self.config.response_signing_algorithm);
938
939        // Sign the response
940        let token =
941            jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
942                AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
943            })?;
944
945        Ok(token)
946    }
947
948    /// Generate FAPI 2.0 token response
949    pub async fn generate_token_response(
950        &self,
951        client_id: &str,
952        user_id: &str,
953        scopes: Vec<String>,
954        cert_thumbprint: Option<String>,
955        dpop_jkt: Option<String>,
956    ) -> Result<FapiTokenResponse> {
957        // Generate access token
958        let access_token = self
959            .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
960            .await?;
961
962        // Generate refresh token
963        let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
964
965        // Build confirmation claim
966        let mut cnf = json!({});
967
968        if let Some(thumbprint) = cert_thumbprint {
969            cnf["x5t#S256"] = Value::String(thumbprint);
970        }
971
972        if let Some(jkt) = dpop_jkt {
973            cnf["jkt"] = Value::String(jkt);
974        }
975
976        let response = FapiTokenResponse {
977            access_token,
978            token_type: "DPoP".to_string(), // Always DPoP for FAPI 2.0
979            expires_in: 3600,               // 1 hour
980            refresh_token: Some(refresh_token),
981            scope: Some(scopes.join(" ")),
982            id_token: None, // ID token generated by OIDC layer when openid scope present
983            cnf: if cnf.as_object().is_none_or(|o| o.is_empty()) {
984                None
985            } else {
986                Some(cnf)
987            },
988        };
989
990        Ok(response)
991    }
992
993    /// Generate access token
994    async fn generate_access_token(
995        &self,
996        client_id: &str,
997        user_id: &str,
998        scopes: &[String],
999        cert_thumbprint: &Option<String>,
1000        dpop_jkt: &Option<String>,
1001    ) -> Result<String> {
1002        let now = Utc::now();
1003        let exp = now + Duration::hours(1);
1004
1005        let mut claims = json!({
1006            "iss": self.config.issuer,
1007            "aud": client_id,
1008            "sub": user_id,
1009            "iat": now.timestamp(),
1010            "exp": exp.timestamp(),
1011            "scope": scopes.join(" "),
1012            "jti": Uuid::new_v4().to_string(),
1013        });
1014
1015        // Add confirmation claims
1016        let mut cnf = json!({});
1017
1018        if let Some(thumbprint) = cert_thumbprint {
1019            cnf["x5t#S256"] = Value::String(thumbprint.clone());
1020        }
1021
1022        if let Some(jkt) = dpop_jkt {
1023            cnf["jkt"] = Value::String(jkt.clone());
1024        }
1025
1026        if !cnf.as_object().is_none_or(|o| o.is_empty()) {
1027            claims["cnf"] = cnf;
1028        }
1029
1030        // Create JWT header
1031        let header = Header::new(Algorithm::RS256);
1032
1033        // Sign the token
1034        let token =
1035            jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1036                AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
1037            })?;
1038
1039        Ok(token)
1040    }
1041
1042    /// Generate refresh token
1043    async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
1044        let now = Utc::now();
1045        let exp = now + Duration::days(30); // 30 day expiry
1046
1047        let claims = json!({
1048            "iss": self.config.issuer,
1049            "aud": client_id,
1050            "sub": user_id,
1051            "iat": now.timestamp(),
1052            "exp": exp.timestamp(),
1053            "typ": crate::security::secure_jwt::TYP_REFRESH_TOKEN,
1054            "jti": Uuid::new_v4().to_string(),
1055        });
1056
1057        // Create JWT header
1058        let header = Header::new(Algorithm::RS256);
1059
1060        // Sign the token
1061        let token =
1062            jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1063                AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
1064            })?;
1065
1066        Ok(token)
1067    }
1068
1069    /// Create FAPI session
1070    pub async fn create_session(
1071        &self,
1072        client_id: &str,
1073        user_id: &str,
1074        scopes: Vec<String>,
1075        dpop_proof: Option<String>,
1076        cert_thumbprint: Option<String>,
1077        request_jti: Option<String>,
1078    ) -> Result<String> {
1079        let session_id = Uuid::new_v4().to_string();
1080        let now = Utc::now();
1081        let expires_at = now + Duration::hours(24); // 24 hour session
1082
1083        let session = FapiSession {
1084            session_id: session_id.clone(),
1085            client_id: client_id.to_string(),
1086            user_id: user_id.to_string(),
1087            created_at: now,
1088            expires_at,
1089            dpop_proof,
1090            cert_thumbprint,
1091            request_jti,
1092            scopes,
1093            metadata: HashMap::new(),
1094        };
1095
1096        let mut sessions = self.sessions.write().await;
1097        sessions.insert(session_id.clone(), session);
1098
1099        Ok(session_id)
1100    }
1101
1102    /// Get FAPI session
1103    pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
1104        let sessions = self.sessions.read().await;
1105        Ok(sessions.get(session_id).cloned())
1106    }
1107
1108    /// Validate FAPI session
1109    pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
1110        let session = self
1111            .get_session(session_id)
1112            .await?
1113            .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
1114
1115        // Check expiration
1116        if Utc::now() > session.expires_at {
1117            return Err(AuthError::validation("Session expired".to_string()));
1118        }
1119
1120        Ok(session)
1121    }
1122
1123    /// Remove FAPI session
1124    pub async fn remove_session(&self, session_id: &str) -> Result<()> {
1125        let mut sessions = self.sessions.write().await;
1126        sessions.remove(session_id);
1127        Ok(())
1128    }
1129
1130    /// Audit log entry for FAPI compliance
1131    pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
1132        if self.config.enhanced_audit {
1133            // Implement proper audit logging for FAPI compliance
1134            // This should log to secure, tamper-evident storage
1135            // Format: ISO 8601 timestamp, event type, client details, user context
1136            let timestamp = chrono::Utc::now().to_rfc3339();
1137            let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
1138
1139            // In production, write to secure audit log storage
1140            tracing::info!("{}", audit_entry);
1141        }
1142        Ok(())
1143    }
1144
1145    /// Extract client ID from certificate
1146    async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
1147        client_id_from_certificate(cert_bytes)
1148    }
1149
1150    /// Validate FAPI 2.0 compliance of the current configuration.
1151    ///
1152    /// Returns a list of compliance violations. An empty list means the
1153    /// configuration is fully FAPI 2.0 compliant.
1154    pub fn check_compliance(&self) -> Vec<FapiComplianceViolation> {
1155        let mut violations = Vec::new();
1156
1157        if self.config.is_degraded {
1158            violations.push(FapiComplianceViolation {
1159                requirement: "crypto-keys".to_string(),
1160                severity: FapiViolationSeverity::Critical,
1161                message: "RSA key pair not properly configured; all FAPI operations will fail"
1162                    .to_string(),
1163            });
1164        }
1165
1166        if !self.config.require_par {
1167            violations.push(FapiComplianceViolation {
1168                requirement: "par".to_string(),
1169                severity: FapiViolationSeverity::Critical,
1170                message: "FAPI 2.0 Security Profile requires Pushed Authorization Requests"
1171                    .to_string(),
1172            });
1173        }
1174
1175        if !self.config.require_dpop {
1176            violations.push(FapiComplianceViolation {
1177                requirement: "sender-constraint".to_string(),
1178                severity: FapiViolationSeverity::Warning,
1179                message: "DPoP is recommended for sender-constrained tokens".to_string(),
1180            });
1181        }
1182
1183        if !self.config.require_mtls {
1184            violations.push(FapiComplianceViolation {
1185                requirement: "sender-constraint".to_string(),
1186                severity: FapiViolationSeverity::Warning,
1187                message: "mTLS is recommended for client authentication and token binding"
1188                    .to_string(),
1189            });
1190        }
1191
1192        if !self.config.require_dpop && !self.config.require_mtls {
1193            violations.push(FapiComplianceViolation {
1194                requirement: "sender-constraint".to_string(),
1195                severity: FapiViolationSeverity::Critical,
1196                message:
1197                    "FAPI 2.0 requires at least one sender-constraining mechanism (DPoP or mTLS)"
1198                        .to_string(),
1199            });
1200        }
1201
1202        if !self.config.enable_jarm {
1203            violations.push(FapiComplianceViolation {
1204                requirement: "jarm".to_string(),
1205                severity: FapiViolationSeverity::Warning,
1206                message: "JARM is recommended for authorization response integrity".to_string(),
1207            });
1208        }
1209
1210        if !self.config.enhanced_audit {
1211            violations.push(FapiComplianceViolation {
1212                requirement: "audit".to_string(),
1213                severity: FapiViolationSeverity::Warning,
1214                message: "Enhanced audit logging is recommended for FAPI compliance".to_string(),
1215            });
1216        }
1217
1218        if !matches!(
1219            self.config.request_signing_algorithm,
1220            Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
1221        ) {
1222            violations.push(FapiComplianceViolation {
1223                requirement: "algorithm".to_string(),
1224                severity: FapiViolationSeverity::Critical,
1225                message: "Request signing must use RS256, PS256, or ES256".to_string(),
1226            });
1227        }
1228
1229        if self.config.max_request_age > 600 {
1230            violations.push(FapiComplianceViolation {
1231                requirement: "request-lifetime".to_string(),
1232                severity: FapiViolationSeverity::Warning,
1233                message: "Max request age exceeds recommended 10 minutes".to_string(),
1234            });
1235        }
1236
1237        violations
1238    }
1239
1240    /// Returns true if the configuration is fully FAPI 2.0 compliant (no critical violations).
1241    pub fn is_compliant(&self) -> bool {
1242        !self
1243            .check_compliance()
1244            .iter()
1245            .any(|v| matches!(v.severity, FapiViolationSeverity::Critical))
1246    }
1247
1248    /// Validate a sender-constrained access token at a resource server.
1249    ///
1250    /// Verifies that the token's `cnf` claim matches the presented proof
1251    /// (DPoP proof JKT or mTLS certificate thumbprint).
1252    pub async fn validate_sender_constrained_token(
1253        &self,
1254        access_token: &str,
1255        dpop_proof: Option<&str>,
1256        client_cert: Option<&str>,
1257        http_method: &str,
1258        http_uri: &str,
1259    ) -> Result<serde_json::Value> {
1260        // Validate the token's signature and standard claims via SecureJwtValidator
1261        let token_data = self
1262            .jwt_validator
1263            .validate_token(access_token, &self.config.public_key)?;
1264
1265        // Decode the raw JWT payload to access the cnf claim which is not in SecureJwtClaims
1266        let header = jsonwebtoken::decode_header(access_token)
1267            .map_err(|e| AuthError::token(format!("Invalid token header: {}", e)))?;
1268        let mut validation = Validation::new(header.alg);
1269        validation.set_audience(&[&self.config.issuer]);
1270        validation.validate_exp = true;
1271        let raw_claims = jsonwebtoken::decode::<serde_json::Value>(
1272            access_token,
1273            &self.config.public_key,
1274            &validation,
1275        )
1276        .map_err(|e| AuthError::token(format!("Token decode failed: {}", e)))?;
1277
1278        // Extract cnf claim from the raw payload
1279        let cnf = raw_claims.claims.get("cnf").ok_or_else(|| {
1280            AuthError::token("Token is not sender-constrained (missing cnf claim)".to_string())
1281        })?;
1282
1283        // Validate DPoP binding if cnf contains jkt
1284        if let Some(expected_jkt) = cnf.get("jkt").and_then(|v| v.as_str()) {
1285            let proof = dpop_proof.ok_or_else(|| {
1286                AuthError::token(
1287                    "Token is DPoP-bound but no DPoP proof header provided".to_string(),
1288                )
1289            })?;
1290            self.dpop_manager
1291                .validate_dpop_proof(proof, http_method, http_uri, None, Some(expected_jkt))
1292                .await?;
1293        }
1294
1295        // Validate mTLS certificate binding if cnf contains x5t#S256
1296        if let Some(expected_thumbprint) = cnf.get("x5t#S256").and_then(|v| v.as_str()) {
1297            let cert = client_cert.ok_or_else(|| {
1298                AuthError::token(
1299                    "Token is certificate-bound but no client certificate provided".to_string(),
1300                )
1301            })?;
1302            // RFC 8705 x5t#S256: SHA-256 over the DER encoding of the presented certificate
1303            use base64::Engine;
1304            use sha2::{Digest, Sha256};
1305            let cert_der = decode_client_certificate(cert)?;
1306            let presented_thumbprint =
1307                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(&cert_der));
1308            if !bool::from(subtle::ConstantTimeEq::ct_eq(
1309                presented_thumbprint.as_bytes(),
1310                expected_thumbprint.as_bytes(),
1311            )) {
1312                return Err(AuthError::token(
1313                    "Certificate thumbprint does not match token binding".to_string(),
1314                ));
1315            }
1316        }
1317
1318        // Return the validated token claims
1319        Ok(serde_json::json!({
1320            "sub": token_data.sub,
1321            "iss": token_data.iss,
1322            "exp": token_data.exp,
1323            "scope": token_data.scope,
1324        }))
1325    }
1326
1327    /// Validate a Rich Authorization Request (RFC 9396) authorization_details parameter.
1328    pub fn validate_authorization_details(
1329        &self,
1330        authorization_details: &[AuthorizationDetail],
1331    ) -> Result<()> {
1332        if authorization_details.is_empty() {
1333            return Err(AuthError::InvalidRequest(
1334                "authorization_details must not be empty".to_string(),
1335            ));
1336        }
1337
1338        for (i, detail) in authorization_details.iter().enumerate() {
1339            if detail.r#type.is_empty() {
1340                return Err(AuthError::InvalidRequest(format!(
1341                    "authorization_details[{}]: type is required",
1342                    i
1343                )));
1344            }
1345
1346            // Validate locations if present
1347            for location in &detail.locations {
1348                if !location.starts_with("https://") {
1349                    return Err(AuthError::InvalidRequest(format!(
1350                        "authorization_details[{}]: location must use HTTPS: {}",
1351                        i, location
1352                    )));
1353                }
1354            }
1355
1356            // Validate actions are non-empty strings
1357            for action in &detail.actions {
1358                if action.is_empty() {
1359                    return Err(AuthError::InvalidRequest(format!(
1360                        "authorization_details[{}]: empty action not allowed",
1361                        i
1362                    )));
1363                }
1364            }
1365        }
1366
1367        Ok(())
1368    }
1369}
1370
1371/// FAPI 2.0 compliance violation
1372#[derive(Debug, Clone)]
1373pub struct FapiComplianceViolation {
1374    /// Which FAPI requirement is violated
1375    pub requirement: String,
1376    /// Severity of the violation
1377    pub severity: FapiViolationSeverity,
1378    /// Human-readable description
1379    pub message: String,
1380}
1381
1382/// Severity of a compliance violation
1383#[derive(Debug, Clone, PartialEq, Eq)]
1384pub enum FapiViolationSeverity {
1385    /// Must be fixed for FAPI 2.0 compliance
1386    Critical,
1387    /// Recommended but not strictly required
1388    Warning,
1389}
1390
1391/// Rich Authorization Request detail (RFC 9396)
1392#[derive(Debug, Clone, Serialize, Deserialize)]
1393pub struct AuthorizationDetail {
1394    /// Type of authorization (e.g. "payment_initiation", "account_information")
1395    pub r#type: String,
1396
1397    /// Resource server locations this authorization applies to
1398    #[serde(default)]
1399    pub locations: Vec<String>,
1400
1401    /// Permitted actions (e.g. "read", "write", "execute")
1402    #[serde(default)]
1403    pub actions: Vec<String>,
1404
1405    /// Data types the client wants to access
1406    #[serde(default)]
1407    pub datatypes: Vec<String>,
1408
1409    /// Unique identifier for the authorization detail
1410    #[serde(skip_serializing_if = "Option::is_none")]
1411    pub identifier: Option<String>,
1412
1413    /// Additional fields specific to the authorization type
1414    #[serde(flatten)]
1415    pub additional_fields: HashMap<String, Value>,
1416}
1417
1418impl Default for FapiConfig {
1419    fn default() -> Self {
1420        // Load configuration from environment variables or use secure defaults
1421        let issuer =
1422            std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
1423
1424        let mut is_degraded = false;
1425
1426        // Load private key from environment — FAPI *requires* asymmetric keys.
1427        // There is intentionally no insecure fallback; callers must either set
1428        // FAPI_PRIVATE_KEY_PATH or construct FapiConfig manually.
1429        let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
1430            std::fs::read(&key_path)
1431                .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
1432                .and_then(|bytes| {
1433                    EncodingKey::from_rsa_pem(&bytes)
1434                        .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
1435                })
1436                .unwrap_or_else(|_| {
1437                    tracing::error!(
1438                        "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH is set but the key could not \
1439                         be loaded. FAPI REQUIRES an RSA private key for request/response signing. \
1440                         Using an ephemeral HMAC placeholder — ALL FAPI OPERATIONS WILL BE REJECTED \
1441                         until a valid RSA key is provided. Set FAPI_PRIVATE_KEY_PATH to a valid \
1442                         PEM-encoded RSA private key file."
1443                    );
1444                    is_degraded = true;
1445                    use ring::rand::{SecureRandom, SystemRandom};
1446                    let rng = SystemRandom::new();
1447                    let mut bytes = [0u8; 32];
1448                    rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1449                    EncodingKey::from_secret(&bytes)
1450                })
1451        } else {
1452            tracing::error!(
1453                "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH not set. FAPI REQUIRES an RSA \
1454                 private key for request and response signing. Using an ephemeral HMAC \
1455                 placeholder — ALL FAPI OPERATIONS WILL BE REJECTED until a valid RSA key \
1456                 is provided. Set FAPI_PRIVATE_KEY_PATH to a PEM-encoded RSA private key file."
1457            );
1458            is_degraded = true;
1459            use ring::rand::{SecureRandom, SystemRandom};
1460            let rng = SystemRandom::new();
1461            let mut bytes = [0u8; 32];
1462            rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1463            EncodingKey::from_secret(&bytes)
1464        };
1465
1466        // Same treatment for the public key.
1467        let public_key = if let Ok(key_path) = std::env::var("FAPI_PUBLIC_KEY_PATH") {
1468            std::fs::read(&key_path)
1469                .map_err(|e| tracing::warn!("Failed to load public key from {}: {}", key_path, e))
1470                .and_then(|bytes| {
1471                    DecodingKey::from_rsa_pem(&bytes)
1472                        .map_err(|e| tracing::warn!("Invalid RSA public key format: {}", e))
1473                })
1474                .unwrap_or_else(|_| {
1475                    tracing::error!(
1476                        "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH is set but the key could not \
1477                         be loaded. FAPI verification will not work correctly."
1478                    );
1479                    is_degraded = true;
1480                    use ring::rand::{SecureRandom, SystemRandom};
1481                    let rng = SystemRandom::new();
1482                    let mut secret = [0u8; 32];
1483                    rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1484                    DecodingKey::from_secret(&secret)
1485                })
1486        } else {
1487            tracing::error!(
1488                "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH not set. FAPI verification will \
1489                 not work correctly. Set FAPI_PUBLIC_KEY_PATH to a PEM-encoded RSA public key file."
1490            );
1491            is_degraded = true;
1492            use ring::rand::{SecureRandom, SystemRandom};
1493            let rng = SystemRandom::new();
1494            let mut secret = [0u8; 32];
1495            rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1496            DecodingKey::from_secret(&secret)
1497        };
1498
1499        Self {
1500            issuer,
1501            request_signing_algorithm: Algorithm::RS256,
1502            response_signing_algorithm: Algorithm::RS256,
1503            private_key,
1504            public_key,
1505            max_request_age: 300, // 5 minutes
1506            require_dpop: true,
1507            require_mtls: true,
1508            require_par: true,
1509            enable_jarm: true,
1510            enhanced_audit: true,
1511            is_degraded,
1512        }
1513    }
1514}
1515
1516/// Decode a client certificate passed as text: PEM (`-----BEGIN CERTIFICATE-----`) or bare
1517/// base64 of the DER encoding. The text must come from the TLS handshake (or a proxy that
1518/// 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
1519/// only ever receive an encoded form; hashing or parsing the text bytes themselves is wrong.
1520fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
1521    use base64::Engine;
1522    use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
1523
1524    const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
1525    const END: &str = "-----END CERTIFICATE-----";
1526    let bad = || {
1527        AuthError::auth_method(
1528            "mtls",
1529            "Client certificate must be PEM or base64-encoded DER",
1530        )
1531    };
1532
1533    let trimmed = input.trim();
1534    let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
1535        let end = rest.find(END).ok_or_else(bad)?;
1536        // Exactly one certificate: nothing but whitespace may follow the END line.
1537        if !rest[end + END.len()..].trim().is_empty() {
1538            return Err(bad());
1539        }
1540        &rest[..end]
1541    } else {
1542        trimmed
1543    };
1544    let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
1545    if compact.is_empty() {
1546        return Err(bad());
1547    }
1548    STANDARD
1549        .decode(&compact)
1550        .or_else(|_| STANDARD_NO_PAD.decode(&compact))
1551        .or_else(|_| URL_SAFE.decode(&compact))
1552        .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
1553        .map_err(|_| bad())
1554}
1555
1556/// The client identity a certificate carries: its single subject CN, otherwise its single
1557/// DNS/URI subjectAltName. Parsed from the DER, never searched for as text in the raw bytes.
1558fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
1559    use x509_parser::extensions::GeneralName;
1560
1561    let cert = match x509_parser::parse_x509_certificate(cert_der) {
1562        Ok(([], cert)) => cert,
1563        _ => {
1564            return Err(AuthError::auth_method(
1565                "mtls",
1566                "Invalid client certificate format",
1567            ));
1568        }
1569    };
1570
1571    let common_names: Vec<String> = cert
1572        .subject()
1573        .iter_common_name()
1574        .filter_map(|cn| cn.as_str().ok().map(str::to_string))
1575        .collect();
1576    if common_names.len() == 1 && !common_names[0].is_empty() {
1577        return Ok(common_names[0].clone());
1578    }
1579
1580    if let Ok(Some(san)) = cert.subject_alternative_name() {
1581        let names: Vec<String> = san
1582            .value
1583            .general_names
1584            .iter()
1585            .filter_map(|name| match name {
1586                GeneralName::DNSName(dns) => Some(dns.to_string()),
1587                GeneralName::URI(uri) => Some(uri.to_string()),
1588                _ => None,
1589            })
1590            .collect();
1591        if names.len() == 1 {
1592            return Ok(names[0].clone());
1593        }
1594    }
1595
1596    Err(AuthError::auth_method(
1597        "mtls",
1598        "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
1599    ))
1600}
1601
1602#[cfg(test)]
1603mod tests {
1604    use super::*;
1605
1606    #[test]
1607    fn test_fapi_config_builder() {
1608        use ring::rand::{SecureRandom, SystemRandom};
1609        let rng = SystemRandom::new();
1610        let mut bytes = [0u8; 32];
1611        rng.fill(&mut bytes).unwrap();
1612        let private_key = EncodingKey::from_secret(&bytes);
1613        let public_key = DecodingKey::from_secret(&bytes);
1614
1615        let config = FapiConfig::builder("https://fapi.example.com", private_key, public_key)
1616            .request_signing_algorithm(Algorithm::ES256)
1617            .max_request_age(120)
1618            .require_dpop(false)
1619            .degraded()
1620            .build();
1621
1622        assert_eq!(config.issuer, "https://fapi.example.com");
1623        assert_eq!(config.request_signing_algorithm, Algorithm::ES256);
1624        assert_eq!(config.max_request_age, 120);
1625        assert!(!config.require_dpop);
1626        assert!(config.require_mtls); // default is true
1627        assert!(config.is_degraded);
1628    }
1629
1630    #[test]
1631    fn test_fapi_session_builder() {
1632        let session = FapiSession::builder(
1633            "sess_123",
1634            "client_456",
1635            "user_789",
1636            Duration::try_hours(1).unwrap(),
1637        )
1638        .dpop_proof("proof_abc")
1639        .add_scope("openid")
1640        .add_scopes(vec!["profile", "email"])
1641        .add_metadata("custom_flag", json!(true))
1642        .build();
1643
1644        assert_eq!(session.session_id, "sess_123");
1645        assert_eq!(session.client_id, "client_456");
1646        assert_eq!(session.user_id, "user_789");
1647        assert_eq!(session.dpop_proof.as_deref(), Some("proof_abc"));
1648        assert_eq!(session.scopes, vec!["openid", "profile", "email"]);
1649        assert_eq!(session.metadata["custom_flag"], true);
1650    }
1651
1652    #[tokio::test]
1653    async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
1654        use crate::security::secure_jwt::SecureJwtConfig;
1655        use crate::server::jwt::private_key_jwt::ClientJwtConfig;
1656        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1657
1658        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
1659        let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1660        let manager = FapiManager::new(
1661            FapiConfig::default(),
1662            Arc::new(DpopManager::new(validator())),
1663            Arc::new(MutualTlsManager::new()),
1664            Arc::new(PARManager::new(Arc::new(
1665                crate::storage::MemoryStorage::new(),
1666            ))),
1667            assertions.clone(),
1668            Arc::new(validator()),
1669        );
1670
1671        // A registered client with a real key.
1672        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1673        let raw = key.public_key_raw();
1674        let point = &raw[raw.len() - 65..];
1675        let jwk = json!({
1676            "kty": "EC", "crv": "P-256",
1677            "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1678            "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1679        });
1680        assertions
1681            .register_client(
1682                ClientJwtConfig::builder("fapi-client", jwk)
1683                    .algorithms(vec![Algorithm::ES256])
1684                    .audience("https://auth.example.com/token")
1685                    .build(),
1686            )
1687            .await
1688            .unwrap();
1689        let encoding_key = EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap();
1690
1691        // Genuine assertion: authenticated.
1692        let good = assertions
1693            .create_client_assertion(
1694                "fapi-client",
1695                "https://auth.example.com/token",
1696                &encoding_key,
1697                Algorithm::ES256,
1698            )
1699            .unwrap();
1700        assert_eq!(
1701            manager.authenticate_client_jwt(&good).await.unwrap(),
1702            "fapi-client"
1703        );
1704
1705        // Each way to fail gives the same bare message: unknown client, wrong audience from the
1706        // real client (a reason that is only known after the signature verified), replay, junk.
1707        let wrong_audience = assertions
1708            .create_client_assertion(
1709                "fapi-client",
1710                "https://elsewhere.example/token",
1711                &encoding_key,
1712                Algorithm::ES256,
1713            )
1714            .unwrap();
1715        let unknown = assertions
1716            .create_client_assertion(
1717                "ghost",
1718                "https://auth.example.com/token",
1719                &encoding_key,
1720                Algorithm::ES256,
1721            )
1722            .unwrap();
1723        for (why, assertion) in [
1724            ("wrong audience", wrong_audience.as_str()),
1725            ("unknown client", unknown.as_str()),
1726            ("replay", good.as_str()),
1727            ("junk", "not-a-jwt"),
1728        ] {
1729            let message = manager
1730                .authenticate_client_jwt(assertion)
1731                .await
1732                .expect_err(why)
1733                .to_string();
1734            assert!(
1735                message.contains("Client authentication failed"),
1736                "{why}: {message}"
1737            );
1738            for leak in [
1739                "udience",
1740                "registered",
1741                "ignature",
1742                "replay",
1743                "JTI",
1744                "Algorithm",
1745                "expired",
1746            ] {
1747                assert!(
1748                    !message.contains(leak),
1749                    "{why}: {message:?} mentions {leak:?}"
1750                );
1751            }
1752        }
1753    }
1754
1755    #[tokio::test]
1756    async fn test_fapi_manager_creation() {
1757        // Comprehensive FAPI configuration validation
1758        let config = FapiConfig::default();
1759
1760        // Verify FAPI security requirements are enabled by default
1761        assert_eq!(config.issuer, "https://auth.example.com"); // Corrected expected value
1762        assert!(config.require_dpop);
1763        assert!(config.require_mtls);
1764        assert!(config.require_par);
1765        assert!(config.enable_jarm);
1766        assert!(config.enhanced_audit);
1767    }
1768
1769    #[tokio::test]
1770    async fn test_fapi_request_validation() {
1771        // Test request object validation according to FAPI requirements
1772        // This should validate JWT request objects, signatures, and claims
1773        let config = FapiConfig::default();
1774
1775        // Mock request object with required FAPI claims
1776        let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1777
1778        // SECURITY CRITICAL: Perform comprehensive JWT validation
1779        let validation_result = validate_fapi_request_object(request_object, &config);
1780        assert!(
1781            validation_result.is_ok(),
1782            "FAPI request object validation failed"
1783        );
1784
1785        // Ensure basic structure is valid but NEVER skip signature verification in production
1786        assert!(!request_object.is_empty());
1787    }
1788
1789    /// Validate FAPI request object with proper JWT verification
1790    fn validate_fapi_request_object(
1791        request_object: &str,
1792        _config: &FapiConfig,
1793    ) -> Result<(), String> {
1794        // Parse JSON structure
1795        let parsed: serde_json::Value = serde_json::from_str(request_object)
1796            .map_err(|_| "Invalid JSON structure in request object")?;
1797
1798        // Validate required FAPI claims
1799        let required_claims = ["iss", "aud", "exp", "iat", "jti"];
1800        for claim in &required_claims {
1801            if parsed.get(claim).is_none() {
1802                return Err(format!("Missing required FAPI claim: {}", claim));
1803            }
1804        }
1805
1806        // Validate expiration
1807        if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
1808            let now = chrono::Utc::now().timestamp();
1809            if exp <= now {
1810                return Err("Request object has expired".to_string());
1811            }
1812        }
1813
1814        // In production: Verify JWT signature against client's public key
1815        // For testing: Accept if structure is valid
1816        Ok(())
1817    }
1818
1819    #[tokio::test]
1820    async fn test_fapi_response_generation() {
1821        // Test JARM (JWT Secured Authorization Response Mode) generation
1822        // This should create signed JWT responses for authorization responses
1823        let config = FapiConfig::default();
1824
1825        // Mock authorization response
1826        let auth_response = serde_json::json!({
1827            "code": "auth_code_123",
1828            "state": "client_state",
1829            "iss": config.issuer,
1830            "aud": "client_id",
1831            "exp": 9999999999i64
1832        });
1833
1834        // In real implementation, sign the response as a JWT
1835        assert!(auth_response["code"].is_string());
1836    }
1837
1838    #[tokio::test]
1839    async fn test_fapi_token_generation() {
1840        // Test FAPI-compliant token generation with DPoP and mTLS
1841        let config = FapiConfig::default();
1842
1843        // Mock FAPI token request with required security features
1844        let scopes = ["accounts".to_string(), "payments".to_string()];
1845        let client_id = "fapi_client_123";
1846        let user_id = "user_456";
1847        let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
1848
1849        // Verify FAPI-specific requirements would be enforced
1850        assert!(config.require_dpop);
1851        assert!(config.require_mtls);
1852        assert!(!scopes.is_empty());
1853        assert!(!client_id.is_empty());
1854        assert!(!user_id.is_empty());
1855        assert!(cert_thumbprint.is_some());
1856    }
1857
1858    #[tokio::test]
1859    async fn test_fapi_session_management() {
1860        // Test FAPI session management and security requirements
1861        let config = FapiConfig::default();
1862
1863        // Mock FAPI session with enhanced security
1864        let session_data = serde_json::json!({
1865            "client_id": "fapi_client",
1866            "user_id": "fapi_user",
1867            "scopes": ["accounts", "payments"],
1868            "mtls_cert": "client_certificate",
1869            "dpop_key": "client_dpop_key"
1870        });
1871
1872        // Verify session includes FAPI security elements
1873        assert!(session_data["mtls_cert"].is_string());
1874        assert!(session_data["dpop_key"].is_string());
1875        assert!(config.enhanced_audit);
1876    }
1877
1878    // ---- certificate input decoding and client-id derivation ----
1879
1880    fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
1881        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1882        let mut dn = rcgen::DistinguishedName::new();
1883        dn.push(rcgen::DnType::CommonName, cn);
1884        if let Some(org) = org {
1885            dn.push(rcgen::DnType::OrganizationName, org);
1886        }
1887        params.distinguished_name = dn;
1888        let key = rcgen::KeyPair::generate().unwrap();
1889        params.self_signed(&key).unwrap()
1890    }
1891
1892    #[test]
1893    fn decode_client_certificate_accepts_pem_and_base64_der() {
1894        use base64::Engine;
1895        let cert = test_cert("client-a", None);
1896        let der = cert.der().to_vec();
1897
1898        assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
1899        let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
1900        assert_eq!(decode_client_certificate(&b64).unwrap(), der);
1901        let wrapped = format!("  {}\n{}  \n", &b64[..20], &b64[20..]);
1902        assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
1903    }
1904
1905    #[test]
1906    fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
1907        let a = test_cert("client-a", None).pem();
1908        let b = test_cert("client-b", None).pem();
1909        assert!(decode_client_certificate("").is_err());
1910        assert!(decode_client_certificate("!!! not base64 !!!").is_err());
1911        assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
1912        // Two certificates in one value: refuse rather than silently using the first.
1913        assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
1914    }
1915
1916    #[test]
1917    fn client_id_comes_from_the_parsed_subject_cn() {
1918        let cert = test_cert("client-a", None);
1919        assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
1920    }
1921
1922    #[test]
1923    fn client_id_is_not_found_by_searching_the_raw_bytes() {
1924        // Text that merely looks like "CN=..." inside another attribute (here Organization) is
1925        // not an identity: the id comes from the parsed subject.
1926        let cert = test_cert("real-client", Some("CN=victim-client,"));
1927        assert_eq!(
1928            client_id_from_certificate(cert.der()).unwrap(),
1929            "real-client"
1930        );
1931    }
1932
1933    #[test]
1934    fn client_id_needs_a_unique_identity() {
1935        // No CN and no SAN: there is nothing to derive, so no id is invented.
1936        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1937        params.distinguished_name = rcgen::DistinguishedName::new(); // rcgen defaults to a CN
1938        let key = rcgen::KeyPair::generate().unwrap();
1939        let nameless = params.self_signed(&key).unwrap();
1940        assert!(client_id_from_certificate(nameless.der()).is_err());
1941        assert!(client_id_from_certificate(b"not a certificate").is_err());
1942    }
1943}