use std::future::Future;
use std::pin::Pin;
use actix_web::http::Method;
use actix_web::{HttpRequest, HttpResponse, dev::Payload, web};
use serde::Serialize;
use subtle::ConstantTimeEq;
use uuid::Uuid;
use crate::AxiamError;
use crate::token::JwksVerifier;
const CSRF_COOKIE_NAME: &str = crate::token::manager::COOKIE_CSRF;
const CSRF_HEADER_NAME: &str = "X-CSRF-Token";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeerCertificate {
thumbprint: String,
}
impl PeerCertificate {
#[must_use]
pub fn from_der(der: &[u8]) -> Self {
Self {
thumbprint: crate::token::certificate_thumbprint_s256(der),
}
}
#[must_use]
pub fn thumbprint(&self) -> &str {
&self.thumbprint
}
}
#[derive(Debug, Clone)]
pub struct AxiamUser {
pub user_id: Uuid,
pub tenant_id: Uuid,
pub roles: Vec<String>,
}
#[derive(Debug)]
pub struct AxiamExtractorError {
error: AxiamError,
challenge: Option<String>,
}
impl From<AxiamError> for AxiamExtractorError {
fn from(err: AxiamError) -> Self {
Self {
error: err,
challenge: None,
}
}
}
impl std::fmt::Display for AxiamExtractorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.error)
}
}
#[derive(Serialize)]
struct ErrorBody {
error: String,
message: String,
}
impl actix_web::ResponseError for AxiamExtractorError {
fn status_code(&self) -> actix_web::http::StatusCode {
match &self.error {
AxiamError::Auth { .. } => actix_web::http::StatusCode::UNAUTHORIZED,
AxiamError::Authz { .. } => actix_web::http::StatusCode::FORBIDDEN,
AxiamError::Network { .. } => actix_web::http::StatusCode::UNAUTHORIZED,
}
}
fn error_response(&self) -> HttpResponse {
let (error, message) = match &self.error {
AxiamError::Auth { message, .. } => ("authentication_failed", message.clone()),
AxiamError::Authz { message, .. } => ("authorization_denied", message.clone()),
AxiamError::Network { message, .. } => ("authentication_failed", message.clone()),
};
let mut builder = HttpResponse::build(self.status_code());
if let Some(challenge) = &self.challenge {
builder.insert_header((
actix_web::http::header::WWW_AUTHENTICATE,
challenge.as_str(),
));
}
builder.json(ErrorBody {
error: error.into(),
message,
})
}
}
impl AxiamExtractorError {
pub fn error(&self) -> &AxiamError {
&self.error
}
fn auth(message: impl Into<String>, challenge: Option<String>) -> Self {
Self {
error: AxiamError::Auth {
message: message.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
},
challenge,
}
}
fn missing_credentials(challenge: Option<String>) -> Self {
Self::auth("missing authentication credentials", challenge)
}
fn invalid_scheme(challenge: Option<String>) -> Self {
Self::auth("invalid Authorization scheme, expected Bearer", challenge)
}
fn misconfigured(challenge: Option<String>) -> Self {
Self::auth(
"missing JwksVerifier app_data — extractor misconfigured",
challenge,
)
}
fn invalid_claim(name: &str, challenge: Option<String>) -> Self {
Self::auth(format!("invalid {name} claim"), challenge)
}
fn csrf_validation_failed() -> Self {
Self {
error: AxiamError::Authz {
kind: crate::error::AuthzKind::Denied,
message: "CSRF validation failed: missing or mismatched X-CSRF-Token header".into(),
action: None,
resource_id: None,
reason_code: None,
},
challenge: None,
}
}
}
fn is_state_changing(method: &Method) -> bool {
!matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
}
fn csrf_valid(req: &HttpRequest) -> bool {
let header_value = match req
.headers()
.get(CSRF_HEADER_NAME)
.and_then(|v| v.to_str().ok())
{
Some(v) if !v.is_empty() => v,
_ => return false,
};
let cookie_value = match req.cookie(CSRF_COOKIE_NAME) {
Some(c) if !c.value().is_empty() => c,
_ => return false,
};
bool::from(
header_value
.as_bytes()
.ct_eq(cookie_value.value().as_bytes()),
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CredentialSource {
Cookie,
AuthorizationHeader,
}
fn extract_token(
req: &HttpRequest,
no_credential_challenge: Option<String>,
) -> Result<(String, CredentialSource), AxiamExtractorError> {
if let Some(cookie) = req.cookie("axiam_access") {
return Ok((cookie.value().to_owned(), CredentialSource::Cookie));
}
let header = req
.headers()
.get("Authorization")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| AxiamExtractorError::missing_credentials(no_credential_challenge.clone()))?;
let header = header.trim();
let mut parts = header.splitn(2, char::is_whitespace);
let scheme = parts.next().unwrap_or("");
let credentials = parts.next().unwrap_or("").trim();
if !scheme.eq_ignore_ascii_case("bearer") || credentials.is_empty() {
return Err(AxiamExtractorError::invalid_scheme(no_credential_challenge));
}
Ok((
credentials.to_owned(),
CredentialSource::AuthorizationHeader,
))
}
impl actix_web::FromRequest for AxiamUser {
type Error = AxiamExtractorError;
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
let verifier = req.app_data::<web::Data<JwksVerifier>>().cloned();
let mcp = verifier.as_ref().and_then(|v| v.mcp_challenges().cloned());
let no_credential_challenge = mcp.as_ref().map(|c| c.no_credential().to_string());
let invalid_token_challenge = mcp.as_ref().map(|c| c.invalid_token().to_string());
let token_result = extract_token(req, no_credential_challenge);
let method_is_state_changing = is_state_changing(req.method());
let csrf_ok = csrf_valid(req);
let peer_thumbprint = req
.conn_data::<PeerCertificate>()
.map(|c| c.thumbprint().to_owned());
Box::pin(async move {
let (token, source) = token_result?;
if source == CredentialSource::Cookie && method_is_state_changing && !csrf_ok {
return Err(AxiamExtractorError::csrf_validation_failed());
}
let verifier = verifier.ok_or_else(|| {
AxiamExtractorError::misconfigured(invalid_token_challenge.clone())
})?;
let claims = verifier
.verify_with_proofs(
&token,
crate::token::PresentedProofs {
certificate_thumbprint: peer_thumbprint.as_deref(),
dpop_thumbprint: None,
},
)
.await
.map_err(|e| AxiamExtractorError {
error: e,
challenge: invalid_token_challenge.clone(),
})?;
let user_id = Uuid::parse_str(&claims.sub).map_err(|_| {
AxiamExtractorError::invalid_claim("sub", invalid_token_challenge.clone())
})?;
let tenant_id = Uuid::parse_str(&claims.tenant_id).map_err(|_| {
AxiamExtractorError::invalid_claim("tenant_id", invalid_token_challenge.clone())
})?;
let roles = claims
.scope
.as_deref()
.map(|s| s.split_whitespace().map(str::to_owned).collect())
.unwrap_or_default();
Ok(AxiamUser {
user_id,
tenant_id,
roles,
})
})
}
}