use std::ops::Deref;
use async_trait::async_trait;
use axum::{
extract::FromRequestParts,
http::{Request, request::Parts},
};
use crate::{
auth::{PermissionError, Principal, PrincipalRequirement},
http::{ApiProblem, IdempotencyScope, ProblemCode, RequestContext},
};
#[derive(Clone)]
pub struct VerifiedAuthentication {
principal: Principal,
idempotency_scope: IdempotencyScope,
}
impl VerifiedAuthentication {
#[must_use]
pub const fn new(principal: Principal, idempotency_scope: IdempotencyScope) -> Self {
Self {
principal,
idempotency_scope,
}
}
#[must_use]
pub const fn principal(&self) -> &Principal {
&self.principal
}
#[must_use]
pub const fn idempotency_scope(&self) -> &IdempotencyScope {
&self.idempotency_scope
}
pub fn install<B>(self, request: &mut Request<B>) {
let Self {
principal,
idempotency_scope,
} = self;
let mut context = request
.extensions_mut()
.remove::<RequestContext>()
.unwrap_or_else(|| RequestContext::from_headers(request.headers()));
context.set_principal(principal);
request.extensions_mut().insert(context);
request.extensions_mut().insert(idempotency_scope);
}
}
impl std::fmt::Debug for VerifiedAuthentication {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("VerifiedAuthentication")
.field("principal", &"[REDACTED]")
.field("idempotency_scope", &"[REDACTED]")
.finish()
}
}
#[async_trait]
pub trait HttpAuthenticationHook: Send + Sync + 'static {
async fn authenticate(
&self,
request: &Parts,
) -> Result<Option<VerifiedAuthentication>, ApiProblem>;
}
#[derive(Debug, Clone)]
pub struct CurrentPrincipal(Principal);
impl CurrentPrincipal {
#[must_use]
pub fn new(principal: Principal) -> Self {
Self(principal)
}
#[must_use]
pub const fn principal(&self) -> &Principal {
&self.0
}
pub fn require_role(&self, role: impl Into<String>) -> Result<(), ApiProblem> {
PrincipalRequirement::role(role)
.and_then(|guard| guard.check(self.principal()))
.map_err(permission_error_to_problem)
}
pub fn require_any_role(
&self,
roles: impl IntoIterator<Item = impl Into<String>>,
) -> Result<(), ApiProblem> {
PrincipalRequirement::any_roles(roles)
.and_then(|guard| guard.check(self.principal()))
.map_err(permission_error_to_problem)
}
pub fn require_all_roles(
&self,
roles: impl IntoIterator<Item = impl Into<String>>,
) -> Result<(), ApiProblem> {
PrincipalRequirement::all_roles(roles)
.and_then(|guard| guard.check(self.principal()))
.map_err(permission_error_to_problem)
}
pub fn require_scope(&self, scope: impl Into<String>) -> Result<(), ApiProblem> {
PrincipalRequirement::scope(scope)
.and_then(|guard| guard.check(self.principal()))
.map_err(permission_error_to_problem)
}
pub fn require_any_scope(
&self,
scopes: impl IntoIterator<Item = impl Into<String>>,
) -> Result<(), ApiProblem> {
PrincipalRequirement::any_scopes(scopes)
.and_then(|guard| guard.check(self.principal()))
.map_err(permission_error_to_problem)
}
pub fn require_all_scopes(
&self,
scopes: impl IntoIterator<Item = impl Into<String>>,
) -> Result<(), ApiProblem> {
PrincipalRequirement::all_scopes(scopes)
.and_then(|guard| guard.check(self.principal()))
.map_err(permission_error_to_problem)
}
#[must_use]
pub fn into_inner(self) -> Principal {
self.0
}
}
impl AsRef<Principal> for CurrentPrincipal {
fn as_ref(&self) -> &Principal {
self.principal()
}
}
impl Deref for CurrentPrincipal {
type Target = Principal;
fn deref(&self) -> &Self::Target {
self.principal()
}
}
impl<S> FromRequestParts<S> for CurrentPrincipal
where
S: Send + Sync,
{
type Rejection = ApiProblem;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let context = RequestContext::from_parts(parts);
context.principal().cloned().map(Self).ok_or_else(|| {
ApiProblem::unauthorized(ProblemCode::UNAUTHENTICATED, "authentication is required")
.with_request_context(context)
})
}
}
#[derive(Debug, Clone)]
pub struct OptionalPrincipal(Option<Principal>);
impl OptionalPrincipal {
#[must_use]
pub const fn new(principal: Option<Principal>) -> Self {
Self(principal)
}
#[must_use]
pub const fn principal(&self) -> Option<&Principal> {
self.0.as_ref()
}
#[must_use]
pub fn into_inner(self) -> Option<Principal> {
self.0
}
}
impl<S> FromRequestParts<S> for OptionalPrincipal
where
S: Send + Sync,
{
type Rejection = std::convert::Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let context = RequestContext::from_parts(parts);
Ok(Self(context.principal().cloned()))
}
}
fn permission_error_to_problem(error: PermissionError) -> ApiProblem {
match error {
PermissionError::Denied => {
ApiProblem::forbidden(ProblemCode::FORBIDDEN, "permission denied")
}
PermissionError::Unavailable => ApiProblem::service_unavailable(
ProblemCode::PERMISSION_UNAVAILABLE,
"permission backend is unavailable",
),
PermissionError::InvalidPrincipal(_) | PermissionError::InvalidAuthority(_) => {
ApiProblem::bad_request(ProblemCode::INVALID_PRINCIPAL, "principal is invalid")
}
PermissionError::InvalidPolicy(_) => ApiProblem::internal_error(),
}
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
use crate::auth::Principal;
use super::{CurrentPrincipal, OptionalPrincipal};
#[test]
fn current_principal_can_require_roles_and_scopes() {
let principal = CurrentPrincipal::new(
Principal::user("usr_1")
.expect("static test principal id is valid")
.with_roles(["admin", "operator"])
.expect("static test roles are valid")
.with_scopes(["user:*", "audit:read"])
.expect("static test scopes are valid"),
);
assert!(principal.require_role("admin").is_ok());
assert!(principal.require_all_roles(["admin", "operator"]).is_ok());
assert!(
principal
.require_any_scope(["client:read", "user:read"])
.is_ok()
);
assert!(
principal
.require_all_scopes(["user:write", "audit:read"])
.is_ok()
);
}
#[test]
fn current_principal_maps_denial_to_forbidden_problem() {
let principal = CurrentPrincipal::new(
Principal::user("usr_1").expect("static test principal id is valid"),
);
let problem = principal
.require_scope("admin:read")
.expect_err("missing scope should be denied");
assert_eq!(problem.status(), StatusCode::FORBIDDEN);
assert_eq!(problem.body().code(), "forbidden");
}
#[test]
fn current_principal_hides_invalid_policy_details() {
let principal = CurrentPrincipal::new(
Principal::user("usr_1").expect("static test principal id is valid"),
);
let problem = principal
.require_any_role(std::iter::empty::<&str>())
.expect_err("empty role policy should be invalid");
assert_eq!(problem.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(problem.body().code(), "internal_error");
}
#[test]
fn optional_principal_exposes_optional_reference() {
let principal = Principal::user("usr_1").expect("static test principal id is valid");
let optional = OptionalPrincipal::new(Some(principal));
assert_eq!(
optional.principal().map(crate::auth::Principal::id),
Some("usr_1")
);
}
}