cf-api-gateway 0.2.1

API Gateway module
Documentation
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
#![allow(clippy::unwrap_used, clippy::expect_used)]

//! Integration tests for auth middleware
//!
//! These tests verify that:
//! 1. Auth middleware is properly attached to the router
//! 2. `SecurityContext` is always inserted by middleware
//! 3. Public routes work without authentication
//! 4. Protected routes enforce authentication when enabled

use anyhow::Result;
use async_trait::async_trait;
use authn_resolver_sdk::{
    AuthNResolverClient, AuthNResolverError, AuthenticationResult, ClientCredentialsRequest,
};
use axum::{
    Extension, Json, Router,
    body::Body,
    http::{Method, Request, StatusCode, header},
};
use modkit::{
    ClientHub, Module,
    api::{OperationBuilder, operation_builder::LicenseFeature},
    config::ConfigProvider,
    context::ModuleCtx,
    contracts::{ApiGatewayCapability, OpenApiRegistry, RestApiCapability},
};
use modkit_security::SecurityContext;
use serde_json::json;
use std::sync::Arc;
use tower::ServiceExt;
use uuid::Uuid;

/// Test configuration provider
struct TestConfigProvider {
    config: serde_json::Value,
}

impl ConfigProvider for TestConfigProvider {
    fn get_module_config(&self, module: &str) -> Option<&serde_json::Value> {
        self.config.get(module)
    }
}

/// Create test context for `api_gateway` module
fn create_api_gateway_ctx(config: serde_json::Value) -> ModuleCtx {
    let hub = Arc::new(ClientHub::new());

    ModuleCtx::new(
        "api-gateway",
        Uuid::new_v4(),
        Arc::new(TestConfigProvider { config }),
        hub,
        tokio_util::sync::CancellationToken::new(),
        None,
    )
}

/// Create test context for other test modules
fn create_test_module_ctx() -> ModuleCtx {
    ModuleCtx::new(
        "test_module",
        Uuid::new_v4(),
        Arc::new(TestConfigProvider { config: json!({}) }),
        Arc::new(ClientHub::new()),
        tokio_util::sync::CancellationToken::new(),
        None,
    )
}

/// Test response type
#[derive(Clone)]
#[modkit_macros::api_dto(response)]
struct TestResponse {
    message: String,
    user_id: String,
}

/// Handler that requires `SecurityContext` (via Extension extractor)
async fn protected_handler(Extension(ctx): Extension<SecurityContext>) -> Json<TestResponse> {
    Json(TestResponse {
        message: "Protected resource accessed".to_owned(),
        user_id: ctx.subject_id().to_string(),
    })
}

/// Handler that doesn't require auth
async fn public_handler() -> Json<TestResponse> {
    Json(TestResponse {
        message: "Public resource accessed".to_owned(),
        user_id: "anonymous".to_owned(),
    })
}

/// Test module with protected and public routes
pub struct TestAuthModule;

#[async_trait]
impl Module for TestAuthModule {
    async fn init(&self, _ctx: &ModuleCtx) -> Result<()> {
        Ok(())
    }
}

struct License;

impl AsRef<str> for License {
    fn as_ref(&self) -> &'static str {
        "gts.x.core.lic.feat.v1~x.core.global.base.v1"
    }
}

impl LicenseFeature for License {}

impl RestApiCapability for TestAuthModule {
    fn register_rest(
        &self,
        _ctx: &ModuleCtx,
        router: Router,
        openapi: &dyn OpenApiRegistry,
    ) -> Result<Router> {
        // Protected route with explicit auth requirement
        let router = OperationBuilder::get("/tests/v1/api/protected")
            .operation_id("test.protected")
            .authenticated()
            .require_license_features::<License>([])
            .summary("Protected endpoint")
            .handler(protected_handler)
            .json_response_with_schema::<TestResponse>(openapi, http::StatusCode::OK, "Success")
            .error_401(openapi)
            .error_403(openapi)
            .register(router, openapi);

        // Protected route with path parameter (to test pattern matching)
        let router = OperationBuilder::get("/tests/v1/api/users/{id}")
            .operation_id("test.get_user")
            .authenticated()
            .require_license_features::<License>([])
            .summary("Get user by ID")
            .path_param("id", "User ID")
            .handler(protected_handler)
            .json_response_with_schema::<TestResponse>(openapi, http::StatusCode::OK, "Success")
            .error_401(openapi)
            .error_403(openapi)
            .register(router, openapi);

        // Public route with explicit public marking
        let router = OperationBuilder::get("/tests/v1/api/public")
            .operation_id("test.public")
            .public()
            .summary("Public endpoint")
            .handler(public_handler)
            .json_response_with_schema::<TestResponse>(openapi, http::StatusCode::OK, "Success")
            .register(router, openapi);

        Ok(router)
    }
}

