tensor-wasm-api 0.3.8

HTTP serverless API gateway (axum).
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Craton Software Company

//! Tower middleware helpers: timeouts, concurrency limits, body limits,
//! authentication, tenant scoping, and tracing spans.
//!
//! Each helper returns a single `tower` layer (or middleware function) that
//! the server module composes into the axum router. Keeping the helpers thin
//! makes them easy to reuse in integration tests and benchmarks where a custom
//! stack is desired.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use axum::extract::Request;
use axum::http::{HeaderMap, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
use subtle::ConstantTimeEq;
use tensor_wasm_core::types::TenantId;
use tower::limit::ConcurrencyLimitLayer;
use tower_http::classify::{ServerErrorsAsFailures, SharedClassifier};
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;

use crate::token_scope::{parse_tokens_env, TokenScope};

/// Default per-request timeout used by [`crate::server::build_router`].
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Default process-wide cap on in-flight requests. Retained for callers that
/// want a single number; production deployments should prefer the per-route
/// caps below.
pub const DEFAULT_CONCURRENCY_LIMIT: usize = 64;

/// Per-route concurrency caps (api S-26). A single global semaphore lets a
/// probe storm starve `/invoke`; per-route caps isolate the budgets.
///
/// Probe routes (`/healthz`, `/metrics`) get a generous budget because they
/// are cheap and a k8s deployment may have many replicas all scraping at
/// once. Invoke is the heaviest path โ€” keep it tight. Reads and writes get
/// asymmetric caps because writes tend to compile Wasm and allocate engine
/// resources.
pub const PROBE_CONCURRENCY_LIMIT: usize = 256;
/// Concurrent `/invoke` ceiling. Tighter than the default because invokes
/// hold a Wasmtime instance lock across `call_async`.
pub const INVOKE_CONCURRENCY_LIMIT: usize = 32;
/// Concurrent read-route ceiling (GETs that are not probes).
pub const READ_CONCURRENCY_LIMIT: usize = 64;
/// Concurrent write-route ceiling (POST/PUT/DELETE excluding invoke).
pub const WRITE_CONCURRENCY_LIMIT: usize = 16;

/// Maximum allowed inbound request body size, in bytes. 64 MiB.
///
/// Documented in `API.md` under "Request limits". Requests larger than this
/// are rejected with `413 Payload Too Large` by axum's
/// [`DefaultBodyLimit`](axum::extract::DefaultBodyLimit) at extract time
/// (i.e., when a handler reads the body via `Bytes`, `Json`, etc.). We use
/// axum's native `DefaultBodyLimit::max` rather than
/// `tower_http::limit::RequestBodyLimitLayer`: the tower-http layer rewraps
/// the request body in `Limited<Body>`, which breaks composition with
/// `axum::middleware::from_fn` (bearer auth, tenant scope) downstream, and
/// `DefaultBodyLimit::max` gives the same 413 contract without the rewrap.
pub const MAX_REQUEST_BODY_BYTES: usize = 64 * 1024 * 1024;

/// Environment variable carrying a comma-separated allowlist of bearer
/// tokens accepted by [`bearer_auth`]. Empty / unset = dev mode pass-through
/// (but only when [`ENV_ALLOW_DEV_MODE`] explicitly opts in โ€” see below).
pub const ENV_API_TOKENS: &str = "TENSOR_WASM_API_TOKENS";

/// Environment variable that explicitly opts the gateway into dev mode
/// (auth disabled, every request passes through with `AuthContext::dev`).
///
/// Accepted truthy values are `"1"` and `"true"` (case-insensitive, trimmed).
/// Any other value โ€” including unset โ€” leaves dev mode *disabled*.
///
/// Closes the M4 finding: an empty / unset [`ENV_API_TOKENS`] used to make
/// [`bearer_auth`] fail *open* (wildcard pass-through), so a deployment that
/// merely forgot to populate the allowlist silently accepted every request.
/// We now fail *closed*: when no tokens are configured AND this opt-in is not
/// set, [`bearer_auth`] rejects every request with `401 Unauthorized`. The
/// startup `warn!` in [`AuthConfig::from_env`] is preserved so an operator who
/// genuinely wants dev mode still sees the loud signal โ€” they just have to
/// acknowledge it by setting this variable.
///
/// Only [`AuthConfig::from_env`] consults this variable. Configs built
/// programmatically via [`AuthConfig::from_tokens`] / [`AuthConfig::from_scopes`]
/// / [`AuthConfig::default`] are treated as an explicit in-process opt-in
/// (they cannot be poisoned by hostile ambient environment), so they preserve
/// the historical pass-through behaviour for tests and embedders.
pub const ENV_ALLOW_DEV_MODE: &str = "TENSOR_WASM_API_ALLOW_DEV_MODE";

/// Environment variable carrying a comma-separated allowlist of bearer
/// tokens that are additionally permitted to call `POST /kernels` (the
/// kernel-publish scope โ€” see [`KernelPublishTokens`]).
///
/// Empty / unset = no token is permitted to publish. In that case
/// `POST /kernels` returns `403 kernel_publish_scope_required`. The
/// `/kernels` GET routes are unaffected โ€” every authenticated tenant may
/// list and resolve.
///
/// Each entry must be a raw bearer token string that also appears in
/// [`ENV_API_TOKENS`] (otherwise [`bearer_auth`] would 401 the request
/// before scope evaluation runs). Allowlisting a token here that is not
/// in `TENSOR_WASM_API_TOKENS` is harmless โ€” the request never reaches
/// the scope gate โ€” but logically nonsensical.
///
/// Closes the T1 security finding: previously `POST /kernels` accepted
/// any allowlisted bearer (or any caller in dev mode), letting a
/// tenant-1 token publish kernels that every other tenant could then
/// resolve. The publish gate is now distinct from the API allowlist so
/// operators can hand out tenant tokens widely while restricting
/// publish authority to a small set of trusted clients.
pub const ENV_KERNEL_PUBLISH_TOKENS: &str = "TENSOR_WASM_API_KERNEL_PUBLISH_TOKENS";

/// Maximum byte length permitted for an inbound `Authorization` header
/// value before [`bearer_auth`] will even attempt to parse it.
///
/// Hyper's default cap on the combined header block sits around 16 KiB,
/// so an attacker can still send a single `Authorization: Bearer <huge>`
/// value of several KiB. The downstream constant-time comparison in
/// [`AuthConfig::scope_for`] is `O(token_len)` per allowlisted token,
/// so unbounded oversized values let a hostile client burn CPU at
/// roughly `O(num_tokens * token_len)` per request. Capping the value
/// length here (1 KiB) keeps that cost flat โ€” any legitimate bearer
/// token in production is well under this limit (JWTs are typically
/// 500โ€“800 bytes, opaque tokens are far smaller).
///
/// A value longer than this returns `401 Unauthorized` with
/// `kind: "invalid_auth"`. We deliberately reject as `401` rather than
/// `400` so the response shape stays uniform with other auth failures
/// (missing header, mismatched token) and an attacker cannot use the
/// status code to probe the size cap.
pub const MAX_AUTH_HEADER_BYTES: usize = 1024;

/// Environment variable that, when set to `1`, makes the `X-TensorWasm-Tenant`
/// header mandatory. Otherwise its absence defaults to tenant `0`.
pub const ENV_REQUIRE_TENANT: &str = "TENSOR_WASM_API_REQUIRE_TENANT";

/// Name of the header used to scope a request to a tenant.
pub const HEADER_TENANT: &str = "X-TensorWasm-Tenant";

/// Environment variable that, when set, restricts the set of `Host` header
/// values the server will accept. Comma-separated list of authority strings
/// (e.g. `api.example.com,api2.example.com:8443`). Unset = accept any
/// `Host`, which is the previous behaviour but is unsafe behind a layered
/// proxy that may pass arbitrary `Host` values through.
///
/// Closes api S-30 (lack of Host validation). The check rejects requests
/// whose `Host` is not in the allowlist with `400 Bad Request`.
pub const ENV_TRUSTED_HOSTS: &str = "TENSOR_WASM_API_TRUSTED_HOSTS";

/// Parsed `Host` allowlist used by [`host_validate`].
///
/// Closes api S-30 (lack of Host validation). The previous implementation
/// cached the parsed env value in a process-wide `OnceLock`, which made
/// tests that wanted to vary the allowlist unable to do so (the first test
/// to touch the cell froze it for every later test in the same process).
///
/// Now the allowlist travels through `axum::Extension<TrustedHosts>`:
/// [`crate::server::build_router_with_audit`] inserts a `from_env()` value
/// at build time; tests can override by inserting a different value into
/// the router extensions. Tests that bypass the server builder still get
/// the env-var fallback (cached per-process in a private `OnceLock` so the
/// per-request cost stays zero), but an explicit extension always wins.
///
/// Precedence: **explicit `axum::Extension<TrustedHosts>` > env-var
/// fallback (`TENSOR_WASM_API_TRUSTED_HOSTS`)**.
#[derive(Debug, Clone, Default)]
pub struct TrustedHosts(Arc<Vec<String>>);

impl TrustedHosts {
    /// Parse the allowlist from [`ENV_TRUSTED_HOSTS`]. Splits on `,`,
    /// trims surrounding whitespace, drops empty entries, and lowercases
    /// each remaining entry for case-insensitive matching. Unset / empty
    /// env var yields an empty list (= [`Self::allow_all`]).
    pub fn from_env() -> Self {
        let raw = std::env::var(ENV_TRUSTED_HOSTS).unwrap_or_default();
        Self::from_raw(&raw)
    }

    /// Helper: parse a comma-separated string as if it were the env
    /// variable. Public for the explicit-construction path used by tests.
    pub fn from_raw(raw: &str) -> Self {
        let parsed: Vec<String> = raw
            .split(',')
            .map(|s| s.trim().to_ascii_lowercase())
            .filter(|s| !s.is_empty())
            .collect();
        Self(Arc::new(parsed))
    }

    /// Explicit "no allowlist" constructor โ€” every Host value is admitted
    /// (the legacy default when the env var is unset).
    pub fn allow_all() -> Self {
        Self(Arc::new(Vec::new()))
    }

    /// Construct from an iterator of allowlist entries. Entries are
    /// lowercased on insertion so case-insensitive matching in
    /// [`Self::contains`] is just a byte comparison.
    pub fn from_hosts<I, S>(iter: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let parsed: Vec<String> = iter
            .into_iter()
            .map(|s| s.into().trim().to_ascii_lowercase())
            .filter(|s| !s.is_empty())
            .collect();
        Self(Arc::new(parsed))
    }

    /// `true` when no entries are configured โ€” every host is admitted.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// `true` when the supplied host (raw value from `Host:` or
    /// `:authority`) matches one of the allowlist entries.
    ///
    /// Matching rules:
    ///
    /// * **Case-insensitive exact match** on the supplied host.
    /// * If the supplied host carries a default-port suffix (`:80` or
    ///   `:443`) and no allowlist entry contains a `:`, the port is
    ///   stripped before comparison. This lets operators list bare
    ///   hostnames (`api.example.com`) and still admit clients that
    ///   include the default port in the `Host` header. If any
    ///   allowlist entry contains a port, we do an exact match on the
    ///   full `host:port` string โ€” the operator chose to be specific.
    pub fn contains(&self, host: &str) -> bool {
        if self.0.is_empty() {
            return true;
        }
        let host_lc = host.trim().to_ascii_lowercase();
        if self.0.contains(&host_lc) {
            return true;
        }
        // Default-port strip: only apply when no allowlist entry carries
        // a port (otherwise the operator's port-bound entry must match
        // exactly).
        let allow_has_port = self.0.iter().any(|a| a.contains(':'));
        if allow_has_port {
            return false;
        }
        if let Some(stripped) = strip_default_port(&host_lc) {
            return self.0.iter().any(|allowed| allowed == stripped);
        }
        false
    }
}

/// Strip a trailing `:80` or `:443` from a (already-lowercased) host
/// string. Returns `None` if no default-port suffix is present.
fn strip_default_port(host_lc: &str) -> Option<&str> {
    for suffix in [":443", ":80"] {
        if let Some(stripped) = host_lc.strip_suffix(suffix) {
            return Some(stripped);
        }
    }
    None
}

/// Per-process cached env-var fallback for [`host_validate`] when no
/// `axum::Extension<TrustedHosts>` is present. Tests that drive the
/// middleware through the server builder always get an explicit
/// extension and never touch this; tests that bypass the builder
/// (e.g. wrap `host_validate` with `axum::middleware::from_fn` directly)
/// see the env value parsed once.
fn env_trusted_hosts_fallback() -> TrustedHosts {
    static ONCE: std::sync::OnceLock<TrustedHosts> = std::sync::OnceLock::new();
    ONCE.get_or_init(TrustedHosts::from_env).clone()
}

/// Allowlist of bearer tokens permitted to call `POST /kernels`.
///
/// Internally stores the [`crate::rate_limit::TokenId`] of each
/// allowlisted bearer (the `xxhash64` digest used elsewhere for rate
/// limiting), NOT the raw token string. Keeping `TokenId`s here means
/// the value can flow through `axum::Extension` and tracing without
/// risking the raw secret leaking into a span attribute or audit
/// record, and `allows()` reduces to a hash-set lookup.
///
/// The list is empty by default โ€” that is the safe posture: with no
/// publish-scoped tokens configured, `POST /kernels` returns
/// `403 kernel_publish_scope_required`. Dev mode (empty
/// `TENSOR_WASM_API_TOKENS`) is even stricter: the publish handler
/// rejects outright with `kernel_publish_disabled_in_dev_mode` to deny
/// the unauthenticated-attacker path the security review flagged.
///
/// Sourced from [`ENV_KERNEL_PUBLISH_TOKENS`] at server startup; tests
/// drive it directly via [`KernelPublishTokens::from_tokens`] so they
/// do not poison the process environment.
#[derive(Debug, Clone, Default)]
pub struct KernelPublishTokens {
    /// Stable token identifiers permitted to publish kernels. Stored as
    /// `Arc<HashSet<...>>` so cheap clones into request extensions and
    /// per-request reads stay allocation-free.
    token_ids: Arc<std::collections::HashSet<crate::rate_limit::TokenId>>,
}

impl KernelPublishTokens {
    /// Parse the allowlist from [`ENV_KERNEL_PUBLISH_TOKENS`]. Splits on
    /// `,`, trims surrounding whitespace, drops empty entries, hashes
    /// each remaining entry into a [`crate::rate_limit::TokenId`]. Unset
    /// / empty env var yields the empty allowlist โ€” every `POST
    /// /kernels` is rejected with `kernel_publish_scope_required`.
    pub fn from_env() -> Self {
        let raw = std::env::var(ENV_KERNEL_PUBLISH_TOKENS).unwrap_or_default();
        Self::from_raw(&raw)
    }

    /// Parse a comma-separated string as if it were the env variable.
    /// Public for the explicit-construction path used by tests.
    pub fn from_raw(raw: &str) -> Self {
        let token_ids = raw
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(crate::rate_limit::TokenId::from_bearer)
            .collect();
        Self {
            token_ids: Arc::new(token_ids),
        }
    }

    /// Construct from an iterator of raw bearer-token strings. Used by
    /// integration tests that drive the publish-scope path directly.
    pub fn from_tokens<I, S>(iter: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let token_ids = iter
            .into_iter()
            .map(|s| crate::rate_limit::TokenId::from_bearer(s.as_ref()))
            .collect();
        Self {
            token_ids: Arc::new(token_ids),
        }
    }

    /// `true` when no entries are configured. With an empty allowlist
    /// the kernel-publish gate denies every `POST /kernels` โ€” the safe
    /// default.
    pub fn is_empty(&self) -> bool {
        self.token_ids.is_empty()
    }

    /// `true` when `token_id` is permitted to publish kernels.
    pub fn allows(&self, token_id: crate::rate_limit::TokenId) -> bool {
        self.token_ids.contains(&token_id)
    }
}

/// Middleware: reject requests whose `Host` header (or HTTP/2
/// `:authority` pseudo-header) is not in the configured allowlist.
///
/// Source of truth for the allowlist:
///
/// 1. `axum::Extension<TrustedHosts>` if present on the request โ€” the
///    server builder inserts this from
///    [`TrustedHosts::from_env`] at startup, and tests can override.
/// 2. Otherwise, a per-process env-var fallback parsed once from
///    `TENSOR_WASM_API_TRUSTED_HOSTS`.
///
/// Empty allowlist (no entries / env unset) = pass-through.
///
/// Host extraction order:
///
/// 1. `Host:` request header.
/// 2. If absent, `req.uri().authority()` โ€” the URI carries the HTTP/2
///    `:authority` pseudo-header in `hyper`'s normalised request form.
/// 3. If both absent and the allowlist is non-empty, respond `400`.
///
/// Closes api S-30. T19 perf re-order: layered OUTSIDE the trace layer
/// (and the CORS layer) so hostile Host probes are rejected before any
/// trace span is allocated or any `traceparent` propagator hop runs.
/// Still layered BEFORE bearer_auth so an attacker probing for valid
/// hosts cannot also probe for valid tokens. The probe router inherits
/// this gate too; operators with split-Host probes can simply omit the
/// env var. Rejected requests do NOT get a trace span and are NOT
/// counted by the HTTP metrics layer (which sits inside the trace
/// layer) โ€” an intentional tradeoff so a hostile Host probe storm
/// cannot burn either trace budget or metric cardinality. See the
/// comment block in `build_router_full`.
pub async fn host_validate(req: Request, next: Next) -> Response {
    let allow = req
        .extensions()
        .get::<TrustedHosts>()
        .cloned()
        .unwrap_or_else(env_trusted_hosts_fallback);
    if allow.is_empty() {
        return next.run(req).await;
    }
    // 1) Try the `Host:` header first (HTTP/1.1 canonical path).
    let host_header = req
        .headers()
        .get(axum::http::header::HOST)
        .and_then(|h| h.to_str().ok())
        .map(|s| s.to_owned());
    // 2) Fall back to the URI authority (HTTP/2 `:authority` pseudo-header
    //    surfaces here in hyper's normalised request form).
    let authority = req.uri().authority().map(|a| a.as_str().to_owned());
    let host = host_header.or(authority);

    match host {
        Some(h) if allow.contains(&h) => next.run(req).await,
        _ => envelope(
            StatusCode::BAD_REQUEST,
            "bad_request",
            "Host header missing or not in TENSOR_WASM_API_TRUSTED_HOSTS allowlist",
        ),
    }
}

/// Build a per-request timeout layer.
///
/// Requests that exceed `d` are aborted with `408 Request Timeout`.
pub fn timeout_layer(d: Duration) -> TimeoutLayer {
    TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, d)
}

