cf-gears-api-gateway 0.4.6

API Gateway module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
use axum::http::Method;
use axum::response::IntoResponse;
use std::{collections::HashMap, sync::Arc};

use crate::middleware::common;

use authn_resolver_sdk::{AuthNResolverClient, AuthNResolverError};
use toolkit_canonical_errors::CanonicalError;
use toolkit_gateway::ProxyRegistry;
use toolkit_security::SecurityContext;

/// Route matcher for a specific HTTP method (authenticated routes).
#[derive(Clone)]
pub struct RouteMatcher {
    matcher: matchit::Router<()>,
}

impl RouteMatcher {
    fn new() -> Self {
        Self {
            matcher: matchit::Router::new(),
        }
    }

    fn insert(&mut self, path: &str) -> Result<(), matchit::InsertError> {
        self.matcher.insert(path, ())
    }

    fn find(&self, path: &str) -> bool {
        self.matcher.at(path).is_ok()
    }
}

/// Route matcher for anonymous (unauthenticated) routes.
///
/// "Anonymous" is the auth axis, distinct from external *visibility*: a route
/// in here requires no bearer token. Do not conflate with `is_exposed`
/// (visibility) elsewhere in the codebase.
#[derive(Clone)]
pub struct AnonymousRouteMatcher {
    matcher: matchit::Router<()>,
}

impl AnonymousRouteMatcher {
    fn new() -> Self {
        Self {
            matcher: matchit::Router::new(),
        }
    }

    fn insert(&mut self, path: &str) -> Result<(), matchit::InsertError> {
        self.matcher.insert(path, ())
    }

    fn find(&self, path: &str) -> bool {
        self.matcher.at(path).is_ok()
    }
}

/// Whether a route requires authentication.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthRequirement {
    /// No authentication required (public route).
    None,
    /// Authentication required.
    Required,
}

/// Gateway-specific route policy implementation
#[derive(Clone)]
pub struct GatewayRoutePolicy {
    route_matchers: Arc<HashMap<Method, RouteMatcher>>,
    anonymous_matchers: Arc<HashMap<Method, AnonymousRouteMatcher>>,
    require_auth_by_default: bool,
    /// Reverse-proxy route table (embedded edge). When set, dynamically-
    /// registered proxy routes are resolved against it so each is enforced
    /// exactly as the owning gear declared. `None` when the proxy is disabled.
    proxy_registry: Option<Arc<ProxyRegistry>>,
}

impl GatewayRoutePolicy {
    #[must_use]
    pub fn new(
        route_matchers: Arc<HashMap<Method, RouteMatcher>>,
        anonymous_matchers: Arc<HashMap<Method, AnonymousRouteMatcher>>,
        require_auth_by_default: bool,
        proxy_registry: Option<Arc<ProxyRegistry>>,
    ) -> Self {
        Self {
            route_matchers,
            anonymous_matchers,
            require_auth_by_default,
            proxy_registry,
        }
    }

    /// Resolve the authentication requirement for a given (method, path).
    #[must_use]
    pub fn resolve(&self, method: &Method, path: &str) -> AuthRequirement {
        // Check if route is explicitly authenticated
        let is_authenticated = self
            .route_matchers
            .get(method)
            .is_some_and(|matcher| matcher.find(path));

        // Check if the route is explicitly anonymous (no auth) using pattern
        // matching. This is the auth axis, not external visibility.
        let is_anonymous = self
            .anonymous_matchers
            .get(method)
            .is_some_and(|matcher| matcher.find(path));

        // Anonymous routes should not be forced to auth by default
        if is_anonymous {
            return AuthRequirement::None;
        }

        // Dynamically-registered proxy routes are not in the static matchers.
        // Consult the reverse-proxy registry so each proxied route is enforced
        // exactly as the owning gear declared (authenticated vs anonymous).
        if let Some(registry) = &self.proxy_registry
            && let Some(authenticated) = registry.requires_auth(method, path)
        {
            return if authenticated {
                AuthRequirement::Required
            } else {
                AuthRequirement::None
            };
        }

        // Statically-registered routes are the fallback when no proxy entry exists.
        if is_authenticated {
            return AuthRequirement::Required;
        }

        if self.require_auth_by_default {
            AuthRequirement::Required
        } else {
            AuthRequirement::None
        }
    }
}