#[tokio::test]
async fn test_auth_disabled_mode() {
    // Create api-gateway with auth disabled
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": true,
                "cors_enabled": false,
                "auth_disabled": true,
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    // Register test module
    let router = Router::new();
    let test_module = TestAuthModule;
    let router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    // Finalize router (applies middleware)
    let router = api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize");

    // Test protected route WITHOUT token (should work because auth is disabled)
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Protected route should work when auth is disabled"
    );

    // Test public route
    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/public")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Public route should work"
    );
}

#[tokio::test]
async fn test_public_routes_accessible() {
    // Create api-gateway with auth enabled but test public routes
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": true,
                "cors_enabled": false,
                "auth_disabled": true, // Using disabled for simplicity in test
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    // First call rest_prepare to add built-in routes
    let router = Router::new();
    let router = api_gateway
        .rest_prepare(&api_ctx, router)
        .expect("Failed to prepare");

    // Then register test module routes
    let test_module = TestAuthModule;
    let router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    // Finally finalize
    let router = api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize");

    // Test built-in health endpoints
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Health endpoint should be accessible"
    );

    // Test OpenAPI endpoint
    let response = router
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "OpenAPI endpoint should be accessible"
    );
}

#[tokio::test]
async fn test_public_routes_with_prefix_accessible() {
    // Create api-gateway with auth disabled and test prefixed public routes
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": true,
                "cors_enabled": false,
                "auth_disabled": true, // Using disabled for simplicity in test
                "prefix_path": "/cf",
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    // First call rest_prepare to add built-in routes
    let router = Router::new();
    let router = api_gateway
        .rest_prepare(&api_ctx, router)
        .expect("Failed to prepare");

    // Then register test module routes
    let test_module = TestAuthModule;
    let router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    // Finally finalize
    let router = api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize");

    // Test built-in health endpoints
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Health endpoint should be accessible"
    );

    // Test OpenAPI endpoint
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/cf/openapi.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "OpenAPI endpoint should be accessible"
    );

    // Test OpenAPI endpoint
    let response = router
        .oneshot(
            Request::builder()
                .uri("/openapi.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::NOT_FOUND,
        "OpenAPI endpoint should be inaccessible without prefix"
    );
}

#[tokio::test]
async fn test_middleware_always_inserts_security_ctx() {
    // This test verifies that SecurityContext is always available in handlers
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": false,
                "cors_enabled": false,
                "auth_disabled": true,
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    let mut router: Router = Router::new();
    let test_module = TestAuthModule;
    router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    let router = api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize");

    // Make request to protected handler that extracts SecurityContext
    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    // Should NOT get 500 error about missing SecurityContext
    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Handler should receive SecurityContext from middleware"
    );
}

#[tokio::test]
async fn test_openapi_includes_security_metadata() {
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": true,
                "cors_enabled": false,
                "auth_disabled": true,
                "require_auth_by_default": true,
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    let router = Router::new();
    let test_module = TestAuthModule;
    let _router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    // Build OpenAPI spec
    let openapi = api_gateway
        .build_openapi()
        .expect("Failed to build OpenAPI");
    let spec = serde_json::to_value(&openapi).expect("Failed to serialize");

    // Verify security scheme exists
    let security_schemes = spec
        .pointer("/components/securitySchemes")
        .expect("Security schemes should exist");
    assert!(
        security_schemes.get("bearerAuth").is_some(),
        "bearerAuth scheme should be registered"
    );

    // Verify protected route has security requirement
    // Path is /tests/v1/api/protected, JSON pointer escapes / as ~1
    let protected_security = spec.pointer("/paths/~1tests~1v1~1api~1protected/get/security");
    assert!(
        protected_security.is_some(),
        "Protected route should have security requirement in OpenAPI"
    );

    // Verify public route does NOT have security requirement
    let public_security = spec.pointer("/paths/~1tests~1v1~1api~1public/get/security");
    assert!(
        public_security.is_none()
            || public_security
                .unwrap()
                .as_array()
                .is_some_and(Vec::is_empty),
        "Public route should NOT have security requirement in OpenAPI"
    );
}