/// Build the default HTTP tracing layer.
///
/// Emits a `tracing` span per request capturing method, URI, and response
/// status. The classifier treats `5xx` responses as failures.
pub fn trace_layer() -> TraceLayer<SharedClassifier<ServerErrorsAsFailures>> {
    TraceLayer::new_for_http()
}

/// Build a process-wide concurrency limit layer that allows at most `max`
/// in-flight requests.
pub fn concurrency_limit_layer(max: usize) -> ConcurrencyLimitLayer {
    ConcurrencyLimitLayer::new(max)
}

/// Build the global request-body size cap (64 MiB by default).
///
/// Returns `413 Payload Too Large` for any body that exceeds `max_bytes`
/// when a handler tries to extract the body. See [`MAX_REQUEST_BODY_BYTES`]
/// for the rationale on using axum's native limit rather than tower-http's.
pub fn body_limit_layer(max_bytes: usize) -> axum::extract::DefaultBodyLimit {
    axum::extract::DefaultBodyLimit::max(max_bytes)
}

/// Environment variable carrying a comma-separated allowlist of origins
/// permitted for cross-origin requests. Empty / unset = reject all
/// cross-origin requests.
pub const ENV_CORS_ALLOWED_ORIGINS: &str = "TENSOR_WASM_API_CORS_ALLOWED_ORIGINS";

