use std::ops::Deref;
use axum::{extract::FromRequestParts, http::request::Parts};
use crate::{
auth::{
PermissionError, Principal, RequireAllRoles, RequireAllScopes, RequireAnyRole,
RequireAnyScope, RequireRole, RequireScope,
},
http::{ApiProblem, ProblemCode, RequestContext},
};
#[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> {
RequireRole::new(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> {
RequireAnyRole::new(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> {
RequireAllRoles::new(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> {
RequireScope::new(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> {
RequireAnyScope::new(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> {
RequireAllScopes::new(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 = parts
.extensions
.get::<RequestContext>()
.cloned()
.unwrap_or_else(|| RequestContext::from_headers(&parts.headers));
context.principal().cloned().map(Self).ok_or_else(|| {
ApiProblem::unauthorized(
ProblemCode::from_static("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 = parts
.extensions
.get::<RequestContext>()
.cloned()
.unwrap_or_else(|| RequestContext::from_headers(&parts.headers));
Ok(Self(context.principal().cloned()))
}
}
fn permission_error_to_problem(error: PermissionError) -> ApiProblem {
match error {
PermissionError::Denied => {
ApiProblem::forbidden(ProblemCode::from_static("forbidden"), "permission denied")
}
PermissionError::Unavailable => ApiProblem::service_unavailable(
ProblemCode::from_static("permission_unavailable"),
"permission backend is unavailable",
),
PermissionError::InvalidPrincipal(_) | PermissionError::InvalidAuthority(_) => {
ApiProblem::bad_request(
ProblemCode::from_static("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")
);
}
}