krab_core 0.6.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
//! Environment-driven configuration and the secrets-source policy.
//!
//! [`KrabConfig`] and [`HttpConfig`] read the `KRAB_*` environment variables
//! documented in `docs/reference/environment.md`. [`read_env_or_file`] is the
//! one sanctioned way to read a secret: it resolves `NAME`, then `NAME_FILE`,
//! and rejects `NAME_VAULT_REF`, which has no runtime resolver.
//! [`KrabConfig::validate_all`] enforces the per-environment rules — outside
//! `dev`, inline secrets, static bearer tokens and wildcard CORS are refused.

use anyhow::{Context, Result};
use std::fs;

// ---------------------------------------------------------------------------
// Secrets source policy
// ---------------------------------------------------------------------------

/// Severity of a secret-source policy violation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretIssueSeverity {
    /// Hard failure — blocks startup in the affected environment.
    Error,
    /// Advisory — logged but does not block startup.
    Warning,
}

/// A single secret-source policy violation.
#[derive(Debug, Clone)]
pub struct SecretIssue {
    /// The environment variable name that violated policy.
    pub var_name: String,
    /// Machine-readable policy rule code (e.g. `INLINE_SECRET_IN_PROD`).
    pub policy_rule: String,
    /// Whether this issue blocks startup ([`SecretIssueSeverity::Error`]) or is
    /// advisory.
    pub severity: SecretIssueSeverity,
    /// Human-readable description of the violation.
    pub reason: String,
}

impl std::fmt::Display for SecretIssue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sev = match self.severity {
            SecretIssueSeverity::Error => "ERROR",
            SecretIssueSeverity::Warning => "WARN",
        };
        write!(
            f,
            "[{}] {} ({}): {}",
            sev, self.var_name, self.policy_rule, self.reason
        )
    }
}

/// Aggregated result of secrets-source policy validation.
#[derive(Debug, Clone)]
pub struct SecretsValidationReport {
    /// Every violation found, in the order the secret variables were checked.
    pub issues: Vec<SecretIssue>,
}

impl SecretsValidationReport {
    /// True when at least one issue has [`SecretIssueSeverity::Error`], i.e.
    /// the configuration must not be allowed to start.
    pub fn has_errors(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.severity == SecretIssueSeverity::Error)
    }

    /// True when there are no issues at all, warnings included.
    pub fn is_clean(&self) -> bool {
        self.issues.is_empty()
    }
}

/// Per-environment secrets source rules.
///
/// - **Dev**: any source allowed (inline env, `*_FILE`, `*_VAULT_REF`).
/// - **Staging**: `*_FILE` / `*_VAULT_REF` preferred; inline triggers a warning.
/// - **Prod** (or unknown): only `*_FILE` / `*_VAULT_REF`; inline is an error.
fn check_secret_source(var_name: &str, env: &Environment, issues: &mut Vec<SecretIssue>) {
    let has_inline = env_non_empty(var_name).is_some();
    let has_file = env_non_empty(&format!("{var_name}_FILE")).is_some();
    let has_vault = env_non_empty(&format!("{var_name}_VAULT_REF")).is_some();

    // If the secret is not set at all, nothing to validate here (presence
    // checks are done separately by the caller when the secret is required).
    if !has_inline && !has_file && !has_vault {
        return;
    }

    let has_secure = has_file || has_vault;

    match env {
        Environment::Dev => { /* anything goes */ }
        Environment::Staging => {
            if has_vault {
                issues.push(SecretIssue {
                    var_name: var_name.to_string(),
                    policy_rule: "UNRESOLVED_VAULT_REF_IN_STAGING".to_string(),
                    severity: SecretIssueSeverity::Error,
                    reason: format!(
                        "{var_name}_VAULT_REF is set in staging, but runtime vault resolution is not configured; materialize the secret before startup"
                    ),
                });
            }
            if has_inline && !has_secure {
                issues.push(SecretIssue {
                    var_name: var_name.to_string(),
                    policy_rule: "INLINE_SECRET_IN_STAGING".to_string(),
                    severity: SecretIssueSeverity::Warning,
                    reason: format!(
                        "{var_name} is set as an inline env var in staging; \
                         prefer *_FILE or *_VAULT_REF for secret sourcing"
                    ),
                });
            }
        }
        Environment::Prod | Environment::Unknown(_) => {
            if has_vault {
                issues.push(SecretIssue {
                    var_name: var_name.to_string(),
                    policy_rule: "UNRESOLVED_VAULT_REF_IN_PROD".to_string(),
                    severity: SecretIssueSeverity::Error,
                    reason: format!(
                        "{var_name}_VAULT_REF is set in '{}', but runtime vault resolution is not configured; materialize the secret before startup",
                        env.as_str()
                    ),
                });
            }
            if has_inline && !has_secure {
                issues.push(SecretIssue {
                    var_name: var_name.to_string(),
                    policy_rule: "INLINE_SECRET_IN_PROD".to_string(),
                    severity: SecretIssueSeverity::Error,
                    reason: format!(
                        "{var_name} is set as an inline env var in '{}'; \
                         only *_FILE or *_VAULT_REF sourcing is allowed",
                        env.as_str()
                    ),
                });
            }
        }
    }
}

/// Deployment environment, read from `KRAB_ENVIRONMENT` by
/// [`Environment::from_env`].
///
/// Only `Dev` relaxes the security checks. An unrecognised value is kept as
/// `Unknown` and treated with the same rules as `Prod`, so a typo fails
/// closed rather than open.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Environment {
    /// Local development (`dev` or its alias `local`, and the default when
    /// the variable is unset):
    /// any secret source, static auth and allow-all CORS are permitted.
    Dev,
    /// `staging`: production rules, except an inline secret is a warning
    /// rather than an error.
    Staging,
    /// `prod` or `production`: secrets must come from `*_FILE` sourcing and
    /// CORS origins must be listed explicitly.
    Prod,
    /// Any other value, verbatim. Validated as strictly as `Prod`.
    Unknown(String),
}