/// HTTP headers permitted on cross-origin requests. Covers the standard
/// `Authorization` and `Content-Type`, the TensorWasm tenant header used to
/// scope per-tenant calls, and the W3C `traceparent` header so browser
/// callers can stitch their own trace context into the gateway's spans.
const CORS_ALLOWED_HEADERS: &[&str] = &[
    "authorization",
    "content-type",
    "x-tensorwasm-tenant",
    "traceparent",
];

/// Cross-origin policy snapshot loaded from the process environment.
///
/// `allowed_origins` is the explicit allowlist of cross-origin browser
/// callers that may reach the API. The default is empty โ€” i.e.
/// **cross-origin requests are rejected** until the operator widens the
/// allowlist. This matches the gateway's other security defaults
/// (`TENSOR_WASM_API_TOKENS` dev mode is the only opt-out).
///
/// To widen, list one origin per entry exactly as the browser sends the
/// `Origin` header (scheme + host + optional port), comma-separated:
///
/// ```text
/// TENSOR_WASM_API_CORS_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
/// ```
#[derive(Debug, Clone, Default)]
pub struct CorsConfig {
    /// Origins permitted for cross-origin requests. Empty = reject all.
    pub allowed_origins: Vec<String>,
}

impl CorsConfig {
    /// Load the allowlist from `$TENSOR_WASM_API_CORS_ALLOWED_ORIGINS`.
    /// Unset or empty = reject all cross-origin requests.
    pub fn from_env() -> Self {
        let raw = std::env::var(ENV_CORS_ALLOWED_ORIGINS).unwrap_or_default();
        let allowed_origins: Vec<String> = raw
            .split(',')
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty())
            .collect();
        Self { allowed_origins }
    }

    /// Construct directly from an explicit list of origins. The empty list
    /// yields the safe default (no cross-origin requests admitted).
    pub fn from_origins<I, S>(iter: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            allowed_origins: iter.into_iter().map(Into::into).collect(),
        }
    }
}

/// Build the CORS layer for the gateway router.
///
/// * Empty allowlist (`cfg.allowed_origins.is_empty()`) โ†’ returns
///   `CorsLayer::new()`, which sets no `Access-Control-Allow-Origin` header
///   and therefore rejects every cross-origin request. This is the safe
///   default for fresh installs โ€” operators opt in by setting
///   `TENSOR_WASM_API_CORS_ALLOWED_ORIGINS`.
/// * Non-empty allowlist โ†’ returns a layer that admits exactly those
///   origins (parsed back into `HeaderValue`s; unparseable entries are
///   silently dropped โ€” they were already rejected at startup by the
///   bearer-auth allowlist parser's stricter sibling and would never match
///   a real browser `Origin` header anyway).
///
/// The allowed methods (`GET`, `POST`, `DELETE`) and headers
/// (`Authorization`, `Content-Type`, `X-TensorWasm-Tenant`, `Traceparent`)
/// match the API's wire surface โ€” see `API.md`.
pub fn cors_layer(cfg: &CorsConfig) -> CorsLayer {
    use axum::http::Method;
    // Cover every method the gateway routes use: `GET` (healthz, metrics,
    // job poll), `POST` (deploy, invoke, invoke-async), and `DELETE`
    // (function tear-down).
    let allowed_methods = [Method::GET, Method::POST, Method::DELETE];
    let base = CorsLayer::new()
        .allow_methods(allowed_methods)
        .allow_headers(
            CORS_ALLOWED_HEADERS
                .iter()
                .filter_map(|h| h.parse::<axum::http::HeaderName>().ok())
                .collect::<Vec<_>>(),
        );

    if cfg.allowed_origins.is_empty() {
        // No origins configured โ€” `CorsLayer::new()` admits no origins, so
        // no cross-origin browser caller will see an
        // `Access-Control-Allow-Origin` header and the request is rejected
        // by the browser's preflight check.
        base
    } else {
        let parsed: Vec<axum::http::HeaderValue> = cfg
            .allowed_origins
            .iter()
            .filter_map(|origin| origin.parse::<axum::http::HeaderValue>().ok())
            .collect();
        base.allow_origin(AllowOrigin::list(parsed))
    }
}

/// Snapshot of authentication configuration loaded from the process
/// environment at server start. Cloned cheaply into each request.
///
/// `scopes` is empty in dev mode (no `TENSOR_WASM_API_TOKENS` set or env
/// empty), in which case [`bearer_auth`] passes every request through
/// unchecked. Otherwise each allowlisted bearer token maps to the
/// [`TokenScope`] that came out of [`parse_tokens_env`] at startup.
#[derive(Debug, Clone)]
pub struct AuthConfig {
    /// Allowlisted bearer tokens โ†’ tenant scope. Empty = dev mode
    /// (pass-through with startup warning).
    pub scopes: Arc<HashMap<String, TokenScope>>,
    /// Count of entries that used the legacy bare-token shape. The server
    /// emits a single deprecation warning at startup if this is nonzero.
    pub deprecated_count: usize,
    /// Whether dev-mode pass-through is permitted when `scopes` is empty.
    ///
    /// Only meaningful in dev mode (`scopes.is_empty()`). When `false`,
    /// [`bearer_auth`] fails *closed* and rejects every request with
    /// `401 Unauthorized` rather than passing it through with
    /// `AuthContext::dev`. Set from [`ENV_ALLOW_DEV_MODE`] by
    /// [`AuthConfig::from_env`]; defaults to `true` for programmatic
    /// constructors (see [`ENV_ALLOW_DEV_MODE`] for the rationale).
    pub dev_mode_allowed: bool,
}

impl Default for AuthConfig {
    /// An empty allowlist with dev mode *allowed*. Programmatic construction
    /// is an explicit in-process opt-in, so it preserves the historical
    /// pass-through behaviour (the [`ENV_ALLOW_DEV_MODE`] gate applies only to
    /// the env-driven [`AuthConfig::from_env`] path).
    fn default() -> Self {
        Self {
            scopes: Arc::new(HashMap::new()),
            deprecated_count: 0,
            dev_mode_allowed: true,
        }
    }
}