/// Shared state for the authentication middleware.
#[derive(Clone)]
pub struct AuthState {
    pub authn_client: Arc<dyn AuthNResolverClient>,
    pub route_policy: GatewayRoutePolicy,
}

/// Helper to build `GatewayRoutePolicy` from operation requirements.
///
/// # Errors
///
/// Returns an error if a route pattern cannot be inserted into the matcher.
#[allow(clippy::implicit_hasher)]
pub fn build_route_policy(
    cfg: &crate::config::ApiGatewayConfig,
    authenticated_routes: std::collections::HashSet<(Method, String)>,
    anonymous_routes: std::collections::HashSet<(Method, String)>,
    proxy_registry: Option<Arc<ProxyRegistry>>,
) -> Result<GatewayRoutePolicy, anyhow::Error> {
    // Build route matchers per HTTP method (authenticated routes)
    let mut route_matchers_map: HashMap<Method, RouteMatcher> = HashMap::new();

    for (method, path) in authenticated_routes {
        let matcher = route_matchers_map
            .entry(method)
            .or_insert_with(RouteMatcher::new);
        matcher
            .insert(&path)
            .map_err(|e| anyhow::anyhow!("Failed to insert route pattern '{path}': {e}"))?;
    }

    // Build anonymous matchers per HTTP method
    let mut anonymous_matchers_map: HashMap<Method, AnonymousRouteMatcher> = HashMap::new();

    for (method, path) in anonymous_routes {
        let matcher = anonymous_matchers_map
            .entry(method)
            .or_insert_with(AnonymousRouteMatcher::new);
        matcher.insert(&path).map_err(|e| {
            anyhow::anyhow!("Failed to insert anonymous route pattern '{path}': {e}")
        })?;
    }

    Ok(GatewayRoutePolicy::new(
        Arc::new(route_matchers_map),
        Arc::new(anonymous_matchers_map),
        cfg.require_auth_by_default,
        proxy_registry,
    ))
}

/// Authentication middleware that uses the `AuthN` Resolver to validate bearer tokens.
///
/// For each request:
/// 1. Skips CORS preflight requests
/// 2. Resolves the route's auth requirement via `GatewayRoutePolicy`
/// 3. For public routes: inserts anonymous `SecurityContext`
/// 4. For required routes: extracts bearer token, calls `AuthN` Resolver, inserts `SecurityContext`
pub async fn authn_middleware(
    axum::extract::State(state): axum::extract::State<AuthState>,
    mut req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    // Skip CORS preflight — insert anonymous SecurityContext so downstream
    // handlers that extract Extension<SecurityContext> don't panic.
    if is_preflight_request(req.method(), req.headers()) {
        req.extensions_mut().insert(SecurityContext::anonymous());
        return next.run(req).await;
    }

    let path = req
        .extensions()
        .get::<axum::extract::MatchedPath>()
        .map_or_else(|| req.uri().path().to_owned(), |p| p.as_str().to_owned());

    let path = common::resolve_path(&req, path.as_str());

    let requirement = state.route_policy.resolve(req.method(), path.as_str());

    match requirement {
        AuthRequirement::None => {
            log_auth_skipped(req.method(), path.as_str());
            req.extensions_mut().insert(SecurityContext::anonymous());
            next.run(req).await
        }
        AuthRequirement::Required => {
            let Some(token) = extract_bearer_token(req.headers()) else {
                log_missing_bearer(req.method(), path.as_str());
                // `instance` / `trace_id` are filled by the canonical
                // error middleware (`toolkit::api::canonical_error_middleware`)
                // on the way out — this middleware sits inside its layer.
                let mut response = CanonicalError::unauthenticated()
                    .with_reason("MISSING_BEARER")
                    .create()
                    .into_response();
                // No bearer credentials were presented (RFC 6750 §3).
                common::append_bearer_challenge(
                    &mut response,
                    common::BearerChallenge::NoCredentials,
                );
                return response;
            };

            match state.authn_client.authenticate(token).await {
                Ok(result) => {
                    log_auth_succeeded(req.method(), path.as_str(), &result.security_context);
                    req.extensions_mut().insert(result.security_context);
                    next.run(req).await
                }
                Err(err) => authn_error_to_response(&err),
            }
        }
    }
}

