Skip to main content

seiva_http/
authn.rs

1//! The deny-by-default authentication middleware (ADR 0006).
2//!
3//! It runs ahead of every route's [`permission_guard`](crate::permission_guard),
4//! turning an `Authorization: Bearer <token>` into the [`Principal`] the guard
5//! and [`Scoped`](crate::Scoped) read:
6//!
7//! - **No credential header** → [`Principal::anonymous`] is inserted, so
8//!   public routes (`/health`, `/docs`, `/openapi.json`) still serve and a
9//!   guarded route's `permission_guard` answers `403`.
10//! - **A present-but-invalid credential** (bad signature, wrong `aud`/`iss`,
11//!   expired, unknown/revoked key, disallowed algorithm, or an empty/garbled
12//!   header) → `401` RFC 9457 [`Problem`] with a `WWW-Authenticate` header. The
13//!   request never reaches the route.
14//!
15//! Two credential sources, each with its own authenticator, run side by side
16//! (ADR 0006): an opaque `X-API-Key` (checked first) and `Authorization: Bearer`.
17//! With the `mtls` feature a third comes first (ADR 0047): the **client
18//! certificate** the TLS handshake verified, mapped by a
19//! `CertificateAuthenticator` (`seiva_http::mtls`). A request
20//! carrying a verified certificate *and* a header credential is refused (`401`):
21//! one request, one identity.
22//! The [`Authenticator`] is the only authority on identity; the middleware never
23//! trusts a header or body field to set the subject, tenant or permissions.
24
25use std::sync::Arc;
26
27use axum::extract::{Request, State};
28use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE};
29use axum::http::{HeaderName, HeaderValue};
30use axum::middleware::Next;
31use axum::response::{IntoResponse, Response};
32
33use seiva_identity::{Authenticator, Principal};
34
35#[cfg(feature = "mtls")]
36use crate::mtls::{CertificateAuthenticator, PeerCertificate};
37use crate::problem::{Problem, ProblemResponse};
38use crate::request_id::RequestIdExt;
39
40/// The `X-API-Key` request header carrying an opaque API key.
41static X_API_KEY: HeaderName = HeaderName::from_static("x-api-key");
42
43/// The authenticators the [`authn`] middleware consults: an optional
44/// `Authorization: Bearer` path (JWT or static token) and an optional opaque
45/// `X-API-Key` path running alongside it (ADR 0006). At least one is set — the
46/// middleware is never mounted when both are absent (see [`AuthConfig`]).
47///
48/// Build it with [`Authn::bearer_only`] or [`Authn::with_api_key`], then mount
49/// with [`axum::middleware::from_fn_with_state`]`(authn_state, authn)`. A
50/// composition root rarely builds it directly: the `router_with_*` builders take
51/// an [`AuthConfig`] and derive the right `Authn` from it.
52#[derive(Clone)]
53pub struct Authn {
54    bearer: Option<Arc<dyn Authenticator>>,
55    api_key: Option<Arc<dyn Authenticator>>,
56    #[cfg(feature = "mtls")]
57    client_cert: Option<Arc<dyn CertificateAuthenticator>>,
58}
59
60impl Authn {
61    /// Authenticate only `Authorization: Bearer` (no `X-API-Key` path). An
62    /// `X-API-Key` header, if any, is ignored and the request falls through to the
63    /// bearer/anonymous path.
64    #[must_use]
65    pub fn bearer_only(bearer: Arc<dyn Authenticator>) -> Self {
66        Self {
67            bearer: Some(bearer),
68            api_key: None,
69            #[cfg(feature = "mtls")]
70            client_cert: None,
71        }
72    }
73
74    /// Authenticate `X-API-Key` against `api_key` **first**, then
75    /// `Authorization: Bearer` against `bearer`. The two are independent
76    /// mechanisms; a request presenting neither is the anonymous principal.
77    #[must_use]
78    pub fn with_api_key(bearer: Arc<dyn Authenticator>, api_key: Arc<dyn Authenticator>) -> Self {
79        Self {
80            bearer: Some(bearer),
81            api_key: Some(api_key),
82            #[cfg(feature = "mtls")]
83            client_cert: None,
84        }
85    }
86}
87
88/// App-level authentication the `router_with_*` builders mount: an optional
89/// `Authorization: Bearer` authenticator and an optional `X-API-Key` one, each
90/// admitted only when set (ADR 0006). This is the config an `apps/<name>-api`
91/// composition root hands the framework.
92///
93/// A bare `Option<Arc<dyn Authenticator>>` converts into an `AuthConfig` carrying
94/// that bearer and **no** `X-API-Key` path, so every existing call-site keeps
95/// working unchanged; reach the `X-API-Key` path with [`AuthConfig::with_api_key`].
96/// When neither authenticator is set ([`AuthConfig::none`]) no authn layer is
97/// mounted at all — no caller is ever authenticated, so guarded routes answer
98/// `403` while public routes still serve.
99#[derive(Clone, Default)]
100pub struct AuthConfig {
101    bearer: Option<Arc<dyn Authenticator>>,
102    api_key: Option<Arc<dyn Authenticator>>,
103    #[cfg(feature = "mtls")]
104    client_cert: Option<Arc<dyn CertificateAuthenticator>>,
105}
106
107impl AuthConfig {
108    /// No authentication: no caller is ever authenticated (guarded routes `403`,
109    /// public routes still serve). The explicit, inference-friendly form of a bare
110    /// `None` authenticator.
111    #[must_use]
112    pub fn none() -> Self {
113        Self::default()
114    }
115
116    /// Authenticate `Authorization: Bearer` against `bearer`; no `X-API-Key` path.
117    #[must_use]
118    pub fn bearer(bearer: Arc<dyn Authenticator>) -> Self {
119        Self {
120            bearer: Some(bearer),
121            ..Self::default()
122        }
123    }
124
125    /// Also admit `X-API-Key` callers, authenticated against `api_key` (consulted
126    /// **before** the bearer path). Independent of whether a bearer is set, so an
127    /// `AuthConfig::none().with_api_key(..)` admits only `X-API-Key` callers.
128    #[must_use]
129    pub fn with_api_key(mut self, api_key: Arc<dyn Authenticator>) -> Self {
130        self.api_key = Some(api_key);
131        self
132    }
133
134    /// Also admit callers by the **client certificate** the mutual-TLS handshake
135    /// verified (feature `mtls`, ADR 0047), mapped to a [`Principal`] by
136    /// `certificates`. Consulted before `X-API-Key` and `Authorization`; it only
137    /// sees requests served by a [`MtlsListener`](crate::mtls::MtlsListener).
138    #[cfg(feature = "mtls")]
139    #[must_use]
140    pub fn with_client_certificates(
141        mut self,
142        certificates: Arc<dyn CertificateAuthenticator>,
143    ) -> Self {
144        self.client_cert = Some(certificates);
145        self
146    }
147
148    /// The [`Authn`] middleware state for this config, or `None` when no
149    /// authenticator is set — in which case no authn layer is mounted
150    /// (deny-by-default via the per-route guard still applies).
151    pub(crate) fn into_authn(self) -> Option<Authn> {
152        #[cfg(feature = "mtls")]
153        if self.bearer.is_none() && self.api_key.is_none() && self.client_cert.is_none() {
154            return None;
155        }
156        #[cfg(not(feature = "mtls"))]
157        if self.bearer.is_none() && self.api_key.is_none() {
158            return None;
159        }
160        Some(Authn {
161            bearer: self.bearer,
162            api_key: self.api_key,
163            #[cfg(feature = "mtls")]
164            client_cert: self.client_cert,
165        })
166    }
167}
168
169impl From<Option<Arc<dyn Authenticator>>> for AuthConfig {
170    /// A bearer-only (or no-op, when `None`) config — the historical
171    /// `Option<Arc<dyn Authenticator>>` parameter, carried through unchanged.
172    fn from(bearer: Option<Arc<dyn Authenticator>>) -> Self {
173        Self {
174            bearer,
175            ..Self::default()
176        }
177    }
178}
179
180/// Middleware that authenticates the caller and inserts a [`Principal`].
181///
182/// Reads `X-API-Key` first (when an API-key authenticator is configured), then
183/// `Authorization: Bearer`; a request with neither becomes
184/// [`Principal::anonymous`]. Mount it with
185/// [`axum::middleware::from_fn_with_state`]`(authn_state, authn)`, where
186/// `authn_state` is an [`Authn`]. [`router_with_auth`](crate::router_with_auth)
187/// does this for the whole app.
188pub async fn authn(State(authn): State<Authn>, mut request: Request, next: Next) -> Response {
189    // 0. The verified client certificate (feature `mtls`), when a certificate
190    //    authenticator is configured and the connection presented one.
191    #[cfg(feature = "mtls")]
192    if let Some(certificates) = authn.client_cert.as_ref() {
193        if let Some(peer) = request.extensions().get::<PeerCertificate>().cloned() {
194            return certificate_authn(Arc::clone(certificates), peer, request, next).await;
195        }
196    }
197
198    // 1. `X-API-Key` takes precedence, but only when an API-key authenticator is
199    //    configured — otherwise the header is unknown and we fall through.
200    if let Some(api_key_auth) = authn.api_key.as_ref() {
201        if let Some(key) = request
202            .headers()
203            .get(&X_API_KEY)
204            .and_then(|value| value.to_str().ok())
205            .map(str::trim)
206            .map(str::to_owned)
207        {
208            return match api_key_auth.authenticate(&key) {
209                Ok(principal) => {
210                    request.extensions_mut().insert(Arc::new(principal));
211                    next.run(request).await
212                }
213                Err(_) => unauthorized(request, "ApiKey"),
214            };
215        }
216    }
217
218    // 2. `Authorization: Bearer`.
219    let presented = request
220        .headers()
221        .get(AUTHORIZATION)
222        .and_then(|value| value.to_str().ok())
223        .map(str::to_owned);
224
225    let Some(header) = presented else {
226        // No credential: the anonymous principal. The per-route guard, not this
227        // layer, is what denies a guarded route — so public routes keep serving.
228        request
229            .extensions_mut()
230            .insert(Arc::new(Principal::anonymous()));
231        return next.run(request).await;
232    };
233
234    // A credential WAS presented: it must authenticate, or the request is refused.
235    // With no bearer authenticator configured (an `X-API-Key`-only deployment),
236    // there is nothing to validate it against — deny, rather than fall through.
237    let Some(bearer_auth) = authn.bearer.as_ref() else {
238        return unauthorized(request, "Bearer");
239    };
240
241    let bearer = header
242        .strip_prefix("Bearer ")
243        .or_else(|| header.strip_prefix("bearer "))
244        .unwrap_or("")
245        .trim()
246        .to_owned();
247
248    // The bearer path is where a JWT verifier lives, and its RSA/ECDSA signature
249    // check is CPU-bound and synchronous. Run it on the blocking pool so a burst of
250    // verifications never stalls the async executor; a cheap static-token lookup
251    // pays only one thread hop. The authenticator is `Send + Sync` behind an `Arc`.
252    let bearer_auth = Arc::clone(bearer_auth);
253    match tokio::task::spawn_blocking(move || bearer_auth.authenticate(&bearer)).await {
254        Ok(Ok(principal)) => {
255            request.extensions_mut().insert(Arc::new(principal));
256            next.run(request).await
257        }
258        Ok(Err(_)) => unauthorized(request, "Bearer"),
259        // The verification task panicked — an internal fault, never an auth pass.
260        Err(_) => auth_unavailable(request),
261    }
262}
263
264/// The client-certificate path of [`authn`] (ADR 0047).
265#[cfg(feature = "mtls")]
266async fn certificate_authn(
267    certificates: Arc<dyn CertificateAuthenticator>,
268    peer: PeerCertificate,
269    mut request: Request,
270    next: Next,
271) -> Response {
272    let PeerCertificate::Verified(certificate) = peer else {
273        return unauthorized(request, CERTIFICATE_SCHEME);
274    };
275    // One request, one identity: a header credential next to a verified
276    // certificate is ambiguous (which caller is this?), so refuse it rather
277    // than silently pick one.
278    if request.headers().contains_key(AUTHORIZATION) || request.headers().contains_key(&X_API_KEY) {
279        return unauthorized(request, CERTIFICATE_SCHEME);
280    }
281    // The application's mapping may consult a store (enrolment, revocation):
282    // keep it off the async executor, like the bearer path.
283    match tokio::task::spawn_blocking(move || certificates.authenticate(&certificate)).await {
284        Ok(Ok(principal)) => {
285            request.extensions_mut().insert(Arc::new(principal));
286            next.run(request).await
287        }
288        Ok(Err(_)) => unauthorized(request, CERTIFICATE_SCHEME),
289        Err(_) => auth_unavailable(request),
290    }
291}
292
293/// The `WWW-Authenticate` hint on a refused client certificate. HTTP has no
294/// registered scheme for TLS client authentication; this names the mechanism
295/// the caller must fix (its certificate), not a header to send.
296#[cfg(feature = "mtls")]
297const CERTIFICATE_SCHEME: &str = "Certificate";
298
299/// Build the `500` RFC 9457 response for an authentication task that failed to
300/// run to completion (e.g. a panic inside the verifier). Deny by default: a
301/// verifier that cannot produce a verdict is an internal fault, never a pass.
302fn auth_unavailable(request: Request) -> Response {
303    let request_id = request.extensions().request_id();
304    ProblemResponse(
305        Problem::internal("the authentication service failed")
306            .with_instance(request.uri().path().to_owned())
307            .with_request_id_opt(request_id),
308    )
309    .into_response()
310}
311
312/// Build the `401` RFC 9457 response for a present-but-invalid credential, tagged
313/// with the `WWW-Authenticate` scheme the caller should use (`Bearer` or `ApiKey`).
314fn unauthorized(request: Request, scheme: &'static str) -> Response {
315    let request_id = request.extensions().request_id();
316    let mut response = ProblemResponse(
317        Problem::unauthorized("the presented credential did not authenticate")
318            .with_instance(request.uri().path().to_owned())
319            .with_request_id_opt(request_id),
320    )
321    .into_response();
322    response
323        .headers_mut()
324        .insert(WWW_AUTHENTICATE, HeaderValue::from_static(scheme));
325    response
326}