impl AuthConfig {
    /// Load the allowlist from `$TENSOR_WASM_API_TOKENS`. Unset or empty
    /// means "no auth" (dev mode). Logs a one-shot warning in dev mode and
    /// a one-shot deprecation warning whenever any legacy bare entries were
    /// observed.
    pub fn from_env() -> Self {
        let raw = std::env::var(ENV_API_TOKENS).unwrap_or_default();
        let parsed = parse_tokens_env(&raw);
        // M4: empty allowlist is only honoured as dev-mode pass-through when
        // the operator explicitly opts in via ENV_ALLOW_DEV_MODE. Otherwise we
        // fail closed (bearer_auth 401s every request). Accept `1` / `true`
        // (case-insensitive, trimmed) as the truthy set; anything else (incl.
        // unset) leaves dev mode disabled.
        let dev_mode_allowed = std::env::var(ENV_ALLOW_DEV_MODE).is_ok_and(|v| {
            let v = v.trim();
            v == "1" || v.eq_ignore_ascii_case("true")
        });
        if parsed.token_scopes.is_empty() {
            tracing::warn!(
                target: "tensor_wasm_api::middleware",
                env = ENV_API_TOKENS,
                "TENSOR_WASM_API_TOKENS empty; API accepts all requests (dev mode)",
            );
            if !dev_mode_allowed {
                tracing::warn!(
                    target: "tensor_wasm_api::middleware",
                    env = ENV_ALLOW_DEV_MODE,
                    "{} not set; refusing dev-mode pass-through โ€” every request \
                     will be rejected with 401. Configure {} to enable bearer \
                     auth, or set {}=1 to explicitly acknowledge an open gateway",
                    ENV_ALLOW_DEV_MODE,
                    ENV_API_TOKENS,
                    ENV_ALLOW_DEV_MODE,
                );
            }
        }
        if parsed.deprecated_count > 0 {
            tracing::warn!(
                target: "tensor_wasm_api::middleware",
                env = ENV_API_TOKENS,
                count = parsed.deprecated_count,
                "bare bearer tokens in {} are deprecated; switch to \
                 `token:tenant=...` (or `token:tenant=*` for the current \
                 wildcard behaviour) โ€” bare entries are scheduled for \
                 removal in v1.0",
                ENV_API_TOKENS,
            );
        }
        Self {
            scopes: Arc::new(parsed.token_scopes),
            deprecated_count: parsed.deprecated_count,
            dev_mode_allowed,
        }
    }

    /// Construct directly from an explicit allowlist. Each token gets the
    /// wildcard scope โ€” preserves backwards-compatible behaviour for tests
    /// that pre-date scoped tokens. For tests that need a non-wildcard
    /// scope, build the map directly or use [`AuthConfig::from_scopes`].
    pub fn from_tokens<I, S>(iter: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let mut scopes: HashMap<String, TokenScope> = HashMap::new();
        for s in iter {
            scopes.insert(s.into(), TokenScope::all());
        }
        Self {
            scopes: Arc::new(scopes),
            deprecated_count: 0,
            dev_mode_allowed: true,
        }
    }

    /// Construct from an explicit token โ†’ scope map. Used by integration
    /// tests that drive scoped-token paths directly.
    pub fn from_scopes<I, S>(iter: I) -> Self
    where
        I: IntoIterator<Item = (S, TokenScope)>,
        S: Into<String>,
    {
        let mut scopes: HashMap<String, TokenScope> = HashMap::new();
        for (k, v) in iter {
            scopes.insert(k.into(), v);
        }
        Self {
            scopes: Arc::new(scopes),
            deprecated_count: 0,
            dev_mode_allowed: true,
        }
    }

    /// `true` if the supplied bearer token is allowlisted.
    ///
    /// Uses a constant-time byte comparison against every allowlisted entry
    /// so the time taken to reject a bad token does not leak which prefix
    /// (if any) matched an allowlist entry. Delegates to `scope_for`.
    pub fn accepts(&self, token: &str) -> bool {
        self.scope_for(token).is_some()
    }

    /// Resolve `token` to its [`TokenScope`] if allowlisted.
    ///
    /// Iterates the full allowlist and uses [`subtle::ConstantTimeEq`] for
    /// each entry rather than a `HashMap::get`. The hash-table lookup
    /// short-circuits on hash mismatch and then bytes-eq matching entries,
    /// which is timing-leakable for token discovery โ€” an attacker can
    /// measure how long the gateway took to reject a candidate token and
    /// infer how close it got to a real entry. The loop runs over every
    /// allowlist entry on every call, and we deliberately do NOT `break`
    /// after a hit so the wall-clock cost is constant w.r.t. the matched
    /// entry's position. Hashing still happens internally (`scopes` is an
    /// `Arc<HashMap>` for cheap clones) but the lookup path is no longer
    /// hash-keyed; the map is used purely as a `(token, scope)` store here.
    pub fn scope_for(&self, token: &str) -> Option<&TokenScope> {
        let mut found_scope: Option<&TokenScope> = None;
        let token_bytes = token.as_bytes();
        for (allow_token, scope) in self.scopes.iter() {
            // ct_eq requires equal-length inputs; mismatched lengths cannot
            // be equal so we skip them. The length itself is not secret โ€”
            // the operator's `TENSOR_WASM_API_TOKENS` allowlist is fixed at
            // startup and its lengths are observable through other means.
            if allow_token.len() == token_bytes.len()
                && allow_token.as_bytes().ct_eq(token_bytes).into()
            {
                found_scope = Some(scope);
                // Intentionally NOT `break` โ€” keep iterating so the loop
                // time is constant w.r.t. the matched entry's position.
            }
        }
        found_scope
    }

    /// `true` if no allowlist was configured (dev mode).
    pub fn is_dev_mode(&self) -> bool {
        self.scopes.is_empty()
    }
}

/// Snapshot of tenant-header policy loaded from the process environment.
#[derive(Debug, Clone, Copy, Default)]
pub struct TenantConfig {
    /// `true` when `TENSOR_WASM_API_REQUIRE_TENANT=1` was set at startup.
    pub require_header: bool,
}

impl TenantConfig {
    /// Load policy from `$TENSOR_WASM_API_REQUIRE_TENANT` (`"1"` = required).
    pub fn from_env() -> Self {
        let require_header = std::env::var(ENV_REQUIRE_TENANT).is_ok_and(|v| v.trim() == "1");
        Self { require_header }
    }
}

/// Render the standard `{ "error": { "kind": ..., "message": ... } }`
/// envelope at `status`. Shared helper for middleware that cannot import
/// `crate::routes::ApiError` without a cycle.
fn envelope(status: StatusCode, kind: &str, message: &str) -> Response {
    let body = Json(json!({
        "error": { "kind": kind, "message": message }
    }));
    (status, body).into_response()
}

/// Parse the credentials portion of an `Authorization` header value when the
/// scheme matches `Bearer` case-insensitively (RFC 6750 ยง2.1 / RFC 7235 ยง2.1).
///
/// The header value is split on the first run of whitespace separating the
/// scheme token from the credentials. The scheme is compared via
/// `eq_ignore_ascii_case("bearer")` so `Bearer`, `bearer`, and `BEARER`
/// (the latter two emerge from upstream load balancers that normalise
/// header names/values) all match. Both space and horizontal tab are
/// accepted as separators (RFC 7235 BWS = bad whitespace). The trailing
/// credentials are trimmed of surrounding ASCII whitespace before being
/// returned.
///
/// Returns `None` when the value has no whitespace (i.e. is a single token
/// such as `Bearer`) or the scheme is not bearer. An empty-credential
/// case (e.g. `"Bearer   "`) returns `Some("")` so the caller can still
/// enforce its empty-token rejection rule.
///
/// **Control-byte defence.** RFC 7230 ยง3.2.6 bans control characters
/// (other than horizontal tab) from header field values, and
/// [`axum::http::HeaderValue`] already rejects NUL/CR/LF at construction.
/// The `to_str()` conversion in [`bearer_auth`] further restricts the
/// input to "visible ASCII" plus tab. We nonetheless apply an explicit
/// belt-and-braces check here so any future refactor that fans this
/// helper out behind a more permissive byte source cannot silently
/// re-open a CRLF/NUL injection channel into downstream consumers of
/// the returned token (audit log fields, span attributes, etc.).
fn parse_bearer_credentials(value: &str) -> Option<&str> {
    // Defence in depth: reject the entire value if any control byte
    // (other than the horizontal tab we explicitly use as a separator)
    // is present. Covers NUL (C-string truncation), CR/LF (log-line
    // forgery), and the DEL byte (terminal-escape smuggling).
    if value.bytes().any(|b| b != b'\t' && (b < 0x20 || b == 0x7F)) {
        return None;
    }
    // Find the first whitespace byte (space or tab) โ€” anything else
    // separating scheme from credentials would itself be a protocol
    // violation, so we don't bother with general Unicode whitespace.
    let split = value
        .as_bytes()
        .iter()
        .position(|&b| b == b' ' || b == b'\t')?;
    let (scheme, rest) = value.split_at(split);
    if !scheme.eq_ignore_ascii_case("bearer") {
        return None;
    }
    // Trim the leading whitespace run (BWS) plus any trailing whitespace
    // around the credentials. `trim_matches` over the BWS set keeps the
    // behaviour aligned with `str::trim`'s ASCII-whitespace semantics.
    Some(rest.trim_matches(|c: char| c == ' ' || c == '\t'))
}