#[tokio::test]
async fn test_route_pattern_matching_with_path_params() {
    // This test verifies that routes with path parameters (e.g., /users/{id})
    // are properly matched under a configured prefix (auth disabled in this test)
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": false,
                "cors_enabled": false,
                "auth_disabled": true, // Disabled for test simplicity
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    let mut router = Router::new();
    let test_module = TestAuthModule;
    router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    let router = api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize");

    // Test that /tests/v1/api/users/123 is accessible (matches /tests/v1/api/users/{id})
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/users/123")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Route with path parameter should be accessible and matched correctly"
    );

    // Test that /tests/v1/api/users/abc-def-456 is also accessible
    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/users/abc-def-456")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Route with different path parameter value should also be accessible"
    );
}

#[tokio::test]
async fn test_route_pattern_matching_with_prefix_path_params() {
    // This test verifies that routes with path parameters (e.g., /users/{id})
    // are properly matched and authorization is enforced
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": false,
                "cors_enabled": false,
                "auth_disabled": true, // Disabled for test simplicity
                "prefix_path": "/cf",
            }
        }
    });

    let api_ctx = create_api_gateway_ctx(config);
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    let mut router = Router::new();
    let test_module = TestAuthModule;
    router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    let router = api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize");

    // Test that /tests/v1/api/users/123 is accessible (matches /tests/v1/api/users/{id})
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/cf/tests/v1/api/users/123")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Route with path parameter should be accessible and matched correctly"
    );

    // Test that /tests/v1/api/users/abc-def-456 is also accessible
    let response = router
        .oneshot(
            Request::builder()
                .uri("/cf/tests/v1/api/users/abc-def-456")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Route with different path parameter value should also be accessible"
    );
}

// ---------------------------------------------------------------------------
// Auth-enabled tests: verify the actual authn_middleware with a mock AuthN client
// ---------------------------------------------------------------------------

/// Handler function type for the mock `AuthN` Resolver.
type MockAuthNHandler =
    dyn Fn(&str) -> Result<AuthenticationResult, AuthNResolverError> + Send + Sync;

/// Configurable mock `AuthN` Resolver client for auth-enabled tests.
struct MockAuthNResolverClient {
    handler: Arc<MockAuthNHandler>,
}

#[async_trait]
impl AuthNResolverClient for MockAuthNResolverClient {
    async fn authenticate(
        &self,
        bearer_token: &str,
    ) -> Result<AuthenticationResult, AuthNResolverError> {
        (self.handler)(bearer_token)
    }

    async fn exchange_client_credentials(
        &self,
        _request: &ClientCredentialsRequest,
    ) -> Result<AuthenticationResult, AuthNResolverError> {
        Err(AuthNResolverError::Internal(
            "not implemented in mock".to_owned(),
        ))
    }
}

/// Test module for auth-enabled tests.
///
/// Registers both a protected and a public route.
/// The public route also extracts `SecurityContext` so tests can verify
/// that anonymous context is injected for public endpoints.
pub struct TestAuthEnabledModule;

#[async_trait]
impl Module for TestAuthEnabledModule {
    async fn init(&self, _ctx: &ModuleCtx) -> Result<()> {
        Ok(())
    }
}