/// Reads environment variable `name`, trimmed; `None` when it is unset, not
/// valid Unicode, or empty after trimming.
pub fn env_non_empty(name: &str) -> Option<String> {
    std::env::var(name)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

/// Whether a `KRAB_JWT_ALLOWED_ALGS` value names algorithms from both the
/// HMAC family (`HS*`) and an asymmetric family (`RS*`/`PS*`/`ES*`/`EdDSA`).
///
/// Unknown names are ignored here — the request-path parser drops them with a
/// warning — so only recognised algorithms determine the verdict.
pub(crate) fn jwt_allowlist_mixes_hmac_and_asymmetric(raw: &str) -> bool {
    let mut has_hmac = false;
    let mut has_asymmetric = false;

    for alg in raw.split(',').map(str::trim).filter(|alg| !alg.is_empty()) {
        let upper = alg.to_ascii_uppercase();
        if upper.starts_with("HS") {
            has_hmac = true;
        } else if upper.starts_with("RS")
            || upper.starts_with("PS")
            || upper.starts_with("ES")
            || upper == "EDDSA"
        {
            has_asymmetric = true;
        }
    }

    has_hmac && has_asymmetric
}

/// Whether the resolved `KRAB_JWT_ALLOWED_ALGS` allowlist admits only HMAC
/// (`HS*`) algorithms. `None` (unset) is the `HS256` default, so it is.
fn jwt_allowlist_is_hmac_only(raw: Option<&str>) -> bool {
    let Some(raw) = raw else {
        return true;
    };
    let mut has_hmac = false;
    for alg in raw.split(',').map(str::trim).filter(|alg| !alg.is_empty()) {
        let upper = alg.to_ascii_uppercase();
        if upper.starts_with("HS") {
            has_hmac = true;
        } else if upper.starts_with("RS")
            || upper.starts_with("PS")
            || upper.starts_with("ES")
            || upper == "EDDSA"
        {
            return false;
        }
    }
    has_hmac
}

/// Whether any provider in `KRAB_JWT_PROVIDERS_JSON` (or its `_FILE` form)
/// declares a non-empty `jwks_url`. An unreadable or malformed bundle
/// answers `false`: other checks report those.
fn provider_bundle_uses_jwks() -> bool {
    let Ok(Some(raw)) = read_env_or_file("KRAB_JWT_PROVIDERS_JSON") else {
        return false;
    };
    serde_json::from_str::<serde_json::Value>(&raw)
        .ok()
        .and_then(|value| value.as_array().cloned())
        .is_some_and(|providers| {
            providers.iter().any(|provider| {
                provider
                    .get("jwks_url")
                    .and_then(|v| v.as_str())
                    .is_some_and(|url| !url.trim().is_empty())
            })
        })
}

/// Reads a secret named `name` from the environment, the sanctioned way.
///
/// Resolution order:
///
/// 1. `name` itself, if set and non-empty (trimmed).
/// 2. `{name}_FILE`: the contents of the file it points at, trimmed. A file
///    that cannot be read, or is empty, is an error — not `None`.
/// 3. `{name}_VAULT_REF`: always an error, because there is no runtime vault
///    resolver; the secret has to be materialised (for example to a file)
///    before startup.
///
/// Returns `Ok(None)` when none of the three is set. This function does not
/// apply the per-environment policy that forbids inline values outside `dev`;
/// that is [`KrabConfig::validate_secrets_sources`].
pub fn read_env_or_file(name: &str) -> Result<Option<String>> {
    if let Some(value) = env_non_empty(name) {
        return Ok(Some(value));
    }

    let file_var = format!("{name}_FILE");
    if let Some(path) = env_non_empty(&file_var) {
        let raw = fs::read_to_string(&path)
            .with_context(|| format!("failed to read {} from file path '{}'", file_var, path))?;
        let value = raw.trim().to_string();
        anyhow::ensure!(
            !value.is_empty(),
            "{} points to empty file '{}'",
            file_var,
            path
        );
        return Ok(Some(value));
    }

    let vault_ref_var = format!("{name}_VAULT_REF");
    if let Some(vault_ref) = env_non_empty(&vault_ref_var) {
        anyhow::bail!(
            "{} is set to '{}' but runtime vault resolution is not configured; materialize the secret before startup or provide {} / {}_FILE",
            vault_ref_var,
            vault_ref,
            name,
            name
        );
    }

    Ok(None)
}

impl Environment {
    /// Reads `KRAB_ENVIRONMENT`, case-insensitively. Unset means
    /// [`Environment::Dev`]; `local` is an alias of `dev`; `prod` and
    /// `production` both mean [`Environment::Prod`]; anything unrecognised
    /// becomes [`Environment::Unknown`].
    ///
    /// `local` is accepted because every other reader of the variable already
    /// treats it as dev-like: `krab env-check` / `krab doctor`, the auth
    /// service's startup guard, and the migration promotion ladder (where it
    /// is the stage below `dev`). Parsing it as `Unknown` applied prod rules
    /// to a name the rest of the framework calls local development.
    pub fn from_env() -> Self {
        match std::env::var("KRAB_ENVIRONMENT") {
            Ok(v) if v.eq_ignore_ascii_case("dev") || v.eq_ignore_ascii_case("local") => Self::Dev,
            Ok(v) if v.eq_ignore_ascii_case("staging") => Self::Staging,
            Ok(v) if v.eq_ignore_ascii_case("prod") || v.eq_ignore_ascii_case("production") => {
                Self::Prod
            }
            Ok(v) => Self::Unknown(v),
            Err(_) => Self::Dev,
        }
    }

    /// The canonical name (`dev`, `staging`, `prod`), or the raw value for
    /// [`Environment::Unknown`]. Used in log and error messages.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Dev => "dev",
            Self::Staging => "staging",
            Self::Prod => "prod",
            Self::Unknown(v) => v.as_str(),
        }
    }
}

