use std::sync::Arc;
use axum::extract::{Request, State};
use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE};
use axum::http::{HeaderName, HeaderValue};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use seiva_identity::{Authenticator, Principal};
#[cfg(feature = "mtls")]
use crate::mtls::{CertificateAuthenticator, PeerCertificate};
use crate::problem::{Problem, ProblemResponse};
use crate::request_id::RequestIdExt;
static X_API_KEY: HeaderName = HeaderName::from_static("x-api-key");
#[derive(Clone)]
pub struct Authn {
bearer: Option<Arc<dyn Authenticator>>,
api_key: Option<Arc<dyn Authenticator>>,
#[cfg(feature = "mtls")]
client_cert: Option<Arc<dyn CertificateAuthenticator>>,
}
impl Authn {
#[must_use]
pub fn bearer_only(bearer: Arc<dyn Authenticator>) -> Self {
Self {
bearer: Some(bearer),
api_key: None,
#[cfg(feature = "mtls")]
client_cert: None,
}
}
#[must_use]
pub fn with_api_key(bearer: Arc<dyn Authenticator>, api_key: Arc<dyn Authenticator>) -> Self {
Self {
bearer: Some(bearer),
api_key: Some(api_key),
#[cfg(feature = "mtls")]
client_cert: None,
}
}
}
#[derive(Clone, Default)]
pub struct AuthConfig {
bearer: Option<Arc<dyn Authenticator>>,
api_key: Option<Arc<dyn Authenticator>>,
#[cfg(feature = "mtls")]
client_cert: Option<Arc<dyn CertificateAuthenticator>>,
}
impl AuthConfig {
#[must_use]
pub fn none() -> Self {
Self::default()
}
#[must_use]
pub fn bearer(bearer: Arc<dyn Authenticator>) -> Self {
Self {
bearer: Some(bearer),
..Self::default()
}
}
#[must_use]
pub fn with_api_key(mut self, api_key: Arc<dyn Authenticator>) -> Self {
self.api_key = Some(api_key);
self
}
#[cfg(feature = "mtls")]
#[must_use]
pub fn with_client_certificates(
mut self,
certificates: Arc<dyn CertificateAuthenticator>,
) -> Self {
self.client_cert = Some(certificates);
self
}
pub(crate) fn into_authn(self) -> Option<Authn> {
#[cfg(feature = "mtls")]
if self.bearer.is_none() && self.api_key.is_none() && self.client_cert.is_none() {
return None;
}
#[cfg(not(feature = "mtls"))]
if self.bearer.is_none() && self.api_key.is_none() {
return None;
}
Some(Authn {
bearer: self.bearer,
api_key: self.api_key,
#[cfg(feature = "mtls")]
client_cert: self.client_cert,
})
}
}
impl From<Option<Arc<dyn Authenticator>>> for AuthConfig {
fn from(bearer: Option<Arc<dyn Authenticator>>) -> Self {
Self {
bearer,
..Self::default()
}
}
}
pub async fn authn(State(authn): State<Authn>, mut request: Request, next: Next) -> Response {
#[cfg(feature = "mtls")]
if let Some(certificates) = authn.client_cert.as_ref() {
if let Some(peer) = request.extensions().get::<PeerCertificate>().cloned() {
return certificate_authn(Arc::clone(certificates), peer, request, next).await;
}
}
if let Some(api_key_auth) = authn.api_key.as_ref() {
if let Some(key) = request
.headers()
.get(&X_API_KEY)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.map(str::to_owned)
{
return match api_key_auth.authenticate(&key) {
Ok(principal) => {
request.extensions_mut().insert(Arc::new(principal));
next.run(request).await
}
Err(_) => unauthorized(request, "ApiKey"),
};
}
}
let presented = request
.headers()
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let Some(header) = presented else {
request
.extensions_mut()
.insert(Arc::new(Principal::anonymous()));
return next.run(request).await;
};
let Some(bearer_auth) = authn.bearer.as_ref() else {
return unauthorized(request, "Bearer");
};
let bearer = header
.strip_prefix("Bearer ")
.or_else(|| header.strip_prefix("bearer "))
.unwrap_or("")
.trim()
.to_owned();
let bearer_auth = Arc::clone(bearer_auth);
match tokio::task::spawn_blocking(move || bearer_auth.authenticate(&bearer)).await {
Ok(Ok(principal)) => {
request.extensions_mut().insert(Arc::new(principal));
next.run(request).await
}
Ok(Err(_)) => unauthorized(request, "Bearer"),
Err(_) => auth_unavailable(request),
}
}
#[cfg(feature = "mtls")]
async fn certificate_authn(
certificates: Arc<dyn CertificateAuthenticator>,
peer: PeerCertificate,
mut request: Request,
next: Next,
) -> Response {
let PeerCertificate::Verified(certificate) = peer else {
return unauthorized(request, CERTIFICATE_SCHEME);
};
if request.headers().contains_key(AUTHORIZATION) || request.headers().contains_key(&X_API_KEY) {
return unauthorized(request, CERTIFICATE_SCHEME);
}
match tokio::task::spawn_blocking(move || certificates.authenticate(&certificate)).await {
Ok(Ok(principal)) => {
request.extensions_mut().insert(Arc::new(principal));
next.run(request).await
}
Ok(Err(_)) => unauthorized(request, CERTIFICATE_SCHEME),
Err(_) => auth_unavailable(request),
}
}
#[cfg(feature = "mtls")]
const CERTIFICATE_SCHEME: &str = "Certificate";
fn auth_unavailable(request: Request) -> Response {
let request_id = request.extensions().request_id();
ProblemResponse(
Problem::internal("the authentication service failed")
.with_instance(request.uri().path().to_owned())
.with_request_id_opt(request_id),
)
.into_response()
}
fn unauthorized(request: Request, scheme: &'static str) -> Response {
let request_id = request.extensions().request_id();
let mut response = ProblemResponse(
Problem::unauthorized("the presented credential did not authenticate")
.with_instance(request.uri().path().to_owned())
.with_request_id_opt(request_id),
)
.into_response();
response
.headers_mut()
.insert(WWW_AUTHENTICATE, HeaderValue::from_static(scheme));
response
}