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
572/// Is a request object issued at `iat` older than `max_age` seconds at `now`?
573fn request_object_too_old(now: i64, iat: i64, max_age: i64) -> bool {
574    now.checked_sub(iat).is_none_or(|age| age > max_age)
575}
576
577impl FapiManager {
578    /// Create a new FAPI manager
579    pub fn new(
580        config: FapiConfig,
581        dpop_manager: Arc<DpopManager>,
582        mtls_manager: Arc<MutualTlsManager>,
583        par_manager: Arc<PARManager>,
584        private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
585        jwt_validator: Arc<SecureJwtValidator>,
586    ) -> Self {
587        Self {
588            dpop_manager,
589            mtls_manager,
590            par_manager,
591            private_key_jwt_manager,
592            jwt_validator,
593            config,
594            sessions: Arc::new(RwLock::new(HashMap::new())),
595        }
596    }
597
598    /// Validate FAPI 2.0 authorization request
599    pub async fn validate_authorization_request(
600        &self,
601        request_object: &str,
602        client_cert: Option<&str>,
603        dpop_proof: Option<&str>,
604        request_uri: Option<&str>,
605    ) -> Result<FapiRequestObject> {
606        let claims = if let Some(uri) = request_uri {
607            // PAR workflow - validate request_uri and retrieve the request
608            if self.config.require_par {
609                // Use PAR manager to consume the pushed request
610                let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
611                    AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
612                })?;
613
614                tracing::info!(
615                    "FAPI PAR request consumed successfully for client: {}",
616                    par_request.client_id
617                );
618
619                // Convert PAR request to FAPI request object
620                let nonce = par_request.additional_params.get("nonce").cloned();
621                FapiRequestObject {
622                    iss: par_request.client_id.clone(),
623                    aud: self.config.issuer.clone(),
624                    iat: Utc::now().timestamp(),
625                    exp: Utc::now().timestamp() + 300, // 5 minutes
626                    nbf: Some(Utc::now().timestamp()),
627                    jti: uuid::Uuid::new_v4().to_string(),
628                    response_type: par_request.response_type,
629                    client_id: par_request.client_id,
630                    redirect_uri: par_request.redirect_uri,
631                    scope: par_request.scope.unwrap_or_default(),
632                    state: par_request.state,
633                    nonce,
634                    code_challenge: par_request.code_challenge,
635                    code_challenge_method: par_request.code_challenge_method,
636                    additional_claims: par_request
637                        .additional_params
638                        .into_iter()
639                        .map(|(k, v)| (k, serde_json::Value::String(v)))
640                        .collect(),
641                }
642            } else {
643                return Err(AuthError::InvalidRequest(
644                    "request_uri provided but PAR not required".to_string(),
645                ));
646            }
647        } else {
648            // Standard request object validation
649            if self.config.require_par {
650                return Err(AuthError::InvalidRequest(
651                    "PAR is required but no request_uri provided".to_string(),
652                ));
653            }
654
655            // Validate request object JWT using enhanced validation
656            self.validate_request_object(request_object).await?
657        };
658
659        // Validate mTLS if required
660        if self.config.require_mtls {
661            let cert = client_cert.ok_or_else(|| {
662                AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
663            })?;
664            let cert_bytes = decode_client_certificate(cert)?;
665            self.mtls_manager
666                .validate_client_certificate(&cert_bytes, &claims.client_id)
667                .await?;
668        }
669
670        // Validate DPoP if required; the proof is recorded only once the request has been accepted.
671        let pending_proof = if self.config.require_dpop {
672            let proof = dpop_proof.ok_or_else(|| {
673                AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0")
674            })?;
675            Some(
676                self.dpop_manager
677                    .verify_dpop_proof(
678                        proof,
679                        "POST",
680                        &format!("{}/authorize", self.config.issuer),
681                        None,
682                        None,
683                        None,
684                    )
685                    .await?,
686            )
687        } else {
688            None
689        };
690
691        // Validate request object claims
692        self.validate_request_claims(&claims).await?;
693
694        if let Some(pending) = pending_proof {
695            self.dpop_manager.commit_dpop_proof(pending).await?;
696        }
697
698        Ok(claims)
699    }
700
701    /// Validate request object JWT
702    async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
703        // Use the SecureJwtValidator for enhanced security validation
704        let decoding_key = &self.config.public_key;
705
706        // Validate using SecureJwtValidator with enhanced security features
707        match self
708            .jwt_validator
709            .validate_token(request_object, decoding_key)
710        {
711            Ok(secure_claims) => {
712                // Decode JWT header to get algorithm
713                let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
714                    AuthError::token(format!("Invalid request object header: {}", e))
715                })?;
716
717                // Validate algorithm requirement for FAPI
718                if !matches!(
719                    header.alg,
720                    Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
721                ) {
722                    return Err(AuthError::token(
723                        "Request object must use RS256, PS256, or ES256".to_string(),
724                    ));
725                }
726
727                // Set up validation with the same algorithm for FAPI-specific claims
728                let mut validation = Validation::new(header.alg);
729                validation.set_audience(&[&self.config.issuer]);
730                validation.validate_exp = true;
731                validation.validate_nbf = true;
732
733                // Decode the FAPI request object structure
734                let token_data = jsonwebtoken::decode::<FapiRequestObject>(
735                    request_object,
736                    &self.config.public_key,
737                    &validation,
738                )
739                .map_err(|e| {
740                    AuthError::token(format!("Request object validation failed: {}", e))
741                })?;
742
743                let fapi_claims = token_data.claims;
744
745                // Use the validated secure claims for enhanced security checks
746                // Ensure the subject matches between secure validation and FAPI claims
747                if secure_claims.sub != fapi_claims.client_id {
748                    return Err(AuthError::token(
749                        "Subject mismatch between secure validation and FAPI claims".to_string(),
750                    ));
751                }
752
753                // Use secure claims issuer for additional validation
754                if secure_claims.iss != fapi_claims.iss {
755                    return Err(AuthError::token(
756                        "Issuer mismatch between secure validation and FAPI claims".to_string(),
757                    ));
758                }
759
760                // Validate expiry consistency
761                if secure_claims.exp != fapi_claims.exp {
762                    return Err(AuthError::token(
763                        "Expiry mismatch between secure validation and FAPI claims".to_string(),
764                    ));
765                }
766
767                // Additional FAPI validations using the validated claims
768                let now = Utc::now().timestamp();
769
770                // Check request object age
771                if request_object_too_old(now, fapi_claims.iat, self.config.max_request_age) {
772                    return Err(AuthError::token("Request object too old".to_string()));
773                }
774
775                // Validate required claims
776                if fapi_claims.client_id.is_empty() {
777                    return Err(AuthError::token(
778                        "client_id required in request object".to_string(),
779                    ));
780                }
781
782                if fapi_claims.redirect_uri.is_empty() {
783                    return Err(AuthError::token(
784                        "redirect_uri required in request object".to_string(),
785                    ));
786                }
787
788                if fapi_claims.response_type.is_empty() {
789                    return Err(AuthError::token(
790                        "response_type required in request object".to_string(),
791                    ));
792                }
793
794                tracing::info!(
795                    "FAPI request object validated successfully with SecureJwtValidator for client: {}",
796                    fapi_claims.client_id
797                );
798
799                Ok(fapi_claims)
800            }
801            Err(e) => {
802                tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
803                Err(AuthError::token(format!(
804                    "Enhanced JWT validation failed: {}",
805                    e
806                )))
807            }
808        }
809    }
810
811    /// Validate request object claims against FAPI requirements
812    async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
813        // Validate response_type for FAPI 2.0
814        if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
815            return Err(AuthError::InvalidRequest(
816                "FAPI 2.0 requires code or code id_token response type".to_string(),
817            ));
818        }
819
820        // Validate PKCE for public clients
821        if claims.code_challenge.is_none() {
822            return Err(AuthError::InvalidRequest(
823                "PKCE required for FAPI 2.0".to_string(),
824            ));
825        }
826
827        if let Some(method) = &claims.code_challenge_method {
828            if method != "S256" {
829                return Err(AuthError::InvalidRequest(
830                    "FAPI 2.0 requires S256 code challenge method".to_string(),
831                ));
832            }
833        } else {
834            return Err(AuthError::InvalidRequest(
835                "code_challenge_method required for FAPI 2.0".to_string(),
836            ));
837        }
838
839        Ok(())
840    }
841
842    /// Authenticate client using private key JWT (RFC 7523)
843    ///
844    /// The caller learns only that authentication failed: the detailed reasons (unknown client,
845    /// bad signature, wrong audience, replay, ...) are logged, never returned.
846    pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
847        const REFUSED: &str = "Client authentication failed";
848
849        // Use the private key JWT manager for authentication
850        let auth_result = match self
851            .private_key_jwt_manager
852            .authenticate_client(client_assertion)
853            .await
854        {
855            Ok(result) => result,
856            Err(e) => {
857                tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
858                return Err(AuthError::auth_method("private_key_jwt", REFUSED));
859            }
860        };
861
862        if auth_result.authenticated {
863            tracing::info!(
864                "FAPI client authenticated successfully using private key JWT: {}",
865                auth_result.client_id
866            );
867            Ok(auth_result.client_id)
868        } else {
869            tracing::warn!(
870                "FAPI private key JWT authentication failed: {}",
871                auth_result.errors.join("; ")
872            );
873            Err(AuthError::auth_method("private_key_jwt", REFUSED))
874        }
875    }
876
877    /// Validate FAPI token request with enhanced security
878    pub async fn validate_token_request(
879        &self,
880        client_assertion: Option<&str>,
881        client_cert: Option<&str>,
882        dpop_proof: Option<&str>,
883        _authorization_code: &str,
884    ) -> Result<String> {
885        // Client authentication - prefer private key JWT for FAPI 2.0
886        let client_id = if let Some(assertion) = client_assertion {
887            self.authenticate_client_jwt(assertion).await?
888        } else if self.config.require_mtls {
889            if let Some(cert) = client_cert {
890                let cert_bytes = decode_client_certificate(cert)?;
891
892                // Look the client up by the identity the certificate carries; the manager then
893                // verifies the chain AND that this certificate is bound to that client.
894                let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
895
896                self.mtls_manager
897                    .validate_client_certificate(&cert_bytes, &client_id)
898                    .await?;
899
900                client_id.to_string()
901            } else {
902                return Err(AuthError::auth_method(
903                    "mtls",
904                    "Client certificate required for FAPI 2.0 token request",
905                ));
906            }
907        } else {
908            return Err(AuthError::auth_method(
909                "fapi",
910                "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
911            ));
912        };
913
914        // Validate DPoP if required
915        if self.config.require_dpop {
916            let proof = dpop_proof.ok_or_else(|| {
917                AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0 token request")
918            })?;
919            self.dpop_manager
920                .validate_dpop_proof(
921                    proof,
922                    "POST",
923                    &format!("{}/token", self.config.issuer),
924                    None, // an authorization code is not an access token: no `ath` at this endpoint
925                    None,
926                )
927                .await?;
928        }
929
930        Ok(client_id)
931    }
932
933    /// Generate FAPI 2.0 authorization response (JARM)
934    pub async fn generate_authorization_response(
935        &self,
936        client_id: &str,
937        code: Option<&str>,
938        state: Option<&str>,
939        error: Option<&str>,
940        error_description: Option<&str>,
941    ) -> Result<String> {
942        if !self.config.enable_jarm {
943            return Err(AuthError::Configuration {
944                message: "JARM not enabled".to_string(),
945                help: Some("Enable JARM in your configuration to use this feature".to_string()),
946                docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
947                source: None,
948                suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
949            });
950        }
951
952        let now = Utc::now();
953        let exp = now + Duration::minutes(5); // Response expires in 5 minutes
954
955        let response = FapiAuthorizationResponse {
956            iss: self.config.issuer.clone(),
957            aud: client_id.to_string(),
958            iat: now.timestamp(),
959            exp: exp.timestamp(),
960            code: code.map(|c| c.to_string()),
961            state: state.map(|s| s.to_string()),
962            error: error.map(|e| e.to_string()),
963            error_description: error_description.map(|d| d.to_string()),
964            additional_params: HashMap::new(),
965        };
966
967        // Create JWT header
968        let header = Header::new(self.config.response_signing_algorithm);
969
970        // Sign the response
971        let token =
972            jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
973                AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
974            })?;
975
976        Ok(token)
977    }
978
979    /// Generate FAPI 2.0 token response
980    pub async fn generate_token_response(
981        &self,
982        client_id: &str,
983        user_id: &str,
984        scopes: Vec<String>,
985        cert_thumbprint: Option<String>,
986        dpop_jkt: Option<String>,
987    ) -> Result<FapiTokenResponse> {
988        // Generate access token
989        let access_token = self
990            .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
991            .await?;
992
993        // Generate refresh token
994        let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
995
996        // Build confirmation claim
997        let mut cnf = json!({});
998
999        if let Some(thumbprint) = cert_thumbprint {
1000            cnf["x5t#S256"] = Value::String(thumbprint);
1001        }
1002
1003        if let Some(jkt) = dpop_jkt {
1004            cnf["jkt"] = Value::String(jkt);
1005        }
1006
1007        let response = FapiTokenResponse {
1008            access_token,
1009            token_type: "DPoP".to_string(), // Always DPoP for FAPI 2.0
1010            expires_in: 3600,               // 1 hour
1011            refresh_token: Some(refresh_token),
1012            scope: Some(scopes.join(" ")),
1013            id_token: None, // ID token generated by OIDC layer when openid scope present
1014            cnf: if cnf.as_object().is_none_or(|o| o.is_empty()) {
1015                None
1016            } else {
1017                Some(cnf)
1018            },
1019        };
1020
1021        Ok(response)
1022    }
1023
1024    /// Generate access token
1025    async fn generate_access_token(
1026        &self,
1027        client_id: &str,
1028        user_id: &str,
1029        scopes: &[String],
1030        cert_thumbprint: &Option<String>,
1031        dpop_jkt: &Option<String>,
1032    ) -> Result<String> {
1033        let claims =
1034            self.access_token_claims(client_id, user_id, scopes, cert_thumbprint, dpop_jkt);
1035
1036        // Create JWT header
1037        let header = Header::new(Algorithm::RS256);
1038
1039        // Sign the token
1040        let token =
1041            jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1042                AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
1043            })?;
1044
1045        Ok(token)
1046    }
1047
1048    /// The claims of a FAPI access token.
1049    fn access_token_claims(
1050        &self,
1051        client_id: &str,
1052        user_id: &str,
1053        scopes: &[String],
1054        cert_thumbprint: &Option<String>,
1055        dpop_jkt: &Option<String>,
1056    ) -> Value {
1057        let now = Utc::now();
1058        let exp = now + Duration::hours(1);
1059
1060        let mut claims = json!({
1061            "iss": self.config.issuer,
1062            // This server is the audience the resource check accepts; the client is `client_id`.
1063            "aud": self.config.issuer,
1064            "client_id": client_id,
1065            "sub": user_id,
1066            "iat": now.timestamp(),
1067            "nbf": now.timestamp(),
1068            "exp": exp.timestamp(),
1069            "scope": scopes.join(" "),
1070            "jti": Uuid::new_v4().to_string(),
1071            "typ": "access",
1072        });
1073
1074        // Add confirmation claims
1075        let mut cnf = json!({});
1076
1077        if let Some(thumbprint) = cert_thumbprint {
1078            cnf["x5t#S256"] = Value::String(thumbprint.clone());
1079        }
1080
1081        if let Some(jkt) = dpop_jkt {
1082            cnf["jkt"] = Value::String(jkt.clone());
1083        }
1084
1085        if !cnf.as_object().is_none_or(|o| o.is_empty()) {
1086            claims["cnf"] = cnf;
1087        }
1088
1089        claims
1090    }
1091
1092    /// Generate refresh token
1093    async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
1094        let now = Utc::now();
1095        let exp = now + Duration::days(30); // 30 day expiry
1096
1097        let claims = json!({
1098            "iss": self.config.issuer,
1099            "aud": client_id,
1100            "sub": user_id,
1101            "iat": now.timestamp(),
1102            "exp": exp.timestamp(),
1103            "typ": crate::security::secure_jwt::TYP_REFRESH_TOKEN,
1104            "jti": Uuid::new_v4().to_string(),
1105        });
1106
1107        // Create JWT header
1108        let header = Header::new(Algorithm::RS256);
1109
1110        // Sign the token
1111        let token =
1112            jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1113                AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
1114            })?;
1115
1116        Ok(token)
1117    }
1118
1119    /// Create FAPI session
1120    pub async fn create_session(
1121        &self,
1122        client_id: &str,
1123        user_id: &str,
1124        scopes: Vec<String>,
1125        dpop_proof: Option<String>,
1126        cert_thumbprint: Option<String>,
1127        request_jti: Option<String>,
1128    ) -> Result<String> {
1129        let session_id = Uuid::new_v4().to_string();
1130        let now = Utc::now();
1131        let expires_at = now + Duration::hours(24); // 24 hour session
1132
1133        let session = FapiSession {
1134            session_id: session_id.clone(),
1135            client_id: client_id.to_string(),
1136            user_id: user_id.to_string(),
1137            created_at: now,
1138            expires_at,
1139            dpop_proof,
1140            cert_thumbprint,
1141            request_jti,
1142            scopes,
1143            metadata: HashMap::new(),
1144        };
1145
1146        let mut sessions = self.sessions.write().await;
1147        sessions.insert(session_id.clone(), session);
1148
1149        Ok(session_id)
1150    }
1151
1152    /// Get FAPI session
1153    pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
1154        let sessions = self.sessions.read().await;
1155        Ok(sessions.get(session_id).cloned())
1156    }
1157
1158    /// Validate FAPI session
1159    pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
1160        let session = self
1161            .get_session(session_id)
1162            .await?
1163            .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
1164
1165        // Check expiration
1166        if Utc::now() > session.expires_at {
1167            return Err(AuthError::validation("Session expired".to_string()));
1168        }
1169
1170        Ok(session)
1171    }
1172
1173    /// Remove FAPI session
1174    pub async fn remove_session(&self, session_id: &str) -> Result<()> {
1175        let mut sessions = self.sessions.write().await;
1176        sessions.remove(session_id);
1177        Ok(())
1178    }
1179
1180    /// Audit log entry for FAPI compliance
1181    pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
1182        if self.config.enhanced_audit {
1183            // Implement proper audit logging for FAPI compliance
1184            // This should log to secure, tamper-evident storage
1185            // Format: ISO 8601 timestamp, event type, client details, user context
1186            let timestamp = chrono::Utc::now().to_rfc3339();
1187            let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
1188
1189            // In production, write to secure audit log storage
1190            tracing::info!("{}", audit_entry);
1191        }
1192        Ok(())
1193    }
1194
1195    /// Extract client ID from certificate
1196    async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
1197        client_id_from_certificate(cert_bytes)
1198    }
1199
1200    /// Validate FAPI 2.0 compliance of the current configuration.
1201    ///
1202    /// Returns a list of compliance violations. An empty list means the
1203    /// configuration is fully FAPI 2.0 compliant.
1204    pub fn check_compliance(&self) -> Vec<FapiComplianceViolation> {
1205        let mut violations = Vec::new();
1206
1207        if self.config.is_degraded {
1208            violations.push(FapiComplianceViolation {
1209                requirement: "crypto-keys".to_string(),
1210                severity: FapiViolationSeverity::Critical,
1211                message: "RSA key pair not properly configured; all FAPI operations will fail"
1212                    .to_string(),
1213            });
1214        }
1215
1216        if !self.config.require_par {
1217            violations.push(FapiComplianceViolation {
1218                requirement: "par".to_string(),
1219                severity: FapiViolationSeverity::Critical,
1220                message: "FAPI 2.0 Security Profile requires Pushed Authorization Requests"
1221                    .to_string(),
1222            });
1223        }
1224
1225        if !self.config.require_dpop {
1226            violations.push(FapiComplianceViolation {
1227                requirement: "sender-constraint".to_string(),
1228                severity: FapiViolationSeverity::Warning,
1229                message: "DPoP is recommended for sender-constrained tokens".to_string(),
1230            });
1231        }
1232
1233        if !self.config.require_mtls {
1234            violations.push(FapiComplianceViolation {
1235                requirement: "sender-constraint".to_string(),
1236                severity: FapiViolationSeverity::Warning,
1237                message: "mTLS is recommended for client authentication and token binding"
1238                    .to_string(),
1239            });
1240        }
1241
1242        if !self.config.require_dpop && !self.config.require_mtls {
1243            violations.push(FapiComplianceViolation {
1244                requirement: "sender-constraint".to_string(),
1245                severity: FapiViolationSeverity::Critical,
1246                message:
1247                    "FAPI 2.0 requires at least one sender-constraining mechanism (DPoP or mTLS)"
1248                        .to_string(),
1249            });
1250        }
1251
1252        if !self.config.enable_jarm {
1253            violations.push(FapiComplianceViolation {
1254                requirement: "jarm".to_string(),
1255                severity: FapiViolationSeverity::Warning,
1256                message: "JARM is recommended for authorization response integrity".to_string(),
1257            });
1258        }
1259
1260        if !self.config.enhanced_audit {
1261            violations.push(FapiComplianceViolation {
1262                requirement: "audit".to_string(),
1263                severity: FapiViolationSeverity::Warning,
1264                message: "Enhanced audit logging is recommended for FAPI compliance".to_string(),
1265            });
1266        }
1267
1268        if !matches!(
1269            self.config.request_signing_algorithm,
1270            Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
1271        ) {
1272            violations.push(FapiComplianceViolation {
1273                requirement: "algorithm".to_string(),
1274                severity: FapiViolationSeverity::Critical,
1275                message: "Request signing must use RS256, PS256, or ES256".to_string(),
1276            });
1277        }
1278
1279        if self.config.max_request_age > 600 {
1280            violations.push(FapiComplianceViolation {
1281                requirement: "request-lifetime".to_string(),
1282                severity: FapiViolationSeverity::Warning,
1283                message: "Max request age exceeds recommended 10 minutes".to_string(),
1284            });
1285        }
1286
1287        violations
1288    }
1289
1290    /// Returns true if the configuration is fully FAPI 2.0 compliant (no critical violations).
1291    pub fn is_compliant(&self) -> bool {
1292        !self
1293            .check_compliance()
1294            .iter()
1295            .any(|v| matches!(v.severity, FapiViolationSeverity::Critical))
1296    }
1297
1298    /// Validate a sender-constrained access token at a resource server.
1299    ///
1300    /// Verifies that the token's `cnf` claim matches the presented proof
1301    /// (DPoP proof JKT or mTLS certificate thumbprint).
1302    pub async fn validate_sender_constrained_token(
1303        &self,
1304        access_token: &str,
1305        dpop_proof: Option<&str>,
1306        client_cert: Option<&str>,
1307        http_method: &str,
1308        http_uri: &str,
1309    ) -> Result<serde_json::Value> {
1310        // Validate the token's signature and standard claims via SecureJwtValidator
1311        let token_data = self
1312            .jwt_validator
1313            .validate_token(access_token, &self.config.public_key)?;
1314
1315        // Decode the raw JWT payload to access the cnf claim which is not in SecureJwtClaims
1316        let header = jsonwebtoken::decode_header(access_token)
1317            .map_err(|e| AuthError::token(format!("Invalid token header: {}", e)))?;
1318        let mut validation = Validation::new(header.alg);
1319        validation.set_audience(&[&self.config.issuer]);
1320        validation.validate_exp = true;
1321        let raw_claims = jsonwebtoken::decode::<serde_json::Value>(
1322            access_token,
1323            &self.config.public_key,
1324            &validation,
1325        )
1326        .map_err(|e| AuthError::token(format!("Token decode failed: {}", e)))?;
1327
1328        // Extract cnf claim from the raw payload
1329        let cnf = raw_claims.claims.get("cnf").ok_or_else(|| {
1330            AuthError::token("Token is not sender-constrained (missing cnf claim)".to_string())
1331        })?;
1332
1333        // A `cnf` that names no binding we can check, or names one of the wrong type, is not a
1334        // binding: refuse it rather than skip the checks below.
1335        let jkt_member = cnf.get("jkt");
1336        let x5t_member = cnf.get("x5t#S256");
1337        for (name, member) in [("jkt", jkt_member), ("x5t#S256", x5t_member)] {
1338            if member.is_some_and(|v| !v.is_string()) {
1339                return Err(AuthError::token(format!(
1340                    "Token's cnf.{name} is not a string"
1341                )));
1342            }
1343        }
1344        if jkt_member.is_none() && x5t_member.is_none() {
1345            return Err(AuthError::token(
1346                "Token's cnf claim names no supported key binding".to_string(),
1347            ));
1348        }
1349
1350        // Validate DPoP binding if cnf contains jkt. The proof is verified here and recorded
1351        // only after the certificate binding below has passed too.
1352        let pending_proof = if let Some(expected_jkt) = cnf.get("jkt").and_then(|v| v.as_str()) {
1353            let proof = dpop_proof.ok_or_else(|| {
1354                AuthError::token(
1355                    "Token is DPoP-bound but no DPoP proof header provided".to_string(),
1356                )
1357            })?;
1358            Some(
1359                self.dpop_manager
1360                    .verify_dpop_proof(
1361                        proof,
1362                        http_method,
1363                        http_uri,
1364                        Some(access_token),
1365                        None,
1366                        Some(expected_jkt),
1367                    )
1368                    .await?,
1369            )
1370        } else {
1371            None
1372        };
1373
1374        // Validate mTLS certificate binding if cnf contains x5t#S256
1375        if let Some(expected_thumbprint) = cnf.get("x5t#S256").and_then(|v| v.as_str()) {
1376            let cert = client_cert.ok_or_else(|| {
1377                AuthError::token(
1378                    "Token is certificate-bound but no client certificate provided".to_string(),
1379                )
1380            })?;
1381            // RFC 8705 x5t#S256: SHA-256 over the DER encoding of the presented certificate
1382            use base64::Engine;
1383            use sha2::{Digest, Sha256};
1384            let cert_der = decode_client_certificate(cert)?;
1385            let presented_thumbprint =
1386                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(&cert_der));
1387            if !bool::from(subtle::ConstantTimeEq::ct_eq(
1388                presented_thumbprint.as_bytes(),
1389                expected_thumbprint.as_bytes(),
1390            )) {
1391                return Err(AuthError::token(
1392                    "Certificate thumbprint does not match token binding".to_string(),
1393                ));
1394            }
1395        }
1396
1397        if let Some(pending) = pending_proof {
1398            self.dpop_manager.commit_dpop_proof(pending).await?;
1399        }
1400
1401        // Return the validated token claims
1402        Ok(serde_json::json!({
1403            "sub": token_data.sub,
1404            "iss": token_data.iss,
1405            "exp": token_data.exp,
1406            "scope": token_data.scope,
1407        }))
1408    }
1409
1410    /// Validate a Rich Authorization Request (RFC 9396) authorization_details parameter.
1411    pub fn validate_authorization_details(
1412        &self,
1413        authorization_details: &[AuthorizationDetail],
1414    ) -> Result<()> {
1415        if authorization_details.is_empty() {
1416            return Err(AuthError::InvalidRequest(
1417                "authorization_details must not be empty".to_string(),
1418            ));
1419        }
1420
1421        for (i, detail) in authorization_details.iter().enumerate() {
1422            if detail.r#type.is_empty() {
1423                return Err(AuthError::InvalidRequest(format!(
1424                    "authorization_details[{}]: type is required",
1425                    i
1426                )));
1427            }
1428
1429            // Validate locations if present
1430            for location in &detail.locations {
1431                if !location.starts_with("https://") {
1432                    return Err(AuthError::InvalidRequest(format!(
1433                        "authorization_details[{}]: location must use HTTPS: {}",
1434                        i, location
1435                    )));
1436                }
1437            }
1438
1439            // Validate actions are non-empty strings
1440            for action in &detail.actions {
1441                if action.is_empty() {
1442                    return Err(AuthError::InvalidRequest(format!(
1443                        "authorization_details[{}]: empty action not allowed",
1444                        i
1445                    )));
1446                }
1447            }
1448        }
1449
1450        Ok(())
1451    }
1452}
1453
1454/// FAPI 2.0 compliance violation
1455#[derive(Debug, Clone)]
1456pub struct FapiComplianceViolation {
1457    /// Which FAPI requirement is violated
1458    pub requirement: String,
1459    /// Severity of the violation
1460    pub severity: FapiViolationSeverity,
1461    /// Human-readable description
1462    pub message: String,
1463}
1464
1465/// Severity of a compliance violation
1466#[derive(Debug, Clone, PartialEq, Eq)]
1467pub enum FapiViolationSeverity {
1468    /// Must be fixed for FAPI 2.0 compliance
1469    Critical,
1470    /// Recommended but not strictly required
1471    Warning,
1472}
1473
1474/// Rich Authorization Request detail (RFC 9396)
1475#[derive(Debug, Clone, Serialize, Deserialize)]
1476pub struct AuthorizationDetail {
1477    /// Type of authorization (e.g. "payment_initiation", "account_information")
1478    pub r#type: String,
1479
1480    /// Resource server locations this authorization applies to
1481    #[serde(default)]
1482    pub locations: Vec<String>,
1483
1484    /// Permitted actions (e.g. "read", "write", "execute")
1485    #[serde(default)]
1486    pub actions: Vec<String>,
1487
1488    /// Data types the client wants to access
1489    #[serde(default)]
1490    pub datatypes: Vec<String>,
1491
1492    /// Unique identifier for the authorization detail
1493    #[serde(skip_serializing_if = "Option::is_none")]
1494    pub identifier: Option<String>,
1495
1496    /// Additional fields specific to the authorization type
1497    #[serde(flatten)]
1498    pub additional_fields: HashMap<String, Value>,
1499}
1500
1501impl Default for FapiConfig {
1502    fn default() -> Self {
1503        // Load configuration from environment variables or use secure defaults
1504        let issuer =
1505            std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
1506
1507        let mut is_degraded = false;
1508
1509        // Load private key from environment — FAPI *requires* asymmetric keys.
1510        // There is intentionally no insecure fallback; callers must either set
1511        // FAPI_PRIVATE_KEY_PATH or construct FapiConfig manually.
1512        let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
1513            std::fs::read(&key_path)
1514                .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
1515                .and_then(|bytes| {
1516                    EncodingKey::from_rsa_pem(&bytes)
1517                        .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
1518                })
1519                .unwrap_or_else(|_| {
1520                    tracing::error!(
1521                        "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH is set but the key could not \
1522                         be loaded. FAPI REQUIRES an RSA private key for request/response signing. \
1523                         Using an ephemeral HMAC placeholder — ALL FAPI OPERATIONS WILL BE REJECTED \
1524                         until a valid RSA key is provided. Set FAPI_PRIVATE_KEY_PATH to a valid \
1525                         PEM-encoded RSA private key file."
1526                    );
1527                    is_degraded = true;
1528                    use ring::rand::{SecureRandom, SystemRandom};
1529                    let rng = SystemRandom::new();
1530                    let mut bytes = [0u8; 32];
1531                    rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1532                    EncodingKey::from_secret(&bytes)
1533                })
1534        } else {
1535            tracing::error!(
1536                "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH not set. FAPI REQUIRES an RSA \
1537                 private key for request and response signing. Using an ephemeral HMAC \
1538                 placeholder — ALL FAPI OPERATIONS WILL BE REJECTED until a valid RSA key \
1539                 is provided. Set FAPI_PRIVATE_KEY_PATH to a PEM-encoded RSA private key file."
1540            );
1541            is_degraded = true;
1542            use ring::rand::{SecureRandom, SystemRandom};
1543            let rng = SystemRandom::new();
1544            let mut bytes = [0u8; 32];
1545            rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1546            EncodingKey::from_secret(&bytes)
1547        };
1548
1549        // Same treatment for the public key.
1550        let public_key = if let Ok(key_path) = std::env::var("FAPI_PUBLIC_KEY_PATH") {
1551            std::fs::read(&key_path)
1552                .map_err(|e| tracing::warn!("Failed to load public key from {}: {}", key_path, e))
1553                .and_then(|bytes| {
1554                    DecodingKey::from_rsa_pem(&bytes)
1555                        .map_err(|e| tracing::warn!("Invalid RSA public key format: {}", e))
1556                })
1557                .unwrap_or_else(|_| {
1558                    tracing::error!(
1559                        "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH is set but the key could not \
1560                         be loaded. FAPI verification will not work correctly."
1561                    );
1562                    is_degraded = true;
1563                    use ring::rand::{SecureRandom, SystemRandom};
1564                    let rng = SystemRandom::new();
1565                    let mut secret = [0u8; 32];
1566                    rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1567                    DecodingKey::from_secret(&secret)
1568                })
1569        } else {
1570            tracing::error!(
1571                "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH not set. FAPI verification will \
1572                 not work correctly. Set FAPI_PUBLIC_KEY_PATH to a PEM-encoded RSA public key file."
1573            );
1574            is_degraded = true;
1575            use ring::rand::{SecureRandom, SystemRandom};
1576            let rng = SystemRandom::new();
1577            let mut secret = [0u8; 32];
1578            rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1579            DecodingKey::from_secret(&secret)
1580        };
1581
1582        Self {
1583            issuer,
1584            request_signing_algorithm: Algorithm::RS256,
1585            response_signing_algorithm: Algorithm::RS256,
1586            private_key,
1587            public_key,
1588            max_request_age: 300, // 5 minutes
1589            require_dpop: true,
1590            require_mtls: true,
1591            require_par: true,
1592            enable_jarm: true,
1593            enhanced_audit: true,
1594            is_degraded,
1595        }
1596    }
1597}
1598
1599/// Decode a client certificate passed as text: PEM (`-----BEGIN CERTIFICATE-----`) or bare
1600/// base64 of the DER encoding. The text must come from the TLS handshake (or a proxy that
1601/// 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
1602/// only ever receive an encoded form; hashing or parsing the text bytes themselves is wrong.
1603fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
1604    use base64::Engine;
1605    use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
1606
1607    const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
1608    const END: &str = "-----END CERTIFICATE-----";
1609    let bad = || {
1610        AuthError::auth_method(
1611            "mtls",
1612            "Client certificate must be PEM or base64-encoded DER",
1613        )
1614    };
1615
1616    let trimmed = input.trim();
1617    let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
1618        let end = rest.find(END).ok_or_else(bad)?;
1619        // Exactly one certificate: nothing but whitespace may follow the END line.
1620        if !rest[end + END.len()..].trim().is_empty() {
1621            return Err(bad());
1622        }
1623        &rest[..end]
1624    } else {
1625        trimmed
1626    };
1627    let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
1628    if compact.is_empty() {
1629        return Err(bad());
1630    }
1631    STANDARD
1632        .decode(&compact)
1633        .or_else(|_| STANDARD_NO_PAD.decode(&compact))
1634        .or_else(|_| URL_SAFE.decode(&compact))
1635        .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
1636        .map_err(|_| bad())
1637}
1638
1639/// The client identity a certificate carries: its single subject CN, otherwise its single
1640/// DNS/URI subjectAltName. Parsed from the DER, never searched for as text in the raw bytes.
1641fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
1642    use x509_parser::extensions::GeneralName;
1643
1644    let cert = match x509_parser::parse_x509_certificate(cert_der) {
1645        Ok(([], cert)) => cert,
1646        _ => {
1647            return Err(AuthError::auth_method(
1648                "mtls",
1649                "Invalid client certificate format",
1650            ));
1651        }
1652    };
1653
1654    let common_names: Vec<String> = cert
1655        .subject()
1656        .iter_common_name()
1657        .filter_map(|cn| cn.as_str().ok().map(str::to_string))
1658        .collect();
1659    if common_names.len() == 1 && !common_names[0].is_empty() {
1660        return Ok(common_names[0].clone());
1661    }
1662
1663    if let Ok(Some(san)) = cert.subject_alternative_name() {
1664        let names: Vec<String> = san
1665            .value
1666            .general_names
1667            .iter()
1668            .filter_map(|name| match name {
1669                GeneralName::DNSName(dns) => Some(dns.to_string()),
1670                GeneralName::URI(uri) => Some(uri.to_string()),
1671                _ => None,
1672            })
1673            .collect();
1674        if names.len() == 1 {
1675            return Ok(names[0].clone());
1676        }
1677    }
1678
1679    Err(AuthError::auth_method(
1680        "mtls",
1681        "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
1682    ))
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687    use super::*;
1688
1689    #[test]
1690    fn test_fapi_config_builder() {
1691        use ring::rand::{SecureRandom, SystemRandom};
1692        let rng = SystemRandom::new();
1693        let mut bytes = [0u8; 32];
1694        rng.fill(&mut bytes).unwrap();
1695        let private_key = EncodingKey::from_secret(&bytes);
1696        let public_key = DecodingKey::from_secret(&bytes);
1697
1698        let config = FapiConfig::builder("https://fapi.example.com", private_key, public_key)
1699            .request_signing_algorithm(Algorithm::ES256)
1700            .max_request_age(120)
1701            .require_dpop(false)
1702            .degraded()
1703            .build();
1704
1705        assert_eq!(config.issuer, "https://fapi.example.com");
1706        assert_eq!(config.request_signing_algorithm, Algorithm::ES256);
1707        assert_eq!(config.max_request_age, 120);
1708        assert!(!config.require_dpop);
1709        assert!(config.require_mtls); // default is true
1710        assert!(config.is_degraded);
1711    }
1712
1713    #[test]
1714    fn test_fapi_session_builder() {
1715        let session = FapiSession::builder(
1716            "sess_123",
1717            "client_456",
1718            "user_789",
1719            Duration::try_hours(1).unwrap(),
1720        )
1721        .dpop_proof("proof_abc")
1722        .add_scope("openid")
1723        .add_scopes(vec!["profile", "email"])
1724        .add_metadata("custom_flag", json!(true))
1725        .build();
1726
1727        assert_eq!(session.session_id, "sess_123");
1728        assert_eq!(session.client_id, "client_456");
1729        assert_eq!(session.user_id, "user_789");
1730        assert_eq!(session.dpop_proof.as_deref(), Some("proof_abc"));
1731        assert_eq!(session.scopes, vec!["openid", "profile", "email"]);
1732        assert_eq!(session.metadata["custom_flag"], true);
1733    }
1734
1735    #[tokio::test]
1736    async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
1737        use crate::security::secure_jwt::SecureJwtConfig;
1738        use crate::server::jwt::private_key_jwt::ClientJwtConfig;
1739        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1740
1741        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
1742        let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1743        let manager = FapiManager::new(
1744            FapiConfig::default(),
1745            Arc::new(DpopManager::new(validator())),
1746            Arc::new(MutualTlsManager::new()),
1747            Arc::new(PARManager::new(Arc::new(
1748                crate::storage::MemoryStorage::new(),
1749            ))),
1750            assertions.clone(),
1751            Arc::new(validator()),
1752        );
1753
1754        // A registered client with a real key.
1755        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1756        let raw = key.public_key_raw();
1757        let point = &raw[raw.len() - 65..];
1758        let jwk = json!({
1759            "kty": "EC", "crv": "P-256",
1760            "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1761            "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1762        });
1763        assertions
1764            .register_client(
1765                ClientJwtConfig::builder("fapi-client", jwk)
1766                    .algorithms(vec![Algorithm::ES256])
1767                    .audience("https://auth.example.com/token")
1768                    .build(),
1769            )
1770            .await
1771            .unwrap();
1772        let encoding_key = EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap();
1773
1774        // Genuine assertion: authenticated.
1775        let good = assertions
1776            .create_client_assertion(
1777                "fapi-client",
1778                "https://auth.example.com/token",
1779                &encoding_key,
1780                Algorithm::ES256,
1781            )
1782            .unwrap();
1783        assert_eq!(
1784            manager.authenticate_client_jwt(&good).await.unwrap(),
1785            "fapi-client"
1786        );
1787
1788        // Each way to fail gives the same bare message: unknown client, wrong audience from the
1789        // real client (a reason that is only known after the signature verified), replay, junk.
1790        let wrong_audience = assertions
1791            .create_client_assertion(
1792                "fapi-client",
1793                "https://elsewhere.example/token",
1794                &encoding_key,
1795                Algorithm::ES256,
1796            )
1797            .unwrap();
1798        let unknown = assertions
1799            .create_client_assertion(
1800                "ghost",
1801                "https://auth.example.com/token",
1802                &encoding_key,
1803                Algorithm::ES256,
1804            )
1805            .unwrap();
1806        for (why, assertion) in [
1807            ("wrong audience", wrong_audience.as_str()),
1808            ("unknown client", unknown.as_str()),
1809            ("replay", good.as_str()),
1810            ("junk", "not-a-jwt"),
1811        ] {
1812            let message = manager
1813                .authenticate_client_jwt(assertion)
1814                .await
1815                .expect_err(why)
1816                .to_string();
1817            assert!(
1818                message.contains("Client authentication failed"),
1819                "{why}: {message}"
1820            );
1821            for leak in [
1822                "udience",
1823                "registered",
1824                "ignature",
1825                "replay",
1826                "JTI",
1827                "Algorithm",
1828                "expired",
1829            ] {
1830                assert!(
1831                    !message.contains(leak),
1832                    "{why}: {message:?} mentions {leak:?}"
1833                );
1834            }
1835        }
1836    }
1837
1838    #[tokio::test]
1839    async fn test_fapi_manager_creation() {
1840        // Comprehensive FAPI configuration validation
1841        let config = FapiConfig::default();
1842
1843        // Verify FAPI security requirements are enabled by default
1844        assert_eq!(config.issuer, "https://auth.example.com"); // Corrected expected value
1845        assert!(config.require_dpop);
1846        assert!(config.require_mtls);
1847        assert!(config.require_par);
1848        assert!(config.enable_jarm);
1849        assert!(config.enhanced_audit);
1850    }
1851
1852    #[tokio::test]
1853    async fn test_fapi_request_validation() {
1854        // Test request object validation according to FAPI requirements
1855        // This should validate JWT request objects, signatures, and claims
1856        let config = FapiConfig::default();
1857
1858        // Mock request object with required FAPI claims
1859        let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1860
1861        // SECURITY CRITICAL: Perform comprehensive JWT validation
1862        let validation_result = validate_fapi_request_object(request_object, &config);
1863        assert!(
1864            validation_result.is_ok(),
1865            "FAPI request object validation failed"
1866        );
1867
1868        // Ensure basic structure is valid but NEVER skip signature verification in production
1869        assert!(!request_object.is_empty());
1870    }
1871
1872    /// Validate FAPI request object with proper JWT verification
1873    fn validate_fapi_request_object(
1874        request_object: &str,
1875        _config: &FapiConfig,
1876    ) -> Result<(), String> {
1877        // Parse JSON structure
1878        let parsed: serde_json::Value = serde_json::from_str(request_object)
1879            .map_err(|_| "Invalid JSON structure in request object")?;
1880
1881        // Validate required FAPI claims
1882        let required_claims = ["iss", "aud", "exp", "iat", "jti"];
1883        for claim in &required_claims {
1884            if parsed.get(claim).is_none() {
1885                return Err(format!("Missing required FAPI claim: {}", claim));
1886            }
1887        }
1888
1889        // Validate expiration
1890        if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
1891            let now = chrono::Utc::now().timestamp();
1892            if exp <= now {
1893                return Err("Request object has expired".to_string());
1894            }
1895        }
1896
1897        // In production: Verify JWT signature against client's public key
1898        // For testing: Accept if structure is valid
1899        Ok(())
1900    }
1901
1902    #[tokio::test]
1903    async fn test_fapi_response_generation() {
1904        // Test JARM (JWT Secured Authorization Response Mode) generation
1905        // This should create signed JWT responses for authorization responses
1906        let config = FapiConfig::default();
1907
1908        // Mock authorization response
1909        let auth_response = serde_json::json!({
1910            "code": "auth_code_123",
1911            "state": "client_state",
1912            "iss": config.issuer,
1913            "aud": "client_id",
1914            "exp": 9999999999i64
1915        });
1916
1917        // In real implementation, sign the response as a JWT
1918        assert!(auth_response["code"].is_string());
1919    }
1920
1921    #[tokio::test]
1922    async fn test_fapi_token_generation() {
1923        // Test FAPI-compliant token generation with DPoP and mTLS
1924        let config = FapiConfig::default();
1925
1926        // Mock FAPI token request with required security features
1927        let scopes = ["accounts".to_string(), "payments".to_string()];
1928        let client_id = "fapi_client_123";
1929        let user_id = "user_456";
1930        let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
1931
1932        // Verify FAPI-specific requirements would be enforced
1933        assert!(config.require_dpop);
1934        assert!(config.require_mtls);
1935        assert!(!scopes.is_empty());
1936        assert!(!client_id.is_empty());
1937        assert!(!user_id.is_empty());
1938        assert!(cert_thumbprint.is_some());
1939    }
1940
1941    #[tokio::test]
1942    async fn test_fapi_session_management() {
1943        // Test FAPI session management and security requirements
1944        let config = FapiConfig::default();
1945
1946        // Mock FAPI session with enhanced security
1947        let session_data = serde_json::json!({
1948            "client_id": "fapi_client",
1949            "user_id": "fapi_user",
1950            "scopes": ["accounts", "payments"],
1951            "mtls_cert": "client_certificate",
1952            "dpop_key": "client_dpop_key"
1953        });
1954
1955        // Verify session includes FAPI security elements
1956        assert!(session_data["mtls_cert"].is_string());
1957        assert!(session_data["dpop_key"].is_string());
1958        assert!(config.enhanced_audit);
1959    }
1960
1961    // ---- certificate input decoding and client-id derivation ----
1962
1963    fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
1964        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1965        let mut dn = rcgen::DistinguishedName::new();
1966        dn.push(rcgen::DnType::CommonName, cn);
1967        if let Some(org) = org {
1968            dn.push(rcgen::DnType::OrganizationName, org);
1969        }
1970        params.distinguished_name = dn;
1971        let key = rcgen::KeyPair::generate().unwrap();
1972        params.self_signed(&key).unwrap()
1973    }
1974
1975    #[test]
1976    fn decode_client_certificate_accepts_pem_and_base64_der() {
1977        use base64::Engine;
1978        let cert = test_cert("client-a", None);
1979        let der = cert.der().to_vec();
1980
1981        assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
1982        let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
1983        assert_eq!(decode_client_certificate(&b64).unwrap(), der);
1984        let wrapped = format!("  {}\n{}  \n", &b64[..20], &b64[20..]);
1985        assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
1986    }
1987
1988    #[test]
1989    fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
1990        let a = test_cert("client-a", None).pem();
1991        let b = test_cert("client-b", None).pem();
1992        assert!(decode_client_certificate("").is_err());
1993        assert!(decode_client_certificate("!!! not base64 !!!").is_err());
1994        assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
1995        // Two certificates in one value: refuse rather than silently using the first.
1996        assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
1997    }
1998
1999    #[test]
2000    fn client_id_comes_from_the_parsed_subject_cn() {
2001        let cert = test_cert("client-a", None);
2002        assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
2003    }
2004
2005    #[test]
2006    fn client_id_is_not_found_by_searching_the_raw_bytes() {
2007        // Text that merely looks like "CN=..." inside another attribute (here Organization) is
2008        // not an identity: the id comes from the parsed subject.
2009        let cert = test_cert("real-client", Some("CN=victim-client,"));
2010        assert_eq!(
2011            client_id_from_certificate(cert.der()).unwrap(),
2012            "real-client"
2013        );
2014    }
2015
2016    #[test]
2017    fn client_id_needs_a_unique_identity() {
2018        // No CN and no SAN: there is nothing to derive, so no id is invented.
2019        let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2020        params.distinguished_name = rcgen::DistinguishedName::new(); // rcgen defaults to a CN
2021        let key = rcgen::KeyPair::generate().unwrap();
2022        let nameless = params.self_signed(&key).unwrap();
2023        assert!(client_id_from_certificate(nameless.der()).is_err());
2024        assert!(client_id_from_certificate(b"not a certificate").is_err());
2025    }
2026}
2027
2028#[cfg(test)]
2029mod request_object_age {
2030    use super::*;
2031    use crate::security::secure_jwt::SecureJwtConfig;
2032
2033    const ISS: &str = "https://fapi.example.com";
2034    const CLIENT: &str = "client-1";
2035
2036    fn request_object(enc: &EncodingKey, iat: i64) -> String {
2037        let now = Utc::now().timestamp();
2038        let claims = json!({
2039            "iss": CLIENT, "sub": CLIENT, "aud": ISS, "exp": now + 300, "nbf": now - 1,
2040            "iat": iat, "jti": Uuid::new_v4().to_string(), "scope": "read", "typ": "access",
2041            "response_type": "code", "client_id": CLIENT,
2042            "redirect_uri": "https://client.example/cb",
2043            "code_challenge": "abc", "code_challenge_method": "S256",
2044        });
2045        jsonwebtoken::encode(&Header::new(Algorithm::ES256), &claims, enc).unwrap()
2046    }
2047
2048    #[tokio::test]
2049    async fn the_age_of_a_request_object_cannot_wrap() {
2050        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2051        let pem = key.serialize_pem();
2052        let enc = EncodingKey::from_ec_pem(pem.as_bytes()).unwrap();
2053        let config = FapiConfig {
2054            issuer: ISS.to_string(),
2055            private_key: EncodingKey::from_ec_pem(pem.as_bytes()).unwrap(),
2056            public_key: DecodingKey::from_ec_der(key.public_key_raw()),
2057            ..FapiConfig::default()
2058        };
2059        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2060        let secure = SecureJwtValidator::new(SecureJwtConfig {
2061            allowed_algorithms: vec![Algorithm::ES256],
2062            required_issuers: [CLIENT.to_string()].into_iter().collect(),
2063            ec_public_key_pem: Some(key.public_key_pem()),
2064            require_secure_transport: false,
2065            ..SecureJwtConfig::default()
2066        })
2067        .unwrap();
2068        let m = FapiManager::new(
2069            config,
2070            Arc::new(DpopManager::new(validator())),
2071            Arc::new(MutualTlsManager::new()),
2072            Arc::new(PARManager::new(Arc::new(
2073                crate::storage::MemoryStorage::new(),
2074            ))),
2075            Arc::new(PrivateKeyJwtManager::new(validator())),
2076            Arc::new(secure),
2077        );
2078        let now = Utc::now().timestamp();
2079        m.validate_request_object(&request_object(&enc, now))
2080            .await
2081            .expect("a fresh request object is accepted");
2082        // Old enough to be refused for its age, young enough for the token checks before it.
2083        match m
2084            .validate_request_object(&request_object(&enc, now - 3000))
2085            .await
2086        {
2087            Ok(_) => panic!("a request object 50 minutes old: ACCEPTED"),
2088            Err(e) => assert!(e.to_string().contains("too old"), "refused with {e:?}"),
2089        }
2090        // An iat that cannot be a request object's, whatever stops it first.
2091        assert!(
2092            m.validate_request_object(&request_object(&enc, i64::MIN))
2093                .await
2094                .is_err()
2095        );
2096    }
2097
2098    #[test]
2099    fn an_age_that_cannot_be_represented_is_too_old() {
2100        let now = Utc::now().timestamp();
2101        assert!(!request_object_too_old(now, now, 60));
2102        assert!(!request_object_too_old(now, now - 60, 60));
2103        assert!(request_object_too_old(now, now - 61, 60));
2104        // now - iat overflows: it must read as too old, not wrap (or panic).
2105        assert!(request_object_too_old(now, i64::MIN, 60));
2106        assert!(request_object_too_old(now, i64::MIN + 1, 60));
2107        assert!(request_object_too_old(i64::MAX, -1, 60));
2108    }
2109}
2110
2111#[cfg(test)]
2112mod dpop_regression {
2113    //! DPoP proofs at the FAPI resource check: every way a proof can be wrong is refused, with its
2114    //! own reason, and a correct proof is accepted. Each refusal is paired with the accepted case
2115    //! built the same way, so a test cannot pass because every proof fails for one shared reason.
2116    use super::*;
2117    use crate::security::secure_jwt::SecureJwtConfig;
2118    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as B64};
2119    use sha2::{Digest, Sha256};
2120
2121    const ISS: &str = "https://fapi.example.com";
2122    const URI: &str = "https://rs.example.com/resource";
2123
2124    fn ec_key() -> (EncodingKey, serde_json::Value) {
2125        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2126        let raw = key.public_key_raw();
2127        let point = &raw[raw.len() - 65..];
2128        let jwk = json!({
2129            "kty": "EC", "crv": "P-256",
2130            "x": B64.encode(&point[1..33]),
2131            "y": B64.encode(&point[33..65]),
2132        });
2133        (
2134            EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2135            jwk,
2136        )
2137    }
2138
2139    fn ath_of(token: &str) -> String {
2140        B64.encode(Sha256::digest(token.as_bytes()))
2141    }
2142
2143    /// How to build a proof: everything a correct one has, each field overridable.
2144    struct Proof<'a> {
2145        key: &'a (EncodingKey, serde_json::Value),
2146        htm: &'a str,
2147        htu: &'a str,
2148        iat: i64,
2149        jti: &'a str,
2150        ath: Option<String>,
2151        der: bool,
2152        jwk_extra: Option<(&'a str, &'a str)>,
2153    }
2154
2155    impl Proof<'_> {
2156        fn build(&self) -> String {
2157            let mut jwk = self.key.1.clone();
2158            if let Some((k, v)) = self.jwk_extra {
2159                jwk[k] = json!(v);
2160            }
2161            let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
2162            let mut claims =
2163                json!({"jti": self.jti, "htm": self.htm, "htu": self.htu, "iat": self.iat});
2164            if let Some(a) = &self.ath {
2165                claims["ath"] = json!(a);
2166            }
2167            let si = format!(
2168                "{}.{}",
2169                B64.encode(header.to_string()),
2170                B64.encode(claims.to_string())
2171            );
2172            // jsonwebtoken signs in the JWS form: r || s.
2173            let sig =
2174                jsonwebtoken::crypto::sign(si.as_bytes(), &self.key.0, Algorithm::ES256).unwrap();
2175            if !self.der {
2176                return format!("{si}.{sig}");
2177            }
2178            let raw = B64.decode(sig).unwrap();
2179            let int = |v: &[u8]| {
2180                let mut v: Vec<u8> = v.iter().copied().skip_while(|&x| x == 0).collect();
2181                if v.is_empty() || v[0] & 0x80 != 0 {
2182                    v.insert(0, 0);
2183                }
2184                let mut o = vec![0x02, v.len() as u8];
2185                o.extend(v);
2186                o
2187            };
2188            let mut body = int(&raw[..32]);
2189            body.extend(int(&raw[32..]));
2190            let mut der = vec![0x30, body.len() as u8];
2191            der.extend(body);
2192            format!("{si}.{}", B64.encode(der))
2193        }
2194    }
2195
2196    fn manager() -> (FapiManager, Arc<DpopManager>, Vec<u8>) {
2197        let secret = b"0123456789abcdef0123456789abcdef".to_vec();
2198        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2199        let dpop = Arc::new(DpopManager::new(validator()));
2200        let config = FapiConfig::builder(
2201            ISS,
2202            EncodingKey::from_secret(&secret),
2203            DecodingKey::from_secret(&secret),
2204        )
2205        .build();
2206        let m = FapiManager::new(
2207            config,
2208            dpop.clone(),
2209            Arc::new(MutualTlsManager::new()),
2210            Arc::new(PARManager::new(Arc::new(
2211                crate::storage::MemoryStorage::new(),
2212            ))),
2213            Arc::new(PrivateKeyJwtManager::new(validator())),
2214            Arc::new(
2215                SecureJwtValidator::new(SecureJwtConfig {
2216                    required_issuers: [ISS.to_string()].into_iter().collect(),
2217                    require_secure_transport: false,
2218                    ..SecureJwtConfig::default()
2219                })
2220                .unwrap(),
2221            ),
2222        );
2223        (m, dpop, secret)
2224    }
2225
2226    fn sign_hs256(secret: &[u8], claims: &serde_json::Value) -> String {
2227        jsonwebtoken::encode(
2228            &Header::new(Algorithm::HS256),
2229            claims,
2230            &EncodingKey::from_secret(secret),
2231        )
2232        .unwrap()
2233    }
2234
2235    /// A bound access token written out by hand, so the proof cases do not depend on how the
2236    /// manager mints tokens (that has its own test below).
2237    fn token_for(secret: &[u8], jkt: &str) -> String {
2238        let now = Utc::now().timestamp();
2239        sign_hs256(
2240            secret,
2241            &json!({
2242                "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2243                "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2244                "typ": "access", "cnf": {"jkt": jkt},
2245            }),
2246        )
2247    }
2248
2249    async fn check(m: &FapiManager, tok: &str, proof: Option<&str>, method: &str) -> Result<()> {
2250        m.validate_sender_constrained_token(tok, proof, None, method, URI)
2251            .await
2252            .map(|_| ())
2253    }
2254
2255    fn refused(r: Result<()>, reason: &str, what: &str) {
2256        match r {
2257            Ok(()) => panic!("{what}: ACCEPTED"),
2258            Err(e) => assert!(
2259                e.to_string().contains(reason),
2260                "{what}: refused with {e:?}, expected a reason containing {reason:?}"
2261            ),
2262        }
2263    }
2264
2265    /// One bound token, the key it is bound to, and another key.
2266    struct Fixture {
2267        m: FapiManager,
2268        tok: String,
2269        key_a: (EncodingKey, serde_json::Value),
2270        key_b: (EncodingKey, serde_json::Value),
2271        now: i64,
2272    }
2273
2274    impl Fixture {
2275        fn new() -> Self {
2276            let (m, dpop, secret) = manager();
2277            let key_a = ec_key();
2278            let key_b = ec_key();
2279            let jkt = dpop.create_dpop_confirmation(&key_a.1).unwrap().jkt;
2280            let tok = token_for(&secret, &jkt);
2281            Fixture {
2282                m,
2283                tok,
2284                key_a,
2285                key_b,
2286                now: Utc::now().timestamp(),
2287            }
2288        }
2289
2290        /// The correct proof for the bound key; tests override one field.
2291        fn good<'a>(&'a self, jti: &'a str) -> Proof<'a> {
2292            Proof {
2293                key: &self.key_a,
2294                htm: "GET",
2295                htu: URI,
2296                iat: self.now,
2297                jti,
2298                ath: Some(ath_of(&self.tok)),
2299                der: false,
2300                jwk_extra: None,
2301            }
2302        }
2303
2304        async fn present(&self, proof: &str) -> Result<()> {
2305            check(&self.m, &self.tok, Some(proof), "GET").await
2306        }
2307    }
2308
2309    #[tokio::test]
2310    async fn a_correct_proof_from_the_bound_key_is_accepted() {
2311        let f = Fixture::new();
2312        f.present(&f.good("j-ok").build())
2313            .await
2314            .expect("a correct proof from the bound key is accepted");
2315    }
2316
2317    #[tokio::test]
2318    async fn a_proof_from_another_key_is_refused_though_otherwise_correct() {
2319        let f = Fixture::new();
2320        let p = Proof {
2321            key: &f.key_b,
2322            ..f.good("j-other")
2323        }
2324        .build();
2325        refused(f.present(&p).await, "key binding", "other key");
2326    }
2327
2328    #[tokio::test]
2329    async fn a_proof_for_another_method_url_or_time_is_refused() {
2330        let f = Fixture::new();
2331        let p = Proof {
2332            htm: "DELETE",
2333            ..f.good("j-htm")
2334        }
2335        .build();
2336        refused(f.present(&p).await, "HTTP method", "wrong htm");
2337        let p = Proof {
2338            htu: "https://evil.example/x",
2339            ..f.good("j-htu")
2340        }
2341        .build();
2342        refused(f.present(&p).await, "HTTP URI", "wrong htu");
2343        let p = Proof {
2344            iat: f.now - 86_400,
2345            ..f.good("j-old")
2346        }
2347        .build();
2348        refused(f.present(&p).await, "too old", "one-day-old iat");
2349        let p = Proof {
2350            iat: f.now + 86_400,
2351            ..f.good("j-future")
2352        }
2353        .build();
2354        refused(f.present(&p).await, "in the future", "future iat");
2355    }
2356
2357    #[tokio::test]
2358    async fn a_proof_used_twice_is_refused_the_second_time() {
2359        let f = Fixture::new();
2360        let once = f.good("j-replay").build();
2361        f.present(&once).await.expect("first use");
2362        refused(f.present(&once).await, "already used", "replayed proof");
2363    }
2364
2365    #[tokio::test]
2366    async fn no_proof_is_refused_for_a_bound_token() {
2367        let f = Fixture::new();
2368        refused(
2369            check(&f.m, &f.tok, None, "GET").await,
2370            "no DPoP proof header",
2371            "no proof",
2372        );
2373    }
2374
2375    #[tokio::test]
2376    async fn a_proof_must_name_this_access_token() {
2377        let f = Fixture::new();
2378        let p = Proof {
2379            ath: None,
2380            ..f.good("j-no-ath")
2381        }
2382        .build();
2383        refused(f.present(&p).await, "'ath'", "no ath");
2384        let p = Proof {
2385            ath: Some(ath_of("another-token")),
2386            ..f.good("j-bad-ath")
2387        }
2388        .build();
2389        refused(f.present(&p).await, "access token hash", "wrong ath");
2390    }
2391
2392    #[tokio::test]
2393    async fn a_der_signature_or_a_private_key_in_the_header_is_refused() {
2394        let f = Fixture::new();
2395        let p = Proof {
2396            der: true,
2397            ..f.good("j-der")
2398        }
2399        .build();
2400        refused(f.present(&p).await, "r||s", "DER-encoded ES256 signature");
2401        let p = Proof {
2402            jwk_extra: Some(("d", "AAAA")),
2403            ..f.good("j-priv")
2404        }
2405        .build();
2406        refused(f.present(&p).await, "private key", "private key in jwk");
2407    }
2408
2409    #[tokio::test]
2410    async fn a_token_minted_by_the_manager_passes_its_own_resource_check() {
2411        let (m, dpop, secret) = manager();
2412        let key = ec_key();
2413        let jkt = dpop.create_dpop_confirmation(&key.1).unwrap().jkt;
2414        // generate_access_token signs with the configured RSA key; here the claims it signs are
2415        // signed with the test's HMAC secret, which is what the resource check reads them with.
2416        let claims =
2417            m.access_token_claims("client-1", "user-1", &["read".into()], &None, &Some(jkt));
2418        for field in ["typ", "nbf", "client_id"] {
2419            assert!(claims.get(field).is_some(), "minted claims lack {field}");
2420        }
2421        assert_eq!(claims["aud"], json!(ISS));
2422        let tok = sign_hs256(&secret, &claims);
2423        let proof = Proof {
2424            key: &key,
2425            htm: "GET",
2426            htu: URI,
2427            iat: Utc::now().timestamp(),
2428            jti: "j-minted",
2429            ath: Some(ath_of(&tok)),
2430            der: false,
2431            jwk_extra: None,
2432        }
2433        .build();
2434        check(&m, &tok, Some(&proof), "GET")
2435            .await
2436            .expect("a token built from the manager's own claims is accepted");
2437    }
2438
2439    #[tokio::test]
2440    async fn a_cnf_that_names_no_checkable_binding_is_refused() {
2441        let (m, _dpop, secret) = manager();
2442        let now = Utc::now().timestamp();
2443        for (cnf, what) in [
2444            (json!({}), "empty cnf"),
2445            (json!({"foo": "bar"}), "unknown member only"),
2446            (json!({"jkt": 5}), "jkt that is not a string"),
2447        ] {
2448            let tok = sign_hs256(
2449                &secret,
2450                &json!({
2451                    "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2452                    "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2453                    "typ": "access", "cnf": cnf,
2454                }),
2455            );
2456            refused(check(&m, &tok, None, "GET").await, "cnf", what);
2457        }
2458    }
2459
2460    #[tokio::test]
2461    async fn a_proof_from_the_wrong_key_leaves_no_replay_record() {
2462        let f = Fixture::new();
2463        let p = Proof {
2464            key: &f.key_b,
2465            ..f.good("j-wrong-key")
2466        }
2467        .build();
2468        refused(f.present(&p).await, "key binding", "other key");
2469        assert_eq!(
2470            f.m.dpop_manager.replay_record_count().await,
2471            0,
2472            "a proof refused for its key must not take a cache slot"
2473        );
2474        f.present(&f.good("j-right-key").build())
2475            .await
2476            .expect("the bound key");
2477        assert_eq!(f.m.dpop_manager.replay_record_count().await, 1);
2478    }
2479
2480    #[tokio::test]
2481    async fn an_rs256_token_minted_by_the_manager_passes_the_resource_check() {
2482        // Production signs access tokens with RS256 and an RSA key.
2483        let key =
2484            rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
2485                .unwrap();
2486        let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2487        let dpop = Arc::new(DpopManager::new(validator()));
2488        let config = FapiConfig::builder(
2489            ISS,
2490            EncodingKey::from_rsa_pem(key.serialize_pem().as_bytes()).unwrap(),
2491            DecodingKey::from_rsa_der(key.public_key_raw()),
2492        )
2493        .build();
2494        let m = FapiManager::new(
2495            config,
2496            dpop.clone(),
2497            Arc::new(MutualTlsManager::new()),
2498            Arc::new(PARManager::new(Arc::new(
2499                crate::storage::MemoryStorage::new(),
2500            ))),
2501            Arc::new(PrivateKeyJwtManager::new(validator())),
2502            Arc::new(
2503                SecureJwtValidator::new(SecureJwtConfig {
2504                    allowed_algorithms: vec![Algorithm::RS256],
2505                    required_issuers: [ISS.to_string()].into_iter().collect(),
2506                    rsa_public_key_pem: Some(key.public_key_pem()),
2507                    require_secure_transport: false,
2508                    ..SecureJwtConfig::default()
2509                })
2510                .unwrap(),
2511            ),
2512        );
2513        let client = ec_key();
2514        let jkt = dpop.create_dpop_confirmation(&client.1).unwrap().jkt;
2515        let tok = m
2516            .generate_access_token("client-1", "user-1", &["read".into()], &None, &Some(jkt))
2517            .await
2518            .unwrap();
2519        let proof = Proof {
2520            key: &client,
2521            htm: "GET",
2522            htu: URI,
2523            iat: Utc::now().timestamp(),
2524            jti: "j-rs256",
2525            ath: Some(ath_of(&tok)),
2526            der: false,
2527            jwk_extra: None,
2528        }
2529        .build();
2530        check(&m, &tok, Some(&proof), "GET")
2531            .await
2532            .expect("an RS256 token minted by the manager is accepted");
2533    }
2534
2535    #[tokio::test]
2536    async fn a_wrong_certificate_does_not_use_up_the_proof() {
2537        let (m, dpop, secret) = manager();
2538        let key_a = ec_key();
2539        let jkt = dpop.create_dpop_confirmation(&key_a.1).unwrap().jkt;
2540        let cert = rcgen::CertificateParams::default()
2541            .self_signed(&rcgen::KeyPair::generate().unwrap())
2542            .unwrap();
2543        let other = rcgen::CertificateParams::default()
2544            .self_signed(&rcgen::KeyPair::generate().unwrap())
2545            .unwrap();
2546        let x5t = B64.encode(Sha256::digest(cert.der().as_ref()));
2547        let now = Utc::now().timestamp();
2548        // A token bound to both a key and a certificate.
2549        let tok = sign_hs256(
2550            &secret,
2551            &json!({
2552                "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2553                "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2554                "typ": "access", "cnf": {"jkt": jkt, "x5t#S256": x5t},
2555            }),
2556        );
2557        let proof = Proof {
2558            key: &key_a,
2559            htm: "GET",
2560            htu: URI,
2561            iat: now,
2562            jti: "j-both",
2563            ath: Some(ath_of(&tok)),
2564            der: false,
2565            jwk_extra: None,
2566        }
2567        .build();
2568        let wrong = m
2569            .validate_sender_constrained_token(&tok, Some(&proof), Some(&other.pem()), "GET", URI)
2570            .await
2571            .map(|_| ());
2572        refused(wrong, "Certificate thumbprint", "wrong certificate");
2573        assert_eq!(
2574            m.dpop_manager.replay_record_count().await,
2575            0,
2576            "a proof was recorded although the certificate was refused"
2577        );
2578        m.validate_sender_constrained_token(&tok, Some(&proof), Some(&cert.pem()), "GET", URI)
2579            .await
2580            .expect("both bindings satisfied");
2581        assert_eq!(m.dpop_manager.replay_record_count().await, 1);
2582    }
2583}