Skip to main content

api_gateway/middleware/
auth.rs

1use axum::http::Method;
2use axum::response::IntoResponse;
3use std::{collections::HashMap, sync::Arc};
4
5use crate::middleware::common;
6
7use authn_resolver_sdk::{AuthNResolverClient, AuthNResolverError};
8use modkit::api::Problem;
9use modkit_security::SecurityContext;
10
11/// Route matcher for a specific HTTP method (authenticated routes).
12#[derive(Clone)]
13pub struct RouteMatcher {
14    matcher: matchit::Router<()>,
15}
16
17impl RouteMatcher {
18    fn new() -> Self {
19        Self {
20            matcher: matchit::Router::new(),
21        }
22    }
23
24    fn insert(&mut self, path: &str) -> Result<(), matchit::InsertError> {
25        self.matcher.insert(path, ())
26    }
27
28    fn find(&self, path: &str) -> bool {
29        self.matcher.at(path).is_ok()
30    }
31}
32
33/// Public route matcher for explicitly public routes
34#[derive(Clone)]
35pub struct PublicRouteMatcher {
36    matcher: matchit::Router<()>,
37}
38
39impl PublicRouteMatcher {
40    fn new() -> Self {
41        Self {
42            matcher: matchit::Router::new(),
43        }
44    }
45
46    fn insert(&mut self, path: &str) -> Result<(), matchit::InsertError> {
47        self.matcher.insert(path, ())
48    }
49
50    fn find(&self, path: &str) -> bool {
51        self.matcher.at(path).is_ok()
52    }
53}
54
55/// Convert Axum path syntax `:param` to matchit syntax `{param}`
56///
57/// Axum uses `:id` for path parameters, but matchit 0.8 uses `{id}`.
58/// This function converts between the two syntaxes.
59fn convert_axum_path_to_matchit(path: &str) -> String {
60    // Simple regex-free approach: find :word and replace with {word}
61    let mut result = String::with_capacity(path.len());
62    let mut chars = path.chars().peekable();
63
64    while let Some(ch) = chars.next() {
65        if ch == ':' {
66            // Start of a parameter - collect the parameter name
67            result.push('{');
68            while matches!(chars.peek(), Some(c) if c.is_alphanumeric() || *c == '_') {
69                if let Some(c) = chars.next() {
70                    result.push(c);
71                }
72            }
73            result.push('}');
74        } else {
75            result.push(ch);
76        }
77    }
78
79    result
80}
81
82/// Whether a route requires authentication.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum AuthRequirement {
85    /// No authentication required (public route).
86    None,
87    /// Authentication required.
88    Required,
89}
90
91/// Gateway-specific route policy implementation
92#[derive(Clone)]
93pub struct GatewayRoutePolicy {
94    route_matchers: Arc<HashMap<Method, RouteMatcher>>,
95    public_matchers: Arc<HashMap<Method, PublicRouteMatcher>>,
96    require_auth_by_default: bool,
97}
98
99impl GatewayRoutePolicy {
100    #[must_use]
101    pub fn new(
102        route_matchers: Arc<HashMap<Method, RouteMatcher>>,
103        public_matchers: Arc<HashMap<Method, PublicRouteMatcher>>,
104        require_auth_by_default: bool,
105    ) -> Self {
106        Self {
107            route_matchers,
108            public_matchers,
109            require_auth_by_default,
110        }
111    }
112
113    /// Resolve the authentication requirement for a given (method, path).
114    #[must_use]
115    pub fn resolve(&self, method: &Method, path: &str) -> AuthRequirement {
116        // Check if route is explicitly authenticated
117        let is_authenticated = self
118            .route_matchers
119            .get(method)
120            .is_some_and(|matcher| matcher.find(path));
121
122        // Check if route is explicitly public using pattern matching
123        let is_public = self
124            .public_matchers
125            .get(method)
126            .is_some_and(|matcher| matcher.find(path));
127
128        // Public routes should not be forced to auth by default
129        let needs_authn = is_authenticated || (self.require_auth_by_default && !is_public);
130
131        if needs_authn {
132            AuthRequirement::Required
133        } else {
134            AuthRequirement::None
135        }
136    }
137}
138
139/// Shared state for the authentication middleware.
140#[derive(Clone)]
141pub struct AuthState {
142    pub authn_client: Arc<dyn AuthNResolverClient>,
143    pub route_policy: GatewayRoutePolicy,
144}
145
146/// Helper to build `GatewayRoutePolicy` from operation requirements.
147///
148/// # Errors
149///
150/// Returns an error if a route pattern cannot be inserted into the matcher.
151#[allow(clippy::implicit_hasher)]
152pub fn build_route_policy(
153    cfg: &crate::config::ApiGatewayConfig,
154    authenticated_routes: std::collections::HashSet<(Method, String)>,
155    public_routes: std::collections::HashSet<(Method, String)>,
156) -> Result<GatewayRoutePolicy, anyhow::Error> {
157    // Build route matchers per HTTP method (authenticated routes)
158    let mut route_matchers_map: HashMap<Method, RouteMatcher> = HashMap::new();
159
160    for (method, path) in authenticated_routes {
161        let matcher = route_matchers_map
162            .entry(method)
163            .or_insert_with(RouteMatcher::new);
164        // Convert Axum path syntax (:param) to matchit syntax ({param})
165        let matchit_path = convert_axum_path_to_matchit(&path);
166        matcher
167            .insert(&matchit_path)
168            .map_err(|e| anyhow::anyhow!("Failed to insert route pattern '{path}': {e}"))?;
169    }
170
171    // Build public matchers per HTTP method
172    let mut public_matchers_map: HashMap<Method, PublicRouteMatcher> = HashMap::new();
173
174    for (method, path) in public_routes {
175        let matcher = public_matchers_map
176            .entry(method)
177            .or_insert_with(PublicRouteMatcher::new);
178        // Convert Axum path syntax (:param) to matchit syntax ({param})
179        let matchit_path = convert_axum_path_to_matchit(&path);
180        matcher
181            .insert(&matchit_path)
182            .map_err(|e| anyhow::anyhow!("Failed to insert public route pattern '{path}': {e}"))?;
183    }
184
185    Ok(GatewayRoutePolicy::new(
186        Arc::new(route_matchers_map),
187        Arc::new(public_matchers_map),
188        cfg.require_auth_by_default,
189    ))
190}
191
192/// Authentication middleware that uses the `AuthN` Resolver to validate bearer tokens.
193///
194/// For each request:
195/// 1. Skips CORS preflight requests
196/// 2. Resolves the route's auth requirement via `GatewayRoutePolicy`
197/// 3. For public routes: inserts anonymous `SecurityContext`
198/// 4. For required routes: extracts bearer token, calls `AuthN` Resolver, inserts `SecurityContext`
199pub async fn authn_middleware(
200    axum::extract::State(state): axum::extract::State<AuthState>,
201    mut req: axum::extract::Request,
202    next: axum::middleware::Next,
203) -> axum::response::Response {
204    // Skip CORS preflight
205    if is_preflight_request(req.method(), req.headers()) {
206        return next.run(req).await;
207    }
208
209    let path = req
210        .extensions()
211        .get::<axum::extract::MatchedPath>()
212        .map_or_else(|| req.uri().path().to_owned(), |p| p.as_str().to_owned());
213
214    let path = common::resolve_path(&req, path.as_str());
215
216    let requirement = state.route_policy.resolve(req.method(), path.as_str());
217
218    match requirement {
219        AuthRequirement::None => {
220            req.extensions_mut().insert(SecurityContext::anonymous());
221            next.run(req).await
222        }
223        AuthRequirement::Required => {
224            let Some(token) = extract_bearer_token(req.headers()) else {
225                return Problem::new(
226                    axum::http::StatusCode::UNAUTHORIZED,
227                    "Unauthorized",
228                    "Missing or invalid Authorization header",
229                )
230                .into_response();
231            };
232
233            match state.authn_client.authenticate(token).await {
234                Ok(result) => {
235                    req.extensions_mut().insert(result.security_context);
236                    next.run(req).await
237                }
238                Err(err) => authn_error_to_response(&err),
239            }
240        }
241    }
242}
243
244/// Convert `AuthNResolverError` to an RFC-9457 Problem Details response.
245fn authn_error_to_response(err: &AuthNResolverError) -> axum::response::Response {
246    log_authn_error(err);
247    let (status, title, detail) = match err {
248        AuthNResolverError::Unauthorized(_) => (
249            axum::http::StatusCode::UNAUTHORIZED,
250            "Unauthorized",
251            "Authentication failed",
252        ),
253        AuthNResolverError::NoPluginAvailable | AuthNResolverError::ServiceUnavailable(_) => (
254            axum::http::StatusCode::SERVICE_UNAVAILABLE,
255            "Service Unavailable",
256            "Authentication service unavailable",
257        ),
258        AuthNResolverError::TokenAcquisitionFailed(_) | AuthNResolverError::Internal(_) => (
259            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
260            "Internal Server Error",
261            "Internal authentication error",
262        ),
263    };
264    Problem::new(status, title, detail).into_response()
265}
266
267/// Log authentication errors at appropriate levels.
268///
269/// Cognitive complexity is inflated by tracing macro expansion.
270#[allow(clippy::cognitive_complexity)]
271fn log_authn_error(err: &AuthNResolverError) {
272    match err {
273        AuthNResolverError::Unauthorized(msg) => tracing::debug!("AuthN rejected: {msg}"),
274        AuthNResolverError::NoPluginAvailable => tracing::error!("No AuthN plugin available"),
275        AuthNResolverError::ServiceUnavailable(msg) => {
276            tracing::error!("AuthN service unavailable: {msg}");
277        }
278        AuthNResolverError::TokenAcquisitionFailed(msg) => {
279            tracing::error!("AuthN token acquisition failed: {msg}");
280        }
281        AuthNResolverError::Internal(msg) => tracing::error!("AuthN internal error: {msg}"),
282    }
283}
284
285/// Extract Bearer token from Authorization header
286fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<&str> {
287    headers
288        .get(axum::http::header::AUTHORIZATION)
289        .and_then(|v| v.to_str().ok())
290        .and_then(|s| s.strip_prefix("Bearer ").map(str::trim))
291}
292
293/// Check if this is a CORS preflight request
294///
295/// Preflight requests are OPTIONS requests with:
296/// - Origin header present
297/// - Access-Control-Request-Method header present
298fn is_preflight_request(method: &Method, headers: &axum::http::HeaderMap) -> bool {
299    method == Method::OPTIONS
300        && headers.contains_key(axum::http::header::ORIGIN)
301        && headers.contains_key(axum::http::header::ACCESS_CONTROL_REQUEST_METHOD)
302}
303
304#[cfg(test)]
305#[cfg_attr(coverage_nightly, coverage(off))]
306mod tests {
307    use super::*;
308    use axum::http::Method;
309
310    /// Helper to build `GatewayRoutePolicy` with given matchers
311    fn build_test_policy(
312        route_matchers: HashMap<Method, RouteMatcher>,
313        public_matchers: HashMap<Method, PublicRouteMatcher>,
314        require_auth_by_default: bool,
315    ) -> GatewayRoutePolicy {
316        GatewayRoutePolicy::new(
317            Arc::new(route_matchers),
318            Arc::new(public_matchers),
319            require_auth_by_default,
320        )
321    }
322
323    #[test]
324    fn test_convert_axum_path_to_matchit() {
325        assert_eq!(convert_axum_path_to_matchit("/users/:id"), "/users/{id}");
326        assert_eq!(
327            convert_axum_path_to_matchit("/posts/:post_id/comments/:comment_id"),
328            "/posts/{post_id}/comments/{comment_id}"
329        );
330        assert_eq!(convert_axum_path_to_matchit("/health"), "/health"); // No params
331        assert_eq!(
332            convert_axum_path_to_matchit("/api/v1/:resource/:id/status"),
333            "/api/v1/{resource}/{id}/status"
334        );
335    }
336
337    #[test]
338    fn test_matchit_router_with_params() {
339        // matchit 0.8 uses {param} syntax for path parameters (NOT :param)
340        let mut router = matchit::Router::new();
341        router.insert("/users/{id}", "user_route").unwrap();
342
343        let result = router.at("/users/42");
344        assert!(
345            result.is_ok(),
346            "matchit should match /users/{{id}} against /users/42"
347        );
348        assert_eq!(*result.unwrap().value, "user_route");
349    }
350
351    #[test]
352    fn explicit_public_route_with_path_params_returns_none() {
353        let mut public_matchers = HashMap::new();
354        let mut matcher = PublicRouteMatcher::new();
355        // matchit 0.8 uses {param} syntax (Axum uses :param, so conversion needed in production)
356        matcher.insert("/users/{id}").unwrap();
357
358        public_matchers.insert(Method::GET, matcher);
359
360        let policy = build_test_policy(HashMap::new(), public_matchers, true);
361
362        // Path parameters should match concrete values
363        let result = policy.resolve(&Method::GET, "/users/42");
364        assert_eq!(result, AuthRequirement::None);
365    }
366
367    #[test]
368    fn explicit_public_route_exact_match_returns_none() {
369        let mut public_matchers = HashMap::new();
370        let mut matcher = PublicRouteMatcher::new();
371        matcher.insert("/health").unwrap();
372        public_matchers.insert(Method::GET, matcher);
373
374        let policy = build_test_policy(HashMap::new(), public_matchers, true);
375
376        let result = policy.resolve(&Method::GET, "/health");
377        assert_eq!(result, AuthRequirement::None);
378    }
379
380    #[test]
381    fn explicit_authenticated_route_returns_required() {
382        let mut route_matchers = HashMap::new();
383        let mut matcher = RouteMatcher::new();
384        matcher.insert("/admin/metrics").unwrap();
385        route_matchers.insert(Method::GET, matcher);
386
387        let policy = build_test_policy(route_matchers, HashMap::new(), false);
388
389        let result = policy.resolve(&Method::GET, "/admin/metrics");
390        assert_eq!(result, AuthRequirement::Required);
391    }
392
393    #[test]
394    fn route_without_requirement_with_require_auth_by_default_returns_required() {
395        let policy = build_test_policy(HashMap::new(), HashMap::new(), true);
396
397        let result = policy.resolve(&Method::GET, "/profile");
398        assert_eq!(result, AuthRequirement::Required);
399    }
400
401    #[test]
402    fn route_without_requirement_without_require_auth_by_default_returns_none() {
403        let policy = build_test_policy(HashMap::new(), HashMap::new(), false);
404
405        let result = policy.resolve(&Method::GET, "/profile");
406        assert_eq!(result, AuthRequirement::None);
407    }
408
409    #[test]
410    fn unknown_route_with_require_auth_by_default_true_returns_required() {
411        let policy = build_test_policy(HashMap::new(), HashMap::new(), true);
412
413        let result = policy.resolve(&Method::POST, "/unknown");
414        assert_eq!(result, AuthRequirement::Required);
415    }
416
417    #[test]
418    fn unknown_route_with_require_auth_by_default_false_returns_none() {
419        let policy = build_test_policy(HashMap::new(), HashMap::new(), false);
420
421        let result = policy.resolve(&Method::POST, "/unknown");
422        assert_eq!(result, AuthRequirement::None);
423    }
424
425    #[test]
426    fn public_route_overrides_require_auth_by_default() {
427        let mut public_matchers = HashMap::new();
428        let mut matcher = PublicRouteMatcher::new();
429        matcher.insert("/public").unwrap();
430        public_matchers.insert(Method::GET, matcher);
431
432        let policy = build_test_policy(HashMap::new(), public_matchers, true);
433
434        let result = policy.resolve(&Method::GET, "/public");
435        assert_eq!(result, AuthRequirement::None);
436    }
437
438    #[test]
439    fn authenticated_route_has_priority_over_default() {
440        let mut route_matchers = HashMap::new();
441        let mut matcher = RouteMatcher::new();
442        // matchit 0.8 uses {param} syntax
443        matcher.insert("/users/{id}").unwrap();
444        route_matchers.insert(Method::GET, matcher);
445
446        let policy = build_test_policy(route_matchers, HashMap::new(), false);
447
448        let result = policy.resolve(&Method::GET, "/users/123");
449        assert_eq!(result, AuthRequirement::Required);
450    }
451
452    #[test]
453    fn different_methods_resolve_independently() {
454        let mut route_matchers = HashMap::new();
455
456        // GET /users is authenticated
457        let mut get_matcher = RouteMatcher::new();
458        get_matcher.insert("/user-management/v1/users").unwrap();
459        route_matchers.insert(Method::GET, get_matcher);
460
461        // POST /users is not in matchers
462        let policy = build_test_policy(route_matchers, HashMap::new(), false);
463
464        // GET should be authenticated
465        let get_result = policy.resolve(&Method::GET, "/user-management/v1/users");
466        assert_eq!(get_result, AuthRequirement::Required);
467
468        // POST should be public (no requirement, require_auth_by_default=false)
469        let post_result = policy.resolve(&Method::POST, "/user-management/v1/users");
470        assert_eq!(post_result, AuthRequirement::None);
471    }
472}