/// HTTP-layer settings: authentication mode, rate limiting, proxy trust and
/// CORS. Built by [`HttpConfig::from_env`].
#[derive(Debug, Clone)]
pub struct HttpConfig {
    /// `KRAB_AUTH_MODE` (default `jwt`). [`KrabConfig::validate`] accepts
    /// `jwt` or `oidc` outside `dev`; `static` is dev-only.
    pub auth_mode: String,
    /// `KRAB_SERVICE_AUTH_SCOPE` (default `service:internal`): the scope a
    /// caller's token must carry to reach `/internal` and `/api/internal`
    /// paths.
    pub service_auth_scope: String,
    /// `KRAB_RATE_LIMIT_CAPACITY` (default 120): the most requests one client
    /// IP may make per rate-limit window.
    pub rate_limit_capacity: u64,
    /// `KRAB_RATE_LIMIT_REFILL_PER_SEC` (default 60). Together with the
    /// capacity it sets the window length, `ceil(capacity / refill)` seconds
    /// clamped to 1–300; the limiter is a fixed-window counter, not a token
    /// bucket.
    pub rate_limit_refill_per_sec: u64,
    /// Behavior when distributed rate-limit store errors occur.
    /// true = fail-open, false = fail-closed.
    pub rate_limit_fail_open: bool,
    /// Length (seconds) of the per-client-IP auth-failure window. Shared across
    /// replicas when the runtime store is Redis-backed.
    ///
    /// The window is fixed (tumbling), not sliding: the counter key carries
    /// `floor(unix_secs / window)`, so it resets at the boundary rather than
    /// ageing out failure by failure. A client can therefore spend up to
    /// `2 * auth_fail_threshold` failures across two adjacent windows.
    pub auth_fail_window_secs: u64,
    /// Max auth failures a client IP may accumulate in one window before the
    /// next failure is answered 429. Shared across replicas like the window.
    /// `0` is a valid lockdown setting: it blocks on the first auth failure in
    /// the window. Unparseable values fall back to the default.
    pub auth_fail_threshold: u64,
    /// Trust `x-forwarded-for` / `x-real-ip` request headers for client IP extraction.
    pub trust_proxy_headers: bool,
    /// Allowed CORS origins from `KRAB_CORS_ORIGINS` (comma-separated).
    /// In staging/prod, this must be non-empty.
    pub cors_origins: Vec<String>,
    /// Whether runtime may treat CORS as allow-all when no explicit origin list exists.
    /// This is only enabled in `dev` by default.
    pub cors_allow_any_origin: bool,
}

impl HttpConfig {
    /// Reads the `KRAB_*` HTTP variables. Never fails: an unparseable number
    /// falls back to its default. `KRAB_RATE_LIMIT_FAIL_OPEN` defaults to
    /// true only in `dev`, and allow-all CORS is enabled only in `dev`.
    pub fn from_env() -> Self {
        let environment = Environment::from_env();
        let env_bool = |name: &str| {
            std::env::var(name)
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .ok()
        };
        let cors_origins = std::env::var("KRAB_CORS_ORIGINS")
            .map(|v| {
                v.split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        Self {
            auth_mode: std::env::var("KRAB_AUTH_MODE").unwrap_or_else(|_| "jwt".to_string()),
            service_auth_scope: std::env::var("KRAB_SERVICE_AUTH_SCOPE")
                .unwrap_or_else(|_| "service:internal".to_string()),
            rate_limit_capacity: std::env::var("KRAB_RATE_LIMIT_CAPACITY")
                .ok()
                .and_then(|v| v.parse::<u64>().ok())
                .unwrap_or(120),
            rate_limit_refill_per_sec: std::env::var("KRAB_RATE_LIMIT_REFILL_PER_SEC")
                .ok()
                .and_then(|v| v.parse::<u64>().ok())
                .unwrap_or(60),
            rate_limit_fail_open: env_bool("KRAB_RATE_LIMIT_FAIL_OPEN")
                .unwrap_or(matches!(environment, Environment::Dev)),
            auth_fail_window_secs: std::env::var("KRAB_AUTH_FAILURE_WINDOW_SECS")
                .ok()
                .and_then(|v| v.parse::<u64>().ok())
                .filter(|&v| v > 0)
                .unwrap_or(60),
            auth_fail_threshold: std::env::var("KRAB_AUTH_FAILURE_THRESHOLD")
                .ok()
                .and_then(|v| v.parse::<u64>().ok())
                .unwrap_or(100),
            trust_proxy_headers: env_bool("KRAB_TRUST_PROXY_HEADERS").unwrap_or(false),
            cors_origins,
            cors_allow_any_origin: matches!(environment, Environment::Dev),
        }
    }
}

/// Unified application configuration loaded from environment variables.
///
/// Call [`KrabConfig::from_env_checked`] once at startup; pass the result (or
/// specific sub-configs) through the dependency graph instead of reading
/// `std::env::var` ad-hoc in individual modules.
#[derive(Debug, Clone)]
pub struct KrabConfig {
    /// `KRAB_ENVIRONMENT`; decides how strict [`KrabConfig::validate_all`] is.
    pub environment: Environment,
    /// `KRAB_SERVICE_NAME`, or the default the service passes in.
    pub service_name: String,
    /// `KRAB_HOST`, the address to bind (default `127.0.0.1`).
    pub host: String,
    /// `KRAB_PORT`, or the default the service passes in. An empty value also
    /// means the default; an unparseable one is [`ConfigError::InvalidPort`].
    pub port: u16,
    /// `RUST_LOG`, the `tracing` filter directive (default `info`).
    pub log_filter: String,
    /// HTTP-layer settings.
    pub http: HttpConfig,
}

/// A configuration value that could not be parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    /// `KRAB_PORT` is set but is not an integer in 0–65535.
    InvalidPort {
        /// The trimmed value that failed to parse.
        raw: String,
    },
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidPort { raw } => {
                write!(f, "invalid KRAB_PORT='{}': expected integer 0-65535", raw)
            }
        }
    }
}

impl std::error::Error for ConfigError {}

fn parse_port_from_env(default_port: u16) -> Result<u16, ConfigError> {
    match std::env::var("KRAB_PORT") {
        Ok(raw) => {
            let trimmed = raw.trim();
            if trimmed.is_empty() {
                Ok(default_port)
            } else {
                trimmed
                    .parse::<u16>()
                    .map_err(|_| ConfigError::InvalidPort {
                        raw: trimmed.to_string(),
                    })
            }
        }
        Err(_) => Ok(default_port),
    }
}

impl KrabConfig {
    /// Load all configuration from environment variables with typed defaults.
    ///
    /// Returns an error, rather than panicking, when a value such as
    /// `KRAB_PORT` does not parse. The panicking `from_env` wrapper was
    /// deprecated in 0.3.0 and removed in 0.6.0.
    pub fn from_env_checked(
        default_service_name: &str,
        default_port: u16,
    ) -> Result<Self, ConfigError> {
        let port = parse_port_from_env(default_port)?;

        Ok(Self {
            environment: Environment::from_env(),
            service_name: std::env::var("KRAB_SERVICE_NAME")
                .unwrap_or_else(|_| default_service_name.to_string()),
            host: std::env::var("KRAB_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
            port,
            log_filter: std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()),
            http: HttpConfig::from_env(),
        })
    }