/// Bearer-token authentication middleware.
///
/// If the allowlist is empty the request passes through (dev mode โ€” already
/// warned at startup) and a synthetic `AuthContext::dev` is inserted into
/// the request extensions. Otherwise the `Authorization: Bearer <token>`
/// header must match one of the allowlisted tokens; missing or mismatched
/// headers produce `401 Unauthorized` with the standard error envelope and
/// `kind: "unauthorized"`. On success an `AuthContext` keyed by the
/// stable [`crate::rate_limit::TokenId`] derived from the bearer token is
/// inserted into the request extensions for downstream middleware (rate
/// limiting, audit) to consume.
pub async fn bearer_auth(mut req: Request, next: Next) -> Response {
    let cfg = req
        .extensions()
        .get::<AuthConfig>()
        .cloned()
        .unwrap_or_default();

    if cfg.is_dev_mode() {
        // M4: fail closed unless dev mode was explicitly opted into. An empty
        // allowlist that nobody acknowledged is treated as a misconfiguration,
        // not as "auth disabled" โ€” every request is rejected rather than
        // silently granted the wildcard `AuthContext::dev` scope.
        if !cfg.dev_mode_allowed {
            return envelope(
                StatusCode::UNAUTHORIZED,
                "unauthorized",
                "no bearer tokens configured and dev mode is not enabled; set \
                 TENSOR_WASM_API_TOKENS to enable bearer auth, or set \
                 TENSOR_WASM_API_ALLOW_DEV_MODE=1 to allow unauthenticated access",
            );
        }
        req.extensions_mut()
            .insert(crate::rate_limit::AuthContext::dev());
        return next.run(req).await;
    }

    // api S-3: refuse requests with more than one `Authorization` header.
    // `HeaderMap::get` returns the first occurrence โ€” a buggy or hostile
    // client sending two headers would silently get one accepted and the
    // other invisible. Some proxies also concatenate duplicates with
    // commas, which would round-trip through `parse_bearer_credentials`
    // unpredictably. Reject outright.
    let auth_count = req
        .headers()
        .get_all(axum::http::header::AUTHORIZATION)
        .iter()
        .count();
    if auth_count > 1 {
        return envelope(
            StatusCode::BAD_REQUEST,
            "bad_request",
            "duplicate Authorization headers are not allowed",
        );
    }
    // api header-hardening: cap the inbound Authorization value length
    // BEFORE the constant-time compare loop runs. Hyper's default cap on
    // the header block (~16 KiB) is large enough that a single oversized
    // `Authorization: Bearer <huge>` would still burn CPU through every
    // `ct_eq` iteration. See [`MAX_AUTH_HEADER_BYTES`] for the rationale.
    // We inspect the raw bytes so a non-UTF-8 value (rejected by
    // `to_str()` below) is bounded too.
    let raw_auth = req.headers().get(axum::http::header::AUTHORIZATION);
    if let Some(value) = raw_auth {
        if value.as_bytes().len() > MAX_AUTH_HEADER_BYTES {
            return envelope(
                StatusCode::UNAUTHORIZED,
                "invalid_auth",
                "Authorization header exceeds the maximum permitted length",
            );
        }
    }

    let header = raw_auth.and_then(|h| h.to_str().ok());

    let token = match header.and_then(parse_bearer_credentials) {
        Some(t) if !t.is_empty() => t.to_owned(),
        _ => {
            return envelope(
                StatusCode::UNAUTHORIZED,
                "unauthorized",
                "missing or malformed Authorization: Bearer <token> header",
            );
        }
    };

    let scope = match cfg.scope_for(&token) {
        Some(s) => s.clone(),
        None => {
            return envelope(
                StatusCode::UNAUTHORIZED,
                "unauthorized",
                "bearer token is not allowlisted",
            );
        }
    };

    req.extensions_mut()
        .insert(crate::rate_limit::AuthContext::with_scope(&token, scope));
    next.run(req).await
}

/// Parse the `X-TensorWasm-Tenant` header into a `TenantId`, applying the
/// configured policy.
///
/// Outcomes:
///
/// * **More than one `X-TensorWasm-Tenant` header present** => `Err(400
///   duplicate_tenant_header)`. `HeaderMap::get` returns only the first
///   match, so an attacker behind a permissive proxy could send
///   `X-TensorWasm-Tenant: 1, X-TensorWasm-Tenant: 999` and confuse
///   downstream observers about which tenant the request really
///   belongs to. We reject outright before any single value is read.
/// * **Header absent + `TENSOR_WASM_API_REQUIRE_TENANT=1`** => `Err(400
///   missing_tenant)`.
/// * **Header absent otherwise** => `Ok(TenantId(0))`.
/// * **Header present but not a `u64`** => `Err(400 invalid_tenant)`.
///   The distinct `invalid_tenant` kind separates a malformed value
///   from the legitimately-absent case so dashboards can alert on each
///   class independently โ€” a spike in `invalid_tenant` typically
///   indicates a client bug or a probing attacker, whereas a spike in
///   `missing_tenant` indicates a misconfigured client.
#[allow(clippy::result_large_err)]
pub fn extract_tenant(headers: &HeaderMap, cfg: TenantConfig) -> Result<TenantId, Response> {
    // Fix 1: refuse requests carrying more than one X-TensorWasm-Tenant
    // header. The single-`get` path would otherwise pick the first
    // occurrence silently while a downstream observer sees the second.
    let header_count = headers.get_all(HEADER_TENANT).iter().count();
    if header_count > 1 {
        return Err(envelope(
            StatusCode::BAD_REQUEST,
            "duplicate_tenant_header",
            "multiple X-TensorWasm-Tenant headers are not allowed",
        ));
    }
    let raw = headers.get(HEADER_TENANT).and_then(|h| h.to_str().ok());
    match raw {
        None => {
            if cfg.require_header {
                Err(envelope(
                    StatusCode::BAD_REQUEST,
                    "missing_tenant",
                    "X-TensorWasm-Tenant header is required (TENSOR_WASM_API_REQUIRE_TENANT=1)",
                ))
            } else {
                Ok(TenantId(0))
            }
        }
        Some(s) => match s.trim().parse::<u64>() {
            Ok(v) => Ok(TenantId(v)),
            // Fix 2: the header is PRESENT but unparseable โ€” emit
            // `invalid_tenant`, distinct from the absent-and-required
            // `missing_tenant` case above.
            Err(_) => Err(envelope(
                StatusCode::BAD_REQUEST,
                "invalid_tenant",
                "X-TensorWasm-Tenant must be a u64",
            )),
        },
    }
}

/// Middleware that resolves the tenant from `X-TensorWasm-Tenant` and stores it
/// in the request's [`axum::http::Extensions`] for handlers to pick up via
/// `Extension<TenantId>`. On parse failure / required-but-missing, emits
/// the standard error envelope and short-circuits the chain.
pub async fn tenant_scope(mut req: Request, next: Next) -> Response {
    let cfg = req
        .extensions()
        .get::<TenantConfig>()
        .copied()
        .unwrap_or_default();

    let tenant = match extract_tenant(req.headers(), cfg) {
        Ok(t) => t,
        Err(resp) => return resp,
    };

    req.extensions_mut().insert(tenant);
    next.run(req).await
}

/// Returns a [`TraceLayer`] that, in addition to the per-request span,
/// reads the W3C `traceparent` header from the incoming request and uses
/// it as the parent context for the resulting span.
///
/// When a downstream service (or load test client) sends the W3C standard
/// header, traces stitch correctly across the boundary. When no header is
/// present, the span is parented to the local context as usual.
///
/// The function delegates the actual parsing to the OpenTelemetry global
/// `TextMapPropagator`. [`crate::server::build_router_with_audit`] calls
/// [`crate::trace_propagation::install_w3c_propagator`] before any
/// request can hit this layer, so the parsing path is reliably wired
/// regardless of whether the `otlp` feature is enabled on
/// `tensor-wasm-core`. If for some reason no propagator is installed โ€”
/// e.g. in a test that bypasses the server builder โ€” the extraction
/// returns an empty context and the span is parented locally.
pub fn trace_layer_with_propagation() -> tower_http::trace::TraceLayer<
    tower_http::classify::SharedClassifier<tower_http::classify::ServerErrorsAsFailures>,
    impl Fn(&axum::http::Request<axum::body::Body>) -> tracing::Span + Clone,
