use std::ops::Deref;
mod challenge;
pub use challenge::{AuthenticationChallenge, InvalidAuthenticationChallenge};
#[cfg(feature = "http-stack")]
use async_trait::async_trait;
use axum::{
extract::{FromRef, FromRequestParts, OptionalFromRequestParts},
http::request::Parts,
};
use crate::{
auth::{PermissionError, Principal, PrincipalRequirement},
http::{ApiProblem, ProblemCode, RequestContext},
};
#[cfg(feature = "http-stack")]
use crate::http::IdempotencyScope;
#[cfg(feature = "http-stack")]
use axum::http::Request;
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
#[derive(Clone)]
pub struct VerifiedAuthentication {
principal: Principal,
idempotency_scope: IdempotencyScope,
}
#[cfg(feature = "http-stack")]
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);
}
}
#[cfg(feature = "http-stack")]
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()
}
}
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
#[async_trait]
pub trait HttpAuthenticationHook: Send + Sync + 'static {
async fn authenticate(
&self,
request: &Parts,
) -> Result<Option<VerifiedAuthentication>, ApiProblem>;
}
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
#[async_trait]
pub trait HttpAuthorizationHook: Send + Sync + 'static {
async fn authorize(&self, request: &Parts) -> Result<(), 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,
AuthenticationChallenge: FromRef<S>,
{
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",
&AuthenticationChallenge::from_ref(state),
)
.with_request_context(context)
})
}
}
impl<S> OptionalFromRequestParts<S> for CurrentPrincipal
where
S: Send + Sync,
{
type Rejection = std::convert::Infallible;
async fn from_request_parts(
parts: &mut Parts,
_state: &S,
) -> Result<Option<Self>, Self::Rejection> {
let context = RequestContext::from_parts(parts);
Ok(context.principal().cloned().map(Self))
}
}
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::{
Router,
body::{Body, to_bytes},
extract::FromRef,
http::{Request, StatusCode},
routing::get,
};
use tower::ServiceExt;
use crate::{auth::Principal, http::RequestContext};
use super::{AuthenticationChallenge, CurrentPrincipal};
#[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");
}
#[tokio::test]
async fn principal_extractors_only_use_verified_request_context() {
#[derive(Clone)]
struct AppState {
challenge: AuthenticationChallenge,
}
impl FromRef<AppState> for AuthenticationChallenge {
fn from_ref(state: &AppState) -> Self {
state.challenge.clone()
}
}
let app = Router::new()
.route(
"/optional",
get(|principal: Option<CurrentPrincipal>| async move {
principal.map_or_else(
|| "anonymous".to_owned(),
|principal| principal.id().to_owned(),
)
}),
)
.route(
"/required",
get(|principal: CurrentPrincipal| async move { principal.id().to_owned() }),
)
.with_state(AppState {
challenge: AuthenticationChallenge::try_new("Bearer realm=\"api\"").unwrap(),
});
for (path, verified) in [
("/optional", false),
("/optional", true),
("/required", false),
("/required", true),
] {
let mut request = Request::get(path)
.header("x-request-id", "req_identity")
.header("authorization", "Bearer unverified-token")
.header("x-user-id", "unverified-user")
.header("x-client-id", "unverified-client")
.header("x-session-id", "unverified-session")
.body(Body::empty())
.unwrap();
if verified {
let mut context = RequestContext::from_headers(request.headers());
context.set_principal(Principal::user("usr_1").unwrap());
request.extensions_mut().insert(context);
}
let response = app.clone().oneshot(request).await.unwrap();
let status = response.status();
if path == "/required" && !verified {
assert_eq!(
response.headers()["www-authenticate"],
"Bearer realm=\"api\""
);
} else {
assert!(!response.headers().contains_key("www-authenticate"));
}
let body = to_bytes(response.into_body(), 4096).await.unwrap();
if path == "/required" && !verified {
assert_eq!(status, StatusCode::UNAUTHORIZED);
let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(problem["code"], "unauthenticated");
assert_eq!(problem["request_id"], "req_identity");
} else {
assert_eq!(status, StatusCode::OK);
assert_eq!(body, if verified { "usr_1" } else { "anonymous" });
}
}
}
#[tokio::test]
async fn optional_principal_needs_no_authentication_challenge() {
let app = Router::new().route(
"/",
get(|principal: Option<CurrentPrincipal>| async move {
assert!(principal.is_none());
StatusCode::NO_CONTENT
}),
);
let response = app.oneshot(Request::new(Body::empty())).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
assert!(!response.headers().contains_key("www-authenticate"));
}
}