Skip to main content

nidus_auth/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3
4//! Authentication and guard support.
5
6mod middleware;
7
8use async_trait::async_trait;
9use axum::{Json, response::IntoResponse};
10use http::{
11    HeaderMap, StatusCode,
12    header::{AUTHORIZATION, AsHeaderName},
13};
14use serde::Serialize;
15use std::sync::Arc;
16
17pub use middleware::{GuardLayer, GuardService, guard_layer};
18
19/// Composable authorization guard.
20#[async_trait]
21pub trait Guard<S>: Send + Sync + 'static {
22    /// Checks whether the request context is authorized.
23    async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError>;
24}
25
26#[async_trait]
27impl<S, G> Guard<S> for Arc<G>
28where
29    S: Send + Sync + 'static,
30    G: Guard<S>,
31{
32    async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError> {
33        self.as_ref().check(ctx).await
34    }
35}
36
37/// Extension methods for composing guards.
38pub trait GuardExt<S>: Guard<S> + Sized {
39    /// Requires both guards to authorize the request.
40    fn and<G>(self, other: G) -> AndGuard<Self, G>
41    where
42        G: Guard<S>,
43    {
44        AndGuard {
45            first: self,
46            second: other,
47        }
48    }
49
50    /// Requires at least one guard to authorize the request.
51    fn or<G>(self, other: G) -> OrGuard<Self, G>
52    where
53        G: Guard<S>,
54    {
55        OrGuard {
56            first: self,
57            second: other,
58        }
59    }
60}
61
62impl<S, G> GuardExt<S> for G where G: Guard<S> + Sized {}
63
64/// Guard that succeeds only when both inner guards succeed.
65#[derive(Clone, Debug)]
66pub struct AndGuard<A, B> {
67    first: A,
68    second: B,
69}
70
71#[async_trait]
72impl<S, A, B> Guard<S> for AndGuard<A, B>
73where
74    S: Clone + Send + Sync + 'static,
75    A: Guard<S>,
76    B: Guard<S>,
77{
78    async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError> {
79        self.first.check(ctx.clone()).await?;
80        self.second.check(ctx).await
81    }
82}
83
84/// Guard that succeeds when either inner guard succeeds.
85#[derive(Clone, Debug)]
86pub struct OrGuard<A, B> {
87    first: A,
88    second: B,
89}
90
91#[async_trait]
92impl<S, A, B> Guard<S> for OrGuard<A, B>
93where
94    S: Clone + Send + Sync + 'static,
95    A: Guard<S>,
96    B: Guard<S>,
97{
98    async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError> {
99        let first_error = match self.first.check(ctx.clone()).await {
100            Ok(()) => return Ok(()),
101            Err(error) => error,
102        };
103        match self.second.check(ctx).await {
104            Ok(()) => Ok(()),
105            Err(_) => Err(first_error),
106        }
107    }
108}
109
110/// Typed guard context.
111#[derive(Clone, Debug)]
112pub struct GuardContext<S> {
113    state: S,
114    route_label: Arc<str>,
115    headers: HeaderMap,
116}
117
118impl<S> GuardContext<S> {
119    /// Creates a guard context with typed state and a route label.
120    pub fn new(state: S, route_label: impl Into<String>) -> Self {
121        Self {
122            state,
123            route_label: Arc::from(route_label.into()),
124            headers: HeaderMap::new(),
125        }
126    }
127
128    /// Creates a context from an already shared immutable route label.
129    ///
130    /// This constructor supports framework-generated handlers that retain one
131    /// route label for the lifetime of a service. Most application code should
132    /// use [`Self::new`].
133    #[doc(hidden)]
134    pub fn from_shared_route_label(state: S, route_label: Arc<str>) -> Self {
135        Self {
136            state,
137            route_label,
138            headers: HeaderMap::new(),
139        }
140    }
141
142    /// Returns typed state available to the guard.
143    pub fn state(&self) -> &S {
144        &self.state
145    }
146
147    /// Returns the route label being authorized.
148    pub fn route_label(&self) -> &str {
149        &self.route_label
150    }
151
152    /// Returns request headers available to HTTP guards.
153    pub fn headers(&self) -> &HeaderMap {
154        &self.headers
155    }
156
157    /// Returns a request header as a UTF-8 string.
158    ///
159    /// Missing headers return `Ok(None)`. Present headers that are not valid
160    /// UTF-8 return `401 Unauthorized` so guards do not accidentally authorize
161    /// malformed credentials.
162    pub fn header_str<K>(&self, name: K) -> Result<Option<&str>>
163    where
164        K: AsHeaderName,
165    {
166        self.headers
167            .get(name)
168            .map(|value| {
169                value
170                    .to_str()
171                    .map_err(|_| GuardError::unauthorized("header value is not valid UTF-8"))
172            })
173            .transpose()
174    }
175
176    /// Returns the `Authorization: Bearer <token>` token when present.
177    ///
178    /// A missing authorization header returns `Ok(None)`. A present header with
179    /// another scheme, missing token, or whitespace inside the token returns
180    /// `401 Unauthorized`. The authentication scheme is matched
181    /// case-insensitively, as required by HTTP semantics.
182    pub fn bearer_token(&self) -> Result<Option<&str>> {
183        let Some(header) = self.header_str(AUTHORIZATION)? else {
184            return Ok(None);
185        };
186        let Some((scheme, token)) = header.split_once(' ') else {
187            return Err(GuardError::unauthorized(
188                "authorization header must use `Bearer <token>`",
189            ));
190        };
191        if !scheme.eq_ignore_ascii_case("Bearer")
192            || token.is_empty()
193            || token.chars().any(char::is_whitespace)
194        {
195            return Err(GuardError::unauthorized(
196                "authorization header must use `Bearer <token>`",
197            ));
198        }
199        Ok(Some(token))
200    }
201
202    /// Returns an API key from an explicit header as a UTF-8 string.
203    ///
204    /// This helper intentionally does not compare secrets. Use constant-time
205    /// comparison or a server-side secret store in application code when the
206    /// key value is sensitive.
207    pub fn api_key<K>(&self, header_name: K) -> Result<Option<&str>>
208    where
209        K: AsHeaderName,
210    {
211        self.header_str(header_name)
212    }
213
214    /// Attaches request headers to this guard context.
215    pub fn with_headers(mut self, headers: HeaderMap) -> Self {
216        self.headers = headers;
217        self
218    }
219
220    /// Consumes the context and returns its state.
221    pub fn into_state(self) -> S {
222        self.state
223    }
224}
225
226/// Result type for guards.
227pub type Result<T, E = GuardError> = std::result::Result<T, E>;
228
229/// Authorization failure.
230#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
231#[error("{reason}")]
232pub struct GuardError {
233    status_code: StatusCode,
234    reason: String,
235}
236
237impl GuardError {
238    /// Creates a guard error with an explicit HTTP status and reason.
239    pub fn new(status_code: StatusCode, reason: impl Into<String>) -> Self {
240        Self {
241            status_code,
242            reason: reason.into(),
243        }
244    }
245
246    /// Creates a 401 authorization error.
247    pub fn unauthorized(reason: impl Into<String>) -> Self {
248        Self::new(StatusCode::UNAUTHORIZED, reason)
249    }
250
251    /// Creates a 403 authorization error.
252    pub fn forbidden(reason: impl Into<String>) -> Self {
253        Self::new(StatusCode::FORBIDDEN, reason)
254    }
255
256    /// Returns the HTTP status code corresponding to this guard failure.
257    pub fn status_code(&self) -> StatusCode {
258        self.status_code
259    }
260
261    /// Returns the authorization failure reason.
262    pub fn reason(&self) -> &str {
263        &self.reason
264    }
265
266    /// Returns the stable machine-readable error code.
267    pub fn code(&self) -> &'static str {
268        match self.status_code {
269            StatusCode::UNAUTHORIZED => "unauthorized",
270            StatusCode::FORBIDDEN => "forbidden",
271            _ => "authorization_failed",
272        }
273    }
274}
275
276impl IntoResponse for GuardError {
277    fn into_response(self) -> axum::response::Response {
278        let status = self.status_code;
279        let body = Json(GuardErrorBody {
280            error: GuardErrorDetails {
281                code: self.code(),
282                message: self.reason,
283            },
284        });
285        (status, body).into_response()
286    }
287}
288
289#[derive(Debug, Serialize)]
290struct GuardErrorBody {
291    error: GuardErrorDetails,
292}
293
294#[derive(Debug, Serialize)]
295struct GuardErrorDetails {
296    code: &'static str,
297    message: String,
298}