> {
    use tracing_opentelemetry::OpenTelemetrySpanExt;

    TraceLayer::new_for_http().make_span_with(|req: &axum::http::Request<axum::body::Body>| {
        // Surface the raw traceparent value as a span field for log-based
        // correlation, even when no OTel propagator is installed. The
        // header is sanitised first (see `sanitise_traceparent`) so a
        // hostile client cannot smuggle CR/LF, NUL, or megabytes of
        // arbitrary text into every log line that touches this request.
        let raw_tp = req
            .headers()
            .get("traceparent")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        let sanitised_tp = sanitise_traceparent(raw_tp);

        // Record only the URI **path**, never the query string. Query
        // parameters frequently carry tokens/secrets (e.g. an attacker
        // probing `GET /healthz?secret=exfil`) and we MUST NOT plant
        // them in span attributes that flow to log sinks. Handlers that
        // legitimately need the query string read it from
        // `req.uri().query()` themselves under their own scrubbing.
        //
        // Both `path` and `method` flow through bounded sanitisers
        // (`sanitize_path` / `normalize_method`) before reaching the
        // span so that path-traversal probes (`/functions/../etc/passwd`)
        // and CRLF-injection payloads (`/foo%0d%0aevil-header:%20yes`)
        // can neither forge log lines nor smuggle terminal-escape
        // sequences into operator dashboards. `traceparent` has its
        // own dedicated sanitiser above.
        let sanitised_path = sanitize_path(req.uri().path());
        let normalised_method = normalize_method(req.method().as_str());
        let span = tracing::info_span!(
            "http.request",
            method = %normalised_method,
            path = %sanitised_path,
            version = ?req.version(),
            traceparent = %sanitised_tp,
        );

        // Extract the parent `opentelemetry::Context` from the incoming
        // headers via the globally-installed `TextMapPropagator`. The
        // `set_parent` call hooks the freshly-created tracing span into
        // the upstream W3C trace, so subsequent `#[instrument]` spans on
        // tenant lookup, executor spawn, snapshot restore, and dispatch
        // all share the same `trace_id`.
        let parent_cx = crate::trace_propagation::extract_parent_context(req.headers());
        span.set_parent(parent_cx);

        span
    })
}

/// Maximum byte length a `traceparent` header value is allowed to
/// occupy in a span attribute. The W3C Trace Context spec caps a
/// well-formed value at 55 bytes; 64 gives a tiny margin for future
/// versioned suffixes while still bounding the per-span log footprint
/// to a constant. Anything longer is truncated.
const TRACEPARENT_MAX_BYTES: usize = 64;

/// Sentinel emitted in span attributes when a `traceparent` header
/// contains characters that would corrupt log output (CR, LF, NUL).
/// Choosing a fixed token rather than the original (filtered) value
/// keeps grep/audit signatures stable across hostile inputs.
const TRACEPARENT_INVALID_SENTINEL: &str = "<invalid>";

/// Render an inbound `traceparent` header value as a bounded, log-safe
/// string for use as a tracing span attribute.
///
/// The header is attacker-controlled, so we apply three defences:
///
/// 1. **Reject control characters.** Any CR, LF, or NUL byte indicates
///    an attempt to inject a fake log line (CRLF) or terminate a C
///    string in a downstream consumer (NUL). We collapse the entire
///    value to the [`TRACEPARENT_INVALID_SENTINEL`] in that case rather
///    than try to filter โ€” partial sanitisation is exactly the kind of
///    surface that breeds bypasses.
/// 2. **Clamp length to 64 bytes.** The W3C grammar caps a valid value
///    at 55 bytes; anything longer is either malformed or hostile
///    padding. Truncation happens at a UTF-8 char boundary so we never
///    return invalid UTF-8 to the tracing layer.
/// 3. **Strip non-printable bytes** (anything outside `0x20..=0x7E`).
///    Printable ASCII is the entire grammar the spec allows, and
///    keeping span attributes plain ASCII prevents terminal-escape
///    smuggling through log viewers.
///
/// When the input is already a clean ASCII-printable string short
/// enough to fit, we return `Cow::Borrowed` to avoid the allocation.
fn sanitise_traceparent(raw: &str) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;

    // Defence 1: reject the whole value when control chars appear.
    // CRLF is the classic log-injection vector; NUL the classic C
    // boundary trick. Bail before doing any other processing so the
    // sentinel is stable.
    if raw.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0) {
        return Cow::Owned(TRACEPARENT_INVALID_SENTINEL.to_string());
    }

    // Fast path: already short, already printable ASCII -> borrow.
    let is_clean =
        raw.len() <= TRACEPARENT_MAX_BYTES && raw.bytes().all(|b| (0x20..=0x7E).contains(&b));
    if is_clean {
        return Cow::Borrowed(raw);
    }

    // Slow path: build a filtered, clamped owned copy. Walk by char so
    // truncation never lands mid-codepoint, and skip anything outside
    // printable ASCII.
    let mut out = String::with_capacity(raw.len().min(TRACEPARENT_MAX_BYTES));
    for ch in raw.chars() {
        let b = ch as u32;
        if !(0x20..=0x7E).contains(&b) {
            continue;
        }
        let ch_len = ch.len_utf8();
        if out.len() + ch_len > TRACEPARENT_MAX_BYTES {
            break;
        }
        out.push(ch);
    }
    Cow::Owned(out)
}

/// Maximum byte length that a request path is allowed to occupy in a
/// tracing span attribute (see [`sanitize_path`]). Anything longer is
/// truncated with a `โ€ฆ` suffix to keep operator log lines bounded and
/// to deny a hostile client a cheap way to balloon every log record
/// that touches their request.
///
/// 256 bytes comfortably accommodates every route template the API
/// exposes today (the longest, `/functions/{id}/invoke-async`, is far
/// under that even after path-parameter substitution) while still
/// bounding the per-span attribute footprint to a constant. Bump only
/// after auditing the dashboard layouts in `docs/OBSERVABILITY.md` โ€”
/// a wider value widens the log-line budget linearly.
pub const MAX_PATH_LEN: usize = 256;

/// Sentinel returned by [`normalize_method`] for any HTTP method that
/// does not match the `[A-Z]{1,16}` shape. Keeping a fixed token rather
/// than the original (filtered) value preserves grep/audit signatures
/// across hostile inputs โ€” every malformed method bucket maps to the
/// same string.
const METHOD_OTHER_SENTINEL: &str = "OTHER";

/// Upper bound on the byte length of an accepted HTTP method name.
/// Standard methods are at most 7 bytes (`OPTIONS`); 16 leaves room
/// for legitimate WebDAV-style extensions (`MKCALENDAR`, `PROPPATCH`)
/// while rejecting padding-style abuse.
const METHOD_MAX_LEN: usize = 16;