    /// Validate security-critical configuration at startup.
    ///
    /// In `Dev` environments all checks are skipped. In `Staging`, `Prod`, or any
    /// unrecognised environment, required secrets must be present or this returns
    /// an error — callers should propagate the error and abort the process.
    pub fn validate(&self) -> anyhow::Result<()> {
        let has_non_empty = |name: &str| !std::env::var(name).unwrap_or_default().trim().is_empty();

        match self.environment {
            Environment::Dev => return Ok(()),
            Environment::Staging | Environment::Prod | Environment::Unknown(_) => {}
        }

        // Every non-dev environment, including unrecognised ones: those already
        // get the prod secret rules above, and exempting them from this one
        // meant a typo such as `KRAB_ENVIRONMENT=prdo` shipped wildcard CORS.
        if self.http.cors_origins.is_empty() {
            anyhow::bail!(
                "KRAB_CORS_ORIGINS must be explicitly configured in '{}' environment; refusing wildcard CORS",
                self.environment.as_str()
            );
        }

        let auth_mode = self.http.auth_mode.as_str();
        if auth_mode.eq_ignore_ascii_case("static") {
            anyhow::bail!(
                "KRAB_AUTH_MODE=static is not allowed in '{}' environment; use KRAB_AUTH_MODE=jwt (or oidc) with provider-based validation",
                self.environment.as_str()
            );
        } else if auth_mode.eq_ignore_ascii_case("jwt") || auth_mode.eq_ignore_ascii_case("oidc") {
            let has_provider_json = has_non_empty("KRAB_JWT_PROVIDERS_JSON");
            let has_provider_json_file = has_non_empty("KRAB_JWT_PROVIDERS_JSON_FILE");
            let has_provider_json_vault_ref = has_non_empty("KRAB_JWT_PROVIDERS_JSON_VAULT_REF");
            let token = std::env::var("KRAB_BEARER_TOKEN").unwrap_or_default();
            if !token.trim().is_empty() {
                anyhow::bail!(
                    "KRAB_BEARER_TOKEN must be unset/empty in '{}' environment when KRAB_AUTH_MODE={} \
                     (static bearer tokens are not allowed outside dev)",
                    self.environment.as_str(),
                    auth_mode
                );
            }

            let has_keys = has_non_empty("KRAB_JWT_KEYS_JSON");
            let has_secret = has_non_empty("KRAB_JWT_SECRET");
            let has_keys_file = has_non_empty("KRAB_JWT_KEYS_JSON_FILE");
            let has_secret_file = has_non_empty("KRAB_JWT_SECRET_FILE");
            let has_keys_vault_ref = has_non_empty("KRAB_JWT_KEYS_JSON_VAULT_REF");
            let has_secret_vault_ref = has_non_empty("KRAB_JWT_SECRET_VAULT_REF");
            let has_issuer = has_non_empty("KRAB_OIDC_ISSUER");
            let has_audience = has_non_empty("KRAB_OIDC_AUDIENCE");
            // A published key set is a key source that needs no secret at all.
            let jwks_url = std::env::var("KRAB_OIDC_JWKS_URL").unwrap_or_default();
            let has_jwks_url = !jwks_url.trim().is_empty();
            if has_jwks_url && !jwks_url.trim().starts_with("https://") {
                anyhow::bail!(
                    "KRAB_OIDC_JWKS_URL must use https:// in '{}' environment; keys fetched over \
                     plain HTTP can be substituted by anyone on the path",
                    self.environment.as_str()
                );
            }

            let has_secure_secret_source =
                has_keys_file || has_secret_file || has_keys_vault_ref || has_secret_vault_ref;

            if (has_keys || has_secret) && !has_secure_secret_source {
                anyhow::bail!(
                    "In '{}' environment, inline KRAB_JWT_SECRET/KRAB_JWT_KEYS_JSON is forbidden; use *_FILE or *_VAULT_REF secret sourcing",
                    self.environment.as_str()
                );
            }

            let has_provider_bundle =
                has_provider_json || has_provider_json_file || has_provider_json_vault_ref;
            let has_fallback_provider_tuple =
                (has_keys || has_secret || has_keys_file || has_secret_file || has_jwks_url)
                    && has_issuer
                    && has_audience;

            if !has_provider_bundle && !has_fallback_provider_tuple {
                anyhow::bail!(
                    "JWT/OIDC provider configuration required in '{}' environment; set KRAB_JWT_PROVIDERS_JSON \
                     or provide KRAB_OIDC_ISSUER + KRAB_OIDC_AUDIENCE + a key source: KRAB_OIDC_JWKS_URL, \
                     or secure secret sourcing via KRAB_JWT_SECRET_FILE/KRAB_JWT_KEYS_JSON_FILE (or *_VAULT_REF)",
                    self.environment.as_str()
                );
            }

            // Issuer/audience validation is only performed when the values are
            // configured, so outside dev they must BE configured or a token
            // from any issuer, minted for any audience, verifies. The fallback
            // tuple enforces KRAB_OIDC_ISSUER + KRAB_OIDC_AUDIENCE above; a
            // provider bundle must declare both per provider.
            if has_provider_bundle {
                self.require_issuer_and_audience_in_provider_bundle()?;
            }

            // An algorithm allowlist mixing the HMAC family with an
            // asymmetric family is the classic key-confusion footgun (a
            // public verification key doubles as an HMAC secret). The
            // request path also refuses to verify under such a list; reject
            // it at startup with an actionable error.
            if let Some(raw) = env_non_empty("KRAB_JWT_ALLOWED_ALGS") {
                if jwt_allowlist_mixes_hmac_and_asymmetric(&raw) {
                    anyhow::bail!(
                        "KRAB_JWT_ALLOWED_ALGS='{}' mixes HMAC (HS*) and asymmetric \
                         (RS*/PS*/ES*/EdDSA) algorithm families; split verification across \
                         providers with distinct key material instead of allowing both \
                         families against the same keys",
                        raw
                    );
                }
            }

            // A published key set holds only asymmetric keys (`oct` keys in
            // one are ignored: a public document cannot carry a secret). With
            // an HMAC-only allowlist — including the HS256 default — such a
            // configuration starts cleanly and then rejects every token.
            let allowlist = env_non_empty("KRAB_JWT_ALLOWED_ALGS");
            if jwt_allowlist_is_hmac_only(allowlist.as_deref())
                && (has_jwks_url || provider_bundle_uses_jwks())
            {
                anyhow::bail!(
                    "A JWKS URL is configured (KRAB_OIDC_JWKS_URL or a provider's jwks_url) but \
                     KRAB_JWT_ALLOWED_ALGS {} allows only HMAC algorithms, which never verify \
                     against a published key set; set KRAB_JWT_ALLOWED_ALGS to the provider's \
                     signing algorithms (for example RS256)",
                    match &allowlist {
                        Some(raw) => format!("('{raw}')"),
                        None => "(unset, default HS256)".to_string(),
                    }
                );
            }
        } else {
            anyhow::bail!(
                "Unsupported KRAB_AUTH_MODE='{}' in '{}' environment; use jwt or oidc",
                auth_mode,
                self.environment.as_str()
            );
        }

        Ok(())
    }

