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