/// Render a request path as a bounded, log-safe string for use as a
/// tracing span attribute.
///
/// The path is attacker-controlled (it flows out of the request URI
/// after axum's routing layer), so we apply three defences:
///
/// 1. **Truncate to [`MAX_PATH_LEN`] bytes** with a `โ€ฆ` ellipsis
///    suffix when the input is longer. Truncation lands on a UTF-8
///    char boundary so we never emit invalid UTF-8 to the tracing
///    layer. The ellipsis is one Unicode code point (`U+2026`, three
///    UTF-8 bytes) so the returned `Cow::Owned` is at most
///    `MAX_PATH_LEN + 3` bytes โ€” the test in
///    `tests/trace_sanitization_test.rs` asserts `MAX_PATH_LEN + 4`
///    to give a one-byte margin against future ellipsis tweaks.
/// 2. **Replace non-printable / non-ASCII bytes with `?`.** Anything
///    outside `0x20..=0x7E` (printable ASCII) is collapsed to a
///    single `?` so terminal-escape sequences cannot smuggle out of
///    a log viewer and multi-byte UTF-8 sequences (e.g. `รฉ` โ†’
///    `0xC3 0xA9`) cannot be reconstructed downstream.
/// 3. **Strip CR / LF / NUL specifically.** The printable-byte filter
///    above already catches these, but we apply the explicit strip as
///    defence in depth: a future relaxation of the printable filter
///    must NOT re-open the CRLF-injection channel (forging fake JSON
///    log lines) or the NUL channel (terminating C-string consumers).
///
/// When the input is already a clean ASCII-printable string short
/// enough to fit, we return `Cow::Borrowed` to avoid the allocation.
pub fn sanitize_path(raw: &str) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;

    // Fast path: already short, already printable ASCII, no
    // CR/LF/NUL -> borrow. Walking once via `bytes().all` lets the
    // compiler fuse the checks; we only allocate when something
    // actually needs rewriting.
    let is_clean = raw.len() <= MAX_PATH_LEN
        && raw
            .bytes()
            .all(|b| (0x20..=0x7E).contains(&b) && b != b'\r' && b != b'\n' && b != 0);
    if is_clean {
        return Cow::Borrowed(raw);
    }

    // Slow path: build a filtered, clamped owned copy. Walk by char
    // so truncation never lands mid-codepoint; replace anything
    // outside printable ASCII with a literal `?` rather than dropping
    // it, so a path like `/cafรฉ` round-trips to `/caf??` (two bytes
    // for `รฉ` โ†’ two `?` substitutions) and the resulting attribute
    // length is observable to operators rather than silently
    // shrinking.
    //
    // We reserve `MAX_PATH_LEN` up front; the ellipsis (if any) is
    // appended afterwards so the truncation check operates on the
    // pre-ellipsis byte budget.
    let mut out = String::with_capacity(raw.len().min(MAX_PATH_LEN));
    let mut truncated = false;
    for ch in raw.chars() {
        // Defence 3: strip CR/LF/NUL explicitly even though the
        // printable filter below would catch them. A future relaxation
        // must not re-open the injection channel.
        if ch == '\r' || ch == '\n' || ch == '\0' {
            out.push('?');
            if out.len() >= MAX_PATH_LEN {
                truncated = true;
                break;
            }
            continue;
        }
        let b = ch as u32;
        let replacement = if (0x20..=0x7E).contains(&b) {
            // Printable ASCII: keep the character as-is (it occupies
            // one byte in UTF-8 by definition).
            ch
        } else {
            // Non-printable or non-ASCII: collapse to `?`. This
            // includes every byte of a multi-byte UTF-8 sequence
            // because we iterate by `char`, not by byte, so each
            // non-ASCII code point contributes exactly one `?` to
            // the output regardless of how many bytes it occupies
            // in the input.
            '?'
        };
        let ch_len = replacement.len_utf8();
        if out.len() + ch_len > MAX_PATH_LEN {
            truncated = true;
            break;
        }
        out.push(replacement);
    }
    if truncated {
        // Append a single-code-point ellipsis (`โ€ฆ`, U+2026, 3 bytes
        // in UTF-8) so the truncated value is visually distinguishable
        // from a non-truncated one. Total length stays bounded at
        // `MAX_PATH_LEN + 3` bytes โ€” see the doc comment above.
        out.push('โ€ฆ');
    }
    Cow::Owned(out)
}