    /// Enforce that every provider in `KRAB_JWT_PROVIDERS_JSON` declares a
    /// non-empty `issuer` and `audience`. Called only outside dev.
    ///
    /// When the bundle is sourced through an unresolvable reference (a
    /// `*_VAULT_REF` with no runtime vault resolution) this fails too — the
    /// secrets-source policy already rejects that configuration in
    /// staging/prod, and a bundle whose contents cannot be inspected cannot
    /// be certified to validate issuer and audience.
    fn require_issuer_and_audience_in_provider_bundle(&self) -> anyhow::Result<()> {
        let raw = match read_env_or_file("KRAB_JWT_PROVIDERS_JSON") {
            Ok(Some(raw)) => raw,
            Ok(None) => return Ok(()),
            Err(err) => {
                return Err(err.context(format!(
                    "KRAB_JWT_PROVIDERS_JSON could not be resolved in '{}' environment",
                    self.environment.as_str()
                )))
            }
        };

        let parsed: serde_json::Value = serde_json::from_str(&raw)
            .map_err(|err| anyhow::anyhow!("KRAB_JWT_PROVIDERS_JSON is not valid JSON: {err}"))?;
        let providers = parsed
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("KRAB_JWT_PROVIDERS_JSON must be a JSON array"))?;

        for (index, provider) in providers.iter().enumerate() {
            let name = provider
                .get("name")
                .and_then(|v| v.as_str())
                .map(ToString::to_string)
                .unwrap_or_else(|| format!("#{index}"));
            let non_empty = |key: &str| {
                provider
                    .get(key)
                    .and_then(|v| v.as_str())
                    .map(str::trim)
                    .is_some_and(|v| !v.is_empty())
            };

            if !non_empty("issuer") || !non_empty("audience") {
                anyhow::bail!(
                    "JWT provider '{}' in KRAB_JWT_PROVIDERS_JSON must declare non-empty \
                     'issuer' and 'audience' in '{}' environment; issuer/audience validation \
                     only runs when they are configured, so leaving them unset would accept \
                     tokens from any issuer for any audience",
                    name,
                    self.environment.as_str()
                );
            }

            // The same rule as KRAB_OIDC_JWKS_URL: the bundle is the other
            // way to name a key set, and it must not be the unchecked one.
            if let Some(url) = provider
                .get("jwks_url")
                .and_then(|v| v.as_str())
                .map(str::trim)
                .filter(|v| !v.is_empty())
            {
                if !url.starts_with("https://") {
                    anyhow::bail!(
                        "JWT provider '{}' in KRAB_JWT_PROVIDERS_JSON has a jwks_url that does not \
                         use https:// in '{}' environment; keys fetched over plain HTTP can be \
                         substituted by anyone on the path",
                        name,
                        self.environment.as_str()
                    );
                }
            }
        }

