1use crate::distributed::rate_limiting::{DistributedRateLimiter, RateLimitResult};
28use crate::errors::{AuthError, Result};
29use crate::security::secure_jwt::SecureJwtValidator;
30use crate::server::{DpopManager, MutualTlsManager, PARManager, PrivateKeyJwtManager};
31use chrono::{DateTime, Duration, Utc};
32use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
33use serde::{Deserialize, Serialize};
34use serde_json::{Value, json};
35use std::collections::HashMap;
36use std::sync::Arc;
37use tokio::sync::RwLock;
38use uuid::Uuid;
39
40#[derive(Clone)]
56pub struct FapiManager {
57 dpop_manager: Arc<DpopManager>,
59
60 mtls_manager: Arc<MutualTlsManager>,
62
63 par_manager: Arc<PARManager>,
65
66 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
68
69 jwt_validator: Arc<SecureJwtValidator>,
71
72 config: FapiConfig,
74
75 sessions: Arc<RwLock<HashMap<String, FapiSession>>>,
77
78 rate_limiter: Option<Arc<DistributedRateLimiter>>,
80}
81
82impl std::fmt::Debug for FapiManager {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 let mut d = f.debug_struct("FapiManager");
85 d.field("dpop_manager", &self.dpop_manager);
86 d.field("mtls_manager", &self.mtls_manager);
87 d.field("par_manager", &self.par_manager);
88 d.field("private_key_jwt_manager", &self.private_key_jwt_manager);
89 d.field("jwt_validator", &self.jwt_validator);
90 d.field("config", &self.config);
91 d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
92 d.field("rate_limiter", &self.rate_limiter.is_some());
93 d.finish()
94 }
95}
96
97#[derive(Clone)]
99pub struct FapiConfig {
100 pub issuer: String,
102
103 pub request_signing_algorithm: Algorithm,
105
106 pub response_signing_algorithm: Algorithm,
108
109 pub private_key: EncodingKey,
111
112 pub public_key: DecodingKey,
114
115 pub max_request_age: i64,
117
118 pub require_dpop: bool,
120
121 pub require_mtls: bool,
123
124 pub require_par: bool,
126
127 pub enable_jarm: bool,
129
130 pub enhanced_audit: bool,
132
133 pub is_degraded: bool,
137}
138
139impl std::fmt::Debug for FapiConfig {
140 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141 f.debug_struct("FapiConfig")
142 .field("issuer", &self.issuer)
143 .field("request_signing_algorithm", &self.request_signing_algorithm)
144 .field(
145 "response_signing_algorithm",
146 &self.response_signing_algorithm,
147 )
148 .field("private_key", &"<EncodingKey>")
149 .field("public_key", &"<DecodingKey>")
150 .field("max_request_age", &self.max_request_age)
151 .field("require_dpop", &self.require_dpop)
152 .field("require_mtls", &self.require_mtls)
153 .field("require_par", &self.require_par)
154 .field("enable_jarm", &self.enable_jarm)
155 .field("enhanced_audit", &self.enhanced_audit)
156 .field("is_degraded", &self.is_degraded)
157 .finish()
158 }
159}
160
161impl FapiConfig {
162 pub fn builder(
166 issuer: impl Into<String>,
167 private_key: EncodingKey,
168 public_key: DecodingKey,
169 ) -> FapiConfigBuilder {
170 FapiConfigBuilder {
171 issuer: issuer.into(),
172 request_signing_algorithm: Algorithm::PS256,
173 response_signing_algorithm: Algorithm::PS256,
174 private_key,
175 public_key,
176 max_request_age: 60,
177 require_dpop: true,
178 require_mtls: true,
179 require_par: true,
180 enable_jarm: true,
181 enhanced_audit: true,
182 is_degraded: false,
183 }
184 }
185
186 #[deprecated(since = "0.5.0", note = "use FapiConfig::from_env() instead")]
188 pub fn load_from_env() -> Self {
189 Self::from_env()
190 }
191
192 pub fn from_env() -> Self {
196 Self::default()
197 }
198}
199
200pub struct FapiConfigBuilder {
202 issuer: String,
203 request_signing_algorithm: Algorithm,
204 response_signing_algorithm: Algorithm,
205 private_key: EncodingKey,
206 public_key: DecodingKey,
207 max_request_age: i64,
208 require_dpop: bool,
209 require_mtls: bool,
210 require_par: bool,
211 enable_jarm: bool,
212 enhanced_audit: bool,
213 is_degraded: bool,
214}
215
216impl FapiConfigBuilder {
217 pub fn request_signing_algorithm(mut self, alg: Algorithm) -> Self {
221 self.request_signing_algorithm = alg;
222 self
223 }
224
225 pub fn response_signing_algorithm(mut self, alg: Algorithm) -> Self {
227 self.response_signing_algorithm = alg;
228 self
229 }
230
231 pub fn max_request_age(mut self, age: i64) -> Self {
233 self.max_request_age = age;
234 self
235 }
236
237 pub fn require_dpop(mut self, require: bool) -> Self {
239 self.require_dpop = require;
240 self
241 }
242
243 pub fn require_mtls(mut self, require: bool) -> Self {
245 self.require_mtls = require;
246 self
247 }
248
249 pub fn require_par(mut self, require: bool) -> Self {
251 self.require_par = require;
252 self
253 }
254
255 pub fn enable_jarm(mut self, enable: bool) -> Self {
257 self.enable_jarm = enable;
258 self
259 }
260
261 pub fn enhanced_audit(mut self, enable: bool) -> Self {
263 self.enhanced_audit = enable;
264 self
265 }
266
267 pub fn degraded(mut self) -> Self {
269 self.is_degraded = true;
270 self
271 }
272
273 pub fn build(self) -> FapiConfig {
275 FapiConfig {
276 issuer: self.issuer,
277 request_signing_algorithm: self.request_signing_algorithm,
278 response_signing_algorithm: self.response_signing_algorithm,
279 private_key: self.private_key,
280 public_key: self.public_key,
281 max_request_age: self.max_request_age,
282 require_dpop: self.require_dpop,
283 require_mtls: self.require_mtls,
284 require_par: self.require_par,
285 enable_jarm: self.enable_jarm,
286 enhanced_audit: self.enhanced_audit,
287 is_degraded: self.is_degraded,
288 }
289 }
290}
291
292#[derive(Clone, Serialize, Deserialize)]
294pub struct FapiSession {
295 pub session_id: String,
297
298 pub client_id: String,
300
301 pub user_id: String,
303
304 pub created_at: DateTime<Utc>,
306
307 pub expires_at: DateTime<Utc>,
309
310 pub dpop_proof: Option<String>,
312
313 pub cert_thumbprint: Option<String>,
315
316 pub request_jti: Option<String>,
318
319 pub scopes: Vec<String>,
321
322 pub metadata: HashMap<String, Value>,
324}
325
326impl std::fmt::Debug for FapiSession {
327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328 let mut d = f.debug_struct("FapiSession");
329 d.field(
330 "session_id",
331 &crate::utils::redact::redacted(&self.session_id),
332 );
333 d.field("client_id", &self.client_id);
334 d.field("user_id", &self.user_id);
335 d.field("created_at", &self.created_at);
336 d.field("expires_at", &self.expires_at);
337 d.field(
338 "dpop_proof",
339 &crate::utils::redact::redacted(&self.dpop_proof),
340 );
341 d.field("cert_thumbprint", &self.cert_thumbprint);
342 d.field("request_jti", &self.request_jti);
343 d.field("scopes", &self.scopes);
344 d.field("metadata", &self.metadata);
345 d.finish()
346 }
347}
348
349impl FapiSession {
350 pub fn builder(
352 session_id: impl Into<String>,
353 client_id: impl Into<String>,
354 user_id: impl Into<String>,
355 expires_in: Duration,
356 ) -> FapiSessionBuilder {
357 let now = Utc::now();
358 FapiSessionBuilder {
359 session_id: session_id.into(),
360 client_id: client_id.into(),
361 user_id: user_id.into(),
362 created_at: now,
363 expires_at: now + expires_in,
364 dpop_proof: None,
365 cert_thumbprint: None,
366 request_jti: None,
367 scopes: Vec::new(),
368 metadata: HashMap::new(),
369 }
370 }
371}
372
373pub struct FapiSessionBuilder {
375 session_id: String,
376 client_id: String,
377 user_id: String,
378 created_at: DateTime<Utc>,
379 expires_at: DateTime<Utc>,
380 dpop_proof: Option<String>,
381 cert_thumbprint: Option<String>,
382 request_jti: Option<String>,
383 scopes: Vec<String>,
384 metadata: HashMap<String, Value>,
385}
386
387impl FapiSessionBuilder {
388 pub fn dpop_proof(mut self, proof: impl Into<String>) -> Self {
390 self.dpop_proof = Some(proof.into());
391 self
392 }
393
394 pub fn cert_thumbprint(mut self, thumbprint: impl Into<String>) -> Self {
396 self.cert_thumbprint = Some(thumbprint.into());
397 self
398 }
399
400 pub fn request_jti(mut self, jti: impl Into<String>) -> Self {
402 self.request_jti = Some(jti.into());
403 self
404 }
405
406 pub fn add_scope(mut self, scope: impl Into<String>) -> Self {
408 self.scopes.push(scope.into());
409 self
410 }
411
412 pub fn add_scopes<I, S>(mut self, scopes: I) -> Self
414 where
415 I: IntoIterator<Item = S>,
416 S: Into<String>,
417 {
418 self.scopes.extend(scopes.into_iter().map(Into::into));
419 self
420 }
421
422 pub fn add_metadata(mut self, key: impl Into<String>, value: Value) -> Self {
424 self.metadata.insert(key.into(), value);
425 self
426 }
427
428 pub fn build(self) -> FapiSession {
430 FapiSession {
431 session_id: self.session_id,
432 client_id: self.client_id,
433 user_id: self.user_id,
434 created_at: self.created_at,
435 expires_at: self.expires_at,
436 dpop_proof: self.dpop_proof,
437 cert_thumbprint: self.cert_thumbprint,
438 request_jti: self.request_jti,
439 scopes: self.scopes,
440 metadata: self.metadata,
441 }
442 }
443}
444
445#[derive(Debug, Clone, Serialize, Deserialize)]
447pub struct FapiRequestObject {
448 pub iss: String,
450
451 pub aud: String,
453
454 pub iat: i64,
456
457 pub exp: i64,
459
460 pub nbf: Option<i64>,
462
463 pub jti: String,
465
466 pub response_type: String,
468
469 pub client_id: String,
471
472 pub redirect_uri: String,
474
475 pub scope: String,
477
478 pub state: Option<String>,
480
481 pub nonce: Option<String>,
483
484 pub code_challenge: Option<String>,
486
487 pub code_challenge_method: Option<String>,
489
490 #[serde(flatten)]
492 pub additional_claims: HashMap<String, Value>,
493}
494
495#[derive(Clone, Serialize, Deserialize)]
497pub struct FapiAuthorizationResponse {
498 pub iss: String,
500
501 pub aud: String,
503
504 pub iat: i64,
506
507 pub exp: i64,
509
510 pub code: Option<String>,
512
513 pub state: Option<String>,
515
516 pub error: Option<String>,
518
519 pub error_description: Option<String>,
521
522 #[serde(flatten)]
524 pub additional_params: HashMap<String, Value>,
525}
526
527impl std::fmt::Debug for FapiAuthorizationResponse {
528 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
529 let mut d = f.debug_struct("FapiAuthorizationResponse");
530 d.field("iss", &self.iss);
531 d.field("aud", &self.aud);
532 d.field("iat", &self.iat);
533 d.field("exp", &self.exp);
534 d.field("code", &crate::utils::redact::redacted(&self.code));
535 d.field("state", &self.state);
536 d.field("error", &self.error);
537 d.field("error_description", &self.error_description);
538 d.field(
539 "additional_params",
540 &crate::utils::redact::redacted(&self.additional_params),
541 );
542 d.finish()
543 }
544}
545
546#[derive(Clone, Serialize, Deserialize)]
548pub struct FapiTokenResponse {
549 pub access_token: String,
551
552 pub token_type: String,
554
555 pub expires_in: i64,
557
558 pub refresh_token: Option<String>,
560
561 pub scope: Option<String>,
563
564 pub id_token: Option<String>,
566
567 pub cnf: Option<Value>,
569}
570
571impl std::fmt::Debug for FapiTokenResponse {
572 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
573 let mut d = f.debug_struct("FapiTokenResponse");
574 d.field(
575 "access_token",
576 &crate::utils::redact::redacted(&self.access_token),
577 );
578 d.field("token_type", &self.token_type);
579 d.field("expires_in", &self.expires_in);
580 d.field(
581 "refresh_token",
582 &crate::utils::redact::redacted(&self.refresh_token),
583 );
584 d.field("scope", &self.scope);
585 d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
586 d.field("cnf", &self.cnf);
587 d.finish()
588 }
589}
590
591fn request_object_too_old(now: i64, iat: i64, max_age: i64) -> bool {
593 now.checked_sub(iat).is_none_or(|age| age > max_age)
594}
595
596impl FapiManager {
597 pub fn new(
599 config: FapiConfig,
600 dpop_manager: Arc<DpopManager>,
601 mtls_manager: Arc<MutualTlsManager>,
602 par_manager: Arc<PARManager>,
603 private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
604 jwt_validator: Arc<SecureJwtValidator>,
605 ) -> Self {
606 Self {
607 dpop_manager,
608 mtls_manager,
609 par_manager,
610 private_key_jwt_manager,
611 jwt_validator,
612 config,
613 sessions: Arc::new(RwLock::new(HashMap::new())),
614 rate_limiter: None,
615 }
616 }
617
618 #[must_use]
626 pub fn with_rate_limiter(mut self, limiter: Arc<DistributedRateLimiter>) -> Self {
627 self.rate_limiter = Some(limiter);
628 self
629 }
630
631 fn limiter_outcome(what: &str, outcome: Result<RateLimitResult>) -> Result<()> {
633 match outcome {
634 Ok(RateLimitResult::Allowed { .. }) => Ok(()),
635 Ok(RateLimitResult::Denied { retry_after, .. }) => {
636 tracing::warn!(bucket = %what, "FAPI rate limit exceeded");
637 Err(AuthError::rate_limit(format!(
638 "Rate limit exceeded; retry after {} seconds",
639 retry_after.as_secs().max(1)
640 )))
641 }
642 Ok(RateLimitResult::Blocked { unblock_at, .. }) => {
643 tracing::warn!(bucket = %what, "FAPI rate limit: caller blocked");
644 let secs = unblock_at
645 .checked_duration_since(std::time::Instant::now())
646 .map_or(1, |d| d.as_secs().max(1));
647 Err(AuthError::rate_limit(format!(
648 "Rate limit exceeded; retry after {secs} seconds"
649 )))
650 }
651 Err(e) => {
652 tracing::error!(error = %e, bucket = %what, "FAPI rate limiter error");
653 Err(AuthError::internal("Rate limiter unavailable"))
654 }
655 }
656 }
657
658 async fn count(&self, key: String) -> Result<()> {
660 match &self.rate_limiter {
661 Some(limiter) => Self::limiter_outcome(&key, limiter.check_rate_limit(&key).await),
662 None => Ok(()),
663 }
664 }
665
666 pub async fn validate_authorization_request_from(
669 &self,
670 peer: &str,
671 request_object: &str,
672 client_cert: Option<&str>,
673 dpop_proof: Option<&str>,
674 request_uri: Option<&str>,
675 ) -> Result<FapiRequestObject> {
676 self.count(format!("fapi:authorize:{peer}")).await?;
677 let request = self
678 .validate_authorization_request(request_object, client_cert, dpop_proof, request_uri)
679 .await?;
680 self.count(format!("fapi_client:{}", request.client_id))
681 .await?;
682 Ok(request)
683 }
684
685 pub async fn validate_authorization_request(
687 &self,
688 request_object: &str,
689 client_cert: Option<&str>,
690 dpop_proof: Option<&str>,
691 request_uri: Option<&str>,
692 ) -> Result<FapiRequestObject> {
693 let claims = if let Some(uri) = request_uri {
694 if self.config.require_par {
696 let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
698 AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
699 })?;
700
701 tracing::info!(
702 "FAPI PAR request consumed successfully for client: {}",
703 par_request.client_id
704 );
705
706 let nonce = par_request.additional_params.get("nonce").cloned();
708 FapiRequestObject {
709 iss: par_request.client_id.clone(),
710 aud: self.config.issuer.clone(),
711 iat: Utc::now().timestamp(),
712 exp: Utc::now().timestamp() + 300, nbf: Some(Utc::now().timestamp()),
714 jti: uuid::Uuid::new_v4().to_string(),
715 response_type: par_request.response_type,
716 client_id: par_request.client_id,
717 redirect_uri: par_request.redirect_uri,
718 scope: par_request.scope.unwrap_or_default(),
719 state: par_request.state,
720 nonce,
721 code_challenge: par_request.code_challenge,
722 code_challenge_method: par_request.code_challenge_method,
723 additional_claims: par_request
724 .additional_params
725 .into_iter()
726 .map(|(k, v)| (k, serde_json::Value::String(v)))
727 .collect(),
728 }
729 } else {
730 return Err(AuthError::InvalidRequest(
731 "request_uri provided but PAR not required".to_string(),
732 ));
733 }
734 } else {
735 if self.config.require_par {
737 return Err(AuthError::InvalidRequest(
738 "PAR is required but no request_uri provided".to_string(),
739 ));
740 }
741
742 self.validate_request_object(request_object).await?
744 };
745
746 if self.config.require_mtls {
748 let cert = client_cert.ok_or_else(|| {
749 AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
750 })?;
751 let cert_bytes = decode_client_certificate(cert)?;
752 self.mtls_manager
753 .validate_client_certificate(&cert_bytes, &claims.client_id)
754 .await?;
755 }
756
757 let pending_proof = if self.config.require_dpop {
759 let proof = dpop_proof.ok_or_else(|| {
760 AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0")
761 })?;
762 Some(
763 self.dpop_manager
764 .verify_dpop_proof(
765 proof,
766 "POST",
767 &format!("{}/authorize", self.config.issuer),
768 None,
769 None,
770 None,
771 )
772 .await?,
773 )
774 } else {
775 None
776 };
777
778 self.validate_request_claims(&claims).await?;
780
781 if let Some(pending) = pending_proof {
782 self.dpop_manager.commit_dpop_proof(pending).await?;
783 }
784
785 Ok(claims)
786 }
787
788 async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
790 let decoding_key = &self.config.public_key;
792
793 match self
795 .jwt_validator
796 .validate_token(request_object, decoding_key)
797 {
798 Ok(secure_claims) => {
799 let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
801 AuthError::token(format!("Invalid request object header: {}", e))
802 })?;
803
804 if !matches!(
806 header.alg,
807 Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
808 ) {
809 return Err(AuthError::token(
810 "Request object must use RS256, PS256, or ES256".to_string(),
811 ));
812 }
813
814 let mut validation = Validation::new(header.alg);
816 validation.set_audience(&[&self.config.issuer]);
817 validation.validate_exp = true;
818 validation.validate_nbf = true;
819
820 let token_data = jsonwebtoken::decode::<FapiRequestObject>(
822 request_object,
823 &self.config.public_key,
824 &validation,
825 )
826 .map_err(|e| {
827 AuthError::token(format!("Request object validation failed: {}", e))
828 })?;
829
830 let fapi_claims = token_data.claims;
831
832 if secure_claims.sub != fapi_claims.client_id {
835 return Err(AuthError::token(
836 "Subject mismatch between secure validation and FAPI claims".to_string(),
837 ));
838 }
839
840 if secure_claims.iss != fapi_claims.iss {
842 return Err(AuthError::token(
843 "Issuer mismatch between secure validation and FAPI claims".to_string(),
844 ));
845 }
846
847 if secure_claims.exp != fapi_claims.exp {
849 return Err(AuthError::token(
850 "Expiry mismatch between secure validation and FAPI claims".to_string(),
851 ));
852 }
853
854 let now = Utc::now().timestamp();
856
857 if request_object_too_old(now, fapi_claims.iat, self.config.max_request_age) {
859 return Err(AuthError::token("Request object too old".to_string()));
860 }
861
862 if fapi_claims.client_id.is_empty() {
864 return Err(AuthError::token(
865 "client_id required in request object".to_string(),
866 ));
867 }
868
869 if fapi_claims.redirect_uri.is_empty() {
870 return Err(AuthError::token(
871 "redirect_uri required in request object".to_string(),
872 ));
873 }
874
875 if fapi_claims.response_type.is_empty() {
876 return Err(AuthError::token(
877 "response_type required in request object".to_string(),
878 ));
879 }
880
881 tracing::info!(
882 "FAPI request object validated successfully with SecureJwtValidator for client: {}",
883 fapi_claims.client_id
884 );
885
886 Ok(fapi_claims)
887 }
888 Err(e) => {
889 tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
890 Err(AuthError::token(format!(
891 "Enhanced JWT validation failed: {}",
892 e
893 )))
894 }
895 }
896 }
897
898 async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
900 if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
902 return Err(AuthError::InvalidRequest(
903 "FAPI 2.0 requires code or code id_token response type".to_string(),
904 ));
905 }
906
907 if claims.code_challenge.is_none() {
909 return Err(AuthError::InvalidRequest(
910 "PKCE required for FAPI 2.0".to_string(),
911 ));
912 }
913
914 if let Some(method) = &claims.code_challenge_method {
915 if method != "S256" {
916 return Err(AuthError::InvalidRequest(
917 "FAPI 2.0 requires S256 code challenge method".to_string(),
918 ));
919 }
920 } else {
921 return Err(AuthError::InvalidRequest(
922 "code_challenge_method required for FAPI 2.0".to_string(),
923 ));
924 }
925
926 Ok(())
927 }
928
929 pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
934 const REFUSED: &str = "Client authentication failed";
935
936 let auth_result = match self
938 .private_key_jwt_manager
939 .authenticate_client(client_assertion)
940 .await
941 {
942 Ok(result) => result,
943 Err(e) => {
944 tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
945 return Err(AuthError::auth_method("private_key_jwt", REFUSED));
946 }
947 };
948
949 if auth_result.authenticated {
950 tracing::info!(
951 "FAPI client authenticated successfully using private key JWT: {}",
952 auth_result.client_id
953 );
954 Ok(auth_result.client_id)
955 } else {
956 tracing::warn!(
957 "FAPI private key JWT authentication failed: {}",
958 auth_result.errors.join("; ")
959 );
960 Err(AuthError::auth_method("private_key_jwt", REFUSED))
961 }
962 }
963
964 pub async fn validate_token_request(
966 &self,
967 client_assertion: Option<&str>,
968 client_cert: Option<&str>,
969 dpop_proof: Option<&str>,
970 _authorization_code: &str,
971 ) -> Result<String> {
972 let client_id = self
973 .authenticate_token_client(client_assertion, client_cert)
974 .await?;
975 self.check_token_dpop(dpop_proof).await?;
976 Ok(client_id)
977 }
978
979 pub async fn validate_token_request_from(
982 &self,
983 peer: &str,
984 client_assertion: Option<&str>,
985 client_cert: Option<&str>,
986 dpop_proof: Option<&str>,
987 _authorization_code: &str,
988 ) -> Result<String> {
989 self.count(format!("fapi:token:{peer}")).await?;
990 let client_id = self
991 .authenticate_token_client(client_assertion, client_cert)
992 .await?;
993 self.count(format!("fapi_client:{client_id}")).await?;
994 self.check_token_dpop(dpop_proof).await?;
995 Ok(client_id)
996 }
997
998 async fn authenticate_token_client(
1000 &self,
1001 client_assertion: Option<&str>,
1002 client_cert: Option<&str>,
1003 ) -> Result<String> {
1004 let client_id = if let Some(assertion) = client_assertion {
1006 self.authenticate_client_jwt(assertion).await?
1007 } else if self.config.require_mtls {
1008 if let Some(cert) = client_cert {
1009 let cert_bytes = decode_client_certificate(cert)?;
1010
1011 let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
1014
1015 self.mtls_manager
1016 .validate_client_certificate(&cert_bytes, &client_id)
1017 .await?;
1018
1019 client_id.to_string()
1020 } else {
1021 return Err(AuthError::auth_method(
1022 "mtls",
1023 "Client certificate required for FAPI 2.0 token request",
1024 ));
1025 }
1026 } else {
1027 return Err(AuthError::auth_method(
1028 "fapi",
1029 "FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
1030 ));
1031 };
1032 Ok(client_id)
1033 }
1034
1035 async fn check_token_dpop(&self, dpop_proof: Option<&str>) -> Result<()> {
1037 if self.config.require_dpop {
1039 let proof = dpop_proof.ok_or_else(|| {
1040 AuthError::auth_method("dpop", "DPoP proof required for FAPI 2.0 token request")
1041 })?;
1042 self.dpop_manager
1043 .validate_dpop_proof(
1044 proof,
1045 "POST",
1046 &format!("{}/token", self.config.issuer),
1047 None, None,
1049 )
1050 .await?;
1051 }
1052 Ok(())
1053 }
1054
1055 pub async fn generate_authorization_response(
1057 &self,
1058 client_id: &str,
1059 code: Option<&str>,
1060 state: Option<&str>,
1061 error: Option<&str>,
1062 error_description: Option<&str>,
1063 ) -> Result<String> {
1064 if !self.config.enable_jarm {
1065 return Err(AuthError::Configuration {
1066 message: "JARM not enabled".to_string(),
1067 help: Some("Enable JARM in your configuration to use this feature".to_string()),
1068 docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
1069 source: None,
1070 suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
1071 });
1072 }
1073
1074 let now = Utc::now();
1075 let exp = now + Duration::minutes(5); let response = FapiAuthorizationResponse {
1078 iss: self.config.issuer.clone(),
1079 aud: client_id.to_string(),
1080 iat: now.timestamp(),
1081 exp: exp.timestamp(),
1082 code: code.map(|c| c.to_string()),
1083 state: state.map(|s| s.to_string()),
1084 error: error.map(|e| e.to_string()),
1085 error_description: error_description.map(|d| d.to_string()),
1086 additional_params: HashMap::new(),
1087 };
1088
1089 let header = Header::new(self.config.response_signing_algorithm);
1091
1092 let token =
1094 jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
1095 AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
1096 })?;
1097
1098 Ok(token)
1099 }
1100
1101 pub async fn generate_token_response(
1103 &self,
1104 client_id: &str,
1105 user_id: &str,
1106 scopes: Vec<String>,
1107 cert_thumbprint: Option<String>,
1108 dpop_jkt: Option<String>,
1109 ) -> Result<FapiTokenResponse> {
1110 let access_token = self
1112 .generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
1113 .await?;
1114
1115 let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
1117
1118 let mut cnf = json!({});
1120
1121 if let Some(thumbprint) = cert_thumbprint {
1122 cnf["x5t#S256"] = Value::String(thumbprint);
1123 }
1124
1125 if let Some(jkt) = dpop_jkt {
1126 cnf["jkt"] = Value::String(jkt);
1127 }
1128
1129 let response = FapiTokenResponse {
1130 access_token,
1131 token_type: "DPoP".to_string(), expires_in: 3600, refresh_token: Some(refresh_token),
1134 scope: Some(scopes.join(" ")),
1135 id_token: None, cnf: if cnf.as_object().is_none_or(|o| o.is_empty()) {
1137 None
1138 } else {
1139 Some(cnf)
1140 },
1141 };
1142
1143 Ok(response)
1144 }
1145
1146 async fn generate_access_token(
1148 &self,
1149 client_id: &str,
1150 user_id: &str,
1151 scopes: &[String],
1152 cert_thumbprint: &Option<String>,
1153 dpop_jkt: &Option<String>,
1154 ) -> Result<String> {
1155 let claims =
1156 self.access_token_claims(client_id, user_id, scopes, cert_thumbprint, dpop_jkt);
1157
1158 let header = Header::new(Algorithm::RS256);
1160
1161 let token =
1163 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1164 AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
1165 })?;
1166
1167 Ok(token)
1168 }
1169
1170 fn access_token_claims(
1172 &self,
1173 client_id: &str,
1174 user_id: &str,
1175 scopes: &[String],
1176 cert_thumbprint: &Option<String>,
1177 dpop_jkt: &Option<String>,
1178 ) -> Value {
1179 let now = Utc::now();
1180 let exp = now + Duration::hours(1);
1181
1182 let mut claims = json!({
1183 "iss": self.config.issuer,
1184 "aud": self.config.issuer,
1186 "client_id": client_id,
1187 "sub": user_id,
1188 "iat": now.timestamp(),
1189 "nbf": now.timestamp(),
1190 "exp": exp.timestamp(),
1191 "scope": scopes.join(" "),
1192 "jti": Uuid::new_v4().to_string(),
1193 "typ": "access",
1194 });
1195
1196 let mut cnf = json!({});
1198
1199 if let Some(thumbprint) = cert_thumbprint {
1200 cnf["x5t#S256"] = Value::String(thumbprint.clone());
1201 }
1202
1203 if let Some(jkt) = dpop_jkt {
1204 cnf["jkt"] = Value::String(jkt.clone());
1205 }
1206
1207 if !cnf.as_object().is_none_or(|o| o.is_empty()) {
1208 claims["cnf"] = cnf;
1209 }
1210
1211 claims
1212 }
1213
1214 async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
1216 let now = Utc::now();
1217 let exp = now + Duration::days(30); let claims = json!({
1220 "iss": self.config.issuer,
1221 "aud": client_id,
1222 "sub": user_id,
1223 "iat": now.timestamp(),
1224 "exp": exp.timestamp(),
1225 "typ": crate::security::secure_jwt::TYP_REFRESH_TOKEN,
1226 "jti": Uuid::new_v4().to_string(),
1227 });
1228
1229 let header = Header::new(Algorithm::RS256);
1231
1232 let token =
1234 jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
1235 AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
1236 })?;
1237
1238 Ok(token)
1239 }
1240
1241 pub async fn create_session(
1243 &self,
1244 client_id: &str,
1245 user_id: &str,
1246 scopes: Vec<String>,
1247 dpop_proof: Option<String>,
1248 cert_thumbprint: Option<String>,
1249 request_jti: Option<String>,
1250 ) -> Result<String> {
1251 let session_id = Uuid::new_v4().to_string();
1252 let now = Utc::now();
1253 let expires_at = now + Duration::hours(24); let session = FapiSession {
1256 session_id: session_id.clone(),
1257 client_id: client_id.to_string(),
1258 user_id: user_id.to_string(),
1259 created_at: now,
1260 expires_at,
1261 dpop_proof,
1262 cert_thumbprint,
1263 request_jti,
1264 scopes,
1265 metadata: HashMap::new(),
1266 };
1267
1268 let mut sessions = self.sessions.write().await;
1269 sessions.insert(session_id.clone(), session);
1270
1271 Ok(session_id)
1272 }
1273
1274 pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
1276 let sessions = self.sessions.read().await;
1277 Ok(sessions.get(session_id).cloned())
1278 }
1279
1280 pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
1282 let session = self
1283 .get_session(session_id)
1284 .await?
1285 .ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
1286
1287 if Utc::now() > session.expires_at {
1289 return Err(AuthError::validation("Session expired".to_string()));
1290 }
1291
1292 Ok(session)
1293 }
1294
1295 pub async fn remove_session(&self, session_id: &str) -> Result<()> {
1297 let mut sessions = self.sessions.write().await;
1298 sessions.remove(session_id);
1299 Ok(())
1300 }
1301
1302 pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
1304 if self.config.enhanced_audit {
1305 let timestamp = chrono::Utc::now().to_rfc3339();
1309 let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
1310
1311 tracing::info!("{}", audit_entry);
1313 }
1314 Ok(())
1315 }
1316
1317 async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
1319 client_id_from_certificate(cert_bytes)
1320 }
1321
1322 pub fn check_compliance(&self) -> Vec<FapiComplianceViolation> {
1327 let mut violations = Vec::new();
1328
1329 if self.config.is_degraded {
1330 violations.push(FapiComplianceViolation {
1331 requirement: "crypto-keys".to_string(),
1332 severity: FapiViolationSeverity::Critical,
1333 message: "RSA key pair not properly configured; all FAPI operations will fail"
1334 .to_string(),
1335 });
1336 }
1337
1338 if !self.config.require_par {
1339 violations.push(FapiComplianceViolation {
1340 requirement: "par".to_string(),
1341 severity: FapiViolationSeverity::Critical,
1342 message: "FAPI 2.0 Security Profile requires Pushed Authorization Requests"
1343 .to_string(),
1344 });
1345 }
1346
1347 if !self.config.require_dpop {
1348 violations.push(FapiComplianceViolation {
1349 requirement: "sender-constraint".to_string(),
1350 severity: FapiViolationSeverity::Warning,
1351 message: "DPoP is recommended for sender-constrained tokens".to_string(),
1352 });
1353 }
1354
1355 if !self.config.require_mtls {
1356 violations.push(FapiComplianceViolation {
1357 requirement: "sender-constraint".to_string(),
1358 severity: FapiViolationSeverity::Warning,
1359 message: "mTLS is recommended for client authentication and token binding"
1360 .to_string(),
1361 });
1362 }
1363
1364 if !self.config.require_dpop && !self.config.require_mtls {
1365 violations.push(FapiComplianceViolation {
1366 requirement: "sender-constraint".to_string(),
1367 severity: FapiViolationSeverity::Critical,
1368 message:
1369 "FAPI 2.0 requires at least one sender-constraining mechanism (DPoP or mTLS)"
1370 .to_string(),
1371 });
1372 }
1373
1374 if !self.config.enable_jarm {
1375 violations.push(FapiComplianceViolation {
1376 requirement: "jarm".to_string(),
1377 severity: FapiViolationSeverity::Warning,
1378 message: "JARM is recommended for authorization response integrity".to_string(),
1379 });
1380 }
1381
1382 if !self.config.enhanced_audit {
1383 violations.push(FapiComplianceViolation {
1384 requirement: "audit".to_string(),
1385 severity: FapiViolationSeverity::Warning,
1386 message: "Enhanced audit logging is recommended for FAPI compliance".to_string(),
1387 });
1388 }
1389
1390 if !matches!(
1391 self.config.request_signing_algorithm,
1392 Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
1393 ) {
1394 violations.push(FapiComplianceViolation {
1395 requirement: "algorithm".to_string(),
1396 severity: FapiViolationSeverity::Critical,
1397 message: "Request signing must use RS256, PS256, or ES256".to_string(),
1398 });
1399 }
1400
1401 if self.config.max_request_age > 600 {
1402 violations.push(FapiComplianceViolation {
1403 requirement: "request-lifetime".to_string(),
1404 severity: FapiViolationSeverity::Warning,
1405 message: "Max request age exceeds recommended 10 minutes".to_string(),
1406 });
1407 }
1408
1409 violations
1410 }
1411
1412 pub fn is_compliant(&self) -> bool {
1414 !self
1415 .check_compliance()
1416 .iter()
1417 .any(|v| matches!(v.severity, FapiViolationSeverity::Critical))
1418 }
1419
1420 pub async fn validate_sender_constrained_token(
1425 &self,
1426 access_token: &str,
1427 dpop_proof: Option<&str>,
1428 client_cert: Option<&str>,
1429 http_method: &str,
1430 http_uri: &str,
1431 ) -> Result<serde_json::Value> {
1432 let token_data = self
1434 .jwt_validator
1435 .validate_token(access_token, &self.config.public_key)?;
1436
1437 let header = jsonwebtoken::decode_header(access_token)
1439 .map_err(|e| AuthError::token(format!("Invalid token header: {}", e)))?;
1440 let mut validation = Validation::new(header.alg);
1441 validation.set_audience(&[&self.config.issuer]);
1442 validation.validate_exp = true;
1443 let raw_claims = jsonwebtoken::decode::<serde_json::Value>(
1444 access_token,
1445 &self.config.public_key,
1446 &validation,
1447 )
1448 .map_err(|e| AuthError::token(format!("Token decode failed: {}", e)))?;
1449
1450 let cnf = raw_claims.claims.get("cnf").ok_or_else(|| {
1452 AuthError::token("Token is not sender-constrained (missing cnf claim)".to_string())
1453 })?;
1454
1455 let jkt_member = cnf.get("jkt");
1458 let x5t_member = cnf.get("x5t#S256");
1459 for (name, member) in [("jkt", jkt_member), ("x5t#S256", x5t_member)] {
1460 if member.is_some_and(|v| !v.is_string()) {
1461 return Err(AuthError::token(format!(
1462 "Token's cnf.{name} is not a string"
1463 )));
1464 }
1465 }
1466 if jkt_member.is_none() && x5t_member.is_none() {
1467 return Err(AuthError::token(
1468 "Token's cnf claim names no supported key binding".to_string(),
1469 ));
1470 }
1471
1472 let pending_proof = if let Some(expected_jkt) = cnf.get("jkt").and_then(|v| v.as_str()) {
1475 let proof = dpop_proof.ok_or_else(|| {
1476 AuthError::token(
1477 "Token is DPoP-bound but no DPoP proof header provided".to_string(),
1478 )
1479 })?;
1480 Some(
1481 self.dpop_manager
1482 .verify_dpop_proof(
1483 proof,
1484 http_method,
1485 http_uri,
1486 Some(access_token),
1487 None,
1488 Some(expected_jkt),
1489 )
1490 .await?,
1491 )
1492 } else {
1493 None
1494 };
1495
1496 if let Some(expected_thumbprint) = cnf.get("x5t#S256").and_then(|v| v.as_str()) {
1498 let cert = client_cert.ok_or_else(|| {
1499 AuthError::token(
1500 "Token is certificate-bound but no client certificate provided".to_string(),
1501 )
1502 })?;
1503 use base64::Engine;
1505 use sha2::{Digest, Sha256};
1506 let cert_der = decode_client_certificate(cert)?;
1507 let presented_thumbprint =
1508 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(&cert_der));
1509 if !bool::from(subtle::ConstantTimeEq::ct_eq(
1510 presented_thumbprint.as_bytes(),
1511 expected_thumbprint.as_bytes(),
1512 )) {
1513 return Err(AuthError::token(
1514 "Certificate thumbprint does not match token binding".to_string(),
1515 ));
1516 }
1517 }
1518
1519 if let Some(pending) = pending_proof {
1520 self.dpop_manager.commit_dpop_proof(pending).await?;
1521 }
1522
1523 Ok(serde_json::json!({
1525 "sub": token_data.sub,
1526 "iss": token_data.iss,
1527 "exp": token_data.exp,
1528 "scope": token_data.scope,
1529 }))
1530 }
1531
1532 pub fn validate_authorization_details(
1534 &self,
1535 authorization_details: &[AuthorizationDetail],
1536 ) -> Result<()> {
1537 if authorization_details.is_empty() {
1538 return Err(AuthError::InvalidRequest(
1539 "authorization_details must not be empty".to_string(),
1540 ));
1541 }
1542
1543 for (i, detail) in authorization_details.iter().enumerate() {
1544 if detail.r#type.is_empty() {
1545 return Err(AuthError::InvalidRequest(format!(
1546 "authorization_details[{}]: type is required",
1547 i
1548 )));
1549 }
1550
1551 for location in &detail.locations {
1553 if !location.starts_with("https://") {
1554 return Err(AuthError::InvalidRequest(format!(
1555 "authorization_details[{}]: location must use HTTPS: {}",
1556 i, location
1557 )));
1558 }
1559 }
1560
1561 for action in &detail.actions {
1563 if action.is_empty() {
1564 return Err(AuthError::InvalidRequest(format!(
1565 "authorization_details[{}]: empty action not allowed",
1566 i
1567 )));
1568 }
1569 }
1570 }
1571
1572 Ok(())
1573 }
1574}
1575
1576#[derive(Debug, Clone)]
1578pub struct FapiComplianceViolation {
1579 pub requirement: String,
1581 pub severity: FapiViolationSeverity,
1583 pub message: String,
1585}
1586
1587#[derive(Debug, Clone, PartialEq, Eq)]
1589pub enum FapiViolationSeverity {
1590 Critical,
1592 Warning,
1594}
1595
1596#[derive(Debug, Clone, Serialize, Deserialize)]
1598pub struct AuthorizationDetail {
1599 pub r#type: String,
1601
1602 #[serde(default)]
1604 pub locations: Vec<String>,
1605
1606 #[serde(default)]
1608 pub actions: Vec<String>,
1609
1610 #[serde(default)]
1612 pub datatypes: Vec<String>,
1613
1614 #[serde(skip_serializing_if = "Option::is_none")]
1616 pub identifier: Option<String>,
1617
1618 #[serde(flatten)]
1620 pub additional_fields: HashMap<String, Value>,
1621}
1622
1623impl Default for FapiConfig {
1624 fn default() -> Self {
1625 let issuer =
1627 std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
1628
1629 let mut is_degraded = false;
1630
1631 let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
1635 std::fs::read(&key_path)
1636 .map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
1637 .and_then(|bytes| {
1638 EncodingKey::from_rsa_pem(&bytes)
1639 .map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
1640 })
1641 .unwrap_or_else(|_| {
1642 tracing::error!(
1643 "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH is set but the key could not \
1644 be loaded. FAPI REQUIRES an RSA private key for request/response signing. \
1645 Using an ephemeral HMAC placeholder — ALL FAPI OPERATIONS WILL BE REJECTED \
1646 until a valid RSA key is provided. Set FAPI_PRIVATE_KEY_PATH to a valid \
1647 PEM-encoded RSA private key file."
1648 );
1649 is_degraded = true;
1650 use ring::rand::{SecureRandom, SystemRandom};
1651 let rng = SystemRandom::new();
1652 let mut bytes = [0u8; 32];
1653 rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1654 EncodingKey::from_secret(&bytes)
1655 })
1656 } else {
1657 tracing::error!(
1658 "SECURITY CRITICAL: FAPI_PRIVATE_KEY_PATH not set. FAPI REQUIRES an RSA \
1659 private key for request and response signing. Using an ephemeral HMAC \
1660 placeholder — ALL FAPI OPERATIONS WILL BE REJECTED until a valid RSA key \
1661 is provided. Set FAPI_PRIVATE_KEY_PATH to a PEM-encoded RSA private key file."
1662 );
1663 is_degraded = true;
1664 use ring::rand::{SecureRandom, SystemRandom};
1665 let rng = SystemRandom::new();
1666 let mut bytes = [0u8; 32];
1667 rng.fill(&mut bytes).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1668 EncodingKey::from_secret(&bytes)
1669 };
1670
1671 let public_key = if let Ok(key_path) = std::env::var("FAPI_PUBLIC_KEY_PATH") {
1673 std::fs::read(&key_path)
1674 .map_err(|e| tracing::warn!("Failed to load public key from {}: {}", key_path, e))
1675 .and_then(|bytes| {
1676 DecodingKey::from_rsa_pem(&bytes)
1677 .map_err(|e| tracing::warn!("Invalid RSA public key format: {}", e))
1678 })
1679 .unwrap_or_else(|_| {
1680 tracing::error!(
1681 "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH is set but the key could not \
1682 be loaded. FAPI verification will not work correctly."
1683 );
1684 is_degraded = true;
1685 use ring::rand::{SecureRandom, SystemRandom};
1686 let rng = SystemRandom::new();
1687 let mut secret = [0u8; 32];
1688 rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1689 DecodingKey::from_secret(&secret)
1690 })
1691 } else {
1692 tracing::error!(
1693 "SECURITY CRITICAL: FAPI_PUBLIC_KEY_PATH not set. FAPI verification will \
1694 not work correctly. Set FAPI_PUBLIC_KEY_PATH to a PEM-encoded RSA public key file."
1695 );
1696 is_degraded = true;
1697 use ring::rand::{SecureRandom, SystemRandom};
1698 let rng = SystemRandom::new();
1699 let mut secret = [0u8; 32];
1700 rng.fill(&mut secret).expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
1701 DecodingKey::from_secret(&secret)
1702 };
1703
1704 Self {
1705 issuer,
1706 request_signing_algorithm: Algorithm::RS256,
1707 response_signing_algorithm: Algorithm::RS256,
1708 private_key,
1709 public_key,
1710 max_request_age: 300, require_dpop: true,
1712 require_mtls: true,
1713 require_par: true,
1714 enable_jarm: true,
1715 enhanced_audit: true,
1716 is_degraded,
1717 }
1718 }
1719}
1720
1721fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
1726 use base64::Engine;
1727 use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
1728
1729 const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
1730 const END: &str = "-----END CERTIFICATE-----";
1731 let bad = || {
1732 AuthError::auth_method(
1733 "mtls",
1734 "Client certificate must be PEM or base64-encoded DER",
1735 )
1736 };
1737
1738 let trimmed = input.trim();
1739 let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
1740 let end = rest.find(END).ok_or_else(bad)?;
1741 if !rest[end + END.len()..].trim().is_empty() {
1743 return Err(bad());
1744 }
1745 &rest[..end]
1746 } else {
1747 trimmed
1748 };
1749 let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
1750 if compact.is_empty() {
1751 return Err(bad());
1752 }
1753 STANDARD
1754 .decode(&compact)
1755 .or_else(|_| STANDARD_NO_PAD.decode(&compact))
1756 .or_else(|_| URL_SAFE.decode(&compact))
1757 .or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
1758 .map_err(|_| bad())
1759}
1760
1761fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
1764 use x509_parser::extensions::GeneralName;
1765
1766 let cert = match x509_parser::parse_x509_certificate(cert_der) {
1767 Ok(([], cert)) => cert,
1768 _ => {
1769 return Err(AuthError::auth_method(
1770 "mtls",
1771 "Invalid client certificate format",
1772 ));
1773 }
1774 };
1775
1776 let common_names: Vec<String> = cert
1777 .subject()
1778 .iter_common_name()
1779 .filter_map(|cn| cn.as_str().ok().map(str::to_string))
1780 .collect();
1781 if common_names.len() == 1 && !common_names[0].is_empty() {
1782 return Ok(common_names[0].clone());
1783 }
1784
1785 if let Ok(Some(san)) = cert.subject_alternative_name() {
1786 let names: Vec<String> = san
1787 .value
1788 .general_names
1789 .iter()
1790 .filter_map(|name| match name {
1791 GeneralName::DNSName(dns) => Some(dns.to_string()),
1792 GeneralName::URI(uri) => Some(uri.to_string()),
1793 _ => None,
1794 })
1795 .collect();
1796 if names.len() == 1 {
1797 return Ok(names[0].clone());
1798 }
1799 }
1800
1801 Err(AuthError::auth_method(
1802 "mtls",
1803 "Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
1804 ))
1805}
1806
1807#[cfg(test)]
1808mod tests {
1809 use super::*;
1810
1811 #[test]
1812 fn test_fapi_config_builder() {
1813 use ring::rand::{SecureRandom, SystemRandom};
1814 let rng = SystemRandom::new();
1815 let mut bytes = [0u8; 32];
1816 rng.fill(&mut bytes).unwrap();
1817 let private_key = EncodingKey::from_secret(&bytes);
1818 let public_key = DecodingKey::from_secret(&bytes);
1819
1820 let config = FapiConfig::builder("https://fapi.example.com", private_key, public_key)
1821 .request_signing_algorithm(Algorithm::ES256)
1822 .max_request_age(120)
1823 .require_dpop(false)
1824 .degraded()
1825 .build();
1826
1827 assert_eq!(config.issuer, "https://fapi.example.com");
1828 assert_eq!(config.request_signing_algorithm, Algorithm::ES256);
1829 assert_eq!(config.max_request_age, 120);
1830 assert!(!config.require_dpop);
1831 assert!(config.require_mtls); assert!(config.is_degraded);
1833 }
1834
1835 #[test]
1836 fn test_fapi_session_builder() {
1837 let session = FapiSession::builder(
1838 "sess_123",
1839 "client_456",
1840 "user_789",
1841 Duration::try_hours(1).unwrap(),
1842 )
1843 .dpop_proof("proof_abc")
1844 .add_scope("openid")
1845 .add_scopes(vec!["profile", "email"])
1846 .add_metadata("custom_flag", json!(true))
1847 .build();
1848
1849 assert_eq!(session.session_id, "sess_123");
1850 assert_eq!(session.client_id, "client_456");
1851 assert_eq!(session.user_id, "user_789");
1852 assert_eq!(session.dpop_proof.as_deref(), Some("proof_abc"));
1853 assert_eq!(session.scopes, vec!["openid", "profile", "email"]);
1854 assert_eq!(session.metadata["custom_flag"], true);
1855 }
1856
1857 #[tokio::test]
1858 async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
1859 use crate::security::secure_jwt::SecureJwtConfig;
1860 use crate::server::jwt::private_key_jwt::ClientJwtConfig;
1861 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1862
1863 let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
1864 let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
1865 let manager = FapiManager::new(
1866 FapiConfig::default(),
1867 Arc::new(DpopManager::new(validator())),
1868 Arc::new(MutualTlsManager::new()),
1869 Arc::new(PARManager::new(Arc::new(
1870 crate::storage::MemoryStorage::new(),
1871 ))),
1872 assertions.clone(),
1873 Arc::new(validator()),
1874 );
1875
1876 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1878 let raw = key.public_key_raw();
1879 let point = &raw[raw.len() - 65..];
1880 let jwk = json!({
1881 "kty": "EC", "crv": "P-256",
1882 "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1883 "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1884 });
1885 assertions
1886 .register_client(
1887 ClientJwtConfig::builder("fapi-client", jwk)
1888 .algorithms(vec![Algorithm::ES256])
1889 .audience("https://auth.example.com/token")
1890 .build(),
1891 )
1892 .await
1893 .unwrap();
1894 let encoding_key = EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap();
1895
1896 let good = assertions
1898 .create_client_assertion(
1899 "fapi-client",
1900 "https://auth.example.com/token",
1901 &encoding_key,
1902 Algorithm::ES256,
1903 )
1904 .unwrap();
1905 assert_eq!(
1906 manager.authenticate_client_jwt(&good).await.unwrap(),
1907 "fapi-client"
1908 );
1909
1910 let wrong_audience = assertions
1913 .create_client_assertion(
1914 "fapi-client",
1915 "https://elsewhere.example/token",
1916 &encoding_key,
1917 Algorithm::ES256,
1918 )
1919 .unwrap();
1920 let unknown = assertions
1921 .create_client_assertion(
1922 "ghost",
1923 "https://auth.example.com/token",
1924 &encoding_key,
1925 Algorithm::ES256,
1926 )
1927 .unwrap();
1928 for (why, assertion) in [
1929 ("wrong audience", wrong_audience.as_str()),
1930 ("unknown client", unknown.as_str()),
1931 ("replay", good.as_str()),
1932 ("junk", "not-a-jwt"),
1933 ] {
1934 let message = manager
1935 .authenticate_client_jwt(assertion)
1936 .await
1937 .expect_err(why)
1938 .to_string();
1939 assert!(
1940 message.contains("Client authentication failed"),
1941 "{why}: {message}"
1942 );
1943 for leak in [
1944 "udience",
1945 "registered",
1946 "ignature",
1947 "replay",
1948 "JTI",
1949 "Algorithm",
1950 "expired",
1951 ] {
1952 assert!(
1953 !message.contains(leak),
1954 "{why}: {message:?} mentions {leak:?}"
1955 );
1956 }
1957 }
1958 }
1959
1960 #[tokio::test]
1961 async fn test_fapi_manager_creation() {
1962 let config = FapiConfig::default();
1964
1965 assert_eq!(config.issuer, "https://auth.example.com"); assert!(config.require_dpop);
1968 assert!(config.require_mtls);
1969 assert!(config.require_par);
1970 assert!(config.enable_jarm);
1971 assert!(config.enhanced_audit);
1972 }
1973
1974 #[tokio::test]
1975 async fn test_fapi_request_validation() {
1976 let config = FapiConfig::default();
1979
1980 let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
1982
1983 let validation_result = validate_fapi_request_object(request_object, &config);
1985 assert!(
1986 validation_result.is_ok(),
1987 "FAPI request object validation failed"
1988 );
1989
1990 assert!(!request_object.is_empty());
1992 }
1993
1994 fn validate_fapi_request_object(
1996 request_object: &str,
1997 _config: &FapiConfig,
1998 ) -> Result<(), String> {
1999 let parsed: serde_json::Value = serde_json::from_str(request_object)
2001 .map_err(|_| "Invalid JSON structure in request object")?;
2002
2003 let required_claims = ["iss", "aud", "exp", "iat", "jti"];
2005 for claim in &required_claims {
2006 if parsed.get(claim).is_none() {
2007 return Err(format!("Missing required FAPI claim: {}", claim));
2008 }
2009 }
2010
2011 if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
2013 let now = chrono::Utc::now().timestamp();
2014 if exp <= now {
2015 return Err("Request object has expired".to_string());
2016 }
2017 }
2018
2019 Ok(())
2022 }
2023
2024 #[tokio::test]
2025 async fn test_fapi_response_generation() {
2026 let config = FapiConfig::default();
2029
2030 let auth_response = serde_json::json!({
2032 "code": "auth_code_123",
2033 "state": "client_state",
2034 "iss": config.issuer,
2035 "aud": "client_id",
2036 "exp": 9999999999i64
2037 });
2038
2039 assert!(auth_response["code"].is_string());
2041 }
2042
2043 #[tokio::test]
2044 async fn test_fapi_token_generation() {
2045 let config = FapiConfig::default();
2047
2048 let scopes = ["accounts".to_string(), "payments".to_string()];
2050 let client_id = "fapi_client_123";
2051 let user_id = "user_456";
2052 let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
2053
2054 assert!(config.require_dpop);
2056 assert!(config.require_mtls);
2057 assert!(!scopes.is_empty());
2058 assert!(!client_id.is_empty());
2059 assert!(!user_id.is_empty());
2060 assert!(cert_thumbprint.is_some());
2061 }
2062
2063 #[tokio::test]
2064 async fn test_fapi_session_management() {
2065 let config = FapiConfig::default();
2067
2068 let session_data = serde_json::json!({
2070 "client_id": "fapi_client",
2071 "user_id": "fapi_user",
2072 "scopes": ["accounts", "payments"],
2073 "mtls_cert": "client_certificate",
2074 "dpop_key": "client_dpop_key"
2075 });
2076
2077 assert!(session_data["mtls_cert"].is_string());
2079 assert!(session_data["dpop_key"].is_string());
2080 assert!(config.enhanced_audit);
2081 }
2082
2083 fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
2086 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2087 let mut dn = rcgen::DistinguishedName::new();
2088 dn.push(rcgen::DnType::CommonName, cn);
2089 if let Some(org) = org {
2090 dn.push(rcgen::DnType::OrganizationName, org);
2091 }
2092 params.distinguished_name = dn;
2093 let key = rcgen::KeyPair::generate().unwrap();
2094 params.self_signed(&key).unwrap()
2095 }
2096
2097 #[test]
2098 fn decode_client_certificate_accepts_pem_and_base64_der() {
2099 use base64::Engine;
2100 let cert = test_cert("client-a", None);
2101 let der = cert.der().to_vec();
2102
2103 assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
2104 let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
2105 assert_eq!(decode_client_certificate(&b64).unwrap(), der);
2106 let wrapped = format!(" {}\n{} \n", &b64[..20], &b64[20..]);
2107 assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
2108 }
2109
2110 #[test]
2111 fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
2112 let a = test_cert("client-a", None).pem();
2113 let b = test_cert("client-b", None).pem();
2114 assert!(decode_client_certificate("").is_err());
2115 assert!(decode_client_certificate("!!! not base64 !!!").is_err());
2116 assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
2117 assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
2119 }
2120
2121 #[test]
2122 fn client_id_comes_from_the_parsed_subject_cn() {
2123 let cert = test_cert("client-a", None);
2124 assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
2125 }
2126
2127 #[test]
2128 fn client_id_is_not_found_by_searching_the_raw_bytes() {
2129 let cert = test_cert("real-client", Some("CN=victim-client,"));
2132 assert_eq!(
2133 client_id_from_certificate(cert.der()).unwrap(),
2134 "real-client"
2135 );
2136 }
2137
2138 #[test]
2139 fn client_id_needs_a_unique_identity() {
2140 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2142 params.distinguished_name = rcgen::DistinguishedName::new(); let key = rcgen::KeyPair::generate().unwrap();
2144 let nameless = params.self_signed(&key).unwrap();
2145 assert!(client_id_from_certificate(nameless.der()).is_err());
2146 assert!(client_id_from_certificate(b"not a certificate").is_err());
2147 }
2148}
2149
2150#[cfg(test)]
2151mod request_object_age {
2152 use super::*;
2153 use crate::security::secure_jwt::SecureJwtConfig;
2154
2155 const ISS: &str = "https://fapi.example.com";
2156 const CLIENT: &str = "client-1";
2157
2158 fn request_object(enc: &EncodingKey, iat: i64) -> String {
2159 let now = Utc::now().timestamp();
2160 let claims = json!({
2161 "iss": CLIENT, "sub": CLIENT, "aud": ISS, "exp": now + 300, "nbf": now - 1,
2162 "iat": iat, "jti": Uuid::new_v4().to_string(), "scope": "read", "typ": "access",
2163 "response_type": "code", "client_id": CLIENT,
2164 "redirect_uri": "https://client.example/cb",
2165 "code_challenge": "abc", "code_challenge_method": "S256",
2166 });
2167 jsonwebtoken::encode(&Header::new(Algorithm::ES256), &claims, enc).unwrap()
2168 }
2169
2170 #[tokio::test]
2171 async fn the_age_of_a_request_object_cannot_wrap() {
2172 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2173 let pem = key.serialize_pem();
2174 let enc = EncodingKey::from_ec_pem(pem.as_bytes()).unwrap();
2175 let config = FapiConfig {
2176 issuer: ISS.to_string(),
2177 private_key: EncodingKey::from_ec_pem(pem.as_bytes()).unwrap(),
2178 public_key: DecodingKey::from_ec_der(key.public_key_raw()),
2179 ..FapiConfig::default()
2180 };
2181 let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2182 let secure = SecureJwtValidator::new(SecureJwtConfig {
2183 allowed_algorithms: vec![Algorithm::ES256],
2184 required_issuers: [CLIENT.to_string()].into_iter().collect(),
2185 ec_public_key_pem: Some(key.public_key_pem()),
2186 require_secure_transport: false,
2187 ..SecureJwtConfig::default()
2188 })
2189 .unwrap();
2190 let m = FapiManager::new(
2191 config,
2192 Arc::new(DpopManager::new(validator())),
2193 Arc::new(MutualTlsManager::new()),
2194 Arc::new(PARManager::new(Arc::new(
2195 crate::storage::MemoryStorage::new(),
2196 ))),
2197 Arc::new(PrivateKeyJwtManager::new(validator())),
2198 Arc::new(secure),
2199 );
2200 let now = Utc::now().timestamp();
2201 m.validate_request_object(&request_object(&enc, now))
2202 .await
2203 .expect("a fresh request object is accepted");
2204 match m
2206 .validate_request_object(&request_object(&enc, now - 3000))
2207 .await
2208 {
2209 Ok(_) => panic!("a request object 50 minutes old: ACCEPTED"),
2210 Err(e) => assert!(e.to_string().contains("too old"), "refused with {e:?}"),
2211 }
2212 assert!(
2214 m.validate_request_object(&request_object(&enc, i64::MIN))
2215 .await
2216 .is_err()
2217 );
2218 }
2219
2220 #[test]
2221 fn an_age_that_cannot_be_represented_is_too_old() {
2222 let now = Utc::now().timestamp();
2223 assert!(!request_object_too_old(now, now, 60));
2224 assert!(!request_object_too_old(now, now - 60, 60));
2225 assert!(request_object_too_old(now, now - 61, 60));
2226 assert!(request_object_too_old(now, i64::MIN, 60));
2228 assert!(request_object_too_old(now, i64::MIN + 1, 60));
2229 assert!(request_object_too_old(i64::MAX, -1, 60));
2230 }
2231}
2232
2233#[cfg(test)]
2234mod dpop_regression {
2235 use super::*;
2239 use crate::security::secure_jwt::SecureJwtConfig;
2240 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as B64};
2241 use sha2::{Digest, Sha256};
2242
2243 const ISS: &str = "https://fapi.example.com";
2244 const URI: &str = "https://rs.example.com/resource";
2245
2246 fn ec_key() -> (EncodingKey, serde_json::Value) {
2247 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2248 let raw = key.public_key_raw();
2249 let point = &raw[raw.len() - 65..];
2250 let jwk = json!({
2251 "kty": "EC", "crv": "P-256",
2252 "x": B64.encode(&point[1..33]),
2253 "y": B64.encode(&point[33..65]),
2254 });
2255 (
2256 EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2257 jwk,
2258 )
2259 }
2260
2261 fn ath_of(token: &str) -> String {
2262 B64.encode(Sha256::digest(token.as_bytes()))
2263 }
2264
2265 struct Proof<'a> {
2267 key: &'a (EncodingKey, serde_json::Value),
2268 htm: &'a str,
2269 htu: &'a str,
2270 iat: i64,
2271 jti: &'a str,
2272 ath: Option<String>,
2273 der: bool,
2274 jwk_extra: Option<(&'a str, &'a str)>,
2275 }
2276
2277 impl Proof<'_> {
2278 fn build(&self) -> String {
2279 let mut jwk = self.key.1.clone();
2280 if let Some((k, v)) = self.jwk_extra {
2281 jwk[k] = json!(v);
2282 }
2283 let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
2284 let mut claims =
2285 json!({"jti": self.jti, "htm": self.htm, "htu": self.htu, "iat": self.iat});
2286 if let Some(a) = &self.ath {
2287 claims["ath"] = json!(a);
2288 }
2289 let si = format!(
2290 "{}.{}",
2291 B64.encode(header.to_string()),
2292 B64.encode(claims.to_string())
2293 );
2294 let sig =
2296 jsonwebtoken::crypto::sign(si.as_bytes(), &self.key.0, Algorithm::ES256).unwrap();
2297 if !self.der {
2298 return format!("{si}.{sig}");
2299 }
2300 let raw = B64.decode(sig).unwrap();
2301 let int = |v: &[u8]| {
2302 let mut v: Vec<u8> = v.iter().copied().skip_while(|&x| x == 0).collect();
2303 if v.is_empty() || v[0] & 0x80 != 0 {
2304 v.insert(0, 0);
2305 }
2306 let mut o = vec![0x02, v.len() as u8];
2307 o.extend(v);
2308 o
2309 };
2310 let mut body = int(&raw[..32]);
2311 body.extend(int(&raw[32..]));
2312 let mut der = vec![0x30, body.len() as u8];
2313 der.extend(body);
2314 format!("{si}.{}", B64.encode(der))
2315 }
2316 }
2317
2318 fn manager() -> (FapiManager, Arc<DpopManager>, Vec<u8>) {
2319 let secret = b"0123456789abcdef0123456789abcdef".to_vec();
2320 let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2321 let dpop = Arc::new(DpopManager::new(validator()));
2322 let config = FapiConfig::builder(
2323 ISS,
2324 EncodingKey::from_secret(&secret),
2325 DecodingKey::from_secret(&secret),
2326 )
2327 .build();
2328 let m = FapiManager::new(
2329 config,
2330 dpop.clone(),
2331 Arc::new(MutualTlsManager::new()),
2332 Arc::new(PARManager::new(Arc::new(
2333 crate::storage::MemoryStorage::new(),
2334 ))),
2335 Arc::new(PrivateKeyJwtManager::new(validator())),
2336 Arc::new(
2337 SecureJwtValidator::new(SecureJwtConfig {
2338 required_issuers: [ISS.to_string()].into_iter().collect(),
2339 require_secure_transport: false,
2340 ..SecureJwtConfig::default()
2341 })
2342 .unwrap(),
2343 ),
2344 );
2345 (m, dpop, secret)
2346 }
2347
2348 fn sign_hs256(secret: &[u8], claims: &serde_json::Value) -> String {
2349 jsonwebtoken::encode(
2350 &Header::new(Algorithm::HS256),
2351 claims,
2352 &EncodingKey::from_secret(secret),
2353 )
2354 .unwrap()
2355 }
2356
2357 fn token_for(secret: &[u8], jkt: &str) -> String {
2360 let now = Utc::now().timestamp();
2361 sign_hs256(
2362 secret,
2363 &json!({
2364 "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2365 "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2366 "typ": "access", "cnf": {"jkt": jkt},
2367 }),
2368 )
2369 }
2370
2371 async fn check(m: &FapiManager, tok: &str, proof: Option<&str>, method: &str) -> Result<()> {
2372 m.validate_sender_constrained_token(tok, proof, None, method, URI)
2373 .await
2374 .map(|_| ())
2375 }
2376
2377 fn refused(r: Result<()>, reason: &str, what: &str) {
2378 match r {
2379 Ok(()) => panic!("{what}: ACCEPTED"),
2380 Err(e) => assert!(
2381 e.to_string().contains(reason),
2382 "{what}: refused with {e:?}, expected a reason containing {reason:?}"
2383 ),
2384 }
2385 }
2386
2387 struct Fixture {
2389 m: FapiManager,
2390 tok: String,
2391 key_a: (EncodingKey, serde_json::Value),
2392 key_b: (EncodingKey, serde_json::Value),
2393 now: i64,
2394 }
2395
2396 impl Fixture {
2397 fn new() -> Self {
2398 let (m, dpop, secret) = manager();
2399 let key_a = ec_key();
2400 let key_b = ec_key();
2401 let jkt = dpop.create_dpop_confirmation(&key_a.1).unwrap().jkt;
2402 let tok = token_for(&secret, &jkt);
2403 Fixture {
2404 m,
2405 tok,
2406 key_a,
2407 key_b,
2408 now: Utc::now().timestamp(),
2409 }
2410 }
2411
2412 fn good<'a>(&'a self, jti: &'a str) -> Proof<'a> {
2414 Proof {
2415 key: &self.key_a,
2416 htm: "GET",
2417 htu: URI,
2418 iat: self.now,
2419 jti,
2420 ath: Some(ath_of(&self.tok)),
2421 der: false,
2422 jwk_extra: None,
2423 }
2424 }
2425
2426 async fn present(&self, proof: &str) -> Result<()> {
2427 check(&self.m, &self.tok, Some(proof), "GET").await
2428 }
2429 }
2430
2431 #[tokio::test]
2432 async fn a_correct_proof_from_the_bound_key_is_accepted() {
2433 let f = Fixture::new();
2434 f.present(&f.good("j-ok").build())
2435 .await
2436 .expect("a correct proof from the bound key is accepted");
2437 }
2438
2439 #[tokio::test]
2440 async fn a_proof_from_another_key_is_refused_though_otherwise_correct() {
2441 let f = Fixture::new();
2442 let p = Proof {
2443 key: &f.key_b,
2444 ..f.good("j-other")
2445 }
2446 .build();
2447 refused(f.present(&p).await, "key binding", "other key");
2448 }
2449
2450 #[tokio::test]
2451 async fn a_proof_for_another_method_url_or_time_is_refused() {
2452 let f = Fixture::new();
2453 let p = Proof {
2454 htm: "DELETE",
2455 ..f.good("j-htm")
2456 }
2457 .build();
2458 refused(f.present(&p).await, "HTTP method", "wrong htm");
2459 let p = Proof {
2460 htu: "https://evil.example/x",
2461 ..f.good("j-htu")
2462 }
2463 .build();
2464 refused(f.present(&p).await, "HTTP URI", "wrong htu");
2465 let p = Proof {
2466 iat: f.now - 86_400,
2467 ..f.good("j-old")
2468 }
2469 .build();
2470 refused(f.present(&p).await, "too old", "one-day-old iat");
2471 let p = Proof {
2472 iat: f.now + 86_400,
2473 ..f.good("j-future")
2474 }
2475 .build();
2476 refused(f.present(&p).await, "in the future", "future iat");
2477 }
2478
2479 #[tokio::test]
2480 async fn a_proof_used_twice_is_refused_the_second_time() {
2481 let f = Fixture::new();
2482 let once = f.good("j-replay").build();
2483 f.present(&once).await.expect("first use");
2484 refused(f.present(&once).await, "already used", "replayed proof");
2485 }
2486
2487 #[tokio::test]
2488 async fn no_proof_is_refused_for_a_bound_token() {
2489 let f = Fixture::new();
2490 refused(
2491 check(&f.m, &f.tok, None, "GET").await,
2492 "no DPoP proof header",
2493 "no proof",
2494 );
2495 }
2496
2497 #[tokio::test]
2498 async fn a_proof_must_name_this_access_token() {
2499 let f = Fixture::new();
2500 let p = Proof {
2501 ath: None,
2502 ..f.good("j-no-ath")
2503 }
2504 .build();
2505 refused(f.present(&p).await, "'ath'", "no ath");
2506 let p = Proof {
2507 ath: Some(ath_of("another-token")),
2508 ..f.good("j-bad-ath")
2509 }
2510 .build();
2511 refused(f.present(&p).await, "access token hash", "wrong ath");
2512 }
2513
2514 #[tokio::test]
2515 async fn a_der_signature_or_a_private_key_in_the_header_is_refused() {
2516 let f = Fixture::new();
2517 let p = Proof {
2518 der: true,
2519 ..f.good("j-der")
2520 }
2521 .build();
2522 refused(f.present(&p).await, "r||s", "DER-encoded ES256 signature");
2523 let p = Proof {
2524 jwk_extra: Some(("d", "AAAA")),
2525 ..f.good("j-priv")
2526 }
2527 .build();
2528 refused(f.present(&p).await, "private key", "private key in jwk");
2529 }
2530
2531 #[tokio::test]
2532 async fn a_token_minted_by_the_manager_passes_its_own_resource_check() {
2533 let (m, dpop, secret) = manager();
2534 let key = ec_key();
2535 let jkt = dpop.create_dpop_confirmation(&key.1).unwrap().jkt;
2536 let claims =
2539 m.access_token_claims("client-1", "user-1", &["read".into()], &None, &Some(jkt));
2540 for field in ["typ", "nbf", "client_id"] {
2541 assert!(claims.get(field).is_some(), "minted claims lack {field}");
2542 }
2543 assert_eq!(claims["aud"], json!(ISS));
2544 let tok = sign_hs256(&secret, &claims);
2545 let proof = Proof {
2546 key: &key,
2547 htm: "GET",
2548 htu: URI,
2549 iat: Utc::now().timestamp(),
2550 jti: "j-minted",
2551 ath: Some(ath_of(&tok)),
2552 der: false,
2553 jwk_extra: None,
2554 }
2555 .build();
2556 check(&m, &tok, Some(&proof), "GET")
2557 .await
2558 .expect("a token built from the manager's own claims is accepted");
2559 }
2560
2561 #[tokio::test]
2562 async fn a_cnf_that_names_no_checkable_binding_is_refused() {
2563 let (m, _dpop, secret) = manager();
2564 let now = Utc::now().timestamp();
2565 for (cnf, what) in [
2566 (json!({}), "empty cnf"),
2567 (json!({"foo": "bar"}), "unknown member only"),
2568 (json!({"jkt": 5}), "jkt that is not a string"),
2569 ] {
2570 let tok = sign_hs256(
2571 &secret,
2572 &json!({
2573 "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2574 "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2575 "typ": "access", "cnf": cnf,
2576 }),
2577 );
2578 refused(check(&m, &tok, None, "GET").await, "cnf", what);
2579 }
2580 }
2581
2582 #[tokio::test]
2583 async fn a_proof_from_the_wrong_key_leaves_no_replay_record() {
2584 let f = Fixture::new();
2585 let p = Proof {
2586 key: &f.key_b,
2587 ..f.good("j-wrong-key")
2588 }
2589 .build();
2590 refused(f.present(&p).await, "key binding", "other key");
2591 assert_eq!(
2592 f.m.dpop_manager.replay_record_count().await,
2593 0,
2594 "a proof refused for its key must not take a cache slot"
2595 );
2596 f.present(&f.good("j-right-key").build())
2597 .await
2598 .expect("the bound key");
2599 assert_eq!(f.m.dpop_manager.replay_record_count().await, 1);
2600 }
2601
2602 #[tokio::test]
2603 async fn an_rs256_token_minted_by_the_manager_passes_the_resource_check() {
2604 let key =
2606 rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
2607 .unwrap();
2608 let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2609 let dpop = Arc::new(DpopManager::new(validator()));
2610 let config = FapiConfig::builder(
2611 ISS,
2612 EncodingKey::from_rsa_pem(key.serialize_pem().as_bytes()).unwrap(),
2613 DecodingKey::from_rsa_der(key.public_key_raw()),
2614 )
2615 .build();
2616 let m = FapiManager::new(
2617 config,
2618 dpop.clone(),
2619 Arc::new(MutualTlsManager::new()),
2620 Arc::new(PARManager::new(Arc::new(
2621 crate::storage::MemoryStorage::new(),
2622 ))),
2623 Arc::new(PrivateKeyJwtManager::new(validator())),
2624 Arc::new(
2625 SecureJwtValidator::new(SecureJwtConfig {
2626 allowed_algorithms: vec![Algorithm::RS256],
2627 required_issuers: [ISS.to_string()].into_iter().collect(),
2628 rsa_public_key_pem: Some(key.public_key_pem()),
2629 require_secure_transport: false,
2630 ..SecureJwtConfig::default()
2631 })
2632 .unwrap(),
2633 ),
2634 );
2635 let client = ec_key();
2636 let jkt = dpop.create_dpop_confirmation(&client.1).unwrap().jkt;
2637 let tok = m
2638 .generate_access_token("client-1", "user-1", &["read".into()], &None, &Some(jkt))
2639 .await
2640 .unwrap();
2641 let proof = Proof {
2642 key: &client,
2643 htm: "GET",
2644 htu: URI,
2645 iat: Utc::now().timestamp(),
2646 jti: "j-rs256",
2647 ath: Some(ath_of(&tok)),
2648 der: false,
2649 jwk_extra: None,
2650 }
2651 .build();
2652 check(&m, &tok, Some(&proof), "GET")
2653 .await
2654 .expect("an RS256 token minted by the manager is accepted");
2655 }
2656
2657 #[tokio::test]
2658 async fn a_wrong_certificate_does_not_use_up_the_proof() {
2659 let (m, dpop, secret) = manager();
2660 let key_a = ec_key();
2661 let jkt = dpop.create_dpop_confirmation(&key_a.1).unwrap().jkt;
2662 let cert = rcgen::CertificateParams::default()
2663 .self_signed(&rcgen::KeyPair::generate().unwrap())
2664 .unwrap();
2665 let other = rcgen::CertificateParams::default()
2666 .self_signed(&rcgen::KeyPair::generate().unwrap())
2667 .unwrap();
2668 let x5t = B64.encode(Sha256::digest(cert.der().as_ref()));
2669 let now = Utc::now().timestamp();
2670 let tok = sign_hs256(
2672 &secret,
2673 &json!({
2674 "iss": ISS, "aud": ISS, "sub": "user-1", "iat": now, "nbf": now - 1,
2675 "exp": now + 3600, "jti": Uuid::new_v4().to_string(), "scope": "read",
2676 "typ": "access", "cnf": {"jkt": jkt, "x5t#S256": x5t},
2677 }),
2678 );
2679 let proof = Proof {
2680 key: &key_a,
2681 htm: "GET",
2682 htu: URI,
2683 iat: now,
2684 jti: "j-both",
2685 ath: Some(ath_of(&tok)),
2686 der: false,
2687 jwk_extra: None,
2688 }
2689 .build();
2690 let wrong = m
2691 .validate_sender_constrained_token(&tok, Some(&proof), Some(&other.pem()), "GET", URI)
2692 .await
2693 .map(|_| ());
2694 refused(wrong, "Certificate thumbprint", "wrong certificate");
2695 assert_eq!(
2696 m.dpop_manager.replay_record_count().await,
2697 0,
2698 "a proof was recorded although the certificate was refused"
2699 );
2700 m.validate_sender_constrained_token(&tok, Some(&proof), Some(&cert.pem()), "GET", URI)
2701 .await
2702 .expect("both bindings satisfied");
2703 assert_eq!(m.dpop_manager.replay_record_count().await, 1);
2704 }
2705
2706 struct Limited {
2709 manager: FapiManager,
2710 assertions: Arc<PrivateKeyJwtManager>,
2711 key: EncodingKey,
2712 }
2713
2714 impl Limited {
2715 async fn new(max: Option<u32>) -> Self {
2717 use crate::distributed::rate_limiting::{RateLimitConfig, RateLimitStrategy};
2718 use crate::security::secure_jwt::SecureJwtConfig;
2719 use crate::server::jwt::private_key_jwt::ClientJwtConfig;
2720 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
2721
2722 let validator = || SecureJwtValidator::new(SecureJwtConfig::default()).unwrap();
2723 let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
2724 let mut manager = FapiManager::new(
2725 FapiConfig {
2726 require_dpop: false,
2727 ..FapiConfig::default()
2728 },
2729 Arc::new(DpopManager::new(validator())),
2730 Arc::new(MutualTlsManager::new()),
2731 Arc::new(PARManager::new(Arc::new(
2732 crate::storage::MemoryStorage::new(),
2733 ))),
2734 assertions.clone(),
2735 Arc::new(validator()),
2736 );
2737 if let Some(max_requests) = max {
2738 let limiter = DistributedRateLimiter::new(RateLimitConfig {
2739 max_requests,
2740 window_duration: std::time::Duration::from_secs(600),
2741 strategy: RateLimitStrategy::FixedWindow,
2742 distributed: false,
2743 redis_url: None,
2744 burst_allowance: None,
2745 adaptive: false,
2746 penalty_duration: None,
2747 })
2748 .await
2749 .unwrap();
2750 manager = manager.with_rate_limiter(Arc::new(limiter));
2751 }
2752 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2753 let raw = key.public_key_raw();
2754 let point = &raw[raw.len() - 65..];
2755 let jwk = json!({
2756 "kty": "EC", "crv": "P-256",
2757 "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
2758 "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
2759 });
2760 assertions
2761 .register_client(
2762 ClientJwtConfig::builder("fapi-client", jwk)
2763 .algorithms(vec![Algorithm::ES256])
2764 .audience("https://auth.example.com/token")
2765 .build(),
2766 )
2767 .await
2768 .unwrap();
2769 Self {
2770 manager,
2771 assertions,
2772 key: EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2773 }
2774 }
2775
2776 fn assertion(&self) -> String {
2778 self.assertions
2779 .create_client_assertion(
2780 "fapi-client",
2781 "https://auth.example.com/token",
2782 &self.key,
2783 Algorithm::ES256,
2784 )
2785 .unwrap()
2786 }
2787
2788 fn unauthenticated_assertion(&self) -> String {
2790 self.assertions
2791 .create_client_assertion(
2792 "fapi-client",
2793 "https://elsewhere.example/token",
2794 &self.key,
2795 Algorithm::ES256,
2796 )
2797 .unwrap()
2798 }
2799
2800 async fn token_from(&self, peer: &str, assertion: &str) -> Result<String> {
2801 self.manager
2802 .validate_token_request_from(peer, Some(assertion), None, None, "code")
2803 .await
2804 }
2805 }
2806
2807 fn is_rate_limited<T>(r: &Result<T>) -> bool {
2808 matches!(r, Err(AuthError::RateLimit { .. }))
2809 }
2810
2811 #[tokio::test]
2812 async fn the_address_bucket_refuses_before_any_signature_work() {
2813 let t = Limited::new(Some(2)).await;
2814 assert_eq!(
2816 t.token_from("203.0.113.1", &t.assertion()).await.unwrap(),
2817 "fapi-client"
2818 );
2819 assert!(!is_rate_limited(&t.token_from("203.0.113.1", "junk").await));
2821 let genuine = t.assertion();
2823 let over = t.token_from("203.0.113.1", &genuine).await;
2824 assert!(
2825 is_rate_limited(&over),
2826 "expected a rate-limit refusal, got {over:?}"
2827 );
2828 assert_eq!(
2831 t.token_from("203.0.113.2", &genuine).await.unwrap(),
2832 "fapi-client"
2833 );
2834 }
2835
2836 #[tokio::test]
2837 async fn the_client_bucket_is_not_escaped_by_changing_address() {
2838 let t = Limited::new(Some(2)).await;
2839 for peer in ["198.51.100.1", "198.51.100.2"] {
2840 assert_eq!(
2841 t.token_from(peer, &t.assertion()).await.unwrap(),
2842 "fapi-client"
2843 );
2844 }
2845 let over = t.token_from("198.51.100.3", &t.assertion()).await;
2846 assert!(
2847 is_rate_limited(&over),
2848 "expected a rate-limit refusal, got {over:?}"
2849 );
2850 }
2851
2852 #[tokio::test]
2853 async fn an_unauthenticated_request_naming_a_client_does_not_spend_its_bucket() {
2854 let t = Limited::new(Some(2)).await;
2855 for i in 0..6 {
2856 let r = t
2857 .token_from(&format!("192.0.2.{i}"), &t.unauthenticated_assertion())
2858 .await;
2859 assert!(r.is_err() && !is_rate_limited(&r), "round {i}: {r:?}");
2860 }
2861 for peer in ["192.0.2.100", "192.0.2.101"] {
2863 assert_eq!(
2864 t.token_from(peer, &t.assertion()).await.unwrap(),
2865 "fapi-client"
2866 );
2867 }
2868 }
2869
2870 #[tokio::test]
2871 async fn authorize_and_token_do_not_share_an_address_allowance() {
2872 let t = Limited::new(Some(1)).await;
2873 assert_eq!(
2874 t.token_from("203.0.113.9", &t.assertion()).await.unwrap(),
2875 "fapi-client"
2876 );
2877 let r = t
2878 .manager
2879 .validate_authorization_request_from("203.0.113.9", "junk", None, None, None)
2880 .await;
2881 assert!(
2882 r.is_err() && !is_rate_limited(&r),
2883 "authorize bucket was spent by token: {r:?}"
2884 );
2885 let again = t
2886 .manager
2887 .validate_authorization_request_from("203.0.113.9", "junk", None, None, None)
2888 .await;
2889 assert!(
2890 is_rate_limited(&again),
2891 "second authorize from one peer: {again:?}"
2892 );
2893 }
2894
2895 #[test]
2896 fn a_limiter_that_cannot_be_consulted_refuses() {
2897 let unavailable = FapiManager::limiter_outcome("k", Err(AuthError::internal("down")));
2898 assert!(unavailable.is_err() && !is_rate_limited(&unavailable));
2899 let blocked = FapiManager::limiter_outcome(
2900 "k",
2901 Ok(RateLimitResult::Blocked {
2902 unblock_at: std::time::Instant::now() + std::time::Duration::from_secs(30),
2903 reason: "test".to_string(),
2904 }),
2905 );
2906 assert!(is_rate_limited(&blocked));
2907 }
2908
2909 #[tokio::test]
2910 async fn without_a_limiter_the_from_entry_points_count_nothing() {
2911 let t = Limited::new(None).await;
2912 for _ in 0..5 {
2913 assert_eq!(
2914 t.token_from("203.0.113.5", &t.assertion()).await.unwrap(),
2915 "fapi-client"
2916 );
2917 }
2918 }
2919}