Skip to main content

micromegas_auth/
axum.rs

1//! Axum middleware for HTTP authentication
2//!
3//! Provides authentication middleware for Axum HTTP services that:
4//! 1. Extracts request parts (headers, method, URI)
5//! 2. Validates using configured AuthProvider
6//! 3. Injects AuthContext into request extensions
7//! 4. Returns 401 Unauthorized on invalid credentials, 503 Service Unavailable
8//!    when a provider's backing store is unreachable
9
10use crate::client_ip::resolve_client_ip;
11use crate::log_sanitize::warn_auth_rejection;
12use crate::types::{AuthProvider, HttpRequestParts, ProviderUnavailable, RequestParts};
13use axum::{
14    extract::Request,
15    http::StatusCode,
16    middleware::Next,
17    response::{IntoResponse, Response},
18};
19use micromegas_tracing::prelude::*;
20use std::sync::Arc;
21
22/// Axum middleware for request-based authentication
23///
24/// This middleware extracts request parts (headers, method, URI),
25/// validates them using the provided AuthProvider, and injects the resulting
26/// AuthContext into the request extensions.
27///
28/// # Example
29///
30/// ```rust,ignore
31/// use axum::{Router, middleware};
32/// use micromegas_auth::axum::auth_middleware;
33/// use micromegas_auth::api_key::ApiKeyAuthProvider;
34/// use std::sync::Arc;
35///
36/// let auth_provider = Arc::new(ApiKeyAuthProvider::new(keyring));
37/// let app = Router::new()
38///     .layer(middleware::from_fn(move |req, next| {
39///         auth_middleware(auth_provider.clone(), req, next)
40///     }));
41/// ```
42pub async fn auth_middleware(
43    auth_provider: Arc<dyn AuthProvider>,
44    mut req: Request,
45    next: Next,
46) -> Result<Response, AuthError> {
47    authenticate(auth_provider.as_ref(), &mut req).await?;
48    Ok(next.run(req).await)
49}
50
51/// Validates `req`, logs a rejection, strips the spoofable `x-auth-*` headers and inserts the
52/// `AuthContext` on success.
53///
54/// `auth_middleware` is this plus running the next layer. Callers that need the rejected request
55/// back (to inspect it before responding) compose this directly.
56pub async fn authenticate(
57    auth_provider: &dyn AuthProvider,
58    req: &mut Request,
59) -> Result<(), AuthError> {
60    match authenticate_quiet(auth_provider, req).await {
61        Ok(()) => Ok(()),
62        Err(QuietAuthError::Rejected(rejection)) => {
63            warn_auth_rejection("[auth_failure]", &rejection.parts, &rejection.error);
64            Err(AuthError::InvalidToken)
65        }
66        Err(QuietAuthError::Unavailable) => Err(AuthError::Unavailable),
67    }
68}
69
70/// A provider rejection with the request details needed to log it later.
71pub struct AuthRejection {
72    pub parts: HttpRequestParts,
73    pub error: anyhow::Error,
74}
75
76/// Failure of [`authenticate_quiet`].
77pub enum QuietAuthError {
78    /// The credential was rejected; the caller decides how to log it.
79    Rejected(Box<AuthRejection>),
80    /// See [`AuthError::Unavailable`].
81    Unavailable,
82}
83
84/// Same as [`authenticate`] but hands a rejection back instead of logging it, so a caller can
85/// fold extra detail into a single warning.
86pub async fn authenticate_quiet(
87    auth_provider: &dyn AuthProvider,
88    req: &mut Request,
89) -> Result<(), QuietAuthError> {
90    // Resolved before building `HttpRequestParts`: axum's `ConnectInfo<SocketAddr>` extension is
91    // already on `req` for every service that enables it, same as `get_client_ip`'s existing
92    // HTTP callers rely on.
93    let client_ip = resolve_client_ip(req.headers(), req.extensions());
94
95    // Extract request parts for authentication
96    let parts = HttpRequestParts {
97        headers: req.headers().clone(),
98        method: req.method().clone(),
99        uri: req.uri().clone(),
100        client_ip,
101    };
102
103    // Validate request using auth provider
104    let auth_ctx = match auth_provider
105        .validate_request(&parts as &dyn RequestParts)
106        .await
107    {
108        Ok(ctx) => ctx,
109        Err(e) if e.downcast_ref::<ProviderUnavailable>().is_some() => {
110            debug!("[auth_failure] {e}");
111            return Err(QuietAuthError::Unavailable);
112        }
113        Err(error) => {
114            return Err(QuietAuthError::Rejected(Box::new(AuthRejection {
115                parts,
116                error,
117            })));
118        }
119    };
120
121    // Log successful authentication (trace level to avoid noise on every request)
122    trace!(
123        "[auth_success] subject={} email={:?} issuer={} admin={}",
124        auth_ctx.subject,
125        auth_ctx.email,
126        auth_ctx.issuer,
127        auth_ctx.is_admin()
128    );
129
130    // SECURITY: Remove any client-provided auth headers to prevent spoofing
131    // These headers should only be trusted when set by the authentication layer
132    // The AuthContext in request extensions is the authoritative source
133    req.headers_mut().remove("x-auth-subject");
134    req.headers_mut().remove("x-auth-email");
135    req.headers_mut().remove("x-auth-issuer");
136    req.headers_mut().remove("x-allow-delegation");
137    req.headers_mut().remove("x-auth-is-admin");
138
139    // Inject auth context into request extensions for downstream handlers
140    req.extensions_mut().insert(auth_ctx);
141
142    Ok(())
143}
144
145/// Authentication errors for HTTP responses
146#[derive(Debug)]
147pub enum AuthError {
148    /// Token validation failed
149    InvalidToken,
150    /// A DB-backed auth provider could not reach its key store. Distinct from
151    /// `InvalidToken` so the client retries instead of treating the credential as
152    /// permanently rejected (`rust/telemetry-sink/src/http_event_sink.rs` classifies
153    /// `4xx` as terminal and `5xx` as retryable).
154    Unavailable,
155}
156
157impl IntoResponse for AuthError {
158    fn into_response(self) -> Response {
159        let (status, message) = match self {
160            AuthError::InvalidToken => (StatusCode::UNAUTHORIZED, "Invalid token"),
161            AuthError::Unavailable => {
162                (StatusCode::SERVICE_UNAVAILABLE, "Auth provider unavailable")
163            }
164        };
165
166        (status, message).into_response()
167    }
168}