/// Normalise an HTTP method name for use as a tracing span attribute.
///
/// Returns the input borrowed when it matches `[A-Z]{1,16}` exactly
/// (every standard method โ€” `GET`, `POST`, `PUT`, `PATCH`, `DELETE`,
/// `HEAD`, `OPTIONS`, `TRACE`, `CONNECT` โ€” passes through verbatim).
/// Anything else โ€” lowercase (`get`), mixed case (`Get`), control
/// characters, non-ASCII, oversized padding โ€” collapses to the
/// `METHOD_OTHER_SENTINEL` (`"OTHER"`).
///
/// HTTP method names are far less risky than paths (hyper rejects
/// most malformed values before they reach this layer) but we still
/// normalise so that:
///
/// * dashboard label cardinality stays bounded (no per-request method
///   variant exploding the metrics index),
/// * a custom client cannot smuggle non-standard bytes into the
///   `method` span field that the path sanitiser would have rejected.
pub fn normalize_method(raw: &str) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;

    let bytes = raw.as_bytes();
    let valid = !bytes.is_empty()
        && bytes.len() <= METHOD_MAX_LEN
        && bytes.iter().all(|b| b.is_ascii_uppercase());
    if valid {
        Cow::Borrowed(raw)
    } else {
        Cow::Owned(METHOD_OTHER_SENTINEL.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::HeaderValue;

    #[test]
    fn timeout_layer_constructs() {
        let _ = timeout_layer(Duration::from_millis(1));
        let _ = timeout_layer(DEFAULT_REQUEST_TIMEOUT);
    }

    #[test]
    fn trace_layer_constructs() {
        let _ = trace_layer();
    }

    #[test]
    fn concurrency_limit_layer_constructs() {
        let _ = concurrency_limit_layer(1);
        let _ = concurrency_limit_layer(DEFAULT_CONCURRENCY_LIMIT);
    }

    #[test]
    fn body_limit_layer_constructs() {
        let _ = body_limit_layer(MAX_REQUEST_BODY_BYTES);
    }

    #[test]
    fn cors_config_default_is_empty_allowlist() {
        let cfg = CorsConfig::default();
        assert!(cfg.allowed_origins.is_empty());
    }

    #[test]
    fn cors_config_from_origins_round_trips() {
        let cfg = CorsConfig::from_origins(["https://app.example.com"]);
        assert_eq!(cfg.allowed_origins, vec!["https://app.example.com"]);
    }

    #[test]
    fn cors_layer_constructs_empty_allowlist() {
        // The empty-allowlist branch is the safe default: it must produce
        // a layer that does not set Access-Control-Allow-Origin. We only
        // exercise construction here; the wire-level rejection check sits
        // in the integration test suite where a full router is in scope.
        let _ = cors_layer(&CorsConfig::default());
    }

    #[test]
    fn cors_layer_constructs_with_origins() {
        let _ = cors_layer(&CorsConfig::from_origins([
            "https://app.example.com",
            "https://admin.example.com",
        ]));
    }

    #[test]
    fn trace_layer_with_propagation_constructs() {
        let _ = trace_layer_with_propagation();
    }

    #[test]
    fn sanitise_traceparent_passes_through_well_formed_value() {
        // A literal example from the W3C Trace Context spec. Already
        // printable ASCII, already under the 64-byte cap, so the
        // helper must return the borrowed pointer (no allocation,
        // exact byte equality).
        let sample = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";
        let out = sanitise_traceparent(sample);
        assert_eq!(out.as_ref(), sample);
        assert!(
            matches!(out, std::borrow::Cow::Borrowed(_)),
            "well-formed value must be borrowed, not allocated",
        );
    }

    #[test]
    fn sanitise_traceparent_rejects_crlf_injection() {
        // CRLF in a header value is the classic log-injection vector;
        // a hostile client could plant a forged "log line" into our
        // structured output. The helper must collapse the whole value
        // to a stable sentinel, NOT a partially-filtered string.
        let attack = "\r\nSET-COOKIE: x=y\r\n";
        let out = sanitise_traceparent(attack);
        assert_eq!(out.as_ref(), "<invalid>");
    }

    #[test]
    fn sanitise_traceparent_rejects_embedded_nul() {
        // NUL bytes truncate C strings in downstream consumers; treat
        // them as hostile and emit the sentinel.
        let attack = "00-aaaa\0bbbb";
        let out = sanitise_traceparent(attack);
        assert_eq!(out.as_ref(), "<invalid>");
    }

    #[test]
    fn sanitise_traceparent_truncates_oversized_input_to_64_bytes() {
        // A 100-byte all-'a' string is printable ASCII but exceeds
        // the 64-byte cap. The helper must clamp to exactly 64
        // bytes โ€” the W3C maximum is 55, so 64 already accommodates
        // every legitimate value with room to spare.
        let input = "a".repeat(100);
        let out = sanitise_traceparent(&input);
        assert_eq!(out.len(), 64);
        assert!(out.chars().all(|c| c == 'a'));
    }

    #[test]
    fn sanitise_traceparent_filters_non_printable_bytes() {
        // ESC (0x1B) is outside printable ASCII and could be used to
        // smuggle terminal escape sequences through log viewers.
        // The helper must strip the byte but keep the surrounding
        // printable context.
        let attack = "00-aaaa\x1Bbbbb-cc";
        let out = sanitise_traceparent(attack);
        assert!(!out.contains('\x1B'));
        assert!(out.contains("aaaa"));
        assert!(out.contains("bbbb"));
    }

    #[test]
    fn auth_config_dev_mode_when_empty() {
        let cfg = AuthConfig::from_tokens(Vec::<String>::new());
        assert!(cfg.is_dev_mode());
        // dev-mode `accepts` is irrelevant, but should return `false` โ€”
        // the dev gate runs in `bearer_auth`, not here.
        assert!(!cfg.accepts("anything"));
    }

    // ---- M4: dev-mode opt-in gate -------------------------------------

    /// Programmatic constructors are an explicit in-process opt-in, so they
    /// keep the historical pass-through behaviour (`dev_mode_allowed == true`).
    /// This preserves every test/embedder that builds a dev `AuthConfig`
    /// directly without touching the process environment.
    #[test]
    fn auth_config_programmatic_constructors_allow_dev_mode() {
        assert!(AuthConfig::default().dev_mode_allowed);
        assert!(AuthConfig::from_tokens(Vec::<String>::new()).dev_mode_allowed);
        assert!(AuthConfig::from_scopes(Vec::<(String, TokenScope)>::new()).dev_mode_allowed);
    }

    /// `from_env` with an empty allowlist and no opt-in must produce a config
    /// that forbids dev mode (M4 fail-closed). The env mutation is scoped by
    /// `temp_env` so it cannot race other tests.
    #[test]
    fn auth_config_from_env_empty_without_opt_in_forbids_dev_mode() {
        temp_env::with_vars(
            [
                (ENV_API_TOKENS, None::<&str>),
                (ENV_ALLOW_DEV_MODE, None::<&str>),
            ],
            || {
                let cfg = AuthConfig::from_env();
                assert!(cfg.is_dev_mode());
                assert!(
                    !cfg.dev_mode_allowed,
                    "empty allowlist + no opt-in must fail closed",
                );
            },
        );
    }

    /// The opt-in honours both `1` and (case-insensitive) `true`.
    #[test]
    fn auth_config_from_env_opt_in_values_enable_dev_mode() {
        for val in ["1", "true", "TRUE", " true "] {
            temp_env::with_vars(
                [
                    (ENV_API_TOKENS, None::<&str>),
                    (ENV_ALLOW_DEV_MODE, Some(val)),
                ],
                || {
                    let cfg = AuthConfig::from_env();
                    assert!(cfg.is_dev_mode());
                    assert!(
                        cfg.dev_mode_allowed,
                        "ENV_ALLOW_DEV_MODE={val:?} must enable dev mode",
                    );
                },
            );
        }
    }

    /// A non-truthy opt-in value leaves dev mode disabled.
    #[test]
    fn auth_config_from_env_non_truthy_opt_in_forbids_dev_mode() {
        for val in ["0", "false", "yes", ""] {
            temp_env::with_vars(
                [
                    (ENV_API_TOKENS, None::<&str>),
                    (ENV_ALLOW_DEV_MODE, Some(val)),
                ],
                || {
                    assert!(
                        !AuthConfig::from_env().dev_mode_allowed,
                        "ENV_ALLOW_DEV_MODE={val:?} must NOT enable dev mode",
                    );
                },
            );
        }
    }

    /// When tokens ARE configured the opt-in is irrelevant โ€” the config is
    /// not in dev mode and `bearer_auth` enforces the allowlist as before.
    #[test]
    fn auth_config_from_env_with_tokens_is_not_dev_mode() {
        temp_env::with_vars(
            [
                (ENV_API_TOKENS, Some("secret:tenant=*")),
                (ENV_ALLOW_DEV_MODE, None::<&str>),
            ],
            || {
                let cfg = AuthConfig::from_env();
                assert!(!cfg.is_dev_mode());
                assert!(cfg.accepts("secret"));
            },
        );
    }

    /// End-to-end: a fail-closed dev config (`dev_mode_allowed == false`) must
    /// reject an unauthenticated request through the real `bearer_auth`
    /// middleware with `401 Unauthorized`, rather than passing it through.
    #[tokio::test]
    async fn bearer_auth_fails_closed_when_dev_mode_not_allowed() {
        use axum::routing::get;
        use tower::ServiceExt as _;

        let cfg = temp_env::with_vars(
            [
                (ENV_API_TOKENS, None::<&str>),
                (ENV_ALLOW_DEV_MODE, None::<&str>),
            ],
            AuthConfig::from_env,
        );
        assert!(!cfg.dev_mode_allowed);

        let router = axum::Router::new()
            .route("/x", get(|| async { "ok" }))
            .layer(axum::middleware::from_fn(bearer_auth))
            .layer(axum::Extension(cfg));

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/x")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    /// End-to-end counterpart: with dev mode explicitly allowed the same
    /// unauthenticated request passes through to the handler (`200 OK`).
    #[tokio::test]
    async fn bearer_auth_passes_through_when_dev_mode_allowed() {
        use axum::routing::get;
        use tower::ServiceExt as _;

        // `default()` is an explicit in-process opt-in (dev_mode_allowed).
        let router = axum::Router::new()
            .route("/x", get(|| async { "ok" }))
            .layer(axum::middleware::from_fn(bearer_auth))
            .layer(axum::Extension(AuthConfig::default()));

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/x")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[test]
    fn auth_config_accepts_matching_token() {
        let cfg = AuthConfig::from_tokens(["foo", "bar"]);
        assert!(!cfg.is_dev_mode());
        assert!(cfg.accepts("foo"));
        assert!(cfg.accepts("bar"));
        assert!(!cfg.accepts("baz"));
    }

    #[test]
    fn auth_config_from_tokens_defaults_to_wildcard_scope() {
        let cfg = AuthConfig::from_tokens(["foo"]);
        let scope = cfg.scope_for("foo").expect("scope present");
        assert!(
            scope.tenants.is_all(),
            "from_tokens must default to wildcard"
        );
    }

    #[test]
    fn auth_config_from_scopes_round_trips() {
        let cfg = AuthConfig::from_scopes([
            (
                "foo",
                crate::token_scope::TokenScope::from_tenants([TenantId(1)]),
            ),
            ("bar", crate::token_scope::TokenScope::all()),
        ]);
        assert!(cfg.accepts("foo"));
        assert!(cfg.accepts("bar"));
        let foo = cfg.scope_for("foo").expect("foo");
        assert!(foo.allows(TenantId(1)));
        assert!(!foo.allows(TenantId(2)));
        let bar = cfg.scope_for("bar").expect("bar");
        assert!(bar.allows(TenantId(99)));
    }

    #[test]
    fn extract_tenant_default_zero_when_optional() {
        let headers = HeaderMap::new();
        let cfg = TenantConfig {
            require_header: false,
        };
        let tid = extract_tenant(&headers, cfg).expect("default to TenantId(0)");
        assert_eq!(tid, TenantId(0));
    }

    #[test]
    fn extract_tenant_errors_when_required_and_missing() {
        let headers = HeaderMap::new();
        let cfg = TenantConfig {
            require_header: true,
        };
        let err = extract_tenant(&headers, cfg).expect_err("required header missing");
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn extract_tenant_parses_header_value() {
        let mut headers = HeaderMap::new();
        headers.insert(HEADER_TENANT, HeaderValue::from_static("7"));
        let tid = extract_tenant(
            &headers,
            TenantConfig {
                require_header: false,
            },
        )
        .expect("parses");
        assert_eq!(tid, TenantId(7));
    }

    #[test]
    fn parse_bearer_credentials_accepts_canonical_scheme() {
        assert_eq!(parse_bearer_credentials("Bearer abc"), Some("abc"));
    }

    #[test]
    fn parse_bearer_credentials_is_case_insensitive() {
        // Load balancers (e.g. Envoy / nginx lowercase plugins) may have
        // normalised the scheme; RFC 6750 ยง2.1 says scheme matching is
        // case-insensitive.
        assert_eq!(parse_bearer_credentials("bearer abc"), Some("abc"));
        assert_eq!(parse_bearer_credentials("BEARER abc"), Some("abc"));
        assert_eq!(parse_bearer_credentials("BeArEr abc"), Some("abc"));
    }

    #[test]
    fn parse_bearer_credentials_accepts_tab_separator() {
        assert_eq!(parse_bearer_credentials("Bearer\tabc"), Some("abc"));
    }

    #[test]
    fn parse_bearer_credentials_trims_surrounding_whitespace() {
        assert_eq!(parse_bearer_credentials("Bearer   abc"), Some("abc"));
        assert_eq!(parse_bearer_credentials("Bearer abc  "), Some("abc"));
        assert_eq!(parse_bearer_credentials("Bearer \t abc \t "), Some("abc"));
    }

    #[test]
    fn parse_bearer_credentials_rejects_other_schemes() {
        assert_eq!(parse_bearer_credentials("Basic ZGVhZGJlZWY="), None);
        assert_eq!(parse_bearer_credentials("Token abc"), None);
    }

    #[test]
    fn parse_bearer_credentials_returns_none_for_no_whitespace() {
        // No separator at all => not a parseable Authorization value.
        assert_eq!(parse_bearer_credentials("Bearer"), None);
        assert_eq!(parse_bearer_credentials(""), None);
    }

    #[test]
    fn parse_bearer_credentials_empty_token_is_some_empty() {
        // Caller (`bearer_auth`) is responsible for the empty-token check;
        // we surface the empty string so it can reject with the same shape
        // as a missing header.
        assert_eq!(parse_bearer_credentials("Bearer   "), Some(""));
    }

    #[test]
    fn extract_tenant_rejects_garbage_header() {
        let mut headers = HeaderMap::new();
        headers.insert(HEADER_TENANT, HeaderValue::from_static("not-a-number"));
        let err = extract_tenant(
            &headers,
            TenantConfig {
                require_header: false,
            },
        )
        .expect_err("rejects garbage");
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }
}