bindcar 0.7.0

HTTP REST API for managing BIND9 zones via rndc
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
// Copyright (c) 2025 Erick Bourgeois, firestoned
// SPDX-License-Identifier: MIT

//! Unit tests for auth module

use crate::auth::{authenticate, AuthError};
use axum::{
    body::Body,
    http::{Request, StatusCode},
    middleware,
    routing::get,
    Router,
};
use tower::ServiceExt;

async fn test_handler() -> &'static str {
    "success"
}

#[tokio::test]
#[cfg_attr(feature = "k8s-token-review", serial_test::serial)]
async fn test_authenticate_with_valid_token() {
    #[cfg(feature = "k8s-token-review")]
    {
        // When k8s-token-review is enabled, actual token validation happens
        // This test would need a real Kubernetes cluster, so we skip detailed testing
        // The feature-specific tests handle validation logic
        use std::env;
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    let app = Router::new()
        .route("/test", get(test_handler))
        .layer(middleware::from_fn(authenticate));

    let request = Request::builder()
        .uri("/test")
        .header("authorization", "Bearer valid-token")
        .body(Body::empty())
        .unwrap();

    let response = app.oneshot(request).await.unwrap();

    #[cfg(not(feature = "k8s-token-review"))]
    assert_eq!(response.status(), StatusCode::OK);

    #[cfg(feature = "k8s-token-review")]
    {
        // With k8s-token-review, this will fail without a real cluster
        // which is expected behavior
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        use std::env;
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }
}

#[tokio::test]
async fn test_authenticate_missing_header() {
    let app = Router::new()
        .route("/test", get(test_handler))
        .layer(middleware::from_fn(authenticate));

    let request = Request::builder().uri("/test").body(Body::empty()).unwrap();

    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn test_authenticate_invalid_format() {
    let app = Router::new()
        .route("/test", get(test_handler))
        .layer(middleware::from_fn(authenticate));

    let request = Request::builder()
        .uri("/test")
        .header("authorization", "InvalidFormat token")
        .body(Body::empty())
        .unwrap();

    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn test_authenticate_empty_token() {
    let app = Router::new()
        .route("/test", get(test_handler))
        .layer(middleware::from_fn(authenticate));

    let request = Request::builder()
        .uri("/test")
        .header("authorization", "Bearer ")
        .body(Body::empty())
        .unwrap();

    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
#[cfg_attr(feature = "k8s-token-review", serial_test::serial)]
async fn test_authenticate_token_with_special_characters() {
    #[cfg(feature = "k8s-token-review")]
    {
        use std::env;
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    let app = Router::new()
        .route("/test", get(test_handler))
        .layer(middleware::from_fn(authenticate));

    // JWT-like token with dots and hyphens
    let request = Request::builder()
        .uri("/test")
        .header("authorization", "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Ik1qSTBNVEV5TXpRMU5qYzRPVEF4TWpNME5UWTNPRGt3TVRJek5EVTJOVGM0T1RBeCJ9.test")
        .body(Body::empty())
        .unwrap();

    let response = app.oneshot(request).await.unwrap();

    #[cfg(not(feature = "k8s-token-review"))]
    assert_eq!(response.status(), StatusCode::OK);

    #[cfg(feature = "k8s-token-review")]
    {
        // With k8s-token-review, validation will fail without a real cluster
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        use std::env;
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }
}

#[tokio::test]
async fn test_authenticate_case_sensitive_bearer() {
    let app = Router::new()
        .route("/test", get(test_handler))
        .layer(middleware::from_fn(authenticate));

    // Test lowercase "bearer" - should fail
    let request = Request::builder()
        .uri("/test")
        .header("authorization", "bearer token123")
        .body(Body::empty())
        .unwrap();

    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn test_auth_error_serialization() {
    let error = AuthError {
        error: "Test error message".to_string(),
    };

    let json = serde_json::to_string(&error).unwrap();
    assert!(json.contains("Test error message"));
    assert!(json.contains("error"));
}

// Kubernetes client builder tests (only when feature is enabled)
#[cfg(feature = "k8s-token-review")]
mod kube_client_builder_tests {
    use crate::auth::{build_explicit_kube_client, detect_kube_auth_mode, KubeAuthMode};
    use serial_test::serial;
    use std::env;
    use std::io::Write;
    use tempfile::NamedTempFile;

    // --- detect_kube_auth_mode: explicit mode ---

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_explicit_when_all_vars_set() {
        env::set_var("KUBE_API_SERVER", "https://api.example.com:6443");
        env::set_var("KUBE_TOKEN_PATH", "/var/run/secrets/token");
        env::set_var("KUBE_CA_CERT_PATH", "/var/run/secrets/ca.crt");

        let mode = detect_kube_auth_mode();

        match mode {
            KubeAuthMode::Explicit {
                server,
                token_path,
                ca_cert_path,
            } => {
                assert_eq!(server, "https://api.example.com:6443");
                assert_eq!(token_path, "/var/run/secrets/token");
                assert_eq!(ca_cert_path, "/var/run/secrets/ca.crt");
            }
            KubeAuthMode::Default => panic!("Expected Explicit mode, got Default"),
        }

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    // --- detect_kube_auth_mode: fallback to Default when no vars set ---

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_no_vars_set() {
        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when no env vars are set"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    // --- detect_kube_auth_mode: partial vars always fall back to Default ---

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_only_api_server_set() {
        env::set_var("KUBE_API_SERVER", "https://api.example.com:6443");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when only KUBE_API_SERVER is set"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_only_token_path_set() {
        env::remove_var("KUBE_API_SERVER");
        env::set_var("KUBE_TOKEN_PATH", "/var/run/secrets/token");
        env::remove_var("KUBE_CA_CERT_PATH");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when only KUBE_TOKEN_PATH is set"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_only_ca_cert_path_set() {
        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::set_var("KUBE_CA_CERT_PATH", "/var/run/secrets/ca.crt");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when only KUBE_CA_CERT_PATH is set"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_api_server_and_token_set_missing_ca() {
        env::set_var("KUBE_API_SERVER", "https://api.example.com:6443");
        env::set_var("KUBE_TOKEN_PATH", "/var/run/secrets/token");
        env::remove_var("KUBE_CA_CERT_PATH");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when KUBE_CA_CERT_PATH is missing"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_api_server_and_ca_set_missing_token() {
        env::set_var("KUBE_API_SERVER", "https://api.example.com:6443");
        env::remove_var("KUBE_TOKEN_PATH");
        env::set_var("KUBE_CA_CERT_PATH", "/var/run/secrets/ca.crt");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when KUBE_TOKEN_PATH is missing"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    #[test]
    #[serial]
    fn test_detect_kube_auth_mode_default_when_token_and_ca_set_missing_api_server() {
        env::remove_var("KUBE_API_SERVER");
        env::set_var("KUBE_TOKEN_PATH", "/var/run/secrets/token");
        env::set_var("KUBE_CA_CERT_PATH", "/var/run/secrets/ca.crt");

        let mode = detect_kube_auth_mode();

        assert!(
            matches!(mode, KubeAuthMode::Default),
            "Expected Default mode when KUBE_API_SERVER is missing"
        );

        env::remove_var("KUBE_API_SERVER");
        env::remove_var("KUBE_TOKEN_PATH");
        env::remove_var("KUBE_CA_CERT_PATH");
    }

    // --- build_explicit_kube_client: file error handling ---

    #[tokio::test]
    async fn test_build_explicit_kube_client_fails_with_missing_token_file() {
        let result = build_explicit_kube_client(
            "https://api.example.com:6443".to_string(),
            "/nonexistent/bindcar-test/token".to_string(),
            "/nonexistent/bindcar-test/ca.crt".to_string(),
        )
        .await;

        assert!(result.is_err(), "Expected error for missing token file");
        // Client doesn't implement Debug, so extract the error string via if let.
        if let Err(err) = result {
            assert!(
                err.contains("token")
                    || err.contains("No such file")
                    || err.contains("failed to read"),
                "Error should describe the token file problem, got: {}",
                err
            );
        }
    }

    #[tokio::test]
    async fn test_build_explicit_kube_client_fails_with_missing_ca_file() {
        let mut token_file = NamedTempFile::new().unwrap();
        write!(token_file, "fake-sa-token").unwrap();
        let token_path = token_file.path().to_str().unwrap().to_string();

        let result = build_explicit_kube_client(
            "https://api.example.com:6443".to_string(),
            token_path,
            "/nonexistent/bindcar-test/ca.crt".to_string(),
        )
        .await;

        assert!(result.is_err(), "Expected error for missing CA cert file");
        if let Err(err) = result {
            assert!(
                err.contains("certificate")
                    || err.contains("ca")
                    || err.contains("No such file")
                    || err.contains("failed to read"),
                "Error should describe the CA certificate problem, got: {}",
                err
            );
        }
    }

    #[tokio::test]
    async fn test_build_explicit_kube_client_fails_with_invalid_ca_cert() {
        let mut token_file = NamedTempFile::new().unwrap();
        write!(token_file, "fake-sa-token").unwrap();
        let token_path = token_file.path().to_str().unwrap().to_string();

        let mut ca_file = NamedTempFile::new().unwrap();
        write!(ca_file, "this is not a valid PEM certificate").unwrap();
        let ca_path = ca_file.path().to_str().unwrap().to_string();

        let result = build_explicit_kube_client(
            "https://api.example.com:6443".to_string(),
            token_path,
            ca_path,
        )
        .await;

        assert!(
            result.is_err(),
            "Expected error for invalid CA certificate content"
        );
    }
}

// Kubernetes TokenReview tests (only when feature is enabled)
#[cfg(feature = "k8s-token-review")]
mod k8s_token_review_tests {
    use crate::auth::{
        audiences_compatible, check_authorization_posture, validate_token_with_k8s,
        TokenReviewConfig,
    };
    use serial_test::serial;
    use std::env;

    // ---- A1: audience binding (status.audiences) ----

    #[test]
    fn test_audiences_compatible_exact_match() {
        let requested = vec!["bindcar".to_string()];
        let returned = vec!["bindcar".to_string()];
        assert!(audiences_compatible(&requested, &returned));
    }

    #[test]
    fn test_audiences_compatible_intersection() {
        let requested = vec!["bindcar".to_string(), "https://bindcar.svc".to_string()];
        let returned = vec!["https://bindcar.svc".to_string()];
        assert!(audiences_compatible(&requested, &returned));
    }

    #[test]
    fn test_audiences_incompatible_empty_returned() {
        // The A1 exploit case: apiserver authenticates a valid token but echoes
        // no compatible audience. Must be rejected, not accepted.
        let requested = vec!["bindcar".to_string()];
        let returned: Vec<String> = vec![];
        assert!(!audiences_compatible(&requested, &returned));
    }

    #[test]
    fn test_audiences_incompatible_apiserver_audience() {
        // A pod's default SA token carries the apiserver audience, never "bindcar".
        let requested = vec!["bindcar".to_string()];
        let returned = vec!["https://kubernetes.default.svc".to_string()];
        assert!(!audiences_compatible(&requested, &returned));
    }

    // ---- A2: fail-closed authorization posture ----

    #[test]
    fn test_authorization_posture_rejects_allow_all_default() {
        // No allowlist + no override = allow-all: must refuse to start.
        assert!(check_authorization_posture(false, false).is_err());
    }

    #[test]
    fn test_authorization_posture_allows_restricted() {
        assert!(check_authorization_posture(true, false).is_ok());
    }

    #[test]
    fn test_authorization_posture_allows_explicit_override() {
        assert!(check_authorization_posture(false, true).is_ok());
    }

    #[test]
    #[serial]
    fn test_is_authorization_restricted_empty_is_unrestricted() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();
        assert!(!config.is_authorization_restricted());
    }

    #[test]
    #[serial]
    fn test_is_authorization_restricted_with_namespace() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::set_var("BIND_ALLOWED_NAMESPACES", "dns-system");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();
        assert!(config.is_authorization_restricted());

        env::remove_var("BIND_ALLOWED_NAMESPACES");
    }

    #[test]
    #[serial]
    fn test_is_authorization_restricted_with_service_account() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::set_var(
            "BIND_ALLOWED_SERVICE_ACCOUNTS",
            "system:serviceaccount:dns-system:external-dns",
        );

        let config = TokenReviewConfig::from_env();
        assert!(config.is_authorization_restricted());

        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[tokio::test]
    #[serial]
    async fn test_validate_token_with_k8s_requires_cluster() {
        // Clear environment to ensure consistent test
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        // This test validates the error handling when not in a cluster
        let result = validate_token_with_k8s("test-token").await;

        // Outside a cluster, this should fail with a clear error message
        assert!(
            result.is_err(),
            "Expected token validation to fail outside cluster"
        );

        // We just need to confirm it failed - the error message can vary

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[tokio::test]
    async fn test_validate_token_empty_string() {
        let result = validate_token_with_k8s("").await;

        // Even an empty token should attempt validation and fail
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_validate_token_malformed() {
        // Test with a clearly malformed token
        let result = validate_token_with_k8s("not-a-valid-jwt-token").await;

        // Should fail validation
        assert!(result.is_err());
    }

    #[test]
    #[serial_test::serial]
    fn test_token_review_config_default_audiences() {
        // Clear environment
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();

        // Default audience should be "bindcar"
        assert_eq!(config.audiences, vec!["bindcar"]);
        assert!(config.allowed_namespaces.is_empty());
        assert!(config.allowed_service_accounts.is_empty());

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial_test::serial]
    fn test_token_review_config_custom_audiences() {
        env::set_var("BIND_TOKEN_AUDIENCES", "api1,api2,api3");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();

        assert_eq!(config.audiences, vec!["api1", "api2", "api3"]);
        assert!(config.allowed_namespaces.is_empty());
        assert!(config.allowed_service_accounts.is_empty());

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial]
    fn test_token_review_config_with_whitespace() {
        env::set_var("BIND_TOKEN_AUDIENCES", " api1 , api2 , api3 ");
        env::set_var("BIND_ALLOWED_NAMESPACES", " dns-system , kube-system ");
        env::set_var(
            "BIND_ALLOWED_SERVICE_ACCOUNTS",
            " system:serviceaccount:ns1:sa1 , system:serviceaccount:ns2:sa2 ",
        );

        let config = TokenReviewConfig::from_env();

        // Whitespace should be trimmed
        assert_eq!(config.audiences, vec!["api1", "api2", "api3"]);
        assert_eq!(config.allowed_namespaces, vec!["dns-system", "kube-system"]);
        assert_eq!(
            config.allowed_service_accounts,
            vec![
                "system:serviceaccount:ns1:sa1",
                "system:serviceaccount:ns2:sa2"
            ]
        );

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial]
    fn test_token_review_config_empty_values() {
        env::set_var("BIND_TOKEN_AUDIENCES", "");
        env::set_var("BIND_ALLOWED_NAMESPACES", "");
        env::set_var("BIND_ALLOWED_SERVICE_ACCOUNTS", "");

        let config = TokenReviewConfig::from_env();

        // Empty strings should result in default audience
        assert_eq!(config.audiences, vec!["bindcar"]);
        assert!(config.allowed_namespaces.is_empty());
        assert!(config.allowed_service_accounts.is_empty());

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial]
    fn test_is_namespace_allowed_empty_list() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();

        // Empty list means allow all
        assert!(config.is_namespace_allowed("any-namespace"));
        assert!(config.is_namespace_allowed("dns-system"));
        assert!(config.is_namespace_allowed("default"));

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial]
    fn test_is_namespace_allowed_with_allowlist() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::set_var("BIND_ALLOWED_NAMESPACES", "dns-system,kube-system");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();

        assert!(config.is_namespace_allowed("dns-system"));
        assert!(config.is_namespace_allowed("kube-system"));
        assert!(!config.is_namespace_allowed("default"));
        assert!(!config.is_namespace_allowed("other-namespace"));

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial]
    fn test_is_service_account_allowed_empty_list() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");

        let config = TokenReviewConfig::from_env();

        // Empty list means allow all
        assert!(config.is_service_account_allowed("system:serviceaccount:ns:sa"));
        assert!(config.is_service_account_allowed("system:serviceaccount:default:test"));

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    #[serial]
    fn test_is_service_account_allowed_with_allowlist() {
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::set_var(
            "BIND_ALLOWED_SERVICE_ACCOUNTS",
            "system:serviceaccount:dns-system:external-dns,system:serviceaccount:dns-system:cert-manager",
        );

        let config = TokenReviewConfig::from_env();

        assert!(config.is_service_account_allowed("system:serviceaccount:dns-system:external-dns"));
        assert!(config.is_service_account_allowed("system:serviceaccount:dns-system:cert-manager"));
        assert!(!config.is_service_account_allowed("system:serviceaccount:dns-system:other-app"));
        assert!(!config.is_service_account_allowed("system:serviceaccount:default:my-app"));

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }

    #[test]
    fn test_extract_namespace_valid() {
        let username = "system:serviceaccount:dns-system:external-dns";
        let namespace = TokenReviewConfig::extract_namespace(username);

        assert_eq!(namespace, Some("dns-system".to_string()));
    }

    #[test]
    fn test_extract_namespace_different_namespace() {
        let username = "system:serviceaccount:kube-system:coredns";
        let namespace = TokenReviewConfig::extract_namespace(username);

        assert_eq!(namespace, Some("kube-system".to_string()));
    }

    #[test]
    fn test_extract_namespace_invalid_format() {
        // Not enough parts
        assert_eq!(TokenReviewConfig::extract_namespace("invalid"), None);

        // Wrong prefix
        assert_eq!(
            TokenReviewConfig::extract_namespace("user:serviceaccount:ns:sa"),
            None
        );

        // Missing serviceaccount
        assert_eq!(
            TokenReviewConfig::extract_namespace("system:namespace:ns:sa"),
            None
        );

        // Too few colons
        assert_eq!(
            TokenReviewConfig::extract_namespace("system:serviceaccount:ns"),
            None
        );
    }

    #[test]
    fn test_extract_namespace_with_special_characters() {
        let username = "system:serviceaccount:my-dns-system-123:app-name_v2";
        let namespace = TokenReviewConfig::extract_namespace(username);

        assert_eq!(namespace, Some("my-dns-system-123".to_string()));
    }

    #[test]
    #[serial]
    fn test_config_combination_strict_production() {
        env::set_var("BIND_TOKEN_AUDIENCES", "bindcar,https://bindcar.svc");
        env::set_var("BIND_ALLOWED_NAMESPACES", "dns-system");
        env::set_var(
            "BIND_ALLOWED_SERVICE_ACCOUNTS",
            "system:serviceaccount:dns-system:external-dns",
        );

        let config = TokenReviewConfig::from_env();

        assert_eq!(config.audiences, vec!["bindcar", "https://bindcar.svc"]);
        assert_eq!(config.allowed_namespaces, vec!["dns-system"]);
        assert_eq!(
            config.allowed_service_accounts,
            vec!["system:serviceaccount:dns-system:external-dns"]
        );

        // Validate combinations
        assert!(config.is_namespace_allowed("dns-system"));
        assert!(!config.is_namespace_allowed("default"));
        assert!(config.is_service_account_allowed("system:serviceaccount:dns-system:external-dns"));
        assert!(!config.is_service_account_allowed("system:serviceaccount:dns-system:other"));

        // Cleanup
        env::remove_var("BIND_TOKEN_AUDIENCES");
        env::remove_var("BIND_ALLOWED_NAMESPACES");
        env::remove_var("BIND_ALLOWED_SERVICE_ACCOUNTS");
    }
}

// ---------------------------------------------------------------------------
// B-4: shared-secret auth + startup posture guard (pure, env-free tests)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod b4_auth_posture_tests {
    use crate::auth::{check_startup_auth_posture, compare_shared_secret, is_loopback_host};

    #[test]
    fn test_is_loopback_host() {
        assert!(is_loopback_host("127.0.0.1"));
        assert!(is_loopback_host("127.0.0.5"));
        assert!(is_loopback_host("::1"));
        assert!(is_loopback_host("localhost"));
        assert!(is_loopback_host("LocalHost"));
        assert!(!is_loopback_host("0.0.0.0"));
        assert!(!is_loopback_host("10.0.0.5"));
        assert!(!is_loopback_host("example.com"));
    }

    #[test]
    fn test_compare_shared_secret_noop_when_unconfigured() {
        // Not configured (None) => any token passes this layer.
        assert!(compare_shared_secret("anything", None).is_ok());
        assert!(compare_shared_secret("", None).is_ok());
    }

    #[test]
    fn test_compare_shared_secret_matches_and_rejects() {
        assert!(compare_shared_secret("s3cret-token", Some("s3cret-token")).is_ok());
        // Presence-only style token (B-4) must now be rejected when a real secret is set.
        assert!(compare_shared_secret("valid-token", Some("s3cret-token")).is_err());
        assert!(compare_shared_secret("", Some("s3cret-token")).is_err());
        assert!(compare_shared_secret("s3cret-token-extra", Some("s3cret-token")).is_err());
    }

    #[test]
    fn test_compare_shared_secret_length_independent() {
        // A15: comparison is over fixed-size SHA-256 digests, so tokens of very
        // different lengths still compare correctly (exact match passes, any
        // mismatch fails) without a length-based short-circuit.
        let secret = "a-reasonably-long-shared-secret-value";
        assert!(compare_shared_secret(secret, Some(secret)).is_ok());
        assert!(compare_shared_secret("x", Some(secret)).is_err());
        assert!(compare_shared_secret(&"z".repeat(4096), Some(secret)).is_err());
    }

    #[test]
    fn test_startup_posture_allows_loopback_without_auth() {
        // Disabled or presence-only auth on loopback is acceptable for local dev.
        assert!(check_startup_auth_posture(false, false, "127.0.0.1", false).is_ok());
        assert!(check_startup_auth_posture(false, false, "localhost", false).is_ok());
        assert!(check_startup_auth_posture(true, false, "::1", false).is_ok());
    }

    #[test]
    fn test_startup_posture_refuses_nonloopback_without_real_auth() {
        // Presence-only (auth enabled, no real auth) on a non-loopback bind must refuse.
        assert!(check_startup_auth_posture(true, false, "0.0.0.0", false).is_err());
        // Disabled auth on a non-loopback bind must refuse.
        assert!(check_startup_auth_posture(false, false, "0.0.0.0", false).is_err());
        assert!(check_startup_auth_posture(false, false, "10.0.0.5", false).is_err());
    }

    #[test]
    fn test_startup_posture_allows_nonloopback_with_real_auth() {
        assert!(check_startup_auth_posture(true, true, "0.0.0.0", false).is_ok());
    }

    #[test]
    fn test_startup_posture_allows_explicit_override() {
        // --i-know-this-is-insecure lets an operator opt into the risk.
        assert!(check_startup_auth_posture(false, false, "0.0.0.0", true).is_ok());
        assert!(check_startup_auth_posture(true, false, "0.0.0.0", true).is_ok());
    }
}