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#[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#[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
55fn convert_axum_path_to_matchit(path: &str) -> String {
60 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 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#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum AuthRequirement {
85 None,
87 Required,
89}
90
91#[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 #[must_use]
115 pub fn resolve(&self, method: &Method, path: &str) -> AuthRequirement {
116 let is_authenticated = self
118 .route_matchers
119 .get(method)
120 .is_some_and(|matcher| matcher.find(path));
121
122 let is_public = self
124 .public_matchers
125 .get(method)
126 .is_some_and(|matcher| matcher.find(path));
127
128 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#[derive(Clone)]
141pub struct AuthState {
142 pub authn_client: Arc<dyn AuthNResolverClient>,
143 pub route_policy: GatewayRoutePolicy,
144}
145
146#[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 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 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 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 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
192pub 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 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
244fn 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#[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
285fn 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
293fn 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 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"); 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 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 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 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 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 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 let policy = build_test_policy(route_matchers, HashMap::new(), false);
463
464 let get_result = policy.resolve(&Method::GET, "/user-management/v1/users");
466 assert_eq!(get_result, AuthRequirement::Required);
467
468 let post_result = policy.resolve(&Method::POST, "/user-management/v1/users");
470 assert_eq!(post_result, AuthRequirement::None);
471 }
472}