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