fn log_auth_skipped(method: &Method, path: &str) {
    tracing::debug!(method = %method, path, "authentication skipped: public route");
}

fn log_missing_bearer(method: &Method, path: &str) {
    tracing::debug!(method = %method, path, "authentication failed: missing bearer token");
}

fn log_auth_succeeded(method: &Method, path: &str, security_context: &SecurityContext) {
    tracing::debug!(
        method = %method,
        path,
        subject_id = %security_context.subject_id(),
        "authentication succeeded"
    );
}

/// Convert `AuthNResolverError` to a canonical Problem Details response.
///
/// `instance` / `trace_id` are filled by the canonical error middleware
/// (`toolkit::api::canonical_error_middleware`) on the way out — this
/// middleware sits inside its layer.
fn authn_error_to_response(err: &AuthNResolverError) -> axum::response::Response {
    log_authn_error(err);
    match err {
        AuthNResolverError::Unauthorized(_) => {
            // A token was presented but rejected (RFC 6750 §3).
            let mut response = CanonicalError::unauthenticated()
                .with_reason("AUTHN_FAILED")
                .create()
                .into_response();
            common::append_bearer_challenge(&mut response, common::BearerChallenge::InvalidToken);
            response
        }
        AuthNResolverError::NoPluginAvailable | AuthNResolverError::ServiceUnavailable(_) => {
            CanonicalError::service_unavailable()
                .with_retry_after_seconds(5)
                .create()
                .into_response()
        }
        AuthNResolverError::TokenAcquisitionFailed(_) | AuthNResolverError::Internal(_) => {
            CanonicalError::internal("authentication infrastructure failure")
                .create()
                .into_response()
        }
    }
}

/// Log authentication errors at appropriate levels.
///
/// Cognitive complexity is inflated by tracing macro expansion.
#[allow(clippy::cognitive_complexity)]
fn log_authn_error(err: &AuthNResolverError) {
    match err {
        AuthNResolverError::Unauthorized(msg) => tracing::debug!("AuthN rejected: {msg}"),
        AuthNResolverError::NoPluginAvailable => tracing::error!("No AuthN plugin available"),
        AuthNResolverError::ServiceUnavailable(msg) => {
            tracing::error!("AuthN service unavailable: {msg}");
        }
        AuthNResolverError::TokenAcquisitionFailed(msg) => {
            tracing::error!("AuthN token acquisition failed: {msg}");
        }
        AuthNResolverError::Internal(msg) => tracing::error!("AuthN internal error: {msg}"),
    }
}

/// Extract Bearer token from Authorization header
fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<&str> {
    headers
        .get(axum::http::header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.strip_prefix("Bearer ").map(str::trim))
}

