Skip to main content

navree_http/
auth.rs

1//! Authentication and authorization seams: [`Authenticator`],
2//! [`RouteAuthorizer`], [`Guard`] and the [`CurrentPrincipal`] extractor.
3
4use std::fmt;
5
6use http::request::Parts;
7use navree_contracts::{AuthState, Principal};
8use navree_kernel::BoxFuture;
9
10use crate::extract::FromRequestParts;
11use crate::{AppError, RouteMeta};
12
13/// Establishes who is making a request (implemented by navree-auth; fakes in
14/// tests). Registered as `dyn Authenticator` and resolved with
15/// `AppContext::try_get`.
16///
17/// The pipeline calls it once per request, in the `AuthContext` layer slot,
18/// and stores the result as [`AuthState`] in the request extensions.
19/// `Ok(None)` means a guest; an error is returned to the client as is.
20pub trait Authenticator: Send + Sync + 'static {
21    /// The principal of the request, if any.
22    fn authenticate<'a>(
23        &'a self,
24        parts: &'a mut Parts,
25    ) -> BoxFuture<'a, Result<Option<Principal>, AppError>>;
26}
27
28/// Checks a route's roles, permissions and abilities (implemented by
29/// navree-access). Registered as `dyn RouteAuthorizer` and resolved with
30/// `AppContext::try_get`.
31///
32/// Called after authentication, throttling and guards, only for routes that
33/// declare roles, permissions or `can`. It may store data for extractors in
34/// `parts.extensions` (a record loaded for `can(.., from = "id")`).
35pub trait RouteAuthorizer: Send + Sync + 'static {
36    /// `Ok(())` to let the request through; usually 403 or 404 otherwise.
37    fn authorize<'a>(
38        &'a self,
39        parts: &'a mut Parts,
40        meta: &'a RouteMeta,
41    ) -> BoxFuture<'a, Result<(), AppError>>;
42}
43
44/// A custom per-route check, run after authentication and throttling and
45/// before authorization and the handler. A guard alone is not an access
46/// declaration.
47pub trait Guard: Send + Sync + 'static + fmt::Debug {
48    /// `Ok(())` to continue; the error is returned to the client.
49    fn check<'a>(&'a self, parts: &'a mut Parts) -> BoxFuture<'a, Result<(), AppError>>;
50}
51
52/// The authenticated principal of the request; 401 for guests.
53#[derive(Clone, Debug)]
54pub struct CurrentPrincipal(pub Principal);
55
56impl CurrentPrincipal {
57    /// The principal the pipeline authenticated for the request of `parts`;
58    /// 401 for a guest.
59    pub fn from_parts(parts: &Parts) -> Result<Self, AppError> {
60        parts
61            .extensions
62            .get::<AuthState>()
63            .and_then(|state| state.0.clone())
64            .map(CurrentPrincipal)
65            .ok_or_else(AppError::unauthenticated)
66    }
67}
68
69impl FromRequestParts for CurrentPrincipal {
70    type Rejection = AppError;
71
72    async fn from_request_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
73        Self::from_parts(parts)
74    }
75}