1use 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#[derive(Debug, Clone)]
41pub struct FapiManager {
42 dpop_manager: Arc<DpopManager>,
44
45 mtls_manager: Arc<MutualTlsManager>,
47
48 par_manager: Arc<PARManager>,
50
51 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
53
54 jwt_validator: Arc<SecureJwtValidator>,
56
57 config: FapiConfig,
59
60 sessions: Arc<RwLock<HashMap<String, FapiSession>>>,
62}
63
64#[derive(Clone)]
66pub struct FapiConfig {
67 pub issuer: String,
69
70 pub request_signing_algorithm: Algorithm,
72
73 pub response_signing_algorithm: Algorithm,
75
76 pub private_key: EncodingKey,
78
79 pub public_key: DecodingKey,
81
82 pub max_request_age: i64,
84
85 pub require_dpop: bool,
87
88 pub require_mtls: bool,
90
91 pub require_par: bool,
93
94 pub enable_jarm: bool,
96
97 pub enhanced_audit: bool,
99
100 pub is_degraded: bool,
104}
105
106impl std::fmt::Debug for FapiConfig {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.debug_struct("FapiConfig")
109 .field("issuer", &self.issuer)
110 .field("request_signing_algorithm", &self.request_signing_algorithm)
111 .field(
112 "response_signing_algorithm",
113 &self.response_signing_algorithm,
114 )
115 .field("private_key", &"<EncodingKey>")
116 .field("public_key", &"<DecodingKey>")
117 .field("max_request_age", &self.max_request_age)
118 .field("require_dpop", &self.require_dpop)
119 .field("require_mtls", &self.require_mtls)
120 .field("require_par", &self.require_par)
121 .field("enable_jarm", &self.enable_jarm)
122 .field("enhanced_audit", &self.enhanced_audit)
123 .field("is_degraded", &self.is_degraded)
124 .finish()
125 }
126}
127
128impl FapiConfig {
129 pub fn builder(
133 issuer: impl Into<String>,
134 private_key: EncodingKey,
135 public_key: DecodingKey,
136 ) -> FapiConfigBuilder {
137 FapiConfigBuilder {
138 issuer: issuer.into(),
139 request_signing_algorithm: Algorithm::PS256,
140 response_signing_algorithm: Algorithm::PS256,
141 private_key,
142 public_key,
143 max_request_age: 60,
144 require_dpop: true,
145 require_mtls: true,
146 require_par: true,
147 enable_jarm: true,
148 enhanced_audit: true,
149 is_degraded: false,
150 }
151 }
152
153 #[deprecated(since = "0.5.0", note = "use FapiConfig::from_env() instead")]
155 pub fn load_from_env() -> Self {
156 Self::from_env()
157 }
158
159 pub fn from_env() -> Self {
163 Self::default()
164 }
165}
166
167pub struct FapiConfigBuilder {
169 issuer: String,
170 request_signing_algorithm: Algorithm,
171 response_signing_algorithm: Algorithm,
172 private_key: EncodingKey,
173 public_key: DecodingKey,
174 max_request_age: i64,
175 require_dpop: bool,
176 require_mtls: bool,
177 require_par: bool,
178 enable_jarm: bool,
179 enhanced_audit: bool,
180 is_degraded: bool,
181}
182
183impl FapiConfigBuilder {
184 pub fn request_signing_algorithm(mut self, alg: Algorithm) -> Self {
188 self.request_signing_algorithm = alg;
189 self
190 }
191
192 pub fn response_signing_algorithm(mut self, alg: Algorithm) -> Self {
194 self.response_signing_algorithm = alg;
195 self
196 }
197
198 pub fn max_request_age(mut self, age: i64) -> Self {
200 self.max_request_age = age;
201 self
202 }
203
204 pub fn require_dpop(mut self, require: bool) -> Self {
206 self.require_dpop = require;
207 self
208 }
209
210 pub fn require_mtls(mut self, require: bool) -> Self {
212 self.require_mtls = require;
213 self
214 }
215
216 pub fn require_par(mut self, require: bool) -> Self {
218 self.require_par = require;
219 self
220 }
221
222 pub fn enable_jarm(mut self, enable: bool) -> Self {
224 self.enable_jarm = enable;
225 self
226 }
227
228 pub fn enhanced_audit(mut self, enable: bool) -> Self {
230 self.enhanced_audit = enable;
231 self
232 }
233
234 pub fn degraded(mut self) -> Self {
236 self.is_degraded = true;
237 self
238 }
239
240 pub fn build(self) -> FapiConfig {
242 FapiConfig {
243 issuer: self.issuer,
244 request_signing_algorithm: self.request_signing_algorithm,
245 response_signing_algorithm: self.response_signing_algorithm,
246 private_key: self.private_key,
247 public_key: self.public_key,
248 max_request_age: self.max_request_age,
249 require_dpop: self.require_dpop,
250 require_mtls: self.require_mtls,
251 require_par: self.require_par,
252 enable_jarm: self.enable_jarm,
253 enhanced_audit: self.enhanced_audit,
254 is_degraded: self.is_degraded,
255 }
256 }
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct FapiSession {
262 pub session_id: String,
264
265 pub client_id: String,
267
268 pub user_id: String,
270
271 pub created_at: DateTime<Utc>,
273
274 pub expires_at: DateTime<Utc>,
276
277 pub dpop_proof: Option<String>,
279
280 pub cert_thumbprint: Option<String>,
282
283 pub request_jti: Option<String>,
285
286 pub scopes: Vec<String>,
288
289 pub metadata: HashMap<String, Value>,
291}
292
293impl FapiSession {
294 pub fn builder(
296 session_id: impl Into<String>,
297 client_id: impl Into<String>,
298 user_id: impl Into<String>,
299 expires_in: Duration,
300 ) -> FapiSessionBuilder {
301 let now = Utc::now();
302 FapiSessionBuilder {
303 session_id: session_id.into(),
304 client_id: client_id.into(),
305 user_id: user_id.into(),
306 created_at: now,
307 expires_at: now + expires_in,
308 dpop_proof: None,
309 cert_thumbprint: None,
310 request_jti: None,
311 scopes: Vec::new(),
312 metadata: HashMap::new(),
313 }
314 }
315}
316
317pub struct FapiSessionBuilder {
319 session_id: String,
320 client_id: String,
321 user_id: String,
322 created_at: DateTime<Utc>,
323 expires_at: DateTime<Utc>,
324 dpop_proof: Option<String>,
325 cert_thumbprint: Option<String>,
326 request_jti: Option<String>,
327 scopes: Vec<String>,
328 metadata: HashMap<String, Value>,
329}
330
331impl FapiSessionBuilder {
332 pub fn dpop_proof(mut self, proof: impl Into<String>) -> Self {
334 self.dpop_proof = Some(proof.into());
335 self
336 }
337
338 pub fn cert_thumbprint(mut self, thumbprint: impl Into<String>) -> Self {
340 self.cert_thumbprint = Some(thumbprint.into());
341 self
342 }
343
344 pub fn request_jti(mut self, jti: impl Into<String>) -> Self {
346 self.request_jti = Some(jti.into());
347 self
348 }
349
350 pub fn add_scope(mut self, scope: impl Into<String>) -> Self {
352 self.scopes.push(scope.into());
353 self
354 }
355
356 pub fn add_scopes<I, S>(mut self, scopes: I) -> Self
358 where
359 I: IntoIterator<Item = S>,
360 S: Into<String>,
361 {
362 self.scopes.extend(scopes.into_iter().map(Into::into));
363 self
364 }
365
366 pub fn add_metadata(mut self, key: impl Into<String>, value: Value) -> Self {
368 self.metadata.insert(key.into(), value);
369 self
370 }
371
372 pub fn build(self) -> FapiSession {
374 FapiSession {
375 session_id: self.session_id,
376 client_id: self.client_id,
377 user_id: self.user_id,
378 created_at: self.created_at,
379 expires_at: self.expires_at,
380 dpop_proof: self.dpop_proof,
381 cert_thumbprint: self.cert_thumbprint,
382 request_jti: self.request_jti,
383 scopes: self.scopes,
384 metadata: self.metadata,
385 }
386 }
387}
388
389#[derive(Debug, Clone, Serialize, Deserialize)]
391pub struct FapiRequestObject {
392 pub iss: String,
394
395 pub aud: String,
397
398 pub iat: i64,
400
401 pub exp: i64,
403
404 pub nbf: Option<i64>,
406
407 pub jti: String,
409
410 pub response_type: String,
412
413 pub client_id: String,
415
416 pub redirect_uri: String,
418
419 pub scope: String,
421
422 pub state: Option<String>,
424
425 pub nonce: Option<String>,
427
428 pub code_challenge: Option<String>,
430
431 pub code_challenge_method: Option<String>,
433
434 #[serde(flatten)]
436 pub additional_claims: HashMap<String, Value>,
437}
438
439#[derive(Debug, Clone, Serialize, Deserialize)]
441pub struct FapiAuthorizationResponse {
442 pub iss: String,
444
445 pub aud: String,
447
448 pub iat: i64,
450
451 pub exp: i64,
453
454 pub code: Option<String>,
456
457 pub state: Option<String>,
459
460 pub error: Option<String>,
462
463 pub error_description: Option<String>,
465
466 #[serde(flatten)]
468 pub additional_params: HashMap<String, Value>,
469}
470
471#[derive(Debug, Clone, Serialize, Deserialize)]
473pub struct FapiTokenResponse {
474 pub access_token: String,
476
477 pub token_type: String,
479
480 pub expires_in: i64,
482
483 pub refresh_token: Option<String>,
485
486 pub scope: Option<String>,
488
489 pub id_token: Option<String>,
491
492 pub cnf: Option<Value>,
494}
495
496impl FapiManager {
497 pub fn new(
499 config: FapiConfig,
500 dpop_manager: Arc<DpopManager>,
501 mtls_manager: Arc<MutualTlsManager>,
502 par_manager: Arc<PARManager>,
503 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
504 jwt_validator: Arc<SecureJwtValidator>,
505 ) -> Self {
506 Self {
507 dpop_manager,
508 mtls_manager,
509 par_manager,
510 private_key_jwt_manager,
511 jwt_validator,
512 config,
513 sessions: Arc::new(RwLock::new(HashMap::new())),
514 }
515 }
516
517 pub async fn validate_authorization_request(
519 &self,
520 request_object: &str,
521 client_cert: Option<&str>,
522 dpop_proof: Option<&str>,
523 request_uri: Option<&str>,
524 ) -> Result<FapiRequestObject> {
525 let claims = if let Some(uri) = request_uri {
526 if self.config.require_par {
528 let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
530 AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
531 })?;
532
533 tracing::info!(
534 "FAPI PAR request consumed successfully for client: {}",
535 par_request.client_id
536 );
537
538 let nonce = par_request.additional_params.get("nonce").cloned();
540 FapiRequestObject {
541 iss: par_request.client_id.clone(),
542 aud: self.config.issuer.clone(),
543 iat: Utc::now().timestamp(),
544 exp: Utc::now().timestamp() + 300, nbf: Some(Utc::now().timestamp()),
546 jti: uuid::Uuid::new_v4().to_string(),
547 response_type: par_request.response_type,
548 client_id: par_request.client_id,
549 redirect_uri: par_request.redirect_uri,
550 scope: par_request.scope.unwrap_or_default(),
551 state: par_request.state,
552 nonce,
553 code_challenge: par_request.code_challenge,
554 code_challenge_method: par_request.code_challenge_method,
555 additional_claims: par_request
556 .additional_params
557 .into_iter()
558 .map(|(k, v)| (k, serde_json::Value::String(v)))
559 .collect(),
560 }
561 } else {
562 return Err(AuthError::InvalidRequest(
563 "request_uri provided but PAR not required".to_string(),
564 ));
565 }
566 } else {
567 if self.config.require_par {
569 return Err(AuthError::InvalidRequest(
570 "PAR is required but no request_uri provided".to_string(),
571 ));
572 }
573
574 self.validate_request_object(request_object).await?
576 };
577
578 if self.config.require_mtls {
580 let cert = client_cert.ok_or_else(|| {
581 AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
582 })?;
583 let cert_bytes = decode_client_certificate(cert)?;
584 self.mtls_manager
585 .validate_client_certificate(&cert_bytes, &claims.client_id)
586 .await?;
587 }
588
589 if self.config.require_dpop {
591 let proof = dpop_proof.ok_or_else(|| {
592 AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0")
593 })?;
594 self.dpop_manager
595 .validate_dpop_proof(
596 proof,
597 "POST",
598 &format!("{}/authorize", self.config.issuer),
599 None,
600 None,
601 )
602 .await?;
603 }
604
605 self.validate_request_claims(&claims).await?;
607
608 Ok(claims)
609 }
610
611 async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
613 let decoding_key = &self.config.public_key;
615
616 match self
618 .jwt_validator
619 .validate_token(request_object, decoding_key)
620 {
621 Ok(secure_claims) => {
622 let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
624 AuthError::token(format!("Invalid request object header: {}", e))
625 })?;
626
627 if !matches!(
629 header.alg,
630 Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
631 ) {
632 return Err(AuthError::token(
633 "Request object must use RS256, PS256, or ES256".to_string(),
634 ));
635 }
636
637 let mut validation = Validation::new(header.alg);
639 validation.set_audience(&[&self.config.issuer]);
640 validation.validate_exp = true;
641 validation.validate_nbf = true;
642
643 let token_data = jsonwebtoken::decode::<FapiRequestObject>(
645 request_object,
646 &self.config.public_key,
647 &validation,
648 )
649 .map_err(|e| {
650 AuthError::token(format!("Request object validation failed: {}", e))
651 })?;
652
653 let fapi_claims = token_data.claims;
654
655 if secure_claims.sub != fapi_claims.client_id {
658 return Err(AuthError::token(
659 "Subject mismatch between secure validation and FAPI claims".to_string(),
660 ));
661 }
662
663 if secure_claims.iss != fapi_claims.iss {
665 return Err(AuthError::token(
666 "Issuer mismatch between secure validation and FAPI claims".to_string(),
667 ));
668 }
669
670 if secure_claims.exp != fapi_claims.exp {
672 return Err(AuthError::token(
673 "Expiry mismatch between secure validation and FAPI claims".to_string(),
674 ));
675 }
676
677 let now = Utc::now().timestamp();
679
680 if now - fapi_claims.iat > self.config.max_request_age {
682 return Err(AuthError::token("Request object too old".to_string()));
683 }
684
685 if fapi_claims.client_id.is_empty() {
687 return Err(AuthError::token(
688 "client_id required in request object".to_string(),
689 ));
690 }
691
692 if fapi_claims.redirect_uri.is_empty() {
693 return Err(AuthError::token(
694 "redirect_uri required in request object".to_string(),
695 ));
696 }
697
698 if fapi_claims.response_type.is_empty() {
699 return Err(AuthError::token(
700 "response_type required in request object".to_string(),
701 ));
702 }
703
704 tracing::info!(
705 "FAPI request object validated successfully with SecureJwtValidator for client: {}",
706 fapi_claims.client_id
707 );
708
709 Ok(fapi_claims)
710 }
711 Err(e) => {
712 tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
713 Err(AuthError::token(format!(
714 "Enhanced JWT validation failed: {}",
715 e
716 )))
717 }
718 }
719 }
720
721 async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
723 if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
725 return Err(AuthError::InvalidRequest(
726 "FAPI 2.0 requires code or code id_token response type".to_string(),
727 ));
728 }
729
730 if claims.code_challenge.is_none() {
732 return Err(AuthError::InvalidRequest(
733 "PKCE required for FAPI 2.0".to_string(),
734 ));
735 }
736
737 if let Some(method) = &claims.code_challenge_method {
738 if method != "S256" {
739 return Err(AuthError::InvalidRequest(
740 "FAPI 2.0 requires S256 code challenge method".to_string(),
741 ));
742 }
743 } else {
744 return Err(AuthError::InvalidRequest(
745 "code_challenge_method required for FAPI 2.0".to_string(),
746 ));
747 }
748
749 Ok(())
750 }
751
752 pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
757 const REFUSED: &str = "Client authentication failed";
758
759 let auth_result = match self
761 .private_key_jwt_manager
762 .authenticate_client(client_assertion)
763 .await
764 {
765 Ok(result) => result,
766 Err(e) => {
767 tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
768 return Err(AuthError::auth_method("private_key_jwt", REFUSED));
769 }
770 };
771
772 if auth_result.authenticated {
773 tracing::info!(
774 "FAPI client authenticated successfully using private key JWT: {}",
775 auth_result.client_id
776 );
777 Ok(auth_result.client_id)
778 } else {
779 tracing::warn!(
780 "FAPI private key JWT authentication failed: {}",
781 auth_result.errors.join("; ")
782 );
783 Err(AuthError::auth_method("private_key_jwt", REFUSED))
784 }
785 }
786
787 pub async fn validate_token_request(
789 &self,
790 client_assertion: Option<&str>,
791 client_cert: Option<&str>,
792 dpop_proof: Option<&str>,
793 authorization_code: &str,
794 ) -> Result<String> {
795 let client_id = if let Some(assertion) = client_assertion {
797 self.authenticate_client_jwt(assertion).await?
798 } else if self.config.require_mtls {
799 if let Some(cert) = client_cert {
800 let cert_bytes = decode_client_certificate(cert)?;
801
802 let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
805
806 self.mtls_manager
807 .validate_client_certificate(&cert_bytes, &client_id)
808 .await?;
809
810 client_id.to_string()
811 } else {
812 return Err(AuthError::auth_method(
813 "mtls",
814 "Client certificate required for FAPI 2.0 token request",
815 ));
816 }
817 } else {
818 return Err(AuthError::auth_method(
819 "fapi",
820 "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
821 ));
822 };
823
824 if self.config.require_dpop {
826 let proof = dpop_proof.ok_or_else(|| {
827 AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0 token request")
828 })?;
829 self.dpop_manager
830 .validate_dpop_proof(
831 proof,
832 "POST",
833 &format!("{}/token", self.config.issuer),
834 Some(authorization_code), None,
836 )
837 .await?;
838 }
839
840 Ok(client_id)
841 }
842
843 pub async fn generate_authorization_response(
845 &self,
846 client_id: &str,
847 code: Option<&str>,
848 state: Option<&str>,
849 error: Option<&str>,
850 error_description: Option<&str>,
851 ) -> Result<String> {
852 if !self.config.enable_jarm {
853 return Err(AuthError::Configuration {
854 message: "JARM not enabled".to_string(),
855 help: Some("Enable JARM in your configuration to use this feature".to_string()),
856 docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
857 source: None,
858 suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
859 });
860 }
861
862 let now = Utc::now();
863 let exp = now + Duration::minutes(5); let response = FapiAuthorizationResponse {
866 iss: self.config.issuer.clone(),
867 aud: client_id.to_string(),
868 iat: now.timestamp(),
869 exp: exp.timestamp(),
870 code: code.map(|c| c.to_string()),
871 state: state.map(|s| s.to_string()),
872 error: error.map(|e| e.to_string()),
873 error_description: error_description.map(|d| d.to_string()),
874 additional_params: HashMap::new(),
875 };
876
877 let header = Header::new(self.config.response_signing_algorithm);
879
880 let token =
882 jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
883 AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
884 })?;
885
886 Ok(token)
887 }
888
889 pub async fn generate_token_response(
891 &self,
892 client_id: &str,
893 user_id: &str,
894 scopes: Vec<String>,
895 cert_thumbprint: Option<String>,
896 dpop_jkt: Option<String>,
897 ) -> Result<FapiTokenResponse> {
898 let access_token = self
900 .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
901 .await?;
902
903 let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
905
906 let mut cnf = json!({});
908
909 if let Some(thumbprint) = cert_thumbprint {
910 cnf["x5t#S256"] = Value::String(thumbprint);
911 }
912
913 if let Some(jkt) = dpop_jkt {
914 cnf["jkt"] = Value::String(jkt);
915 }
916
917 let response = FapiTokenResponse {
918 access_token,
919 token_type: "DPoP".to_string(), expires_in: 3600, refresh_token: Some(refresh_token),
922 scope: Some(scopes.join(" ")),
923 id_token: None, cnf: if cnf.as_object().is_none_or(|o| o.is_empty()) {
925 None
926 } else {
927 Some(cnf)
928 },
929 };
930
931 Ok(response)
932 }
933
934 async fn generate_access_token(
936 &self,
937 client_id: &str,
938 user_id: &str,
939 scopes: &[String],
940 cert_thumbprint: &Option<String>,
941 dpop_jkt: &Option<String>,
942 ) -> Result<String> {
943 let now = Utc::now();
944 let exp = now + Duration::hours(1);
945
946 let mut claims = json!({
947 "iss": self.config.issuer,
948 "aud": client_id,
949 "sub": user_id,
950 "iat": now.timestamp(),
951 "exp": exp.timestamp(),
952 "scope": scopes.join(" "),
953 "jti": Uuid::new_v4().to_string(),
954 });
955
956 let mut cnf = json!({});
958
959 if let Some(thumbprint) = cert_thumbprint {
960 cnf["x5t#S256"] = Value::String(thumbprint.clone());
961 }
962
963 if let Some(jkt) = dpop_jkt {
964 cnf["jkt"] = Value::String(jkt.clone());
965 }
966
967 if !cnf.as_object().is_none_or(|o| o.is_empty()) {
968 claims["cnf"] = cnf;
969 }
970
971 let header = Header::new(Algorithm::RS256);
973
974 let token =
976 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
977 AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
978 })?;
979
980 Ok(token)
981 }
982
983 async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
985 let now = Utc::now();
986 let exp = now + Duration::days(30); let claims = json!({
989 "iss": self.config.issuer,
990 "aud": client_id,
991 "sub": user_id,
992 "iat": now.timestamp(),
993 "exp": exp.timestamp(),
994 "typ": crate::security::secure_jwt::TYP_REFRESH_TOKEN,
995 "jti": Uuid::new_v4().to_string(),
996 });
997
998 let header = Header::new(Algorithm::RS256);
1000
1001 let token =
1003 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1004 AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
1005 })?;
1006
1007 Ok(token)
1008 }
1009
1010 pub async fn create_session(
1012 &self,
1013 client_id: &str,
1014 user_id: &str,
1015 scopes: Vec<String>,
1016 dpop_proof: Option<String>,
1017 cert_thumbprint: Option<String>,
1018 request_jti: Option<String>,
1019 ) -> Result<String> {
1020 let session_id = Uuid::new_v4().to_string();
1021 let now = Utc::now();
1022 let expires_at = now + Duration::hours(24); let session = FapiSession {
1025 session_id: session_id.clone(),
1026 client_id: client_id.to_string(),
1027 user_id: user_id.to_string(),
1028 created_at: now,
1029 expires_at,
1030 dpop_proof,
1031 cert_thumbprint,
1032 request_jti,
1033 scopes,
1034 metadata: HashMap::new(),
1035 };
1036
1037 let mut sessions = self.sessions.write().await;
1038 sessions.insert(session_id.clone(), session);
1039
1040 Ok(session_id)
1041 }
1042
1043 pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
1045 let sessions = self.sessions.read().await;
1046 Ok(sessions.get(session_id).cloned())
1047 }
1048
1049 pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
1051 let session = self
1052 .get_session(session_id)
1053 .await?
1054 .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
1055
1056 if Utc::now() > session.expires_at {
1058 return Err(AuthError::validation("Session expired".to_string()));
1059 }
1060
1061 Ok(session)
1062 }
1063
1064 pub async fn remove_session(&self, session_id: &str) -> Result<()> {
1066 let mut sessions = self.sessions.write().await;
1067 sessions.remove(session_id);
1068 Ok(())
1069 }
1070
1071 pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
1073 if self.config.enhanced_audit {
1074 let timestamp = chrono::Utc::now().to_rfc3339();
1078 let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
1079
1080 tracing::info!("{}", audit_entry);
1082 }
1083 Ok(())
1084 }
1085
1086 async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
1088 client_id_from_certificate(cert_bytes)
1089 }
1090
1091 pub fn check_compliance(&self) -> Vec<FapiComplianceViolation> {
1096 let mut violations = Vec::new();
1097
1098 if self.config.is_degraded {
1099 violations.push(FapiComplianceViolation {
1100 requirement: "crypto-keys".to_string(),
1101 severity: FapiViolationSeverity::Critical,
1102 message: "RSA key pair not properly configured; all FAPI operations will fail"
1103 .to_string(),
1104 });
1105 }
1106
1107 if !self.config.require_par {
1108 violations.push(FapiComplianceViolation {
1109 requirement: "par".to_string(),
1110 severity: FapiViolationSeverity::Critical,
1111 message: "FAPI 2.0 Security Profile requires Pushed Authorization Requests"
1112 .to_string(),
1113 });
1114 }
1115
1116 if !self.config.require_dpop {
1117 violations.push(FapiComplianceViolation {
1118 requirement: "sender-constraint".to_string(),
1119 severity: FapiViolationSeverity::Warning,
1120 message: "DPoP is recommended for sender-constrained tokens".to_string(),
1121 });
1122 }
1123
1124 if !self.config.require_mtls {
1125 violations.push(FapiComplianceViolation {
1126 requirement: "sender-constraint".to_string(),
1127 severity: FapiViolationSeverity::Warning,
1128 message: "mTLS is recommended for client authentication and token binding"
1129 .to_string(),
1130 });
1131 }
1132
1133 if !self.config.require_dpop && !self.config.require_mtls {
1134 violations.push(FapiComplianceViolation {
1135 requirement: "sender-constraint".to_string(),
1136 severity: FapiViolationSeverity::Critical,
1137 message:
1138 "FAPI 2.0 requires at least one sender-constraining mechanism (DPoP or mTLS)"
1139 .to_string(),
1140 });
1141 }
1142
1143 if !self.config.enable_jarm {
1144 violations.push(FapiComplianceViolation {
1145 requirement: "jarm".to_string(),
1146 severity: FapiViolationSeverity::Warning,
1147 message: "JARM is recommended for authorization response integrity".to_string(),
1148 });
1149 }
1150
1151 if !self.config.enhanced_audit {
1152 violations.push(FapiComplianceViolation {
1153 requirement: "audit".to_string(),
1154 severity: FapiViolationSeverity::Warning,
1155 message: "Enhanced audit logging is recommended for FAPI compliance".to_string(),
1156 });
1157 }
1158
1159 if !matches!(
1160 self.config.request_signing_algorithm,
1161 Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
1162 ) {
1163 violations.push(FapiComplianceViolation {
1164 requirement: "algorithm".to_string(),
1165 severity: FapiViolationSeverity::Critical,
1166 message: "Request signing must use RS256, PS256, or ES256".to_string(),
1167 });
1168 }
1169
1170 if self.config.max_request_age > 600 {
1171 violations.push(FapiComplianceViolation {
1172 requirement: "request-lifetime".to_string(),
1173 severity: FapiViolationSeverity::Warning,
1174 message: "Max request age exceeds recommended 10 minutes".to_string(),
1175 });
1176 }
1177
1178 violations
1179 }
1180
1181 pub fn is_compliant(&self) -> bool {
1183 !self
1184 .check_compliance()
1185 .iter()
1186 .any(|v| matches!(v.severity, FapiViolationSeverity::Critical))
1187 }
1188
1189 pub async fn validate_sender_constrained_token(
1194 &self,
1195 access_token: &str,
1196 dpop_proof: Option<&str>,
1197 client_cert: Option<&str>,
1198 http_method: &str,
1199 http_uri: &str,
1200 ) -> Result<serde_json::Value> {
1201 let token_data = self
1203 .jwt_validator
1204 .validate_token(access_token, &self.config.public_key)?;
1205
1206 let header = jsonwebtoken::decode_header(access_token)
1208 .map_err(|e| AuthError::token(format!("Invalid token header: {}", e)))?;
1209 let mut validation = Validation::new(header.alg);
1210 validation.set_audience(&[&self.config.issuer]);
1211 validation.validate_exp = true;
1212 let raw_claims = jsonwebtoken::decode::<serde_json::Value>(
1213 access_token,
1214 &self.config.public_key,
1215 &validation,
1216 )
1217 .map_err(|e| AuthError::token(format!("Token decode failed: {}", e)))?;
1218
1219 let cnf = raw_claims.claims.get("cnf").ok_or_else(|| {
1221 AuthError::token("Token is not sender-constrained (missing cnf claim)".to_string())
1222 })?;
1223
1224 if let Some(expected_jkt) = cnf.get("jkt").and_then(|v| v.as_str()) {
1226 let proof = dpop_proof.ok_or_else(|| {
1227 AuthError::token(
1228 "Token is DPoP-bound but no DPoP proof header provided".to_string(),
1229 )
1230 })?;
1231 self.dpop_manager
1232 .validate_dpop_proof(proof, http_method, http_uri, None, Some(expected_jkt))
1233 .await?;
1234 }
1235
1236 if let Some(expected_thumbprint) = cnf.get("x5t#S256").and_then(|v| v.as_str()) {
1238 let cert = client_cert.ok_or_else(|| {
1239 AuthError::token(
1240 "Token is certificate-bound but no client certificate provided".to_string(),
1241 )
1242 })?;
1243 use base64::Engine;
1245 use sha2::{Digest, Sha256};
1246 let cert_der = decode_client_certificate(cert)?;
1247 let presented_thumbprint =
1248 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(&cert_der));
1249 if !bool::from(subtle::ConstantTimeEq::ct_eq(
1250 presented_thumbprint.as_bytes(),
1251 expected_thumbprint.as_bytes(),
1252 )) {
1253 return Err(AuthError::token(
1254 "Certificate thumbprint does not match token binding".to_string(),
1255 ));
1256 }
1257 }
1258
1259 Ok(serde_json::json!({
1261 "sub": token_data.sub,
1262 "iss": token_data.iss,
1263 "exp": token_data.exp,
1264 "scope": token_data.scope,
1265 }))
1266 }
1267
1268 pub fn validate_authorization_details(
1270 &self,
1271 authorization_details: &[AuthorizationDetail],
1272 ) -> Result<()> {
1273 if authorization_details.is_empty() {
1274 return Err(AuthError::InvalidRequest(
1275 "authorization_details must not be empty".to_string(),
1276 ));
1277 }
1278
1279 for (i, detail) in authorization_details.iter().enumerate() {
1280 if detail.r#type.is_empty() {
1281 return Err(AuthError::InvalidRequest(format!(
1282 "authorization_details[{}]: type is required",
1283 i
1284 )));
1285 }
1286
1287 for location in &detail.locations {
1289 if !location.starts_with("https://") {
1290 return Err(AuthError::InvalidRequest(format!(
1291 "authorization_details[{}]: location must use HTTPS: {}",
1292 i, location
1293 )));
1294 }
1295 }
1296
1297 for action in &detail.actions {
1299 if action.is_empty() {
1300 return Err(AuthError::InvalidRequest(format!(
1301 "authorization_details[{}]: empty action not allowed",
1302 i
1303 )));
1304 }
1305 }
1306 }
1307
1308 Ok(())
1309 }
1310}
1311
1312#[derive(Debug, Clone)]
1314pub struct FapiComplianceViolation {
1315 pub requirement: String,
1317 pub severity: FapiViolationSeverity,
1319 pub message: String,
1321}
1322
1323#[derive(Debug, Clone, PartialEq, Eq)]
1325pub enum FapiViolationSeverity {
1326 Critical,
1328 Warning,
1330}
1331
1332#[derive(Debug, Clone, Serialize, Deserialize)]
1334pub struct AuthorizationDetail {
1335 pub r#type: String,
1337
1338 #[serde(default)]
1340 pub locations: Vec<String>,
1341
1342 #[serde(default)]
1344 pub actions: Vec<String>,
1345
1346 #[serde(default)]
1348 pub datatypes: Vec<String>,
1349
1350 #[serde(skip_serializing_if = "Option::is_none")]
1352 pub identifier: Option<String>,
1353
1354 #[serde(flatten)]
1356 pub additional_fields: HashMap<String, Value>,
1357}
1358
1359impl Default for FapiConfig {
1360 fn default() -> Self {
1361 let issuer =
1363 std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
1364
1365 let mut is_degraded = false;
1366
1367 let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
1371 std::fs::read(&key_path)
1372 .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
1373 .and_then(|bytes| {
1374 EncodingKey::from_rsa_pem(&bytes)
1375 .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
1376 })
1377 .unwrap_or_else(|_| {
1378 tracing::error!(
1379 "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH is set but the key could not \
1380 be loaded. FAPI REQUIRES an RSA private key for request/response signing. \
1381 Using an ephemeral HMAC placeholder — ALL FAPI OPERATIONS WILL BE REJECTED \
1382 until a valid RSA key is provided. Set FAPI_PRIVATE_KEY_PATH to a valid \
1383 PEM-encoded RSA private key file."
1384 );
1385 is_degraded = true;
1386 use ring::rand::{SecureRandom, SystemRandom};
1387 let rng = SystemRandom::new();
1388 let mut bytes = [0u8; 32];
1389 rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1390 EncodingKey::from_secret(&bytes)
1391 })
1392 } else {
1393 tracing::error!(
1394 "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH not set. FAPI REQUIRES an RSA \
1395 private key for request and response signing. Using an ephemeral HMAC \
1396 placeholder — ALL FAPI OPERATIONS WILL BE REJECTED until a valid RSA key \
1397 is provided. Set FAPI_PRIVATE_KEY_PATH to a PEM-encoded RSA private key file."
1398 );
1399 is_degraded = true;
1400 use ring::rand::{SecureRandom, SystemRandom};
1401 let rng = SystemRandom::new();
1402 let mut bytes = [0u8; 32];
1403 rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1404 EncodingKey::from_secret(&bytes)
1405 };
1406
1407 let public_key = if let Ok(key_path) = std::env::var("FAPI_PUBLIC_KEY_PATH") {
1409 std::fs::read(&key_path)
1410 .map_err(|e| tracing::warn!("Failed to load public key from {}: {}", key_path, e))
1411 .and_then(|bytes| {
1412 DecodingKey::from_rsa_pem(&bytes)
1413 .map_err(|e| tracing::warn!("Invalid RSA public key format: {}", e))
1414 })
1415 .unwrap_or_else(|_| {
1416 tracing::error!(
1417 "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH is set but the key could not \
1418 be loaded. FAPI verification will not work correctly."
1419 );
1420 is_degraded = true;
1421 use ring::rand::{SecureRandom, SystemRandom};
1422 let rng = SystemRandom::new();
1423 let mut secret = [0u8; 32];
1424 rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1425 DecodingKey::from_secret(&secret)
1426 })
1427 } else {
1428 tracing::error!(
1429 "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH not set. FAPI verification will \
1430 not work correctly. Set FAPI_PUBLIC_KEY_PATH to a PEM-encoded RSA public key file."
1431 );
1432 is_degraded = true;
1433 use ring::rand::{SecureRandom, SystemRandom};
1434 let rng = SystemRandom::new();
1435 let mut secret = [0u8; 32];
1436 rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1437 DecodingKey::from_secret(&secret)
1438 };
1439
1440 Self {
1441 issuer,
1442 request_signing_algorithm: Algorithm::RS256,
1443 response_signing_algorithm: Algorithm::RS256,
1444 private_key,
1445 public_key,
1446 max_request_age: 300, require_dpop: true,
1448 require_mtls: true,
1449 require_par: true,
1450 enable_jarm: true,
1451 enhanced_audit: true,
1452 is_degraded,
1453 }
1454 }
1455}
1456
1457fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
1462 use base64::Engine;
1463 use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
1464
1465 const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
1466 const END: &str = "-----END CERTIFICATE-----";
1467 let bad = || {
1468 AuthError::auth_method(
1469 "mtls",
1470 "Client certificate must be PEM or base64-encoded DER",
1471 )
1472 };
1473
1474 let trimmed = input.trim();
1475 let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
1476 let end = rest.find(END).ok_or_else(bad)?;
1477 if !rest[end + END.len()..].trim().is_empty() {
1479 return Err(bad());
1480 }
1481 &rest[..end]
1482 } else {
1483 trimmed
1484 };
1485 let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
1486 if compact.is_empty() {
1487 return Err(bad());
1488 }
1489 STANDARD
1490 .decode(&compact)
1491 .or_else(|_| STANDARD_NO_PAD.decode(&compact))
1492 .or_else(|_| URL_SAFE.decode(&compact))
1493 .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
1494 .map_err(|_| bad())
1495}
1496
1497fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
1500 use x509_parser::extensions::GeneralName;
1501
1502 let cert = match x509_parser::parse_x509_certificate(cert_der) {
1503 Ok(([], cert)) => cert,
1504 _ => {
1505 return Err(AuthError::auth_method(
1506 "mtls",
1507 "Invalid client certificate format",
1508 ));
1509 }
1510 };
1511
1512 let common_names: Vec<String> = cert
1513 .subject()
1514 .iter_common_name()
1515 .filter_map(|cn| cn.as_str().ok().map(str::to_string))
1516 .collect();
1517 if common_names.len() == 1 && !common_names[0].is_empty() {
1518 return Ok(common_names[0].clone());
1519 }
1520
1521 if let Ok(Some(san)) = cert.subject_alternative_name() {
1522 let names: Vec<String> = san
1523 .value
1524 .general_names
1525 .iter()
1526 .filter_map(|name| match name {
1527 GeneralName::DNSName(dns) => Some(dns.to_string()),
1528 GeneralName::URI(uri) => Some(uri.to_string()),
1529 _ => None,
1530 })
1531 .collect();
1532 if names.len() == 1 {
1533 return Ok(names[0].clone());
1534 }
1535 }
1536
1537 Err(AuthError::auth_method(
1538 "mtls",
1539 "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
1540 ))
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545 use super::*;
1546
1547 #[test]
1548 fn test_fapi_config_builder() {
1549 use ring::rand::{SecureRandom, SystemRandom};
1550 let rng = SystemRandom::new();
1551 let mut bytes = [0u8; 32];
1552 rng.fill(&mut bytes).unwrap();
1553 let private_key = EncodingKey::from_secret(&bytes);
1554 let public_key = DecodingKey::from_secret(&bytes);
1555
1556 let config = FapiConfig::builder("https://fapi.example.com", private_key, public_key)
1557 .request_signing_algorithm(Algorithm::ES256)
1558 .max_request_age(120)
1559 .require_dpop(false)
1560 .degraded()
1561 .build();
1562
1563 assert_eq!(config.issuer, "https://fapi.example.com");
1564 assert_eq!(config.request_signing_algorithm, Algorithm::ES256);
1565 assert_eq!(config.max_request_age, 120);
1566 assert!(!config.require_dpop);
1567 assert!(config.require_mtls); assert!(config.is_degraded);
1569 }
1570
1571 #[test]
1572 fn test_fapi_session_builder() {
1573 let session = FapiSession::builder(
1574 "sess_123",
1575 "client_456",
1576 "user_789",
1577 Duration::try_hours(1).unwrap(),
1578 )
1579 .dpop_proof("proof_abc")
1580 .add_scope("openid")
1581 .add_scopes(vec!["profile", "email"])
1582 .add_metadata("custom_flag", json!(true))
1583 .build();
1584
1585 assert_eq!(session.session_id, "sess_123");
1586 assert_eq!(session.client_id, "client_456");
1587 assert_eq!(session.user_id, "user_789");
1588 assert_eq!(session.dpop_proof.as_deref(), Some("proof_abc"));
1589 assert_eq!(session.scopes, vec!["openid", "profile", "email"]);
1590 assert_eq!(session.metadata["custom_flag"], true);
1591 }
1592
1593 #[tokio::test]
1594 async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
1595 use crate::security::secure_jwt::SecureJwtConfig;
1596 use crate::server::jwt::private_key_jwt::ClientJwtConfig;
1597 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1598
1599 let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
1600 let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1601 let manager = FapiManager::new(
1602 FapiConfig::default(),
1603 Arc::new(DpopManager::new(validator())),
1604 Arc::new(MutualTlsManager::new()),
1605 Arc::new(PARManager::new(Arc::new(
1606 crate::storage::MemoryStorage::new(),
1607 ))),
1608 assertions.clone(),
1609 Arc::new(validator()),
1610 );
1611
1612 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1614 let raw = key.public_key_raw();
1615 let point = &raw[raw.len() - 65..];
1616 let jwk = json!({
1617 "kty": "EC", "crv": "P-256",
1618 "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1619 "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1620 });
1621 assertions
1622 .register_client(
1623 ClientJwtConfig::builder("fapi-client", jwk)
1624 .algorithms(vec![Algorithm::ES256])
1625 .audience("https://auth.example.com/token")
1626 .build(),
1627 )
1628 .await
1629 .unwrap();
1630 let encoding_key = EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap();
1631
1632 let good = assertions
1634 .create_client_assertion(
1635 "fapi-client",
1636 "https://auth.example.com/token",
1637 &encoding_key,
1638 Algorithm::ES256,
1639 )
1640 .unwrap();
1641 assert_eq!(
1642 manager.authenticate_client_jwt(&good).await.unwrap(),
1643 "fapi-client"
1644 );
1645
1646 let wrong_audience = assertions
1649 .create_client_assertion(
1650 "fapi-client",
1651 "https://elsewhere.example/token",
1652 &encoding_key,
1653 Algorithm::ES256,
1654 )
1655 .unwrap();
1656 let unknown = assertions
1657 .create_client_assertion(
1658 "ghost",
1659 "https://auth.example.com/token",
1660 &encoding_key,
1661 Algorithm::ES256,
1662 )
1663 .unwrap();
1664 for (why, assertion) in [
1665 ("wrong audience", wrong_audience.as_str()),
1666 ("unknown client", unknown.as_str()),
1667 ("replay", good.as_str()),
1668 ("junk", "not-a-jwt"),
1669 ] {
1670 let message = manager
1671 .authenticate_client_jwt(assertion)
1672 .await
1673 .expect_err(why)
1674 .to_string();
1675 assert!(
1676 message.contains("Client authentication failed"),
1677 "{why}: {message}"
1678 );
1679 for leak in [
1680 "udience",
1681 "registered",
1682 "ignature",
1683 "replay",
1684 "JTI",
1685 "Algorithm",
1686 "expired",
1687 ] {
1688 assert!(
1689 !message.contains(leak),
1690 "{why}: {message:?} mentions {leak:?}"
1691 );
1692 }
1693 }
1694 }
1695
1696 #[tokio::test]
1697 async fn test_fapi_manager_creation() {
1698 let config = FapiConfig::default();
1700
1701 assert_eq!(config.issuer, "https://auth.example.com"); assert!(config.require_dpop);
1704 assert!(config.require_mtls);
1705 assert!(config.require_par);
1706 assert!(config.enable_jarm);
1707 assert!(config.enhanced_audit);
1708 }
1709
1710 #[tokio::test]
1711 async fn test_fapi_request_validation() {
1712 let config = FapiConfig::default();
1715
1716 let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1718
1719 let validation_result = validate_fapi_request_object(request_object, &config);
1721 assert!(
1722 validation_result.is_ok(),
1723 "FAPI request object validation failed"
1724 );
1725
1726 assert!(!request_object.is_empty());
1728 }
1729
1730 fn validate_fapi_request_object(
1732 request_object: &str,
1733 _config: &FapiConfig,
1734 ) -> Result<(), String> {
1735 let parsed: serde_json::Value = serde_json::from_str(request_object)
1737 .map_err(|_| "Invalid JSON structure in request object")?;
1738
1739 let required_claims = ["iss", "aud", "exp", "iat", "jti"];
1741 for claim in &required_claims {
1742 if parsed.get(claim).is_none() {
1743 return Err(format!("Missing required FAPI claim: {}", claim));
1744 }
1745 }
1746
1747 if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
1749 let now = chrono::Utc::now().timestamp();
1750 if exp <= now {
1751 return Err("Request object has expired".to_string());
1752 }
1753 }
1754
1755 Ok(())
1758 }
1759
1760 #[tokio::test]
1761 async fn test_fapi_response_generation() {
1762 let config = FapiConfig::default();
1765
1766 let auth_response = serde_json::json!({
1768 "code": "auth_code_123",
1769 "state": "client_state",
1770 "iss": config.issuer,
1771 "aud": "client_id",
1772 "exp": 9999999999i64
1773 });
1774
1775 assert!(auth_response["code"].is_string());
1777 }
1778
1779 #[tokio::test]
1780 async fn test_fapi_token_generation() {
1781 let config = FapiConfig::default();
1783
1784 let scopes = ["accounts".to_string(), "payments".to_string()];
1786 let client_id = "fapi_client_123";
1787 let user_id = "user_456";
1788 let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
1789
1790 assert!(config.require_dpop);
1792 assert!(config.require_mtls);
1793 assert!(!scopes.is_empty());
1794 assert!(!client_id.is_empty());
1795 assert!(!user_id.is_empty());
1796 assert!(cert_thumbprint.is_some());
1797 }
1798
1799 #[tokio::test]
1800 async fn test_fapi_session_management() {
1801 let config = FapiConfig::default();
1803
1804 let session_data = serde_json::json!({
1806 "client_id": "fapi_client",
1807 "user_id": "fapi_user",
1808 "scopes": ["accounts", "payments"],
1809 "mtls_cert": "client_certificate",
1810 "dpop_key": "client_dpop_key"
1811 });
1812
1813 assert!(session_data["mtls_cert"].is_string());
1815 assert!(session_data["dpop_key"].is_string());
1816 assert!(config.enhanced_audit);
1817 }
1818
1819 fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
1822 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1823 let mut dn = rcgen::DistinguishedName::new();
1824 dn.push(rcgen::DnType::CommonName, cn);
1825 if let Some(org) = org {
1826 dn.push(rcgen::DnType::OrganizationName, org);
1827 }
1828 params.distinguished_name = dn;
1829 let key = rcgen::KeyPair::generate().unwrap();
1830 params.self_signed(&key).unwrap()
1831 }
1832
1833 #[test]
1834 fn decode_client_certificate_accepts_pem_and_base64_der() {
1835 use base64::Engine;
1836 let cert = test_cert("client-a", None);
1837 let der = cert.der().to_vec();
1838
1839 assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
1840 let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
1841 assert_eq!(decode_client_certificate(&b64).unwrap(), der);
1842 let wrapped = format!(" {}\n{} \n", &b64[..20], &b64[20..]);
1843 assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
1844 }
1845
1846 #[test]
1847 fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
1848 let a = test_cert("client-a", None).pem();
1849 let b = test_cert("client-b", None).pem();
1850 assert!(decode_client_certificate("").is_err());
1851 assert!(decode_client_certificate("!!! not base64 !!!").is_err());
1852 assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
1853 assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
1855 }
1856
1857 #[test]
1858 fn client_id_comes_from_the_parsed_subject_cn() {
1859 let cert = test_cert("client-a", None);
1860 assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
1861 }
1862
1863 #[test]
1864 fn client_id_is_not_found_by_searching_the_raw_bytes() {
1865 let cert = test_cert("real-client", Some("CN=victim-client,"));
1868 assert_eq!(
1869 client_id_from_certificate(cert.der()).unwrap(),
1870 "real-client"
1871 );
1872 }
1873
1874 #[test]
1875 fn client_id_needs_a_unique_identity() {
1876 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1878 params.distinguished_name = rcgen::DistinguishedName::new(); let key = rcgen::KeyPair::generate().unwrap();
1880 let nameless = params.self_signed(&key).unwrap();
1881 assert!(client_id_from_certificate(nameless.der()).is_err());
1882 assert!(client_id_from_certificate(b"not a certificate").is_err());
1883 }
1884}