footing 0.1.19

Feature-gated foundations for Rust backend services
Documentation
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},
};

/// Authentication result installed before Foundation policies execute.
///
/// Authentication hooks return this value only after validating credentials.
/// Installing both values together prevents principal-based rate limiting and
/// authenticated idempotency from observing different identity boundaries.
#[derive(Clone)]
pub struct VerifiedAuthentication {
    principal: Principal,
    idempotency_scope: IdempotencyScope,
}

impl VerifiedAuthentication {
    #[must_use]
    /// Creates a verified authentication result and its idempotency boundary.
    pub const fn new(principal: Principal, idempotency_scope: IdempotencyScope) -> Self {
        Self {
            principal,
            idempotency_scope,
        }
    }

    #[must_use]
    /// Returns the verified principal.
    pub const fn principal(&self) -> &Principal {
        &self.principal
    }

    #[must_use]
    /// Returns the verified idempotency scope.
    pub const fn idempotency_scope(&self) -> &IdempotencyScope {
        &self.idempotency_scope
    }

    /// Installs the verified principal and scope on a request atomically.
    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]
/// Validates request credentials before rate-limit and idempotency policies.
///
/// Returning `None` explicitly marks an anonymous request. Implementations must
/// never derive identity from unverified header bytes.
pub trait HttpAuthenticationHook: Send + Sync + 'static {
    /// Authenticates one request without consuming its body.
    async fn authenticate(
        &self,
        request: &Parts,
    ) -> Result<Option<VerifiedAuthentication>, ApiProblem>;
}

#[derive(Debug, Clone)]
/// Represents current principal.
pub struct CurrentPrincipal(Principal);

impl CurrentPrincipal {
    #[must_use]
    /// Creates a new instance.
    pub fn new(principal: Principal) -> Self {
        Self(principal)
    }

    #[must_use]
    /// Returns the principal.
    pub const fn principal(&self) -> &Principal {
        &self.0
    }

    /// Requires role.
    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)
    }

    /// Requires any role.
    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)
    }

    /// Requires all roles.
    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)
    }

    /// Requires scope.
    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)
    }

    /// Requires any scope.
    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)
    }

    /// Requires all scopes.
    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]
    /// Consumes this value and returns inner.
    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)]
/// Represents optional principal.
pub struct OptionalPrincipal(Option<Principal>);

impl OptionalPrincipal {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(principal: Option<Principal>) -> Self {
        Self(principal)
    }

    #[must_use]
    /// Returns the principal.
    pub const fn principal(&self) -> Option<&Principal> {
        self.0.as_ref()
    }

    #[must_use]
    /// Consumes this value and returns inner.
    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")
        );
    }
}