impl RestApiCapability for TestAuthEnabledModule {
    fn register_rest(
        &self,
        _ctx: &ModuleCtx,
        router: Router,
        openapi: &dyn OpenApiRegistry,
    ) -> Result<Router> {
        let router = OperationBuilder::get("/tests/v1/api/protected")
            .operation_id("test_auth.protected")
            .authenticated()
            .require_license_features::<License>([])
            .summary("Protected endpoint")
            .handler(protected_handler)
            .json_response_with_schema::<TestResponse>(openapi, http::StatusCode::OK, "Success")
            .error_401(openapi)
            .error_403(openapi)
            .register(router, openapi);

        // Public route that extracts SecurityContext so tests can verify anonymous ctx
        let router = OperationBuilder::get("/tests/v1/api/public-ctx")
            .operation_id("test_auth.public_ctx")
            .public()
            .summary("Public endpoint with security context")
            .handler(protected_handler) // reuse: extracts SecurityContext
            .json_response_with_schema::<TestResponse>(openapi, http::StatusCode::OK, "Success")
            .register(router, openapi);

        Ok(router)
    }
}

async fn create_router(config: serde_json::Value, mock: MockAuthNResolverClient) -> Router {
    let hub = Arc::new(ClientHub::new());
    hub.register::<dyn AuthNResolverClient>(Arc::new(mock));

    let api_ctx = ModuleCtx::new(
        "api-gateway",
        Uuid::new_v4(),
        Arc::new(TestConfigProvider { config }),
        hub,
        tokio_util::sync::CancellationToken::new(),
        None,
    );
    let test_ctx = create_test_module_ctx();

    let api_gateway = api_gateway::ApiGateway::default();
    api_gateway.init(&api_ctx).await.expect("Failed to init");

    let mut router = Router::new();
    let test_module = TestAuthEnabledModule;
    router = test_module
        .register_rest(&test_ctx, router, &api_gateway)
        .expect("Failed to register routes");

    api_gateway
        .rest_finalize(&api_ctx, router)
        .expect("Failed to finalize")
}

/// Create a finalized router with auth **enabled** and the given mock `AuthN` client.
async fn create_auth_enabled_router(mock: MockAuthNResolverClient, cors_enabled: bool) -> Router {
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": false,
                "cors_enabled": cors_enabled,
                "auth_disabled": false,
            }
        }
    });

    create_router(config, mock).await
}

async fn create_auth_enabled_with_prefix_router(
    mock: MockAuthNResolverClient,
    cors_enabled: bool,
) -> Router {
    let config = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "0.0.0.0:8080",
                "enable_docs": false,
                "cors_enabled": cors_enabled,
                "auth_disabled": false,
                "prefix_path": "/cf",
            }
        }
    });

    create_router(config, mock).await
}

/// Build a mock that accepts a specific token and returns a `SecurityContext` with known IDs.
fn mock_accepting_token(
    valid_token: &'static str,
    subject_id: Uuid,
    tenant_id: Uuid,
) -> MockAuthNResolverClient {
    MockAuthNResolverClient {
        handler: Arc::new(move |token| {
            if token == valid_token {
                Ok(AuthenticationResult {
                    security_context: SecurityContext::builder()
                        .subject_id(subject_id)
                        .subject_tenant_id(tenant_id)
                        .build()
                        .unwrap(),
                })
            } else {
                Err(AuthNResolverError::Unauthorized("invalid token".to_owned()))
            }
        }),
    }
}

/// Build a mock that always returns the given error.
fn mock_returning_error(err_fn: fn() -> AuthNResolverError) -> MockAuthNResolverClient {
    MockAuthNResolverClient {
        handler: Arc::new(move |_| Err(err_fn())),
    }
}

// --- Auth-enabled integration tests ---

#[tokio::test]
async fn test_valid_token_returns_200() {
    let subject_id = Uuid::new_v4();
    let tenant_id = Uuid::new_v4();
    let mock = mock_accepting_token("valid-test-token", subject_id, tenant_id);

    let router = create_auth_enabled_router(mock, false).await;

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .header(header::AUTHORIZATION, "Bearer valid-test-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(response.status(), StatusCode::OK);

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(json["user_id"], subject_id.to_string());
}

#[tokio::test]
async fn test_missing_token_returns_401() {
    let mock = mock_accepting_token("any", Uuid::new_v4(), Uuid::new_v4());
    let router = create_auth_enabled_router(mock, false).await;

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                // No Authorization header
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::UNAUTHORIZED,
        "Missing token should yield 401"
    );
}

