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(Debug, 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
61#[derive(Clone)]
63pub struct FapiConfig {
64 pub issuer: String,
66
67 pub request_signing_algorithm: Algorithm,
69
70 pub response_signing_algorithm: Algorithm,
72
73 pub private_key: EncodingKey,
75
76 pub public_key: DecodingKey,
78
79 pub max_request_age: i64,
81
82 pub require_dpop: bool,
84
85 pub require_mtls: bool,
87
88 pub require_par: bool,
90
91 pub enable_jarm: bool,
93
94 pub enhanced_audit: bool,
96}
97
98impl std::fmt::Debug for FapiConfig {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 f.debug_struct("FapiConfig")
101 .field("issuer", &self.issuer)
102 .field("request_signing_algorithm", &self.request_signing_algorithm)
103 .field(
104 "response_signing_algorithm",
105 &self.response_signing_algorithm,
106 )
107 .field("private_key", &"<EncodingKey>")
108 .field("public_key", &"<DecodingKey>")
109 .field("max_request_age", &self.max_request_age)
110 .field("require_dpop", &self.require_dpop)
111 .field("require_mtls", &self.require_mtls)
112 .field("require_par", &self.require_par)
113 .field("enable_jarm", &self.enable_jarm)
114 .field("enhanced_audit", &self.enhanced_audit)
115 .finish()
116 }
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct FapiSession {
122 pub session_id: String,
124
125 pub client_id: String,
127
128 pub user_id: String,
130
131 pub created_at: DateTime<Utc>,
133
134 pub expires_at: DateTime<Utc>,
136
137 pub dpop_proof: Option<String>,
139
140 pub cert_thumbprint: Option<String>,
142
143 pub request_jti: Option<String>,
145
146 pub scopes: Vec<String>,
148
149 pub metadata: HashMap<String, Value>,
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct FapiRequestObject {
156 pub iss: String,
158
159 pub aud: String,
161
162 pub iat: i64,
164
165 pub exp: i64,
167
168 pub nbf: Option<i64>,
170
171 pub jti: String,
173
174 pub response_type: String,
176
177 pub client_id: String,
179
180 pub redirect_uri: String,
182
183 pub scope: String,
185
186 pub state: Option<String>,
188
189 pub nonce: Option<String>,
191
192 pub code_challenge: Option<String>,
194
195 pub code_challenge_method: Option<String>,
197
198 #[serde(flatten)]
200 pub additional_claims: HashMap<String, Value>,
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct FapiAuthorizationResponse {
206 pub iss: String,
208
209 pub aud: String,
211
212 pub iat: i64,
214
215 pub exp: i64,
217
218 pub code: Option<String>,
220
221 pub state: Option<String>,
223
224 pub error: Option<String>,
226
227 pub error_description: Option<String>,
229
230 #[serde(flatten)]
232 pub additional_params: HashMap<String, Value>,
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize)]
237pub struct FapiTokenResponse {
238 pub access_token: String,
240
241 pub token_type: String,
243
244 pub expires_in: i64,
246
247 pub refresh_token: Option<String>,
249
250 pub scope: Option<String>,
252
253 pub id_token: Option<String>,
255
256 pub cnf: Option<Value>,
258}
259
260impl FapiManager {
261 pub fn new(
263 config: FapiConfig,
264 dpop_manager: Arc<DpopManager>,
265 mtls_manager: Arc<MutualTlsManager>,
266 par_manager: Arc<PARManager>,
267 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
268 jwt_validator: Arc<SecureJwtValidator>,
269 ) -> Self {
270 Self {
271 dpop_manager,
272 mtls_manager,
273 par_manager,
274 private_key_jwt_manager,
275 jwt_validator,
276 config,
277 sessions: Arc::new(RwLock::new(HashMap::new())),
278 }
279 }
280
281 pub async fn validate_authorization_request(
283 &self,
284 request_object: &str,
285 client_cert: Option<&str>,
286 dpop_proof: Option<&str>,
287 request_uri: Option<&str>,
288 ) -> Result<FapiRequestObject> {
289 let claims = if let Some(uri) = request_uri {
290 if self.config.require_par {
292 let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
294 AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
295 })?;
296
297 tracing::info!(
298 "FAPI PAR request consumed successfully for client: {}",
299 par_request.client_id
300 );
301
302 FapiRequestObject {
305 iss: par_request.client_id.clone(),
306 aud: self.config.issuer.clone(),
307 iat: Utc::now().timestamp(),
308 exp: Utc::now().timestamp() + 300, nbf: Some(Utc::now().timestamp()),
310 jti: uuid::Uuid::new_v4().to_string(),
311 response_type: par_request.response_type,
312 client_id: par_request.client_id,
313 redirect_uri: par_request.redirect_uri,
314 scope: par_request.scope.unwrap_or_default(),
315 state: par_request.state,
316 nonce: None, code_challenge: par_request.code_challenge,
318 code_challenge_method: par_request.code_challenge_method,
319 additional_claims: par_request
320 .additional_params
321 .into_iter()
322 .map(|(k, v)| (k, serde_json::Value::String(v)))
323 .collect(),
324 }
325 } else {
326 return Err(AuthError::InvalidRequest(
327 "request_uri provided but PAR not required".to_string(),
328 ));
329 }
330 } else {
331 if self.config.require_par {
333 return Err(AuthError::InvalidRequest(
334 "PAR is required but no request_uri provided".to_string(),
335 ));
336 }
337
338 self.validate_request_object(request_object).await?
340 };
341
342 if self.config.require_mtls {
344 let cert = client_cert.ok_or_else(|| {
345 AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
346 })?;
347 let cert_bytes = decode_client_certificate(cert)?;
348 self.mtls_manager
349 .validate_client_certificate(&cert_bytes, &claims.client_id)
350 .await?;
351 }
352
353 if self.config.require_dpop {
355 if dpop_proof.is_none() {
356 return Err(AuthError::auth_method(
357 "dpop",
358 "DPoP proof required for FAPI 2.0",
359 ));
360 }
361
362 let proof = dpop_proof.unwrap();
363 self.dpop_manager
364 .validate_dpop_proof(
365 proof,
366 "POST",
367 &format!("{}/authorize", self.config.issuer),
368 None,
369 None,
370 )
371 .await?;
372 }
373
374 self.validate_request_claims(&claims).await?;
376
377 Ok(claims)
378 }
379
380 async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
382 let decoding_key = &self.config.public_key;
384
385 match self
387 .jwt_validator
388 .validate_token(request_object, decoding_key, true)
389 {
390 Ok(secure_claims) => {
391 let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
393 AuthError::InvalidToken(format!("Invalid request object header: {}", e))
394 })?;
395
396 if !matches!(
398 header.alg,
399 Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
400 ) {
401 return Err(AuthError::InvalidToken(
402 "Request object must use RS256, PS256, or ES256".to_string(),
403 ));
404 }
405
406 let mut validation = Validation::new(header.alg);
408 validation.set_audience(&[&self.config.issuer]);
409 validation.validate_exp = true;
410 validation.validate_nbf = true;
411
412 let token_data = jsonwebtoken::decode::<FapiRequestObject>(
414 request_object,
415 &self.config.public_key,
416 &validation,
417 )
418 .map_err(|e| {
419 AuthError::InvalidToken(format!("Request object validation failed: {}", e))
420 })?;
421
422 let fapi_claims = token_data.claims;
423
424 if secure_claims.sub != fapi_claims.client_id {
427 return Err(AuthError::InvalidToken(
428 "Subject mismatch between secure validation and FAPI claims".to_string(),
429 ));
430 }
431
432 if secure_claims.iss != fapi_claims.iss {
434 return Err(AuthError::InvalidToken(
435 "Issuer mismatch between secure validation and FAPI claims".to_string(),
436 ));
437 }
438
439 if secure_claims.exp != fapi_claims.exp {
441 return Err(AuthError::InvalidToken(
442 "Expiry mismatch between secure validation and FAPI claims".to_string(),
443 ));
444 }
445
446 let now = Utc::now().timestamp();
448
449 if now - fapi_claims.iat > self.config.max_request_age {
451 return Err(AuthError::InvalidToken(
452 "Request object too old".to_string(),
453 ));
454 }
455
456 if fapi_claims.client_id.is_empty() {
458 return Err(AuthError::InvalidToken(
459 "client_id required in request object".to_string(),
460 ));
461 }
462
463 if fapi_claims.redirect_uri.is_empty() {
464 return Err(AuthError::InvalidToken(
465 "redirect_uri required in request object".to_string(),
466 ));
467 }
468
469 if fapi_claims.response_type.is_empty() {
470 return Err(AuthError::InvalidToken(
471 "response_type required in request object".to_string(),
472 ));
473 }
474
475 tracing::info!(
476 "FAPI request object validated successfully with SecureJwtValidator for client: {}",
477 fapi_claims.client_id
478 );
479
480 Ok(fapi_claims)
481 }
482 Err(e) => {
483 tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
484 Err(AuthError::InvalidToken(format!(
485 "Enhanced JWT validation failed: {}",
486 e
487 )))
488 }
489 }
490 }
491
492 async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
494 if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
496 return Err(AuthError::InvalidRequest(
497 "FAPI 2.0 requires code or code id_token response type".to_string(),
498 ));
499 }
500
501 if claims.code_challenge.is_none() {
503 return Err(AuthError::InvalidRequest(
504 "PKCE required for FAPI 2.0".to_string(),
505 ));
506 }
507
508 if let Some(method) = &claims.code_challenge_method {
509 if method != "S256" {
510 return Err(AuthError::InvalidRequest(
511 "FAPI 2.0 requires S256 code challenge method".to_string(),
512 ));
513 }
514 } else {
515 return Err(AuthError::InvalidRequest(
516 "code_challenge_method required for FAPI 2.0".to_string(),
517 ));
518 }
519
520 Ok(())
521 }
522
523 pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
528 const REFUSED: &str = "Client authentication failed";
529
530 let auth_result = match self
532 .private_key_jwt_manager
533 .authenticate_client(client_assertion)
534 .await
535 {
536 Ok(result) => result,
537 Err(e) => {
538 tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
539 return Err(AuthError::auth_method("private_key_jwt", REFUSED));
540 }
541 };
542
543 if auth_result.authenticated {
544 tracing::info!(
545 "FAPI client authenticated successfully using private key JWT: {}",
546 auth_result.client_id
547 );
548 Ok(auth_result.client_id)
549 } else {
550 tracing::warn!(
551 "FAPI private key JWT authentication failed: {}",
552 auth_result.errors.join("; ")
553 );
554 Err(AuthError::auth_method("private_key_jwt", REFUSED))
555 }
556 }
557
558 pub async fn validate_token_request(
560 &self,
561 client_assertion: Option<&str>,
562 client_cert: Option<&str>,
563 dpop_proof: Option<&str>,
564 authorization_code: &str,
565 ) -> Result<String> {
566 let client_id = if let Some(assertion) = client_assertion {
568 self.authenticate_client_jwt(assertion).await?
569 } else if self.config.require_mtls {
570 if let Some(cert) = client_cert {
571 let cert_bytes = decode_client_certificate(cert)?;
572
573 let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
576
577 self.mtls_manager
578 .validate_client_certificate(&cert_bytes, &client_id)
579 .await?;
580
581 client_id.to_string()
582 } else {
583 return Err(AuthError::auth_method(
584 "mtls",
585 "Client certificate required for FAPI 2.0 token request",
586 ));
587 }
588 } else {
589 return Err(AuthError::auth_method(
590 "fapi",
591 "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
592 ));
593 };
594
595 if self.config.require_dpop {
597 if dpop_proof.is_none() {
598 return Err(AuthError::auth_method(
599 "dpop",
600 "DPoP proof required for FAPI 2.0 token request",
601 ));
602 }
603
604 let proof = dpop_proof.unwrap();
605 self.dpop_manager
606 .validate_dpop_proof(
607 proof,
608 "POST",
609 &format!("{}/token", self.config.issuer),
610 Some(authorization_code), None,
612 )
613 .await?;
614 }
615
616 Ok(client_id)
617 }
618
619 pub async fn generate_authorization_response(
621 &self,
622 client_id: &str,
623 code: Option<&str>,
624 state: Option<&str>,
625 error: Option<&str>,
626 error_description: Option<&str>,
627 ) -> Result<String> {
628 if !self.config.enable_jarm {
629 return Err(AuthError::Configuration {
630 message: "JARM not enabled".to_string(),
631 help: Some("Enable JARM in your configuration to use this feature".to_string()),
632 docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
633 source: None,
634 suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
635 });
636 }
637
638 let now = Utc::now();
639 let exp = now + Duration::minutes(5); let response = FapiAuthorizationResponse {
642 iss: self.config.issuer.clone(),
643 aud: client_id.to_string(),
644 iat: now.timestamp(),
645 exp: exp.timestamp(),
646 code: code.map(|c| c.to_string()),
647 state: state.map(|s| s.to_string()),
648 error: error.map(|e| e.to_string()),
649 error_description: error_description.map(|d| d.to_string()),
650 additional_params: HashMap::new(),
651 };
652
653 let header = Header::new(self.config.response_signing_algorithm);
655
656 let token =
658 jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
659 AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
660 })?;
661
662 Ok(token)
663 }
664
665 pub async fn generate_token_response(
667 &self,
668 client_id: &str,
669 user_id: &str,
670 scopes: Vec<String>,
671 cert_thumbprint: Option<String>,
672 dpop_jkt: Option<String>,
673 ) -> Result<FapiTokenResponse> {
674 let access_token = self
676 .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
677 .await?;
678
679 let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
681
682 let mut cnf = json!({});
684
685 if let Some(thumbprint) = cert_thumbprint {
686 cnf["x5t#S256"] = Value::String(thumbprint);
687 }
688
689 if let Some(jkt) = dpop_jkt {
690 cnf["jkt"] = Value::String(jkt);
691 }
692
693 let response = FapiTokenResponse {
694 access_token,
695 token_type: "DPoP".to_string(), expires_in: 3600, refresh_token: Some(refresh_token),
698 scope: Some(scopes.join(" ")),
699 id_token: None, cnf: if cnf.as_object().unwrap().is_empty() {
701 None
702 } else {
703 Some(cnf)
704 },
705 };
706
707 Ok(response)
708 }
709
710 async fn generate_access_token(
712 &self,
713 client_id: &str,
714 user_id: &str,
715 scopes: &[String],
716 cert_thumbprint: &Option<String>,
717 dpop_jkt: &Option<String>,
718 ) -> Result<String> {
719 let now = Utc::now();
720 let exp = now + Duration::hours(1);
721
722 let mut claims = json!({
723 "iss": self.config.issuer,
724 "aud": client_id,
725 "sub": user_id,
726 "iat": now.timestamp(),
727 "exp": exp.timestamp(),
728 "scope": scopes.join(" "),
729 "jti": Uuid::new_v4().to_string(),
730 });
731
732 let mut cnf = json!({});
734
735 if let Some(thumbprint) = cert_thumbprint {
736 cnf["x5t#S256"] = Value::String(thumbprint.clone());
737 }
738
739 if let Some(jkt) = dpop_jkt {
740 cnf["jkt"] = Value::String(jkt.clone());
741 }
742
743 if !cnf.as_object().unwrap().is_empty() {
744 claims["cnf"] = cnf;
745 }
746
747 let header = Header::new(Algorithm::RS256);
749
750 let token =
752 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
753 AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
754 })?;
755
756 Ok(token)
757 }
758
759 async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
761 let now = Utc::now();
762 let exp = now + Duration::days(30); let claims = json!({
765 "iss": self.config.issuer,
766 "aud": client_id,
767 "sub": user_id,
768 "iat": now.timestamp(),
769 "exp": exp.timestamp(),
770 "typ": "refresh_token",
771 "jti": Uuid::new_v4().to_string(),
772 });
773
774 let header = Header::new(Algorithm::RS256);
776
777 let token =
779 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
780 AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
781 })?;
782
783 Ok(token)
784 }
785
786 pub async fn create_session(
788 &self,
789 client_id: &str,
790 user_id: &str,
791 scopes: Vec<String>,
792 dpop_proof: Option<String>,
793 cert_thumbprint: Option<String>,
794 request_jti: Option<String>,
795 ) -> Result<String> {
796 let session_id = Uuid::new_v4().to_string();
797 let now = Utc::now();
798 let expires_at = now + Duration::hours(24); let session = FapiSession {
801 session_id: session_id.clone(),
802 client_id: client_id.to_string(),
803 user_id: user_id.to_string(),
804 created_at: now,
805 expires_at,
806 dpop_proof,
807 cert_thumbprint,
808 request_jti,
809 scopes,
810 metadata: HashMap::new(),
811 };
812
813 let mut sessions = self.sessions.write().await;
814 sessions.insert(session_id.clone(), session);
815
816 Ok(session_id)
817 }
818
819 pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
821 let sessions = self.sessions.read().await;
822 Ok(sessions.get(session_id).cloned())
823 }
824
825 pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
827 let session = self
828 .get_session(session_id)
829 .await?
830 .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
831
832 if Utc::now() > session.expires_at {
834 return Err(AuthError::validation("Session expired".to_string()));
835 }
836
837 Ok(session)
838 }
839
840 pub async fn remove_session(&self, session_id: &str) -> Result<()> {
842 let mut sessions = self.sessions.write().await;
843 sessions.remove(session_id);
844 Ok(())
845 }
846
847 pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
849 if self.config.enhanced_audit {
850 let timestamp = chrono::Utc::now().to_rfc3339();
854 let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
855
856 log::info!("{}", audit_entry);
858 }
859 Ok(())
860 }
861
862 async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
864 client_id_from_certificate(cert_bytes)
865 }
866}
867
868impl Default for FapiConfig {
869 fn default() -> Self {
870 let issuer =
872 std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
873
874 let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
876 std::fs::read(&key_path)
877 .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
878 .and_then(|bytes| {
879 EncodingKey::from_rsa_pem(&bytes)
880 .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
881 })
882 .unwrap_or_else(|_| EncodingKey::from_secret(b"dev_fallback_secret"))
883 } else {
884 EncodingKey::from_secret(b"dev_fallback_secret")
885 };
886
887 Self {
888 issuer,
889 request_signing_algorithm: Algorithm::RS256,
890 response_signing_algorithm: Algorithm::RS256,
891 private_key,
892 public_key: DecodingKey::from_secret(b"dev_secret"),
893 max_request_age: 300, require_dpop: true,
895 require_mtls: true,
896 require_par: true,
897 enable_jarm: true,
898 enhanced_audit: true,
899 }
900 }
901}
902
903fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
908 use base64::Engine;
909 use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
910
911 const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
912 const END: &str = "-----END CERTIFICATE-----";
913 let bad = || {
914 AuthError::auth_method(
915 "mtls",
916 "Client certificate must be PEM or base64-encoded DER",
917 )
918 };
919
920 let trimmed = input.trim();
921 let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
922 let end = rest.find(END).ok_or_else(bad)?;
923 if !rest[end + END.len()..].trim().is_empty() {
925 return Err(bad());
926 }
927 &rest[..end]
928 } else {
929 trimmed
930 };
931 let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
932 if compact.is_empty() {
933 return Err(bad());
934 }
935 STANDARD
936 .decode(&compact)
937 .or_else(|_| STANDARD_NO_PAD.decode(&compact))
938 .or_else(|_| URL_SAFE.decode(&compact))
939 .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
940 .map_err(|_| bad())
941}
942
943fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
946 use x509_parser::extensions::GeneralName;
947
948 let cert = match x509_parser::parse_x509_certificate(cert_der) {
949 Ok(([], cert)) => cert,
950 _ => {
951 return Err(AuthError::auth_method(
952 "mtls",
953 "Invalid client certificate format",
954 ));
955 }
956 };
957
958 let common_names: Vec<String> = cert
959 .subject()
960 .iter_common_name()
961 .filter_map(|cn| cn.as_str().ok().map(str::to_string))
962 .collect();
963 if common_names.len() == 1 && !common_names[0].is_empty() {
964 return Ok(common_names[0].clone());
965 }
966
967 if let Ok(Some(san)) = cert.subject_alternative_name() {
968 let names: Vec<String> = san
969 .value
970 .general_names
971 .iter()
972 .filter_map(|name| match name {
973 GeneralName::DNSName(dns) => Some(dns.to_string()),
974 GeneralName::URI(uri) => Some(uri.to_string()),
975 _ => None,
976 })
977 .collect();
978 if names.len() == 1 {
979 return Ok(names[0].clone());
980 }
981 }
982
983 Err(AuthError::auth_method(
984 "mtls",
985 "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
986 ))
987}
988
989#[cfg(test)]
990mod tests {
991 use super::*;
992
993 #[tokio::test]
994 async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
995 use crate::security::secure_jwt::SecureJwtConfig;
996 use crate::server::jwt::private_key_jwt::ClientJwtConfig;
997 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
998
999 let validator = || SecureJwtValidator::new(SecureJwtConfig::default());
1000 let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1001 let manager = FapiManager::new(
1002 FapiConfig::default(),
1003 Arc::new(DpopManager::new(validator())),
1004 Arc::new(MutualTlsManager::new()),
1005 Arc::new(PARManager::new(Arc::new(
1006 crate::storage::MemoryStorage::new(),
1007 ))),
1008 assertions.clone(),
1009 Arc::new(validator()),
1010 );
1011
1012 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1014 let raw = key.public_key_raw();
1015 let point = &raw[raw.len() - 65..];
1016 let jwk = json!({
1017 "kty": "EC", "crv": "P-256",
1018 "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1019 "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1020 });
1021 assertions
1022 .register_client(
1023 ClientJwtConfig::builder("fapi-client", jwk)
1024 .algorithms(vec![Algorithm::ES256])
1025 .audience("https://auth.example.com/token")
1026 .build(),
1027 )
1028 .await
1029 .unwrap();
1030 let signing_pem = key.serialize_pem();
1031
1032 let good = assertions
1034 .create_client_assertion(
1035 "fapi-client",
1036 "https://auth.example.com/token",
1037 signing_pem.as_bytes(),
1038 Algorithm::ES256,
1039 )
1040 .unwrap();
1041 assert_eq!(
1042 manager.authenticate_client_jwt(&good).await.unwrap(),
1043 "fapi-client"
1044 );
1045
1046 let wrong_audience = assertions
1049 .create_client_assertion(
1050 "fapi-client",
1051 "https://elsewhere.example/token",
1052 signing_pem.as_bytes(),
1053 Algorithm::ES256,
1054 )
1055 .unwrap();
1056 let unknown = assertions
1057 .create_client_assertion(
1058 "ghost",
1059 "https://auth.example.com/token",
1060 signing_pem.as_bytes(),
1061 Algorithm::ES256,
1062 )
1063 .unwrap();
1064 for (why, assertion) in [
1065 ("wrong audience", wrong_audience.as_str()),
1066 ("unknown client", unknown.as_str()),
1067 ("replay", good.as_str()),
1068 ("junk", "not-a-jwt"),
1069 ] {
1070 let message = manager
1071 .authenticate_client_jwt(assertion)
1072 .await
1073 .expect_err(why)
1074 .to_string();
1075 assert!(
1076 message.contains("Client authentication failed"),
1077 "{why}: {message}"
1078 );
1079 for leak in [
1080 "udience",
1081 "registered",
1082 "ignature",
1083 "replay",
1084 "JTI",
1085 "Algorithm",
1086 "expired",
1087 ] {
1088 assert!(
1089 !message.contains(leak),
1090 "{why}: {message:?} mentions {leak:?}"
1091 );
1092 }
1093 }
1094 }
1095
1096 #[tokio::test]
1097 async fn test_fapi_manager_creation() {
1098 let config = FapiConfig::default();
1100
1101 assert_eq!(config.issuer, "https://auth.example.com"); assert!(config.require_dpop);
1104 assert!(config.require_mtls);
1105 assert!(config.require_par);
1106 assert!(config.enable_jarm);
1107 assert!(config.enhanced_audit);
1108 }
1109
1110 #[tokio::test]
1111 async fn test_fapi_request_validation() {
1112 let config = FapiConfig::default();
1115
1116 let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1118
1119 let validation_result = validate_fapi_request_object(request_object, &config);
1121 assert!(
1122 validation_result.is_ok(),
1123 "FAPI request object validation failed"
1124 );
1125
1126 assert!(!request_object.is_empty());
1128 }
1129
1130 fn validate_fapi_request_object(
1132 request_object: &str,
1133 _config: &FapiConfig,
1134 ) -> Result<(), String> {
1135 let parsed: serde_json::Value = serde_json::from_str(request_object)
1137 .map_err(|_| "Invalid JSON structure in request object")?;
1138
1139 let required_claims = ["iss", "aud", "exp", "iat", "jti"];
1141 for claim in &required_claims {
1142 if parsed.get(claim).is_none() {
1143 return Err(format!("Missing required FAPI claim: {}", claim));
1144 }
1145 }
1146
1147 if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
1149 let now = chrono::Utc::now().timestamp();
1150 if exp <= now {
1151 return Err("Request object has expired".to_string());
1152 }
1153 }
1154
1155 Ok(())
1158 }
1159
1160 #[tokio::test]
1161 async fn test_fapi_response_generation() {
1162 let config = FapiConfig::default();
1165
1166 let auth_response = serde_json::json!({
1168 "code": "auth_code_123",
1169 "state": "client_state",
1170 "iss": config.issuer,
1171 "aud": "client_id",
1172 "exp": 9999999999i64
1173 });
1174
1175 assert!(auth_response["code"].is_string());
1177 }
1178
1179 #[tokio::test]
1180 async fn test_fapi_token_generation() {
1181 let config = FapiConfig::default();
1183
1184 let scopes = ["accounts".to_string(), "payments".to_string()];
1186 let client_id = "fapi_client_123";
1187 let user_id = "user_456";
1188 let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
1189
1190 assert!(config.require_dpop);
1192 assert!(config.require_mtls);
1193 assert!(!scopes.is_empty());
1194 assert!(!client_id.is_empty());
1195 assert!(!user_id.is_empty());
1196 assert!(cert_thumbprint.is_some());
1197 }
1198
1199 #[tokio::test]
1200 async fn test_fapi_session_management() {
1201 let config = FapiConfig::default();
1203
1204 let session_data = serde_json::json!({
1206 "client_id": "fapi_client",
1207 "user_id": "fapi_user",
1208 "scopes": ["accounts", "payments"],
1209 "mtls_cert": "client_certificate",
1210 "dpop_key": "client_dpop_key"
1211 });
1212
1213 assert!(session_data["mtls_cert"].is_string());
1215 assert!(session_data["dpop_key"].is_string());
1216 assert!(config.enhanced_audit);
1217 }
1218
1219 fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
1222 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1223 let mut dn = rcgen::DistinguishedName::new();
1224 dn.push(rcgen::DnType::CommonName, cn);
1225 if let Some(org) = org {
1226 dn.push(rcgen::DnType::OrganizationName, org);
1227 }
1228 params.distinguished_name = dn;
1229 let key = rcgen::KeyPair::generate().unwrap();
1230 params.self_signed(&key).unwrap()
1231 }
1232
1233 #[test]
1234 fn decode_client_certificate_accepts_pem_and_base64_der() {
1235 use base64::Engine;
1236 let cert = test_cert("client-a", None);
1237 let der = cert.der().to_vec();
1238
1239 assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
1240 let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
1241 assert_eq!(decode_client_certificate(&b64).unwrap(), der);
1242 let wrapped = format!(" {}\n{} \n", &b64[..20], &b64[20..]);
1243 assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
1244 }
1245
1246 #[test]
1247 fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
1248 let a = test_cert("client-a", None).pem();
1249 let b = test_cert("client-b", None).pem();
1250 assert!(decode_client_certificate("").is_err());
1251 assert!(decode_client_certificate("!!! not base64 !!!").is_err());
1252 assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
1253 assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
1255 }
1256
1257 #[test]
1258 fn client_id_comes_from_the_parsed_subject_cn() {
1259 let cert = test_cert("client-a", None);
1260 assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
1261 }
1262
1263 #[test]
1264 fn client_id_is_not_found_by_searching_the_raw_bytes() {
1265 let cert = test_cert("real-client", Some("CN=victim-client,"));
1268 assert_eq!(
1269 client_id_from_certificate(cert.der()).unwrap(),
1270 "real-client"
1271 );
1272 }
1273
1274 #[test]
1275 fn client_id_needs_a_unique_identity() {
1276 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1278 params.distinguished_name = rcgen::DistinguishedName::new(); let key = rcgen::KeyPair::generate().unwrap();
1280 let nameless = params.self_signed(&key).unwrap();
1281 assert!(client_id_from_certificate(nameless.der()).is_err());
1282 assert!(client_id_from_certificate(b"not a certificate").is_err());
1283 }
1284}