/// Check if this is a CORS preflight request
///
/// Preflight requests are OPTIONS requests with:
/// - Origin header present
/// - Access-Control-Request-Method header present
fn is_preflight_request(method: &Method, headers: &axum::http::HeaderMap) -> bool {
    method == Method::OPTIONS
        && headers.contains_key(axum::http::header::ORIGIN)
        && headers.contains_key(axum::http::header::ACCESS_CONTROL_REQUEST_METHOD)
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use axum::http::Method;

    /// Helper to build `GatewayRoutePolicy` with given matchers
    fn build_test_policy(
        route_matchers: HashMap<Method, RouteMatcher>,
        anonymous_matchers: HashMap<Method, AnonymousRouteMatcher>,
        require_auth_by_default: bool,
    ) -> GatewayRoutePolicy {
        GatewayRoutePolicy::new(
            Arc::new(route_matchers),
            Arc::new(anonymous_matchers),
            require_auth_by_default,
            None,
        )
    }

    #[test]
    fn resolve_consults_proxy_registry_for_dynamic_routes() {
        use toolkit_gateway::{Endpoint, GearName, RouteTemplate};

        let registry = Arc::new(ProxyRegistry::new());
        registry.register(
            GearName::from("calc"),
            "calc-1",
            Endpoint::parse("http://calc:8080").unwrap(),
            vec![
                RouteTemplate::new(Method::GET, "/calc/v1/pub", false),
                RouteTemplate::new(Method::POST, "/calc/v1/secure", true),
            ],
        );

        // `require_auth_by_default = true`, but the proxy registry overrides per route.
        let policy = GatewayRoutePolicy::new(
            Arc::new(HashMap::new()),
            Arc::new(HashMap::new()),
            true,
            Some(registry),
        );

        assert_eq!(
            policy.resolve(&Method::GET, "/calc/v1/pub"),
            AuthRequirement::None
        );
        assert_eq!(
            policy.resolve(&Method::POST, "/calc/v1/secure"),
            AuthRequirement::Required
        );
        // A path not in the proxy registry falls back to `require_auth_by_default`.
        assert_eq!(
            policy.resolve(&Method::GET, "/unknown"),
            AuthRequirement::Required
        );
    }

    #[test]
    fn test_matchit_router_with_params() {
        let mut router = matchit::Router::new();
        router.insert("/users/{id}", "user_route").unwrap();

        let result = router.at("/users/42");
        assert!(
            result.is_ok(),
            "matchit should match /users/{{id}} against /users/42"
        );
        assert_eq!(*result.unwrap().value, "user_route");
    }

    #[test]
    fn build_route_policy_allows_colon_in_literal_paths() {
        let cfg = crate::config::ApiGatewayConfig::default();
        let authenticated_routes = std::collections::HashSet::from([
            (Method::GET, "events:poll".to_owned()),
            (Method::GET, "events:stream".to_owned()),
        ]);

        if let Err(err) = build_route_policy(
            &cfg,
            authenticated_routes,
            std::collections::HashSet::new(),
            None,
        ) {
            panic!("literal colon route paths must not be interpreted as path parameters: {err}");
        }
    }

    #[test]
    fn explicit_public_route_with_path_params_returns_none() {
        let mut anonymous_matchers = HashMap::new();
        let mut matcher = AnonymousRouteMatcher::new();
        matcher.insert("/users/{id}").unwrap();

        anonymous_matchers.insert(Method::GET, matcher);

        let policy = build_test_policy(HashMap::new(), anonymous_matchers, true);

        // Path parameters should match concrete values
        let result = policy.resolve(&Method::GET, "/users/42");
        assert_eq!(result, AuthRequirement::None);
    }

    #[test]
    fn explicit_public_route_exact_match_returns_none() {
        let mut anonymous_matchers = HashMap::new();
        let mut matcher = AnonymousRouteMatcher::new();
        matcher.insert("/health").unwrap();
        anonymous_matchers.insert(Method::GET, matcher);

        let policy = build_test_policy(HashMap::new(), anonymous_matchers, true);

        let result = policy.resolve(&Method::GET, "/health");
        assert_eq!(result, AuthRequirement::None);
    }

    #[test]
    fn explicit_authenticated_route_returns_required() {
        let mut route_matchers = HashMap::new();
        let mut matcher = RouteMatcher::new();
        matcher.insert("/admin/metrics").unwrap();
        route_matchers.insert(Method::GET, matcher);

        let policy = build_test_policy(route_matchers, HashMap::new(), false);

        let result = policy.resolve(&Method::GET, "/admin/metrics");
        assert_eq!(result, AuthRequirement::Required);
    }

    #[test]
    fn route_without_requirement_with_require_auth_by_default_returns_required() {
        let policy = build_test_policy(HashMap::new(), HashMap::new(), true);

        let result = policy.resolve(&Method::GET, "/profile");
        assert_eq!(result, AuthRequirement::Required);
    }

    #[test]
    fn route_without_requirement_without_require_auth_by_default_returns_none() {
        let policy = build_test_policy(HashMap::new(), HashMap::new(), false);

        let result = policy.resolve(&Method::GET, "/profile");
        assert_eq!(result, AuthRequirement::None);
    }

    #[test]
    fn unknown_route_with_require_auth_by_default_true_returns_required() {
        let policy = build_test_policy(HashMap::new(), HashMap::new(), true);

        let result = policy.resolve(&Method::POST, "/unknown");
        assert_eq!(result, AuthRequirement::Required);
    }

    #[test]
    fn unknown_route_with_require_auth_by_default_false_returns_none() {
        let policy = build_test_policy(HashMap::new(), HashMap::new(), false);

        let result = policy.resolve(&Method::POST, "/unknown");
        assert_eq!(result, AuthRequirement::None);
    }

    #[test]
    fn public_route_overrides_require_auth_by_default() {
        let mut anonymous_matchers = HashMap::new();
        let mut matcher = AnonymousRouteMatcher::new();
        matcher.insert("/public").unwrap();
        anonymous_matchers.insert(Method::GET, matcher);

        let policy = build_test_policy(HashMap::new(), anonymous_matchers, true);

        let result = policy.resolve(&Method::GET, "/public");
        assert_eq!(result, AuthRequirement::None);
    }

    #[test]
    fn authenticated_route_has_priority_over_default() {
        let mut route_matchers = HashMap::new();
        let mut matcher = RouteMatcher::new();
        matcher.insert("/users/{id}").unwrap();
        route_matchers.insert(Method::GET, matcher);

        let policy = build_test_policy(route_matchers, HashMap::new(), false);

        let result = policy.resolve(&Method::GET, "/users/123");
        assert_eq!(result, AuthRequirement::Required);
    }

    #[test]
    fn explicit_anonymous_overrides_wildcard_authenticated_fallback() {
        // When a gateway registers a wildcard authenticated 404 the fallback
        // like `/{*rest}` (used to convert anonymous 404s to 401s),
        // grabs the anonymous routes too, causing 401 on them
        let mut anonymous_matchers = HashMap::new();
        let mut anonymous_matcher = AnonymousRouteMatcher::new();
        anonymous_matcher.insert("/v1/auth/config").unwrap();
        anonymous_matchers.insert(Method::GET, anonymous_matcher);

        let mut route_matchers = HashMap::new();
        let mut auth_matcher = RouteMatcher::new();
        auth_matcher.insert("/{*rest}").unwrap();
        route_matchers.insert(Method::GET, auth_matcher);

        let policy = build_test_policy(route_matchers, anonymous_matchers, true);

        assert_eq!(
            policy.resolve(&Method::GET, "/v1/auth/config"),
            AuthRequirement::None,
            "explicit public must win over wildcard authenticated fallback"
        );
        // Sanity: a path that only matches the wildcard fallback still requires auth.
        assert_eq!(
            policy.resolve(&Method::GET, "/some/other/path"),
            AuthRequirement::Required,
            "wildcard authenticated still applies to non-public paths"
        );
    }

    #[test]
    fn different_methods_resolve_independently() {
        let mut route_matchers = HashMap::new();

        // GET /users is authenticated
        let mut get_matcher = RouteMatcher::new();
        get_matcher.insert("/user-management/v1/users").unwrap();
        route_matchers.insert(Method::GET, get_matcher);

        // POST /users is not in matchers
        let policy = build_test_policy(route_matchers, HashMap::new(), false);

        // GET should be authenticated
        let get_result = policy.resolve(&Method::GET, "/user-management/v1/users");
        assert_eq!(get_result, AuthRequirement::Required);

        // POST should be public (no requirement, require_auth_by_default=false)
        let post_result = policy.resolve(&Method::POST, "/user-management/v1/users");
        assert_eq!(post_result, AuthRequirement::None);
    }
}