#[tokio::test]
async fn test_invalid_token_returns_401() {
    let mock = mock_accepting_token("good-token", Uuid::new_v4(), Uuid::new_v4());
    let router = create_auth_enabled_router(mock, false).await;

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .header(header::AUTHORIZATION, "Bearer bad-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::UNAUTHORIZED,
        "Invalid token should yield 401"
    );
}

#[tokio::test]
async fn test_no_plugin_available_returns_503() {
    let mock = mock_returning_error(|| AuthNResolverError::NoPluginAvailable);
    let router = create_auth_enabled_router(mock, false).await;

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .header(header::AUTHORIZATION, "Bearer some-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::SERVICE_UNAVAILABLE,
        "NoPluginAvailable should yield 503"
    );
}

#[tokio::test]
async fn test_service_unavailable_returns_503() {
    let mock =
        mock_returning_error(|| AuthNResolverError::ServiceUnavailable("plugin down".to_owned()));
    let router = create_auth_enabled_router(mock, false).await;

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .header(header::AUTHORIZATION, "Bearer some-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::SERVICE_UNAVAILABLE,
        "ServiceUnavailable should yield 503"
    );
}

#[tokio::test]
async fn test_internal_error_returns_500() {
    let mock = mock_returning_error(|| AuthNResolverError::Internal("boom".to_owned()));
    let router = create_auth_enabled_router(mock, false).await;

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/protected")
                .header(header::AUTHORIZATION, "Bearer some-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::INTERNAL_SERVER_ERROR,
        "Internal error should yield 500"
    );
}

#[tokio::test]
async fn test_public_route_with_auth_enabled() {
    // Mock that would reject any token — proves it is never called for public routes
    let mock =
        mock_returning_error(|| AuthNResolverError::Internal("should not be called".to_owned()));
    let router = create_auth_enabled_router(mock, false).await;

    // No Authorization header on a public route
    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/public-ctx")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Public route should return 200 even with auth enabled and no token"
    );

    // Verify the handler received an anonymous SecurityContext (subject_id = Uuid::default)
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(
        json["user_id"],
        Uuid::default().to_string(),
        "Public route should receive anonymous SecurityContext"
    );
}

#[tokio::test]
async fn test_public_route_with_prefix_auth_enabled() {
    // Mock that would reject any token — proves it is never called for public routes
    let mock =
        mock_returning_error(|| AuthNResolverError::Internal("should not be called".to_owned()));
    let router = create_auth_enabled_with_prefix_router(mock, false).await;

    // No Authorization header on a public route
    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/cf/tests/v1/api/public-ctx")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "Public route should return 200 even with auth enabled and no token"
    );

    // Verify the handler received an anonymous SecurityContext (subject_id = Uuid::default)
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(
        json["user_id"],
        Uuid::default().to_string(),
        "Public route should receive anonymous SecurityContext"
    );

    let response = router
        .oneshot(
            Request::builder()
                .uri("/tests/v1/api/public-ctx")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    assert_eq!(
        response.status(),
        StatusCode::NOT_FOUND,
        "Public route should return 404 for unknown paths"
    );
}

#[tokio::test]
async fn test_cors_preflight_skips_auth() {
    // Mock that rejects everything — proves auth is skipped for preflight
    let mock =
        mock_returning_error(|| AuthNResolverError::Internal("should not be called".to_owned()));
    let router = create_auth_enabled_router(mock, true).await;

    let response = router
        .oneshot(
            Request::builder()
                .method(Method::OPTIONS)
                .uri("/tests/v1/api/protected")
                .header(header::ORIGIN, "https://example.com")
                .header(header::ACCESS_CONTROL_REQUEST_METHOD, "GET")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("Request failed");

    // With CORS enabled, a preflight should NOT be rejected by auth.
    // The exact status depends on the CORS layer (usually 200),
    // but it must NOT be 401/403.
    assert_ne!(
        response.status(),
        StatusCode::UNAUTHORIZED,
        "CORS preflight must not be blocked by auth"
    );
    assert_ne!(
        response.status(),
        StatusCode::FORBIDDEN,
        "CORS preflight must not be blocked by auth"
    );
}