use crate::errors::{AuthError, Result};
use crate::security::secure_jwt::SecureJwtValidator;
use crate::server::{DpopManager, MutualTlsManager, PARManager, PrivateKeyJwtManager};
use chrono::{DateTime, Duration, Utc};
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;
#[derive(Clone)]
pub struct FapiManager {
dpop_manager: Arc<DpopManager>,
mtls_manager: Arc<MutualTlsManager>,
par_manager: Arc<PARManager>,
private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
jwt_validator: Arc<SecureJwtValidator>,
config: FapiConfig,
sessions: Arc<RwLock<HashMap<String, FapiSession>>>,
}
impl std::fmt::Debug for FapiManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("FapiManager");
d.field("dpop_manager", &self.dpop_manager);
d.field("mtls_manager", &self.mtls_manager);
d.field("par_manager", &self.par_manager);
d.field("private_key_jwt_manager", &self.private_key_jwt_manager);
d.field("jwt_validator", &self.jwt_validator);
d.field("config", &self.config);
d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
d.finish()
}
}
#[derive(Clone)]
pub struct FapiConfig {
pub issuer: String,
pub request_signing_algorithm: Algorithm,
pub response_signing_algorithm: Algorithm,
pub private_key: EncodingKey,
pub public_key: DecodingKey,
pub max_request_age: i64,
pub require_dpop: bool,
pub require_mtls: bool,
pub require_par: bool,
pub enable_jarm: bool,
pub enhanced_audit: bool,
}
impl std::fmt::Debug for FapiConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FapiConfig")
.field("issuer", &self.issuer)
.field("request_signing_algorithm", &self.request_signing_algorithm)
.field(
"response_signing_algorithm",
&self.response_signing_algorithm,
)
.field("private_key", &"<EncodingKey>")
.field("public_key", &"<DecodingKey>")
.field("max_request_age", &self.max_request_age)
.field("require_dpop", &self.require_dpop)
.field("require_mtls", &self.require_mtls)
.field("require_par", &self.require_par)
.field("enable_jarm", &self.enable_jarm)
.field("enhanced_audit", &self.enhanced_audit)
.finish()
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct FapiSession {
pub session_id: String,
pub client_id: String,
pub user_id: String,
pub created_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
pub dpop_proof: Option<String>,
pub cert_thumbprint: Option<String>,
pub request_jti: Option<String>,
pub scopes: Vec<String>,
pub metadata: HashMap<String, Value>,
}
impl std::fmt::Debug for FapiSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("FapiSession");
d.field(
"session_id",
&crate::utils::redact::redacted(&self.session_id),
);
d.field("client_id", &self.client_id);
d.field("user_id", &self.user_id);
d.field("created_at", &self.created_at);
d.field("expires_at", &self.expires_at);
d.field(
"dpop_proof",
&crate::utils::redact::redacted(&self.dpop_proof),
);
d.field("cert_thumbprint", &self.cert_thumbprint);
d.field("request_jti", &self.request_jti);
d.field("scopes", &self.scopes);
d.field("metadata", &self.metadata);
d.finish()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FapiRequestObject {
pub iss: String,
pub aud: String,
pub iat: i64,
pub exp: i64,
pub nbf: Option<i64>,
pub jti: String,
pub response_type: String,
pub client_id: String,
pub redirect_uri: String,
pub scope: String,
pub state: Option<String>,
pub nonce: Option<String>,
pub code_challenge: Option<String>,
pub code_challenge_method: Option<String>,
#[serde(flatten)]
pub additional_claims: HashMap<String, Value>,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct FapiAuthorizationResponse {
pub iss: String,
pub aud: String,
pub iat: i64,
pub exp: i64,
pub code: Option<String>,
pub state: Option<String>,
pub error: Option<String>,
pub error_description: Option<String>,
#[serde(flatten)]
pub additional_params: HashMap<String, Value>,
}
impl std::fmt::Debug for FapiAuthorizationResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("FapiAuthorizationResponse");
d.field("iss", &self.iss);
d.field("aud", &self.aud);
d.field("iat", &self.iat);
d.field("exp", &self.exp);
d.field("code", &crate::utils::redact::redacted(&self.code));
d.field("state", &self.state);
d.field("error", &self.error);
d.field("error_description", &self.error_description);
d.field(
"additional_params",
&crate::utils::redact::redacted(&self.additional_params),
);
d.finish()
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct FapiTokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: i64,
pub refresh_token: Option<String>,
pub scope: Option<String>,
pub id_token: Option<String>,
pub cnf: Option<Value>,
}
impl std::fmt::Debug for FapiTokenResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("FapiTokenResponse");
d.field(
"access_token",
&crate::utils::redact::redacted(&self.access_token),
);
d.field("token_type", &self.token_type);
d.field("expires_in", &self.expires_in);
d.field(
"refresh_token",
&crate::utils::redact::redacted(&self.refresh_token),
);
d.field("scope", &self.scope);
d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
d.field("cnf", &self.cnf);
d.finish()
}
}
fn request_object_too_old(now: i64, iat: i64, max_age: i64) -> bool {
now.checked_sub(iat).is_none_or(|age| age > max_age)
}
impl FapiManager {
pub fn new(
config: FapiConfig,
dpop_manager: Arc<DpopManager>,
mtls_manager: Arc<MutualTlsManager>,
par_manager: Arc<PARManager>,
private_key_jwt_manager: Arc<PrivateKeyJwtManager>,
jwt_validator: Arc<SecureJwtValidator>,
) -> Self {
Self {
dpop_manager,
mtls_manager,
par_manager,
private_key_jwt_manager,
jwt_validator,
config,
sessions: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn validate_authorization_request(
&self,
request_object: &str,
client_cert: Option<&str>,
dpop_proof: Option<&str>,
request_uri: Option<&str>,
) -> Result<FapiRequestObject> {
let claims = if let Some(uri) = request_uri {
if self.config.require_par {
let par_request = self.par_manager.consume_request(uri).await.map_err(|e| {
AuthError::InvalidRequest(format!("PAR request validation failed: {}", e))
})?;
tracing::info!(
"FAPI PAR request consumed successfully for client: {}",
par_request.client_id
);
FapiRequestObject {
iss: par_request.client_id.clone(),
aud: self.config.issuer.clone(),
iat: Utc::now().timestamp(),
exp: Utc::now().timestamp() + 300, nbf: Some(Utc::now().timestamp()),
jti: uuid::Uuid::new_v4().to_string(),
response_type: par_request.response_type,
client_id: par_request.client_id,
redirect_uri: par_request.redirect_uri,
scope: par_request.scope.unwrap_or_default(),
state: par_request.state,
nonce: None, code_challenge: par_request.code_challenge,
code_challenge_method: par_request.code_challenge_method,
additional_claims: par_request
.additional_params
.into_iter()
.map(|(k, v)| (k, serde_json::Value::String(v)))
.collect(),
}
} else {
return Err(AuthError::InvalidRequest(
"request_uri provided but PAR not required".to_string(),
));
}
} else {
if self.config.require_par {
return Err(AuthError::InvalidRequest(
"PAR is required but no request_uri provided".to_string(),
));
}
self.validate_request_object(request_object).await?
};
if self.config.require_mtls {
let cert = client_cert.ok_or_else(|| {
AuthError::auth_method("mtls", "mTLS certificate required for FAPI 2.0")
})?;
let cert_bytes = decode_client_certificate(cert)?;
self.mtls_manager
.validate_client_certificate(&cert_bytes, &claims.client_id)
.await?;
}
let pending_proof = if self.config.require_dpop {
let Some(proof) = dpop_proof else {
return Err(AuthError::auth_method(
"dpop",
"DPoP proof required for FAPI 2.0",
));
};
Some(
self.dpop_manager
.verify_dpop_proof(
proof,
"POST",
&format!("{}/authorize", self.config.issuer),
None,
None,
None,
)
.await?,
)
} else {
None
};
self.validate_request_claims(&claims).await?;
if let Some(pending) = pending_proof {
self.dpop_manager.commit_dpop_proof(pending).await?;
}
Ok(claims)
}
async fn validate_request_object(&self, request_object: &str) -> Result<FapiRequestObject> {
let decoding_key = &self.config.public_key;
match self
.jwt_validator
.validate_token(request_object, decoding_key, true)
{
Ok(secure_claims) => {
let header = jsonwebtoken::decode_header(request_object).map_err(|e| {
AuthError::InvalidToken(format!("Invalid request object header: {}", e))
})?;
if !matches!(
header.alg,
Algorithm::RS256 | Algorithm::PS256 | Algorithm::ES256
) {
return Err(AuthError::InvalidToken(
"Request object must use RS256, PS256, or ES256".to_string(),
));
}
let mut validation = Validation::new(header.alg);
validation.set_audience(&[&self.config.issuer]);
validation.validate_exp = true;
validation.validate_nbf = true;
let token_data = jsonwebtoken::decode::<FapiRequestObject>(
request_object,
&self.config.public_key,
&validation,
)
.map_err(|e| {
AuthError::InvalidToken(format!("Request object validation failed: {}", e))
})?;
let fapi_claims = token_data.claims;
if secure_claims.sub != fapi_claims.client_id {
return Err(AuthError::InvalidToken(
"Subject mismatch between secure validation and FAPI claims".to_string(),
));
}
if secure_claims.iss != fapi_claims.iss {
return Err(AuthError::InvalidToken(
"Issuer mismatch between secure validation and FAPI claims".to_string(),
));
}
if secure_claims.exp != fapi_claims.exp {
return Err(AuthError::InvalidToken(
"Expiry mismatch between secure validation and FAPI claims".to_string(),
));
}
let now = Utc::now().timestamp();
if request_object_too_old(now, fapi_claims.iat, self.config.max_request_age) {
return Err(AuthError::InvalidToken(
"Request object too old".to_string(),
));
}
if fapi_claims.client_id.is_empty() {
return Err(AuthError::InvalidToken(
"client_id required in request object".to_string(),
));
}
if fapi_claims.redirect_uri.is_empty() {
return Err(AuthError::InvalidToken(
"redirect_uri required in request object".to_string(),
));
}
if fapi_claims.response_type.is_empty() {
return Err(AuthError::InvalidToken(
"response_type required in request object".to_string(),
));
}
tracing::info!(
"FAPI request object validated successfully with SecureJwtValidator for client: {}",
fapi_claims.client_id
);
Ok(fapi_claims)
}
Err(e) => {
tracing::error!("SecureJwtValidator failed for FAPI request object: {}", e);
Err(AuthError::InvalidToken(format!(
"Enhanced JWT validation failed: {}",
e
)))
}
}
}
async fn validate_request_claims(&self, claims: &FapiRequestObject) -> Result<()> {
if !matches!(claims.response_type.as_str(), "code" | "code id_token") {
return Err(AuthError::InvalidRequest(
"FAPI 2.0 requires code or code id_token response type".to_string(),
));
}
if claims.code_challenge.is_none() {
return Err(AuthError::InvalidRequest(
"PKCE required for FAPI 2.0".to_string(),
));
}
if let Some(method) = &claims.code_challenge_method {
if method != "S256" {
return Err(AuthError::InvalidRequest(
"FAPI 2.0 requires S256 code challenge method".to_string(),
));
}
} else {
return Err(AuthError::InvalidRequest(
"code_challenge_method required for FAPI 2.0".to_string(),
));
}
Ok(())
}
pub async fn authenticate_client_jwt(&self, client_assertion: &str) -> Result<String> {
const REFUSED: &str = "Client authentication failed";
let auth_result = match self
.private_key_jwt_manager
.authenticate_client(client_assertion)
.await
{
Ok(result) => result,
Err(e) => {
tracing::warn!("FAPI private key JWT assertion rejected: {}", e);
return Err(AuthError::auth_method("private_key_jwt", REFUSED));
}
};
if auth_result.authenticated {
tracing::info!(
"FAPI client authenticated successfully using private key JWT: {}",
auth_result.client_id
);
Ok(auth_result.client_id)
} else {
tracing::warn!(
"FAPI private key JWT authentication failed: {}",
auth_result.errors.join("; ")
);
Err(AuthError::auth_method("private_key_jwt", REFUSED))
}
}
pub async fn validate_token_request(
&self,
client_assertion: Option<&str>,
client_cert: Option<&str>,
dpop_proof: Option<&str>,
_authorization_code: &str,
) -> Result<String> {
let client_id = if let Some(assertion) = client_assertion {
self.authenticate_client_jwt(assertion).await?
} else if self.config.require_mtls {
if let Some(cert) = client_cert {
let cert_bytes = decode_client_certificate(cert)?;
let client_id = self.extract_client_id_from_certificate(&cert_bytes).await?;
self.mtls_manager
.validate_client_certificate(&cert_bytes, &client_id)
.await?;
client_id.to_string()
} else {
return Err(AuthError::auth_method(
"mtls",
"Client certificate required for FAPI 2.0 token request",
));
}
} else {
return Err(AuthError::auth_method(
"fapi",
"FAPI 2.0 requires either private_key_jwt or mTLS client authentication",
));
};
if self.config.require_dpop {
if dpop_proof.is_none() {
return Err(AuthError::auth_method(
"dpop",
"DPoP proof required for FAPI 2.0 token request",
));
}
let proof = dpop_proof.unwrap();
self.dpop_manager
.validate_dpop_proof(
proof,
"POST",
&format!("{}/token", self.config.issuer),
None, None,
)
.await?;
}
Ok(client_id)
}
pub async fn generate_authorization_response(
&self,
client_id: &str,
code: Option<&str>,
state: Option<&str>,
error: Option<&str>,
error_description: Option<&str>,
) -> Result<String> {
if !self.config.enable_jarm {
return Err(AuthError::Configuration {
message: "JARM not enabled".to_string(),
help: Some("Enable JARM in your configuration to use this feature".to_string()),
docs_url: Some("https://docs.auth-framework.com/fapi#jarm".to_string()),
source: None,
suggested_fix: Some("Set enable_jarm to true in your FAPIConfig".to_string()),
});
}
let now = Utc::now();
let exp = now + Duration::minutes(5);
let response = FapiAuthorizationResponse {
iss: self.config.issuer.clone(),
aud: client_id.to_string(),
iat: now.timestamp(),
exp: exp.timestamp(),
code: code.map(|c| c.to_string()),
state: state.map(|s| s.to_string()),
error: error.map(|e| e.to_string()),
error_description: error_description.map(|d| d.to_string()),
additional_params: HashMap::new(),
};
let header = Header::new(self.config.response_signing_algorithm);
let token =
jsonwebtoken::encode(&header, &response, &self.config.private_key).map_err(|e| {
AuthError::TokenGeneration(format!("Failed to sign JARM response: {}", e))
})?;
Ok(token)
}
pub async fn generate_token_response(
&self,
client_id: &str,
user_id: &str,
scopes: Vec<String>,
cert_thumbprint: Option<String>,
dpop_jkt: Option<String>,
) -> Result<FapiTokenResponse> {
let access_token = self
.generate_access_token(client_id, user_id, &scopes, &cert_thumbprint, &dpop_jkt)
.await?;
let refresh_token = self.generate_refresh_token(client_id, user_id).await?;
let mut cnf = json!({});
if let Some(thumbprint) = cert_thumbprint {
cnf["x5t#S256"] = Value::String(thumbprint);
}
if let Some(jkt) = dpop_jkt {
cnf["jkt"] = Value::String(jkt);
}
let response = FapiTokenResponse {
access_token,
token_type: "DPoP".to_string(), expires_in: 3600, refresh_token: Some(refresh_token),
scope: Some(scopes.join(" ")),
id_token: None, cnf: if cnf.as_object().unwrap().is_empty() {
None
} else {
Some(cnf)
},
};
Ok(response)
}
async fn generate_access_token(
&self,
client_id: &str,
user_id: &str,
scopes: &[String],
cert_thumbprint: &Option<String>,
dpop_jkt: &Option<String>,
) -> Result<String> {
let now = Utc::now();
let exp = now + Duration::hours(1);
let mut claims = json!({
"iss": self.config.issuer,
"aud": client_id,
"sub": user_id,
"iat": now.timestamp(),
"exp": exp.timestamp(),
"scope": scopes.join(" "),
"jti": Uuid::new_v4().to_string(),
});
let mut cnf = json!({});
if let Some(thumbprint) = cert_thumbprint {
cnf["x5t#S256"] = Value::String(thumbprint.clone());
}
if let Some(jkt) = dpop_jkt {
cnf["jkt"] = Value::String(jkt.clone());
}
if !cnf.as_object().unwrap().is_empty() {
claims["cnf"] = cnf;
}
let header = Header::new(Algorithm::RS256);
let token =
jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
AuthError::TokenGeneration(format!("Failed to generate access token: {}", e))
})?;
Ok(token)
}
async fn generate_refresh_token(&self, client_id: &str, user_id: &str) -> Result<String> {
let now = Utc::now();
let exp = now + Duration::days(30);
let claims = json!({
"iss": self.config.issuer,
"aud": client_id,
"sub": user_id,
"iat": now.timestamp(),
"exp": exp.timestamp(),
"typ": "refresh_token",
"jti": Uuid::new_v4().to_string(),
});
let header = Header::new(Algorithm::RS256);
let token =
jsonwebtoken::encode(&header, &claims, &self.config.private_key).map_err(|e| {
AuthError::TokenGeneration(format!("Failed to generate refresh token: {}", e))
})?;
Ok(token)
}
pub async fn create_session(
&self,
client_id: &str,
user_id: &str,
scopes: Vec<String>,
dpop_proof: Option<String>,
cert_thumbprint: Option<String>,
request_jti: Option<String>,
) -> Result<String> {
let session_id = Uuid::new_v4().to_string();
let now = Utc::now();
let expires_at = now + Duration::hours(24);
let session = FapiSession {
session_id: session_id.clone(),
client_id: client_id.to_string(),
user_id: user_id.to_string(),
created_at: now,
expires_at,
dpop_proof,
cert_thumbprint,
request_jti,
scopes,
metadata: HashMap::new(),
};
let mut sessions = self.sessions.write().await;
sessions.insert(session_id.clone(), session);
Ok(session_id)
}
pub async fn get_session(&self, session_id: &str) -> Result<Option<FapiSession>> {
let sessions = self.sessions.read().await;
Ok(sessions.get(session_id).cloned())
}
pub async fn validate_session(&self, session_id: &str) -> Result<FapiSession> {
let session = self
.get_session(session_id)
.await?
.ok_or_else(|| AuthError::validation("Session not found".to_string()))?;
if Utc::now() > session.expires_at {
return Err(AuthError::validation("Session expired".to_string()));
}
Ok(session)
}
pub async fn remove_session(&self, session_id: &str) -> Result<()> {
let mut sessions = self.sessions.write().await;
sessions.remove(session_id);
Ok(())
}
pub async fn audit_log(&self, event: &str, details: &Value) -> Result<()> {
if self.config.enhanced_audit {
let timestamp = chrono::Utc::now().to_rfc3339();
let audit_entry = format!("[{}] FAPI AUDIT: {} - {}", timestamp, event, details);
log::info!("{}", audit_entry);
}
Ok(())
}
async fn extract_client_id_from_certificate(&self, cert_bytes: &[u8]) -> Result<String> {
client_id_from_certificate(cert_bytes)
}
}
impl Default for FapiConfig {
fn default() -> Self {
let issuer =
std::env::var("FAPI_ISSUER").unwrap_or_else(|_| "https://auth.example.com".to_string());
let private_key = if let Ok(key_path) = std::env::var("FAPI_PRIVATE_KEY_PATH") {
std::fs::read(&key_path)
.map_err(|e| tracing::warn!("Failed to load private key from {}: {}", key_path, e))
.and_then(|bytes| {
EncodingKey::from_rsa_pem(&bytes)
.map_err(|e| tracing::warn!("Invalid RSA key format: {}", e))
})
.unwrap_or_else(|_| EncodingKey::from_secret(b"dev_fallback_secret"))
} else {
EncodingKey::from_secret(b"dev_fallback_secret")
};
Self {
issuer,
request_signing_algorithm: Algorithm::RS256,
response_signing_algorithm: Algorithm::RS256,
private_key,
public_key: DecodingKey::from_secret(b"dev_secret"),
max_request_age: 300, require_dpop: true,
require_mtls: true,
require_par: true,
enable_jarm: true,
enhanced_audit: true,
}
}
}
fn decode_client_certificate(input: &str) -> Result<Vec<u8>> {
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
const END: &str = "-----END CERTIFICATE-----";
let bad = || {
AuthError::auth_method(
"mtls",
"Client certificate must be PEM or base64-encoded DER",
)
};
let trimmed = input.trim();
let body = if let Some(rest) = trimmed.strip_prefix(BEGIN) {
let end = rest.find(END).ok_or_else(bad)?;
if !rest[end + END.len()..].trim().is_empty() {
return Err(bad());
}
&rest[..end]
} else {
trimmed
};
let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
if compact.is_empty() {
return Err(bad());
}
STANDARD
.decode(&compact)
.or_else(|_| STANDARD_NO_PAD.decode(&compact))
.or_else(|_| URL_SAFE.decode(&compact))
.or_else(|_| URL_SAFE_NO_PAD.decode(&compact))
.map_err(|_| bad())
}
fn client_id_from_certificate(cert_der: &[u8]) -> Result<String> {
use x509_parser::extensions::GeneralName;
let cert = match x509_parser::parse_x509_certificate(cert_der) {
Ok(([], cert)) => cert,
_ => {
return Err(AuthError::auth_method(
"mtls",
"Invalid client certificate format",
));
}
};
let common_names: Vec<String> = cert
.subject()
.iter_common_name()
.filter_map(|cn| cn.as_str().ok().map(str::to_string))
.collect();
if common_names.len() == 1 && !common_names[0].is_empty() {
return Ok(common_names[0].clone());
}
if let Ok(Some(san)) = cert.subject_alternative_name() {
let names: Vec<String> = san
.value
.general_names
.iter()
.filter_map(|name| match name {
GeneralName::DNSName(dns) => Some(dns.to_string()),
GeneralName::URI(uri) => Some(uri.to_string()),
_ => None,
})
.collect();
if names.len() == 1 {
return Ok(names[0].clone());
}
}
Err(AuthError::auth_method(
"mtls",
"Cannot derive a unique client id from the certificate (need one subject CN or one SAN)",
))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn private_key_jwt_failures_do_not_tell_the_caller_why() {
use crate::security::secure_jwt::SecureJwtConfig;
use crate::server::jwt::private_key_jwt::ClientJwtConfig;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
let validator = || SecureJwtValidator::new(SecureJwtConfig::default());
let assertions = Arc::new(PrivateKeyJwtManager::new(validator()));
let manager = FapiManager::new(
FapiConfig::default(),
Arc::new(DpopManager::new(validator())),
Arc::new(MutualTlsManager::new()),
Arc::new(PARManager::new(Arc::new(
crate::storage::MemoryStorage::new(),
))),
assertions.clone(),
Arc::new(validator()),
);
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
let raw = key.public_key_raw();
let point = &raw[raw.len() - 65..];
let jwk = json!({
"kty": "EC", "crv": "P-256",
"x": URL_SAFE_NO_PAD.encode(&point[1..33]),
"y": URL_SAFE_NO_PAD.encode(&point[33..65]),
});
assertions
.register_client(
ClientJwtConfig::builder("fapi-client", jwk)
.algorithms(vec![Algorithm::ES256])
.audience("https://auth.example.com/token")
.build(),
)
.await
.unwrap();
let signing_pem = key.serialize_pem();
let good = assertions
.create_client_assertion(
"fapi-client",
"https://auth.example.com/token",
signing_pem.as_bytes(),
Algorithm::ES256,
)
.unwrap();
assert_eq!(
manager.authenticate_client_jwt(&good).await.unwrap(),
"fapi-client"
);
let wrong_audience = assertions
.create_client_assertion(
"fapi-client",
"https://elsewhere.example/token",
signing_pem.as_bytes(),
Algorithm::ES256,
)
.unwrap();
let unknown = assertions
.create_client_assertion(
"ghost",
"https://auth.example.com/token",
signing_pem.as_bytes(),
Algorithm::ES256,
)
.unwrap();
for (why, assertion) in [
("wrong audience", wrong_audience.as_str()),
("unknown client", unknown.as_str()),
("replay", good.as_str()),
("junk", "not-a-jwt"),
] {
let message = manager
.authenticate_client_jwt(assertion)
.await
.expect_err(why)
.to_string();
assert!(
message.contains("Client authentication failed"),
"{why}: {message}"
);
for leak in [
"udience",
"registered",
"ignature",
"replay",
"JTI",
"Algorithm",
"expired",
] {
assert!(
!message.contains(leak),
"{why}: {message:?} mentions {leak:?}"
);
}
}
}
#[tokio::test]
async fn test_fapi_manager_creation() {
let config = FapiConfig::default();
assert_eq!(config.issuer, "https://auth.example.com"); assert!(config.require_dpop);
assert!(config.require_mtls);
assert!(config.require_par);
assert!(config.enable_jarm);
assert!(config.enhanced_audit);
}
#[tokio::test]
async fn test_fapi_request_validation() {
let config = FapiConfig::default();
let request_object = r#"{"iss":"client_id","aud":"https://example.com","exp":9999999999,"nbf":1000000000,"iat":1000000000,"jti":"unique_id"}"#;
let validation_result = validate_fapi_request_object(request_object, &config);
assert!(
validation_result.is_ok(),
"FAPI request object validation failed"
);
assert!(!request_object.is_empty());
}
fn validate_fapi_request_object(
request_object: &str,
_config: &FapiConfig,
) -> Result<(), String> {
let parsed: serde_json::Value = serde_json::from_str(request_object)
.map_err(|_| "Invalid JSON structure in request object")?;
let required_claims = ["iss", "aud", "exp", "iat", "jti"];
for claim in &required_claims {
if parsed.get(claim).is_none() {
return Err(format!("Missing required FAPI claim: {}", claim));
}
}
if let Some(exp) = parsed.get("exp").and_then(|v| v.as_i64()) {
let now = chrono::Utc::now().timestamp();
if exp <= now {
return Err("Request object has expired".to_string());
}
}
Ok(())
}
#[tokio::test]
async fn test_fapi_response_generation() {
let config = FapiConfig::default();
let auth_response = serde_json::json!({
"code": "auth_code_123",
"state": "client_state",
"iss": config.issuer,
"aud": "client_id",
"exp": 9999999999i64
});
assert!(auth_response["code"].is_string());
}
#[tokio::test]
async fn test_fapi_token_generation() {
let config = FapiConfig::default();
let scopes = ["accounts".to_string(), "payments".to_string()];
let client_id = "fapi_client_123";
let user_id = "user_456";
let cert_thumbprint = Some("sha256_cert_thumbprint".to_string());
assert!(config.require_dpop);
assert!(config.require_mtls);
assert!(!scopes.is_empty());
assert!(!client_id.is_empty());
assert!(!user_id.is_empty());
assert!(cert_thumbprint.is_some());
}
#[tokio::test]
async fn test_fapi_session_management() {
let config = FapiConfig::default();
let session_data = serde_json::json!({
"client_id": "fapi_client",
"user_id": "fapi_user",
"scopes": ["accounts", "payments"],
"mtls_cert": "client_certificate",
"dpop_key": "client_dpop_key"
});
assert!(session_data["mtls_cert"].is_string());
assert!(session_data["dpop_key"].is_string());
assert!(config.enhanced_audit);
}
fn test_cert(cn: &str, org: Option<&str>) -> rcgen::Certificate {
let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
let mut dn = rcgen::DistinguishedName::new();
dn.push(rcgen::DnType::CommonName, cn);
if let Some(org) = org {
dn.push(rcgen::DnType::OrganizationName, org);
}
params.distinguished_name = dn;
let key = rcgen::KeyPair::generate().unwrap();
params.self_signed(&key).unwrap()
}
#[test]
fn decode_client_certificate_accepts_pem_and_base64_der() {
use base64::Engine;
let cert = test_cert("client-a", None);
let der = cert.der().to_vec();
assert_eq!(decode_client_certificate(&cert.pem()).unwrap(), der);
let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
assert_eq!(decode_client_certificate(&b64).unwrap(), der);
let wrapped = format!(" {}\n{} \n", &b64[..20], &b64[20..]);
assert_eq!(decode_client_certificate(&wrapped).unwrap(), der);
}
#[test]
fn decode_client_certificate_rejects_garbage_and_extra_certificates() {
let a = test_cert("client-a", None).pem();
let b = test_cert("client-b", None).pem();
assert!(decode_client_certificate("").is_err());
assert!(decode_client_certificate("!!! not base64 !!!").is_err());
assert!(decode_client_certificate("-----BEGIN CERTIFICATE-----\nAAAA").is_err());
assert!(decode_client_certificate(&format!("{a}{b}")).is_err());
}
#[test]
fn client_id_comes_from_the_parsed_subject_cn() {
let cert = test_cert("client-a", None);
assert_eq!(client_id_from_certificate(cert.der()).unwrap(), "client-a");
}
#[test]
fn client_id_is_not_found_by_searching_the_raw_bytes() {
let cert = test_cert("real-client", Some("CN=victim-client,"));
assert_eq!(
client_id_from_certificate(cert.der()).unwrap(),
"real-client"
);
}
#[test]
fn client_id_needs_a_unique_identity() {
let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
params.distinguished_name = rcgen::DistinguishedName::new(); let key = rcgen::KeyPair::generate().unwrap();
let nameless = params.self_signed(&key).unwrap();
assert!(client_id_from_certificate(nameless.der()).is_err());
assert!(client_id_from_certificate(b"not a certificate").is_err());
}
}
#[cfg(test)]
mod request_object_age {
use super::*;
#[test]
fn an_age_that_cannot_be_represented_is_too_old() {
let now = Utc::now().timestamp();
assert!(!request_object_too_old(now, now, 60));
assert!(!request_object_too_old(now, now - 60, 60));
assert!(request_object_too_old(now, now - 61, 60));
assert!(request_object_too_old(now, i64::MIN, 60));
assert!(request_object_too_old(now, i64::MIN + 1, 60));
assert!(request_object_too_old(i64::MAX, -1, 60));
}
}