1use crate::errors::{AuthError, Result};
25use crate::security::secure_jwt::SecureJwtValidator;
26use crate::server::{DpopManager, MutualTlsManager, PARManager, PrivateKeyJwtManager};
27use chrono::{DateTime, Duration, Utc};
28use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
29use serde::{Deserialize, Serialize};
30use serde_json::{Value, json};
31use std::collections::HashMap;
32use std::sync::Arc;
33use tokio::sync::RwLock;
34use uuid::Uuid;
35
36#[derive(Clone)]
38pub struct FapiManager {
39 dpop_manager: Arc<DpopManager>,
41
42 mtls_manager: Arc<MutualTlsManager>,
44
45 par_manager: Arc<PARManager>,
47
48 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
50
51 jwt_validator: Arc<SecureJwtValidator>,
53
54 config: FapiConfig,
56
57 sessions: Arc<RwLock<HashMap<String, FapiSession>>>,
59}
60
61impl std::fmt::Debug for FapiManager {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 let mut d = f.debug_struct("FapiManager");
64 d.field("dpop_manager", &self.dpop_manager);
65 d.field("mtls_manager", &self.mtls_manager);
66 d.field("par_manager", &self.par_manager);
67 d.field("private_key_jwt_manager", &self.private_key_jwt_manager);
68 d.field("jwt_validator", &self.jwt_validator);
69 d.field("config", &self.config);
70 d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
71 d.finish()
72 }
73}
74
75#[derive(Clone)]
77pub struct FapiConfig {
78 pub issuer: String,
80
81 pub request_signing_algorithm: Algorithm,
83
84 pub response_signing_algorithm: Algorithm,
86
87 pub private_key: EncodingKey,
89
90 pub public_key: DecodingKey,
92
93 pub max_request_age: i64,
95
96 pub require_dpop: bool,
98
99 pub require_mtls: bool,
101
102 pub require_par: bool,
104
105 pub enable_jarm: bool,
107
108 pub enhanced_audit: bool,
110}
111
112impl std::fmt::Debug for FapiConfig {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("FapiConfig")
115 .field("issuer", &self.issuer)
116 .field("request_signing_algorithm", &self.request_signing_algorithm)
117 .field(
118 "response_signing_algorithm",
119 &self.response_signing_algorithm,
120 )
121 .field("private_key", &"<EncodingKey>")
122 .field("public_key", &"<DecodingKey>")
123 .field("max_request_age", &self.max_request_age)
124 .field("require_dpop", &self.require_dpop)
125 .field("require_mtls", &self.require_mtls)
126 .field("require_par", &self.require_par)
127 .field("enable_jarm", &self.enable_jarm)
128 .field("enhanced_audit", &self.enhanced_audit)
129 .finish()
130 }
131}
132
133#[derive(Clone, Serialize, Deserialize)]
135pub struct FapiSession {
136 pub session_id: String,
138
139 pub client_id: String,
141
142 pub user_id: String,
144
145 pub created_at: DateTime<Utc>,
147
148 pub expires_at: DateTime<Utc>,
150
151 pub dpop_proof: Option<String>,
153
154 pub cert_thumbprint: Option<String>,
156
157 pub request_jti: Option<String>,
159
160 pub scopes: Vec<String>,
162
163 pub metadata: HashMap<String, Value>,
165}
166
167impl std::fmt::Debug for FapiSession {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 let mut d = f.debug_struct("FapiSession");
170 d.field(
171 "session_id",
172 &crate::utils::redact::redacted(&self.session_id),
173 );
174 d.field("client_id", &self.client_id);
175 d.field("user_id", &self.user_id);
176 d.field("created_at", &self.created_at);
177 d.field("expires_at", &self.expires_at);
178 d.field(
179 "dpop_proof",
180 &crate::utils::redact::redacted(&self.dpop_proof),
181 );
182 d.field("cert_thumbprint", &self.cert_thumbprint);
183 d.field("request_jti", &self.request_jti);
184 d.field("scopes", &self.scopes);
185 d.field("metadata", &self.metadata);
186 d.finish()
187 }
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
192pub struct FapiRequestObject {
193 pub iss: String,
195
196 pub aud: String,
198
199 pub iat: i64,
201
202 pub exp: i64,
204
205 pub nbf: Option<i64>,
207
208 pub jti: String,
210
211 pub response_type: String,
213
214 pub client_id: String,
216
217 pub redirect_uri: String,
219
220 pub scope: String,
222
223 pub state: Option<String>,
225
226 pub nonce: Option<String>,
228
229 pub code_challenge: Option<String>,
231
232 pub code_challenge_method: Option<String>,
234
235 #[serde(flatten)]
237 pub additional_claims: HashMap<String, Value>,
238}
239
240#[derive(Clone, Serialize, Deserialize)]
242pub struct FapiAuthorizationResponse {
243 pub iss: String,
245
246 pub aud: String,
248
249 pub iat: i64,
251
252 pub exp: i64,
254
255 pub code: Option<String>,
257
258 pub state: Option<String>,
260
261 pub error: Option<String>,
263
264 pub error_description: Option<String>,
266
267 #[serde(flatten)]
269 pub additional_params: HashMap<String, Value>,
270}
271
272impl std::fmt::Debug for FapiAuthorizationResponse {
273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 let mut d = f.debug_struct("FapiAuthorizationResponse");
275 d.field("iss", &self.iss);
276 d.field("aud", &self.aud);
277 d.field("iat", &self.iat);
278 d.field("exp", &self.exp);
279 d.field("code", &crate::utils::redact::redacted(&self.code));
280 d.field("state", &self.state);
281 d.field("error", &self.error);
282 d.field("error_description", &self.error_description);
283 d.field(
284 "additional_params",
285 &crate::utils::redact::redacted(&self.additional_params),
286 );
287 d.finish()
288 }
289}
290
291#[derive(Clone, Serialize, Deserialize)]
293pub struct FapiTokenResponse {
294 pub access_token: String,
296
297 pub token_type: String,
299
300 pub expires_in: i64,
302
303 pub refresh_token: Option<String>,
305
306 pub scope: Option<String>,
308
309 pub id_token: Option<String>,
311
312 pub cnf: Option<Value>,
314}
315
316impl std::fmt::Debug for FapiTokenResponse {
317 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318 let mut d = f.debug_struct("FapiTokenResponse");
319 d.field(
320 "access_token",
321 &crate::utils::redact::redacted(&self.access_token),
322 );
323 d.field("token_type", &self.token_type);
324 d.field("expires_in", &self.expires_in);
325 d.field(
326 "refresh_token",
327 &crate::utils::redact::redacted(&self.refresh_token),
328 );
329 d.field("scope", &self.scope);
330 d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
331 d.field("cnf", &self.cnf);
332 d.finish()
333 }
334}
335
336impl FapiManager {
337 pub fn new(
339 config: FapiConfig,
340 dpop_manager: Arc<DpopManager>,
341 mtls_manager: Arc<MutualTlsManager>,
342 par_manager: Arc<PARManager>,
343 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
344 jwt_validator: Arc<SecureJwtValidator>,
345 ) -> Self {
346 Self {
347 dpop_manager,
348 mtls_manager,
349 par_manager,
350 private_key_jwt_manager,
351 jwt_validator,
352 config,
353 sessions: Arc::new(RwLock::new(HashMap::new())),
354 }
355 }
356
357 pub async fn validate_authorization_request(
359 &self,
360 request_object: &str,
361 client_cert: Option<&str>,
362 dpop_proof: Option<&str>,
363 request_uri: Option<&str>,
364 ) -> Result<FapiRequestObject> {
365 let claims = if let Some(uri) = request_uri {
366 if self.config.require_par {
368 let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
370 AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
371 })?;
372
373 tracing::info!(
374 "FAPI PAR request consumed successfully for client: {}",
375 par_request.client_id
376 );
377
378 FapiRequestObject {
381 iss: par_request.client_id.clone(),
382 aud: self.config.issuer.clone(),
383 iat: Utc::now().timestamp(),
384 exp: Utc::now().timestamp() + 300, nbf: Some(Utc::now().timestamp()),
386 jti: uuid::Uuid::new_v4().to_string(),
387 response_type: par_request.response_type,
388 client_id: par_request.client_id,
389 redirect_uri: par_request.redirect_uri,
390 scope: par_request.scope.unwrap_or_default(),
391 state: par_request.state,
392 nonce: None, code_challenge: par_request.code_challenge,
394 code_challenge_method: par_request.code_challenge_method,
395 additional_claims: par_request
396 .additional_params
397 .into_iter()
398 .map(|(k, v)| (k, serde_json::Value::String(v)))
399 .collect(),
400 }
401 } else {
402 return Err(AuthError::InvalidRequest(
403 "request_uri provided but PAR not required".to_string(),
404 ));
405 }
406 } else {
407 if self.config.require_par {
409 return Err(AuthError::InvalidRequest(
410 "PAR is required but no request_uri provided".to_string(),
411 ));
412 }
413
414 self.validate_request_object(request_object).await?
416 };
417
418 if self.config.require_mtls {
420 let cert = client_cert.ok_or_else(|| {
421 AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
422 })?;
423 let cert_bytes = decode_client_certificate(cert)?;
424 self.mtls_manager
425 .validate_client_certificate(&cert_bytes, &claims.client_id)
426 .await?;
427 }
428
429 if self.config.require_dpop {
431 if dpop_proof.is_none() {
432 return Err(AuthError::auth_method(
433 "dpop",
434 "DPoP proof required for FAPI 2.0",
435 ));
436 }
437
438 let proof = dpop_proof.unwrap();
439 self.dpop_manager
440 .validate_dpop_proof(
441 proof,
442 "POST",
443 &format!("{}/authorize", self.config.issuer),
444 None,
445 None,
446 )
447 .await?;
448 }
449
450 self.validate_request_claims(&claims).await?;
452
453 Ok(claims)
454 }
455
456 async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
458 let decoding_key = &self.config.public_key;
460
461 match self
463 .jwt_validator
464 .validate_token(request_object, decoding_key, true)
465 {
466 Ok(secure_claims) => {
467 let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
469 AuthError::InvalidToken(format!("Invalid request object header: {}", e))
470 })?;
471
472 if !matches!(
474 header.alg,
475 Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
476 ) {
477 return Err(AuthError::InvalidToken(
478 "Request object must use RS256, PS256, or ES256".to_string(),
479 ));
480 }
481
482 let mut validation = Validation::new(header.alg);
484 validation.set_audience(&[&self.config.issuer]);
485 validation.validate_exp = true;
486 validation.validate_nbf = true;
487
488 let token_data = jsonwebtoken::decode::<FapiRequestObject>(
490 request_object,
491 &self.config.public_key,
492 &validation,
493 )
494 .map_err(|e| {
495 AuthError::InvalidToken(format!("Request object validation failed: {}", e))
496 })?;
497
498 let fapi_claims = token_data.claims;
499
500 if secure_claims.sub != fapi_claims.client_id {
503 return Err(AuthError::InvalidToken(
504 "Subject mismatch between secure validation and FAPI claims".to_string(),
505 ));
506 }
507
508 if secure_claims.iss != fapi_claims.iss {
510 return Err(AuthError::InvalidToken(
511 "Issuer mismatch between secure validation and FAPI claims".to_string(),
512 ));
513 }
514
515 if secure_claims.exp != fapi_claims.exp {
517 return Err(AuthError::InvalidToken(
518 "Expiry mismatch between secure validation and FAPI claims".to_string(),
519 ));
520 }
521
522 let now = Utc::now().timestamp();
524
525 if now - fapi_claims.iat > self.config.max_request_age {
527 return Err(AuthError::InvalidToken(
528 "Request object too old".to_string(),
529 ));
530 }
531
532 if fapi_claims.client_id.is_empty() {
534 return Err(AuthError::InvalidToken(
535 "client_id required in request object".to_string(),
536 ));
537 }
538
539 if fapi_claims.redirect_uri.is_empty() {
540 return Err(AuthError::InvalidToken(
541 "redirect_uri required in request object".to_string(),
542 ));
543 }
544
545 if fapi_claims.response_type.is_empty() {
546 return Err(AuthError::InvalidToken(
547 "response_type required in request object".to_string(),
548 ));
549 }
550
551 tracing::info!(
552 "FAPI request object validated successfully with SecureJwtValidator for client: {}",
553 fapi_claims.client_id
554 );
555
556 Ok(fapi_claims)
557 }
558 Err(e) => {
559 tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
560 Err(AuthError::InvalidToken(format!(
561 "Enhanced JWT validation failed: {}",
562 e
563 )))
564 }
565 }
566 }
567
568 async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
570 if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
572 return Err(AuthError::InvalidRequest(
573 "FAPI 2.0 requires code or code id_token response type".to_string(),
574 ));
575 }
576
577 if claims.code_challenge.is_none() {
579 return Err(AuthError::InvalidRequest(
580 "PKCE required for FAPI 2.0".to_string(),
581 ));
582 }
583
584 if let Some(method) = &claims.code_challenge_method {
585 if method != "S256" {
586 return Err(AuthError::InvalidRequest(
587 "FAPI 2.0 requires S256 code challenge method".to_string(),
588 ));
589 }
590 } else {
591 return Err(AuthError::InvalidRequest(
592 "code_challenge_method required for FAPI 2.0".to_string(),
593 ));
594 }
595
596 Ok(())
597 }
598
599 pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
604 const REFUSED: &str = "Client authentication failed";
605
606 let auth_result = match self
608 .private_key_jwt_manager
609 .authenticate_client(client_assertion)
610 .await
611 {
612 Ok(result) => result,
613 Err(e) => {
614 tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
615 return Err(AuthError::auth_method("private_key_jwt", REFUSED));
616 }
617 };
618
619 if auth_result.authenticated {
620 tracing::info!(
621 "FAPI client authenticated successfully using private key JWT: {}",
622 auth_result.client_id
623 );
624 Ok(auth_result.client_id)
625 } else {
626 tracing::warn!(
627 "FAPI private key JWT authentication failed: {}",
628 auth_result.errors.join("; ")
629 );
630 Err(AuthError::auth_method("private_key_jwt", REFUSED))
631 }
632 }
633
634 pub async fn validate_token_request(
636 &self,
637 client_assertion: Option<&str>,
638 client_cert: Option<&str>,
639 dpop_proof: Option<&str>,
640 authorization_code: &str,
641 ) -> Result<String> {
642 let client_id = if let Some(assertion) = client_assertion {
644 self.authenticate_client_jwt(assertion).await?
645 } else if self.config.require_mtls {
646 if let Some(cert) = client_cert {
647 let cert_bytes = decode_client_certificate(cert)?;
648
649 let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
652
653 self.mtls_manager
654 .validate_client_certificate(&cert_bytes, &client_id)
655 .await?;
656
657 client_id.to_string()
658 } else {
659 return Err(AuthError::auth_method(
660 "mtls",
661 "Client certificate required for FAPI 2.0 token request",
662 ));
663 }
664 } else {
665 return Err(AuthError::auth_method(
666 "fapi",
667 "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
668 ));
669 };
670
671 if self.config.require_dpop {
673 if dpop_proof.is_none() {
674 return Err(AuthError::auth_method(
675 "dpop",
676 "DPoP proof required for FAPI 2.0 token request",
677 ));
678 }
679
680 let proof = dpop_proof.unwrap();
681 self.dpop_manager
682 .validate_dpop_proof(
683 proof,
684 "POST",
685 &format!("{}/token", self.config.issuer),
686 Some(authorization_code), None,
688 )
689 .await?;
690 }
691
692 Ok(client_id)
693 }
694
695 pub async fn generate_authorization_response(
697 &self,
698 client_id: &str,
699 code: Option<&str>,
700 state: Option<&str>,
701 error: Option<&str>,
702 error_description: Option<&str>,
703 ) -> Result<String> {
704 if !self.config.enable_jarm {
705 return Err(AuthError::Configuration {
706 message: "JARM not enabled".to_string(),
707 help: Some("Enable JARM in your configuration to use this feature".to_string()),
708 docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
709 source: None,
710 suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
711 });
712 }
713
714 let now = Utc::now();
715 let exp = now + Duration::minutes(5); let response = FapiAuthorizationResponse {
718 iss: self.config.issuer.clone(),
719 aud: client_id.to_string(),
720 iat: now.timestamp(),
721 exp: exp.timestamp(),
722 code: code.map(|c| c.to_string()),
723 state: state.map(|s| s.to_string()),
724 error: error.map(|e| e.to_string()),
725 error_description: error_description.map(|d| d.to_string()),
726 additional_params: HashMap::new(),
727 };
728
729 let header = Header::new(self.config.response_signing_algorithm);
731
732 let token =
734 jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
735 AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
736 })?;
737
738 Ok(token)
739 }
740
741 pub async fn generate_token_response(
743 &self,
744 client_id: &str,
745 user_id: &str,
746 scopes: Vec<String>,
747 cert_thumbprint: Option<String>,
748 dpop_jkt: Option<String>,
749 ) -> Result<FapiTokenResponse> {
750 let access_token = self
752 .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
753 .await?;
754
755 let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
757
758 let mut cnf = json!({});
760
761 if let Some(thumbprint) = cert_thumbprint {
762 cnf["x5t#S256"] = Value::String(thumbprint);
763 }
764
765 if let Some(jkt) = dpop_jkt {
766 cnf["jkt"] = Value::String(jkt);
767 }
768
769 let response = FapiTokenResponse {
770 access_token,
771 token_type: "DPoP".to_string(), expires_in: 3600, refresh_token: Some(refresh_token),
774 scope: Some(scopes.join(" ")),
775 id_token: None, cnf: if cnf.as_object().unwrap().is_empty() {
777 None
778 } else {
779 Some(cnf)
780 },
781 };
782
783 Ok(response)
784 }
785
786 async fn generate_access_token(
788 &self,
789 client_id: &str,
790 user_id: &str,
791 scopes: &[String],
792 cert_thumbprint: &Option<String>,
793 dpop_jkt: &Option<String>,
794 ) -> Result<String> {
795 let now = Utc::now();
796 let exp = now + Duration::hours(1);
797
798 let mut claims = json!({
799 "iss": self.config.issuer,
800 "aud": client_id,
801 "sub": user_id,
802 "iat": now.timestamp(),
803 "exp": exp.timestamp(),
804 "scope": scopes.join(" "),
805 "jti": Uuid::new_v4().to_string(),
806 });
807
808 let mut cnf = json!({});
810
811 if let Some(thumbprint) = cert_thumbprint {
812 cnf["x5t#S256"] = Value::String(thumbprint.clone());
813 }
814
815 if let Some(jkt) = dpop_jkt {
816 cnf["jkt"] = Value::String(jkt.clone());
817 }
818
819 if !cnf.as_object().unwrap().is_empty() {
820 claims["cnf"] = cnf;
821 }
822
823 let header = Header::new(Algorithm::RS256);
825
826 let token =
828 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
829 AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
830 })?;
831
832 Ok(token)
833 }
834
835 async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
837 let now = Utc::now();
838 let exp = now + Duration::days(30); let claims = json!({
841 "iss": self.config.issuer,
842 "aud": client_id,
843 "sub": user_id,
844 "iat": now.timestamp(),
845 "exp": exp.timestamp(),
846 "typ": "refresh_token",
847 "jti": Uuid::new_v4().to_string(),
848 });
849
850 let header = Header::new(Algorithm::RS256);
852
853 let token =
855 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
856 AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
857 })?;
858
859 Ok(token)
860 }
861
862 pub async fn create_session(
864 &self,
865 client_id: &str,
866 user_id: &str,
867 scopes: Vec<String>,
868 dpop_proof: Option<String>,
869 cert_thumbprint: Option<String>,
870 request_jti: Option<String>,
871 ) -> Result<String> {
872 let session_id = Uuid::new_v4().to_string();
873 let now = Utc::now();
874 let expires_at = now + Duration::hours(24); let session = FapiSession {
877 session_id: session_id.clone(),
878 client_id: client_id.to_string(),
879 user_id: user_id.to_string(),
880 created_at: now,
881 expires_at,
882 dpop_proof,
883 cert_thumbprint,
884 request_jti,
885 scopes,
886 metadata: HashMap::new(),
887 };
888
889 let mut sessions = self.sessions.write().await;
890 sessions.insert(session_id.clone(), session);
891
892 Ok(session_id)
893 }
894
895 pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
897 let sessions = self.sessions.read().await;
898 Ok(sessions.get(session_id).cloned())
899 }
900
901 pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
903 let session = self
904 .get_session(session_id)
905 .await?
906 .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
907
908 if Utc::now() > session.expires_at {
910 return Err(AuthError::validation("Session expired".to_string()));
911 }
912
913 Ok(session)
914 }
915
916 pub async fn remove_session(&self, session_id: &str) -> Result<()> {
918 let mut sessions = self.sessions.write().await;
919 sessions.remove(session_id);
920 Ok(())
921 }
922
923 pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
925 if self.config.enhanced_audit {
926 let timestamp = chrono::Utc::now().to_rfc3339();
930 let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
931
932 log::info!("{}", audit_entry);
934 }
935 Ok(())
936 }
937
938 async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
940 client_id_from_certificate(cert_bytes)
941 }
942}
943
944impl Default for FapiConfig {
945 fn default() -> Self {
946 let issuer =
948 std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
949
950 let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
952 std::fs::read(&key_path)
953 .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
954 .and_then(|bytes| {
955 EncodingKey::from_rsa_pem(&bytes)
956 .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
957 })
958 .unwrap_or_else(|_| EncodingKey::from_secret(b"dev_fallback_secret"))
959 } else {
960 EncodingKey::from_secret(b"dev_fallback_secret")
961 };
962
963 Self {
964 issuer,
965 request_signing_algorithm: Algorithm::RS256,
966 response_signing_algorithm: Algorithm::RS256,
967 private_key,
968 public_key: DecodingKey::from_secret(b"dev_secret"),
969 max_request_age: 300, require_dpop: true,
971 require_mtls: true,
972 require_par: true,
973 enable_jarm: true,
974 enhanced_audit: true,
975 }
976 }
977}
978
979fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
984 use base64::Engine;
985 use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
986
987 const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
988 const END: &str = "-----END CERTIFICATE-----";
989 let bad = || {
990 AuthError::auth_method(
991 "mtls",
992 "Client certificate must be PEM or base64-encoded DER",
993 )
994 };
995
996 let trimmed = input.trim();
997 let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
998 let end = rest.find(END).ok_or_else(bad)?;
999 if !rest[end + END.len()..].trim().is_empty() {
1001 return Err(bad());
1002 }
1003 &rest[..end]
1004 } else {
1005 trimmed
1006 };
1007 let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
1008 if compact.is_empty() {
1009 return Err(bad());
1010 }
1011 STANDARD
1012 .decode(&compact)
1013 .or_else(|_| STANDARD_NO_PAD.decode(&compact))
1014 .or_else(|_| URL_SAFE.decode(&compact))
1015 .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
1016 .map_err(|_| bad())
1017}
1018
1019fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
1022 use x509_parser::extensions::GeneralName;
1023
1024 let cert = match x509_parser::parse_x509_certificate(cert_der) {
1025 Ok(([], cert)) => cert,
1026 _ => {
1027 return Err(AuthError::auth_method(
1028 "mtls",
1029 "Invalid client certificate format",
1030 ));
1031 }
1032 };
1033
1034 let common_names: Vec<String> = cert
1035 .subject()
1036 .iter_common_name()
1037 .filter_map(|cn| cn.as_str().ok().map(str::to_string))
1038 .collect();
1039 if common_names.len() == 1 && !common_names[0].is_empty() {
1040 return Ok(common_names[0].clone());
1041 }
1042
1043 if let Ok(Some(san)) = cert.subject_alternative_name() {
1044 let names: Vec<String> = san
1045 .value
1046 .general_names
1047 .iter()
1048 .filter_map(|name| match name {
1049 GeneralName::DNSName(dns) => Some(dns.to_string()),
1050 GeneralName::URI(uri) => Some(uri.to_string()),
1051 _ => None,
1052 })
1053 .collect();
1054 if names.len() == 1 {
1055 return Ok(names[0].clone());
1056 }
1057 }
1058
1059 Err(AuthError::auth_method(
1060 "mtls",
1061 "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
1062 ))
1063}
1064
1065#[cfg(test)]
1066mod tests {
1067 use super::*;
1068
1069 #[tokio::test]
1070 async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
1071 use crate::security::secure_jwt::SecureJwtConfig;
1072 use crate::server::jwt::private_key_jwt::ClientJwtConfig;
1073 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1074
1075 let validator = || SecureJwtValidator::new(SecureJwtConfig::default());
1076 let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1077 let manager = FapiManager::new(
1078 FapiConfig::default(),
1079 Arc::new(DpopManager::new(validator())),
1080 Arc::new(MutualTlsManager::new()),
1081 Arc::new(PARManager::new(Arc::new(
1082 crate::storage::MemoryStorage::new(),
1083 ))),
1084 assertions.clone(),
1085 Arc::new(validator()),
1086 );
1087
1088 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1090 let raw = key.public_key_raw();
1091 let point = &raw[raw.len() - 65..];
1092 let jwk = json!({
1093 "kty": "EC", "crv": "P-256",
1094 "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1095 "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1096 });
1097 assertions
1098 .register_client(
1099 ClientJwtConfig::builder("fapi-client", jwk)
1100 .algorithms(vec![Algorithm::ES256])
1101 .audience("https://auth.example.com/token")
1102 .build(),
1103 )
1104 .await
1105 .unwrap();
1106 let signing_pem = key.serialize_pem();
1107
1108 let good = assertions
1110 .create_client_assertion(
1111 "fapi-client",
1112 "https://auth.example.com/token",
1113 signing_pem.as_bytes(),
1114 Algorithm::ES256,
1115 )
1116 .unwrap();
1117 assert_eq!(
1118 manager.authenticate_client_jwt(&good).await.unwrap(),
1119 "fapi-client"
1120 );
1121
1122 let wrong_audience = assertions
1125 .create_client_assertion(
1126 "fapi-client",
1127 "https://elsewhere.example/token",
1128 signing_pem.as_bytes(),
1129 Algorithm::ES256,
1130 )
1131 .unwrap();
1132 let unknown = assertions
1133 .create_client_assertion(
1134 "ghost",
1135 "https://auth.example.com/token",
1136 signing_pem.as_bytes(),
1137 Algorithm::ES256,
1138 )
1139 .unwrap();
1140 for (why, assertion) in [
1141 ("wrong audience", wrong_audience.as_str()),
1142 ("unknown client", unknown.as_str()),
1143 ("replay", good.as_str()),
1144 ("junk", "not-a-jwt"),
1145 ] {
1146 let message = manager
1147 .authenticate_client_jwt(assertion)
1148 .await
1149 .expect_err(why)
1150 .to_string();
1151 assert!(
1152 message.contains("Client authentication failed"),
1153 "{why}: {message}"
1154 );
1155 for leak in [
1156 "udience",
1157 "registered",
1158 "ignature",
1159 "replay",
1160 "JTI",
1161 "Algorithm",
1162 "expired",
1163 ] {
1164 assert!(
1165 !message.contains(leak),
1166 "{why}: {message:?} mentions {leak:?}"
1167 );
1168 }
1169 }
1170 }
1171
1172 #[tokio::test]
1173 async fn test_fapi_manager_creation() {
1174 let config = FapiConfig::default();
1176
1177 assert_eq!(config.issuer, "https://auth.example.com"); assert!(config.require_dpop);
1180 assert!(config.require_mtls);
1181 assert!(config.require_par);
1182 assert!(config.enable_jarm);
1183 assert!(config.enhanced_audit);
1184 }
1185
1186 #[tokio::test]
1187 async fn test_fapi_request_validation() {
1188 let config = FapiConfig::default();
1191
1192 let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1194
1195 let validation_result = validate_fapi_request_object(request_object, &config);
1197 assert!(
1198 validation_result.is_ok(),
1199 "FAPI request object validation failed"
1200 );
1201
1202 assert!(!request_object.is_empty());
1204 }
1205
1206 fn validate_fapi_request_object(
1208 request_object: &str,
1209 _config: &FapiConfig,
1210 ) -> Result<(), String> {
1211 let parsed: serde_json::Value = serde_json::from_str(request_object)
1213 .map_err(|_| "Invalid JSON structure in request object")?;
1214
1215 let required_claims = ["iss", "aud", "exp", "iat", "jti"];
1217 for claim in &required_claims {
1218 if parsed.get(claim).is_none() {
1219 return Err(format!("Missing required FAPI claim: {}", claim));
1220 }
1221 }
1222
1223 if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
1225 let now = chrono::Utc::now().timestamp();
1226 if exp <= now {
1227 return Err("Request object has expired".to_string());
1228 }
1229 }
1230
1231 Ok(())
1234 }
1235
1236 #[tokio::test]
1237 async fn test_fapi_response_generation() {
1238 let config = FapiConfig::default();
1241
1242 let auth_response = serde_json::json!({
1244 "code": "auth_code_123",
1245 "state": "client_state",
1246 "iss": config.issuer,
1247 "aud": "client_id",
1248 "exp": 9999999999i64
1249 });
1250
1251 assert!(auth_response["code"].is_string());
1253 }
1254
1255 #[tokio::test]
1256 async fn test_fapi_token_generation() {
1257 let config = FapiConfig::default();
1259
1260 let scopes = ["accounts".to_string(), "payments".to_string()];
1262 let client_id = "fapi_client_123";
1263 let user_id = "user_456";
1264 let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
1265
1266 assert!(config.require_dpop);
1268 assert!(config.require_mtls);
1269 assert!(!scopes.is_empty());
1270 assert!(!client_id.is_empty());
1271 assert!(!user_id.is_empty());
1272 assert!(cert_thumbprint.is_some());
1273 }
1274
1275 #[tokio::test]
1276 async fn test_fapi_session_management() {
1277 let config = FapiConfig::default();
1279
1280 let session_data = serde_json::json!({
1282 "client_id": "fapi_client",
1283 "user_id": "fapi_user",
1284 "scopes": ["accounts", "payments"],
1285 "mtls_cert": "client_certificate",
1286 "dpop_key": "client_dpop_key"
1287 });
1288
1289 assert!(session_data["mtls_cert"].is_string());
1291 assert!(session_data["dpop_key"].is_string());
1292 assert!(config.enhanced_audit);
1293 }
1294
1295 fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
1298 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1299 let mut dn = rcgen::DistinguishedName::new();
1300 dn.push(rcgen::DnType::CommonName, cn);
1301 if let Some(org) = org {
1302 dn.push(rcgen::DnType::OrganizationName, org);
1303 }
1304 params.distinguished_name = dn;
1305 let key = rcgen::KeyPair::generate().unwrap();
1306 params.self_signed(&key).unwrap()
1307 }
1308
1309 #[test]
1310 fn decode_client_certificate_accepts_pem_and_base64_der() {
1311 use base64::Engine;
1312 let cert = test_cert("client-a", None);
1313 let der = cert.der().to_vec();
1314
1315 assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
1316 let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
1317 assert_eq!(decode_client_certificate(&b64).unwrap(), der);
1318 let wrapped = format!(" {}\n{} \n", &b64[..20], &b64[20..]);
1319 assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
1320 }
1321
1322 #[test]
1323 fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
1324 let a = test_cert("client-a", None).pem();
1325 let b = test_cert("client-b", None).pem();
1326 assert!(decode_client_certificate("").is_err());
1327 assert!(decode_client_certificate("!!! not base64 !!!").is_err());
1328 assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
1329 assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
1331 }
1332
1333 #[test]
1334 fn client_id_comes_from_the_parsed_subject_cn() {
1335 let cert = test_cert("client-a", None);
1336 assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
1337 }
1338
1339 #[test]
1340 fn client_id_is_not_found_by_searching_the_raw_bytes() {
1341 let cert = test_cert("real-client", Some("CN=victim-client,"));
1344 assert_eq!(
1345 client_id_from_certificate(cert.der()).unwrap(),
1346 "real-client"
1347 );
1348 }
1349
1350 #[test]
1351 fn client_id_needs_a_unique_identity() {
1352 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1354 params.distinguished_name = rcgen::DistinguishedName::new(); let key = rcgen::KeyPair::generate().unwrap();
1356 let nameless = params.self_signed(&key).unwrap();
1357 assert!(client_id_from_certificate(nameless.der()).is_err());
1358 assert!(client_id_from_certificate(b"not a certificate").is_err());
1359 }
1360}