        Ok(())
    }

    // -----------------------------------------------------------------------
    // Secrets-source policy validation
    // -----------------------------------------------------------------------

    /// Well-known secret env vars checked by the secrets-source policy.
    const SECRET_VARS: &'static [&'static str] = &[
        "DATABASE_URL",
        "KRAB_REDIS_URL",
        "KRAB_SMTP_PASSWORD",
        "KRAB_JWT_SECRET",
        "KRAB_JWT_KEYS_JSON",
        "KRAB_JWT_PROVIDERS_JSON",
        "KRAB_BEARER_TOKEN",
    ];

    /// Validate that every secret variable is sourced according to the
    /// environment's secrets policy. Returns a structured report with
    /// per-variable issues and explicit failure reasons.
    pub fn validate_secrets_sources(&self) -> SecretsValidationReport {
        let mut issues = Vec::new();

        for var in Self::SECRET_VARS {
            check_secret_source(var, &self.environment, &mut issues);
        }

        // Extra rule: KRAB_BEARER_TOKEN must not be populated in non-dev
        if !matches!(self.environment, Environment::Dev)
            && env_non_empty("KRAB_BEARER_TOKEN").is_some()
        {
            issues.push(SecretIssue {
                var_name: "KRAB_BEARER_TOKEN".to_string(),
                policy_rule: "STATIC_TOKEN_IN_NON_DEV".to_string(),
                severity: SecretIssueSeverity::Error,
                reason: format!(
                    "KRAB_BEARER_TOKEN must be unset in '{}' environment; \
                     static bearer tokens are only allowed in dev",
                    self.environment.as_str()
                ),
            });
        }

        SecretsValidationReport { issues }
    }

    /// Combined validation: runs both the existing auth/CORS checks **and**
    /// the secrets-source policy. Returns the first hard error encountered.
    pub fn validate_all(&self) -> anyhow::Result<SecretsValidationReport> {
        // Run auth & CORS checks (existing logic).
        self.validate()?;

        // Run secrets-source policy checks.
        let report = self.validate_secrets_sources();
        if report.has_errors() {
            let first_error = report
                .issues
                .iter()
                .find(|i| i.severity == SecretIssueSeverity::Error)
                .unwrap();
            anyhow::bail!(
                "Secrets policy violation: {} ({})",
                first_error.reason,
                first_error.policy_rule
            );
        }

        Ok(report)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::sync::{Mutex, OnceLock};

    static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    fn clear_auth_env() {
        for key in [
            "KRAB_ENVIRONMENT",
            "KRAB_AUTH_MODE",
            "KRAB_BEARER_TOKEN",
            "KRAB_JWT_SECRET",
            "KRAB_JWT_SECRET_FILE",
            "KRAB_JWT_SECRET_VAULT_REF",
            "KRAB_JWT_KEYS_JSON",
            "KRAB_JWT_KEYS_JSON_FILE",
            "KRAB_JWT_KEYS_JSON_VAULT_REF",
            "KRAB_JWT_PROVIDERS_JSON",
            "KRAB_JWT_PROVIDERS_JSON_FILE",
            "KRAB_JWT_PROVIDERS_JSON_VAULT_REF",
            "KRAB_OIDC_ISSUER",
            "KRAB_OIDC_AUDIENCE",
            "KRAB_JWT_ALLOWED_ALGS",
            "KRAB_CORS_ORIGINS",
            "KRAB_TRUST_PROXY_HEADERS",
            "KRAB_RATE_LIMIT_FAIL_OPEN",
            "KRAB_AUTH_FAILURE_WINDOW_SECS",
            "KRAB_AUTH_FAILURE_THRESHOLD",
        ] {
            std::env::remove_var(key);
        }
    }

    #[test]
    #[serial]
    fn validate_rejects_static_in_non_local_env() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "staging");
        std::env::set_var("KRAB_AUTH_MODE", "static");
        std::env::set_var("KRAB_BEARER_TOKEN", "token");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("KRAB_AUTH_MODE=static is not allowed"));
    }

    #[test]
    #[serial]
    fn validate_requires_provider_configuration_in_non_local_jwt_mode() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("JWT/OIDC provider configuration required"));
    }

    #[test]
    #[serial]
    fn validate_accepts_static_mode_in_dev() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "dev");
        std::env::set_var("KRAB_AUTH_MODE", "static");
        std::env::set_var("KRAB_BEARER_TOKEN", "token");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        assert!(cfg.validate().is_ok());
    }

    #[test]
    #[serial]
    fn validate_accepts_oidc_tuple_in_non_local_env() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "staging");
        std::env::set_var("KRAB_AUTH_MODE", "oidc");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        assert!(cfg.validate().is_ok());
    }

    #[test]
    #[serial]
    fn validate_rejects_inline_secret_in_non_local_env() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET", "secret-inline");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("inline KRAB_JWT_SECRET/KRAB_JWT_KEYS_JSON is forbidden"));
    }

    #[test]
    #[serial]
    fn validate_rejects_empty_cors_origins_in_staging() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "staging");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(err.contains("KRAB_CORS_ORIGINS must be explicitly configured"));
    }

    /// A JWKS URL with issuer and audience is a complete provider in prod,
    /// and it must be https.
    #[test]
    #[serial]
    fn validate_accepts_a_jwks_url_as_the_key_source_and_requires_https() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "RS256");
        std::env::set_var("KRAB_OIDC_JWKS_URL", "https://issuer.example.com/jwks");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("valid port");
        let accepted = cfg.validate();

        std::env::set_var("KRAB_OIDC_JWKS_URL", "http://issuer.example.com/jwks");
        let cfg = KrabConfig::from_env_checked("users", 3002).expect("valid port");
        let rejected = cfg.validate();

        std::env::remove_var("KRAB_OIDC_JWKS_URL");
        std::env::remove_var("KRAB_JWT_ALLOWED_ALGS");
        assert!(accepted.is_ok(), "{accepted:?}");
        assert!(rejected.unwrap_err().to_string().contains("https://"));
    }

    /// A JWKS-only configuration under an HMAC-only allowlist (including the
    /// HS256 default) can never verify a token: published keys are
    /// asymmetric. It used to pass validation and then reject everything.
    #[test]
    #[serial]
    fn validate_rejects_jwks_with_an_hmac_only_allowlist() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var("KRAB_OIDC_JWKS_URL", "https://issuer.example.com/jwks");
        let validate = || {
            KrabConfig::from_env_checked("users", 3002)
                .expect("valid port")
                .validate()
        };

        let default_allowlist = validate();
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "HS256,HS512");
        let explicit_hmac = validate();
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "RS256");
        let asymmetric = validate();

        std::env::remove_var("KRAB_OIDC_JWKS_URL");
        std::env::remove_var("KRAB_JWT_ALLOWED_ALGS");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[{"name":"idp","issuer":"https://i","audience":"a","jwks_url":"https://i/jwks"}]"#,
        );
        let bundle_default = validate();
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "RS256");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[{"name":"idp","issuer":"https://i","audience":"a","jwks_url":"http://i/jwks"}]"#,
        );
        let bundle_plain_http = validate();
        std::env::remove_var("KRAB_JWT_ALLOWED_ALGS");
        std::env::remove_var("KRAB_JWT_PROVIDERS_JSON");
        let err = bundle_plain_http.unwrap_err().to_string();
        assert!(err.contains("does not use https://"), "{err}");

        for result in [&default_allowlist, &explicit_hmac, &bundle_default] {
            let err = result.as_ref().unwrap_err().to_string();
            assert!(err.contains("allows only HMAC"), "{err}");
        }
        assert!(asymmetric.is_ok(), "{asymmetric:?}");
    }

    /// `local` is an alias of `dev`, case-insensitively: the CLI, the auth
    /// service and the promotion ladder all treat it as dev-like, and it used
    /// to parse as `Unknown` and get prod rules here.
    #[test]
    #[serial]
    fn local_is_an_alias_of_dev() {
        let _guard = env_lock();
        for value in ["local", "LOCAL", "Local"] {
            std::env::set_var("KRAB_ENVIRONMENT", value);
            assert_eq!(Environment::from_env(), Environment::Dev, "{value}");
        }
        std::env::set_var("KRAB_ENVIRONMENT", "locale");
        assert_eq!(
            Environment::from_env(),
            Environment::Unknown("locale".to_string())
        );

        // Dev rules: an inline secret is not a policy error under `local`.
        std::env::set_var("KRAB_ENVIRONMENT", "local");
        std::env::set_var("KRAB_TEST_LOCAL_ALIAS_SECRET", "inline-value");
        let mut issues = Vec::new();
        check_secret_source(
            "KRAB_TEST_LOCAL_ALIAS_SECRET",
            &Environment::from_env(),
            &mut issues,
        );
        std::env::remove_var("KRAB_TEST_LOCAL_ALIAS_SECRET");
        std::env::remove_var("KRAB_ENVIRONMENT");
        assert!(issues.is_empty(), "{issues:?}");
    }

    /// An unrecognised environment name gets the same CORS rule as prod; a
    /// typo must not be the way to ship wildcard CORS.
    #[test]
    #[serial]
    fn validate_rejects_empty_cors_origins_in_an_unknown_environment() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prdo");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(
            err.contains("KRAB_CORS_ORIGINS must be explicitly configured"),
            "{err}"
        );
    }

    #[test]
    #[serial]
    fn validate_accepts_non_empty_cors_origins_in_staging() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "staging");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");
        std::env::set_var(
            "KRAB_CORS_ORIGINS",
            "https://app.example.com,https://admin.example.com",
        );

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        assert!(cfg.validate().is_ok());
    }

    #[test]
    #[serial]
    fn from_env_rejects_invalid_port_value() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_PORT", "invalid-port");

        let err = KrabConfig::from_env_checked("users", 3002)
            .expect_err("invalid KRAB_PORT should return a typed config error");

        assert_eq!(
            err,
            ConfigError::InvalidPort {
                raw: "invalid-port".to_string()
            }
        );
        assert!(err.to_string().contains("invalid KRAB_PORT='invalid-port'"));
        std::env::remove_var("KRAB_PORT");
    }

    /// `from_env_checked` reads `KRAB_PORT` and falls back to the caller's
    /// defaults for the service name.
    #[test]
    #[serial]
    fn from_env_checked_reads_port_and_defaults_service_name() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_PORT", "4711");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");

        assert_eq!(cfg.port, 4711);
        assert_eq!(cfg.service_name, "users");
        std::env::remove_var("KRAB_PORT");
    }

    // -----------------------------------------------------------------------
    // Secrets source policy tests
    // -----------------------------------------------------------------------

    fn clear_secrets_env() {
        clear_auth_env();
        for key in [
            "DATABASE_URL",
            "DATABASE_URL_FILE",
            "DATABASE_URL_VAULT_REF",
            "KRAB_REDIS_URL",
            "KRAB_REDIS_URL_FILE",
            "KRAB_REDIS_URL_VAULT_REF",
            "KRAB_SMTP_PASSWORD",
            "KRAB_SMTP_PASSWORD_FILE",
            "KRAB_SMTP_PASSWORD_VAULT_REF",
        ] {
            std::env::remove_var(key);
        }
    }

    #[test]
    #[serial]
    fn secrets_policy_allows_inline_in_dev() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "dev");
        std::env::set_var("DATABASE_URL", "postgres://localhost/krab");
        std::env::set_var("KRAB_REDIS_URL", "redis://localhost");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let report = cfg.validate_secrets_sources();
        assert!(report.is_clean(), "dev should allow inline secrets");
    }

    #[test]
    #[serial]
    fn secrets_policy_warns_inline_in_staging() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "staging");
        std::env::set_var("DATABASE_URL", "postgres://staging/krab");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let report = cfg.validate_secrets_sources();
        assert!(!report.is_clean());
        assert!(
            !report.has_errors(),
            "staging inline should warn, not error"
        );
        let issue = &report.issues[0];
        assert_eq!(issue.var_name, "DATABASE_URL");
        assert_eq!(issue.policy_rule, "INLINE_SECRET_IN_STAGING");
        assert_eq!(issue.severity, SecretIssueSeverity::Warning);
    }

    #[test]
    #[serial]
    fn secrets_policy_rejects_inline_in_prod() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("DATABASE_URL", "postgres://prod/krab");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let report = cfg.validate_secrets_sources();
        assert!(report.has_errors());
        let issue = report
            .issues
            .iter()
            .find(|i| i.var_name == "DATABASE_URL")
            .expect("expected DATABASE_URL issue");
        assert_eq!(issue.policy_rule, "INLINE_SECRET_IN_PROD");
        assert_eq!(issue.severity, SecretIssueSeverity::Error);
    }

    #[test]
    #[serial]
    fn secrets_policy_accepts_file_sourced_in_prod() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("DATABASE_URL_FILE", "/run/secrets/db_url");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let report = cfg.validate_secrets_sources();
        let db_issues: Vec<_> = report
            .issues
            .iter()
            .filter(|i| i.var_name == "DATABASE_URL")
            .collect();
        assert!(
            db_issues.is_empty(),
            "file-sourced secret should pass in prod"
        );
    }

    #[test]
    #[serial]
    fn secrets_policy_report_contains_explicit_reasons() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("DATABASE_URL", "postgres://prod/krab");
        std::env::set_var("KRAB_REDIS_URL", "redis://prod");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let report = cfg.validate_secrets_sources();
        assert!(report.issues.len() >= 2);
        for issue in &report.issues {
            assert!(
                !issue.reason.is_empty(),
                "every issue must have a human-readable reason"
            );
            assert!(
                !issue.policy_rule.is_empty(),
                "every issue must have a machine-readable policy rule"
            );
        }
    }

    #[test]
    #[serial]
    fn read_env_or_file_prefers_inline_value_over_file() {
        let _guard = env_lock();
        std::env::set_var("KRAB_TEST_SECRET", "inline-secret");
        std::env::set_var("KRAB_TEST_SECRET_FILE", "ignored-file-path");

        let resolved = read_env_or_file("KRAB_TEST_SECRET").expect("inline secret should resolve");
        assert_eq!(resolved.as_deref(), Some("inline-secret"));

        std::env::remove_var("KRAB_TEST_SECRET");
        std::env::remove_var("KRAB_TEST_SECRET_FILE");
    }

    #[test]
    #[serial]
    fn read_env_or_file_reads_file_when_inline_missing() {
        let _guard = env_lock();
        std::env::remove_var("KRAB_TEST_SECRET");

        let path = std::env::current_dir().unwrap().join(format!(
            "krab_test_secret_{}_{}.txt",
            std::process::id(),
            1
        ));
        std::fs::write(&path, "file-secret\n").expect("failed to write temp secret file");
        std::env::set_var("KRAB_TEST_SECRET_FILE", path.to_string_lossy().to_string());

        let resolved = read_env_or_file("KRAB_TEST_SECRET").expect("file secret should resolve");
        assert_eq!(resolved.as_deref(), Some("file-secret"));

        std::env::remove_var("KRAB_TEST_SECRET_FILE");
        let _ = std::fs::remove_file(path);
    }

    #[test]
    #[serial]
    fn read_env_or_file_rejects_empty_file_contents() {
        let _guard = env_lock();
        std::env::remove_var("KRAB_TEST_SECRET");

        let path = std::env::current_dir().unwrap().join(format!(
            "krab_test_secret_empty_{}_{}.txt",
            std::process::id(),
            1
        ));
        std::fs::write(&path, "\n\n").expect("failed to write empty temp secret file");
        std::env::set_var("KRAB_TEST_SECRET_FILE", path.to_string_lossy().to_string());

        let err = read_env_or_file("KRAB_TEST_SECRET")
            .unwrap_err()
            .to_string();
        assert!(err.contains("KRAB_TEST_SECRET_FILE points to empty file"));

        std::env::remove_var("KRAB_TEST_SECRET_FILE");
        let _ = std::fs::remove_file(path);
    }

    #[test]
    #[serial]
    fn read_env_or_file_rejects_unresolved_vault_ref() {
        let _guard = env_lock();
        std::env::remove_var("KRAB_TEST_SECRET");
        std::env::remove_var("KRAB_TEST_SECRET_FILE");
        std::env::set_var("KRAB_TEST_SECRET_VAULT_REF", "vault://kv/krab/test-secret");

        let err = read_env_or_file("KRAB_TEST_SECRET")
            .unwrap_err()
            .to_string();
        assert!(err.contains("KRAB_TEST_SECRET_VAULT_REF is set"));
        assert!(err.contains("runtime vault resolution is not configured"));

        std::env::remove_var("KRAB_TEST_SECRET_VAULT_REF");
    }

    #[test]
    #[serial]
    fn validate_all_rejects_prod_inline_secret_even_with_oidc_tuple_present() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var("KRAB_JWT_SECRET", "inline-secret");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate_all().unwrap_err().to_string();
        assert!(err.contains("inline KRAB_JWT_SECRET/KRAB_JWT_KEYS_JSON is forbidden"));
    }

    #[test]
    #[serial]
    fn validate_all_rejects_prod_static_bearer_even_when_file_secret_present() {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");
        std::env::set_var("KRAB_BEARER_TOKEN", "still-not-allowed");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate_all().unwrap_err().to_string();
        assert!(err.contains("KRAB_BEARER_TOKEN must be unset/empty"));
    }

    #[test]
    #[serial]
    fn validate_all_rejects_prod_unresolved_provider_vault_ref_without_materialized_secret_source()
    {
        let _guard = env_lock();
        clear_secrets_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON_VAULT_REF",
            "vault://kv/krab/providers-json",
        );

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate_all().unwrap_err().to_string();
        assert!(
            err.contains("JWT/OIDC provider configuration required")
                || err.contains("Secrets policy violation")
                || err.contains("KRAB_JWT_PROVIDERS_JSON could not be resolved"),
            "unexpected error: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // Issuer/audience enforcement outside dev
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn validate_rejects_provider_bundle_missing_audience_in_prod() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[{"name":"main","issuer":"https://issuer.example.com","keys":{"default":"k"}}]"#,
        );

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(
            err.contains("must declare non-empty 'issuer' and 'audience'"),
            "unexpected error: {err}"
        );
    }

    #[test]
    #[serial]
    fn validate_rejects_provider_bundle_missing_issuer_in_staging() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "staging");
        std::env::set_var("KRAB_AUTH_MODE", "oidc");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[{"name":"main","audience":"krab-api","keys":{"default":"k"}}]"#,
        );

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(
            err.contains("must declare non-empty 'issuer' and 'audience'"),
            "unexpected error: {err}"
        );
    }

    #[test]
    #[serial]
    fn validate_accepts_provider_bundle_with_issuer_and_audience_in_prod() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[{"name":"main","issuer":"https://issuer.example.com","audience":"krab-api","keys":{"default":"k"}}]"#,
        );

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        assert!(cfg.validate().is_ok());
    }

    // -----------------------------------------------------------------------
    // Mixed HMAC/asymmetric algorithm allowlist
    // -----------------------------------------------------------------------

    #[test]
    fn jwt_allowlist_family_mix_detection() {
        use super::jwt_allowlist_mixes_hmac_and_asymmetric as mixed;

        assert!(mixed("HS256,RS256"));
        assert!(mixed("hs512, es256"));
        assert!(mixed("RS384,EdDSA,HS256"));
        assert!(!mixed("HS256,HS384"));
        assert!(!mixed("RS256,ES256,PS512,EdDSA"));
        assert!(!mixed(""));
        // Unknown names never decide the verdict.
        assert!(!mixed("HS256,garbage"));
        assert!(!mixed("garbage,RS256"));
    }

    #[test]
    #[serial]
    fn validate_rejects_mixed_algorithm_families_in_prod() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "HS256,RS256");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        let err = cfg.validate().unwrap_err().to_string();
        assert!(
            err.contains("mixes HMAC (HS*) and asymmetric"),
            "unexpected error: {err}"
        );
    }

    #[test]
    #[serial]
    fn validate_accepts_single_family_allowlist_in_prod() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "prod");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var("KRAB_CORS_ORIGINS", "https://app.example.com");
        std::env::set_var("KRAB_OIDC_ISSUER", "https://issuer.example.com");
        std::env::set_var("KRAB_OIDC_AUDIENCE", "krab-api");
        std::env::set_var("KRAB_JWT_SECRET_FILE", "/run/secrets/krab_jwt_secret");
        std::env::set_var("KRAB_JWT_ALLOWED_ALGS", "RS256,ES256");

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        assert!(cfg.validate().is_ok());
    }

    /// Dev keeps its current, permissive behaviour: a provider bundle without
    /// issuer/audience is accepted (validate() skips all checks in dev).
    #[test]
    #[serial]
    fn validate_accepts_provider_bundle_without_issuer_in_dev() {
        let _guard = env_lock();
        clear_auth_env();
        std::env::set_var("KRAB_ENVIRONMENT", "dev");
        std::env::set_var("KRAB_AUTH_MODE", "jwt");
        std::env::set_var(
            "KRAB_JWT_PROVIDERS_JSON",
            r#"[{"name":"main","keys":{"default":"k"}}]"#,
        );

        let cfg = KrabConfig::from_env_checked("users", 3002).expect("test env has a valid port");
        assert!(cfg.validate().is_ok());
    }

    #[test]
    #[serial]
    fn http_config_reads_auth_failure_knobs() {
        let _guard = env_lock();
        clear_auth_env();

        // Defaults when unset
        let cfg = HttpConfig::from_env();
        assert_eq!(cfg.auth_fail_window_secs, 60);
        assert_eq!(cfg.auth_fail_threshold, 100);

        // Custom valid values
        std::env::set_var("KRAB_AUTH_FAILURE_WINDOW_SECS", "30");
        std::env::set_var("KRAB_AUTH_FAILURE_THRESHOLD", "15");
        let cfg = HttpConfig::from_env();
        assert_eq!(cfg.auth_fail_window_secs, 30);
        assert_eq!(cfg.auth_fail_threshold, 15);

        // A 0 window has no meaningful epoch, so it falls back to the default.
        // An unparseable threshold also falls back.
        std::env::set_var("KRAB_AUTH_FAILURE_WINDOW_SECS", "0");
        std::env::set_var("KRAB_AUTH_FAILURE_THRESHOLD", "invalid");
        let cfg = HttpConfig::from_env();
        assert_eq!(cfg.auth_fail_window_secs, 60);
        assert_eq!(cfg.auth_fail_threshold, 100);

        // A 0 threshold is not an error — it is deliberate lockdown, kept as-is
        // so the first auth failure inside the window is answered 429.
        std::env::set_var("KRAB_AUTH_FAILURE_THRESHOLD", "0");
        let cfg = HttpConfig::from_env();
        assert_eq!(cfg.auth_fail_threshold, 0);

        clear_auth_env();
    }
}