swadhinbiswas ⚡ p55: per-route rate limiting + RFC 9457 error responses + configurable drain timeout · 7/26/2026
ef04ee5
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
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
use std::collections::HashMap;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use async_trait::async_trait;
use futures::future::BoxFuture;
use governor::clock::Clock;
use http::HeaderValue;
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::BodyExt;
use hyper::body::{Bytes, Incoming};
use hyper::{Method, Request, Response, StatusCode};
use crate::ResponseBody;
// ---------------------------------------------------------------------------
// Middleware trait (generic over body type for testability)
// ---------------------------------------------------------------------------
/// Middleware that processes a request and optionally passes it to the next handler.
#[async_trait]
pub trait Middleware<B = Incoming>: Send + Sync {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>>;
}
/// The next element in the middleware chain.
pub struct Next<'a, B = Incoming> {
middlewares: &'a [Arc<dyn Middleware<B>>],
index: usize,
handler: &'a HandlerFn<B>,
}
impl<'a, B> Next<'a, B> {
pub async fn run(self, req: Request<B>) -> Result<Response<ResponseBody>> {
if self.index < self.middlewares.len() {
let mw = &self.middlewares[self.index];
let next = Next {
middlewares: self.middlewares,
index: self.index + 1,
handler: self.handler,
};
let mw_name = std::any::type_name_of_val(mw);
let span = tracing::debug_span!("middleware", mw.name = %mw_name);
let _enter = span.enter();
let result = mw.handle(req, next).await;
drop(_enter);
result
} else {
let span = tracing::debug_span!("handler.dispatch");
let _enter = span.enter();
let result = (self.handler)(req).await;
drop(_enter);
result
}
}
}
/// Handler function type, generic over body type.
pub type HandlerFn<B = Incoming> =
Arc<dyn Fn(Request<B>) -> BoxFuture<'static, Result<Response<ResponseBody>>> + Send + Sync>;
// ---------------------------------------------------------------------------
// Middleware chain (generic over body type)
// ---------------------------------------------------------------------------
/// A composable chain of middleware wrapping an inner handler.
pub struct MiddlewareChain<B = Incoming> {
middlewares: Vec<Arc<dyn Middleware<B>>>,
handler: HandlerFn<B>,
}
impl<B> Clone for MiddlewareChain<B> {
fn clone(&self) -> Self {
Self { middlewares: self.middlewares.clone(), handler: self.handler.clone() }
}
}
impl<B> MiddlewareChain<B> {
pub fn new(handler: HandlerFn<B>) -> Self {
Self { middlewares: Vec::new(), handler }
}
pub fn add(&mut self, mw: impl Middleware<B> + 'static) {
self.middlewares.push(Arc::new(mw));
}
pub fn set_handler(&mut self, handler: HandlerFn<B>) {
self.handler = handler;
}
pub fn is_empty(&self) -> bool {
self.middlewares.is_empty()
}
pub async fn run(&self, req: Request<B>) -> Result<Response<ResponseBody>> {
if self.middlewares.is_empty() {
return (self.handler)(req).await;
}
let next = Next { middlewares: &self.middlewares, index: 0, handler: &self.handler };
next.run(req).await
}
}
// ---------------------------------------------------------------------------
// Middleware implementations (concrete, for Incoming body only)
// ---------------------------------------------------------------------------
pub struct AccessLogger {
tx: tokio::sync::mpsc::UnboundedSender<String>,
}
impl AccessLogger {
pub fn new() -> Self {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
std::thread::spawn(move || {
while let Some(msg) = rx.blocking_recv() {
println!("{}", msg);
}
});
Self { tx }
}
}
impl Default for AccessLogger {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for AccessLogger {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
let method = req.method().clone();
let uri = req.uri().clone();
let start = std::time::Instant::now();
let res = next.run(req).await;
let status = match &res {
Ok(r) => r.status().as_u16(),
Err(_) => 500,
};
let duration = start.elapsed();
let _ = self.tx.send(format!("[{method}] {uri} - {status} - {duration:?}"));
res
}
}
pub struct Cors {
allow_origins: Vec<String>,
allow_methods: String,
allow_headers: String,
expose_headers: Vec<String>,
max_age: String,
allow_credentials: bool,
}
impl Cors {
pub fn permissive() -> Self {
Self {
allow_origins: vec!["*".to_string()],
allow_methods: "GET, POST, PUT, DELETE, PATCH, OPTIONS".to_string(),
allow_headers: "Content-Type, Authorization".to_string(),
expose_headers: Vec::new(),
max_age: "86400".to_string(),
allow_credentials: false,
}
}
pub fn new() -> Self {
Self {
// Secure-by-default: no `Access-Control-Allow-Origin` is emitted
// until the caller configures explicit origins via `allow_origin`.
// Browsers then enforce same-origin. Use `permissive()` for the old
// open `*` behavior.
allow_origins: Vec::new(),
allow_methods: "GET, POST, PUT, DELETE, PATCH, OPTIONS".to_string(),
allow_headers: "Content-Type, Authorization".to_string(),
expose_headers: Vec::new(),
max_age: "86400".to_string(),
allow_credentials: false,
}
}
pub fn allow_origin(mut self, origin: &str) -> Self {
if origin == "*" {
self.allow_origins = vec!["*".to_string()];
} else if self.allow_origins == ["*"] {
self.allow_origins = vec![origin.to_string()];
} else {
self.allow_origins.push(origin.to_string());
}
self
}
pub fn allow_methods(mut self, methods: &str) -> Self {
self.allow_methods = methods.to_string();
self
}
pub fn allow_headers(mut self, headers: &str) -> Self {
self.allow_headers = headers.to_string();
self
}
pub fn expose_headers(mut self, headers: &[&str]) -> Self {
self.expose_headers = headers.iter().map(|h| h.to_string()).collect();
self
}
pub fn allow_credentials(mut self) -> Self {
self.allow_credentials = true;
self
}
pub fn max_age(mut self, seconds: &str) -> Self {
self.max_age = seconds.to_string();
self
}
}
impl Default for Cors {
fn default() -> Self {
// Secure-by-default: same-origin only until configured.
Self::new()
}
}
fn origin_matches(origin: &str, allowed: &[String]) -> bool {
allowed.iter().any(|a| a == "*" || a == origin)
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for Cors {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
let req_origin = req.headers().get("origin").and_then(|v| v.to_str().ok());
let allow_all = self.allow_origins.iter().any(|a| a == "*");
// When credentials are allowed, the wildcard "*" must NOT be echoed:
// browsers reject `Access-Control-Allow-Origin: *` together with
// `Access-Control-Allow-Credentials: true`, and echoing "*" with
// credentials would be insecure. Reflect the concrete request origin
// instead (only when one is present).
let matched_origin = if allow_all {
if self.allow_credentials {
match req_origin {
Some(o) => o.to_string(),
None => return next.run(req).await,
}
} else {
"*".to_string()
}
} else if let Some(origin) = req_origin {
if origin_matches(origin, &self.allow_origins) {
origin.to_string()
} else {
return next.run(req).await;
}
} else {
return next.run(req).await;
};
let add_vary = !allow_all;
if req.method() == Method::OPTIONS {
let origin_val: HeaderValue = matched_origin
.parse()
.map_err(|e| anyhow::anyhow!("invalid CORS origin header value: {e}"))?;
let mut builder = Response::builder()
.status(StatusCode::NO_CONTENT)
.header("access-control-allow-origin", origin_val)
.header("access-control-allow-methods", &self.allow_methods)
.header("access-control-allow-headers", &self.allow_headers)
.header("access-control-max-age", &self.max_age);
if self.allow_credentials {
builder = builder.header("access-control-allow-credentials", "true");
}
if !self.expose_headers.is_empty() {
builder =
builder.header("access-control-expose-headers", self.expose_headers.join(", "));
}
if add_vary {
builder = builder.header("vary", "Origin");
}
let resp = builder
.body(UnsyncBoxBody::new(
http_body_util::Full::new(Bytes::new())
.map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
))
.unwrap();
return Ok(resp);
}
let mut resp = next.run(req).await?;
let origin_val: HeaderValue = matched_origin
.parse()
.map_err(|e| anyhow::anyhow!("invalid CORS origin header value: {e}"))?;
resp.headers_mut().insert("access-control-allow-origin", origin_val);
if self.allow_credentials {
resp.headers_mut()
.insert("access-control-allow-credentials", HeaderValue::from_static("true"));
}
if !self.expose_headers.is_empty() {
let val: HeaderValue = self
.expose_headers
.join(", ")
.parse()
.map_err(|e| anyhow::anyhow!("invalid CORS expose-headers value: {e}"))?;
resp.headers_mut().insert("access-control-expose-headers", val);
}
if add_vary {
resp.headers_mut().insert("vary", HeaderValue::from_static("Origin"));
}
Ok(resp)
}
}
pub struct SecurityHeaders {
hsts: String,
csp_directives: Vec<String>,
include_xfo: bool,
include_csp: bool,
include_hsts: bool,
include_hsts_preload: bool,
}
impl Default for SecurityHeaders {
fn default() -> Self {
Self {
hsts: "max-age=31536000; includeSubDomains".to_string(),
csp_directives: vec!["default-src 'self'".to_string()],
include_xfo: true,
include_csp: true,
include_hsts: true,
include_hsts_preload: false,
}
}
}
impl SecurityHeaders {
pub fn with_hsts_preload(mut self) -> Self {
self.hsts = format!("{}; preload", self.hsts.trim_end_matches("; preload"));
self.include_hsts_preload = true;
self
}
pub fn with_csp_directive(mut self, directive: &str) -> Self {
self.csp_directives.push(directive.to_string());
self
}
pub fn without_xfo(mut self) -> Self {
self.include_xfo = false;
self
}
pub fn without_csp(mut self) -> Self {
self.include_csp = false;
self
}
/// Omit `Strict-Transport-Security`. Use for plaintext (non-TLS) deployments:
/// emitting HSTS over HTTP is both useless and can pin a dev environment to
/// HTTPS that it cannot serve.
pub fn without_hsts(mut self) -> Self {
self.include_hsts = false;
self
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for SecurityHeaders {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
let mut resp = next.run(req).await?;
let headers = resp.headers_mut();
headers.insert("x-content-type-options", HeaderValue::from_static("nosniff"));
if self.include_xfo {
headers.insert("x-frame-options", HeaderValue::from_static("DENY"));
}
if self.include_hsts {
let hsts_val = if self.include_hsts_preload {
format!("{}; preload", self.hsts.trim_end_matches("; preload"))
} else {
self.hsts.clone()
};
headers.insert(
"strict-transport-security",
HeaderValue::from_str(&hsts_val)
.map_err(|e| anyhow::anyhow!("invalid HSTS value: {e}"))?,
);
}
if self.include_csp {
let csp = self.csp_directives.join("; ");
headers.insert(
"content-security-policy",
HeaderValue::from_str(&csp)
.map_err(|e| anyhow::anyhow!("invalid CSP value: {e}"))?,
);
}
headers.insert("x-xss-protection", HeaderValue::from_static("0"));
Ok(resp)
}
}
/// Per-route JWT requirement.
#[derive(Clone, Debug)]
pub enum JwtRequirement {
/// No JWT validation required for this route.
None,
/// JWT required; no additional claims checked.
Required,
/// JWT required AND the token's `roles` claim must include at least one of these.
Roles(Vec<String>),
/// JWT required AND the token's `scope` or `scopes` claim must include at least one of these.
Scopes(Vec<String>),
}
pub struct JwtAuth {
validation: jsonwebtoken::Validation,
decoding_key: jsonwebtoken::DecodingKey,
route_rules: Vec<(String, JwtRequirement)>,
default_requirement: JwtRequirement,
warned_aud_iss: std::sync::atomic::AtomicBool,
}
impl std::fmt::Debug for JwtAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JwtAuth")
.field("default_requirement", &self.default_requirement)
.field("route_rules", &self.route_rules)
.finish()
}
}
impl JwtAuth {
pub fn from_secret(secret: &[u8]) -> Self {
Self {
validation: jsonwebtoken::Validation::default(),
decoding_key: jsonwebtoken::DecodingKey::from_secret(secret),
route_rules: Vec::new(),
default_requirement: JwtRequirement::Required,
warned_aud_iss: std::sync::atomic::AtomicBool::new(false),
}
}
pub fn from_rsa_pem(pem: &str) -> anyhow::Result<Self> {
let decoding_key = jsonwebtoken::DecodingKey::from_rsa_pem(pem.as_bytes())?;
let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::RS256);
validation.algorithms = vec![
jsonwebtoken::Algorithm::RS256,
jsonwebtoken::Algorithm::RS384,
jsonwebtoken::Algorithm::RS512,
];
Ok(Self {
validation,
decoding_key,
route_rules: Vec::new(),
default_requirement: JwtRequirement::Required,
warned_aud_iss: std::sync::atomic::AtomicBool::new(false),
})
}
pub fn from_ec_pem(pem: &str) -> anyhow::Result<Self> {
let decoding_key = jsonwebtoken::DecodingKey::from_ec_pem(pem.as_bytes())?;
let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::ES256);
validation.algorithms =
vec![jsonwebtoken::Algorithm::ES256, jsonwebtoken::Algorithm::ES384];
Ok(Self {
validation,
decoding_key,
route_rules: Vec::new(),
default_requirement: JwtRequirement::Required,
warned_aud_iss: std::sync::atomic::AtomicBool::new(false),
})
}
pub fn from_rsa_der(der: &[u8]) -> Self {
let decoding_key = jsonwebtoken::DecodingKey::from_rsa_der(der);
let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::RS256);
validation.algorithms = vec![
jsonwebtoken::Algorithm::RS256,
jsonwebtoken::Algorithm::RS384,
jsonwebtoken::Algorithm::RS512,
];
Self {
validation,
decoding_key,
route_rules: Vec::new(),
default_requirement: JwtRequirement::Required,
warned_aud_iss: std::sync::atomic::AtomicBool::new(false),
}
}
pub fn from_ec_der(der: &[u8]) -> Self {
let decoding_key = jsonwebtoken::DecodingKey::from_ec_der(der);
let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::ES256);
validation.algorithms =
vec![jsonwebtoken::Algorithm::ES256, jsonwebtoken::Algorithm::ES384];
Self {
validation,
decoding_key,
route_rules: Vec::new(),
default_requirement: JwtRequirement::Required,
warned_aud_iss: std::sync::atomic::AtomicBool::new(false),
}
}
pub fn with_algorithm(mut self, alg: jsonwebtoken::Algorithm) -> Self {
self.validation.algorithms = vec![alg];
self
}
pub fn with_algorithms(mut self, algs: Vec<jsonwebtoken::Algorithm>) -> Self {
self.validation.algorithms = algs;
self
}
pub fn with_issuer(mut self, issuer: &str) -> Self {
self.validation.iss = Some([issuer.to_string()].into());
self
}
pub fn with_audience(mut self, audience: &[&str]) -> Self {
self.validation.aud = Some(audience.iter().map(|a| a.to_string()).collect());
self
}
/// Require JWT validation for requests whose path starts with the given prefix.
pub fn require_for(mut self, path_prefix: &str, requirement: JwtRequirement) -> Self {
self.route_rules.push((path_prefix.to_string(), requirement));
self
}
/// Set the default requirement for routes without an explicit rule.
pub fn default_requirement(mut self, requirement: JwtRequirement) -> Self {
self.default_requirement = requirement;
self
}
fn requirement_for_path(&self, path: &str) -> &JwtRequirement {
for (prefix, req) in &self.route_rules {
if path.starts_with(prefix) {
return req;
}
}
&self.default_requirement
}
}
fn check_claims(
claims: &serde_json::Value,
requirement: &JwtRequirement,
) -> Result<(), &'static str> {
match requirement {
JwtRequirement::None => Ok(()),
JwtRequirement::Required => Ok(()),
JwtRequirement::Roles(required_roles) => {
let roles = claims.get("roles").and_then(|v| v.as_array());
match roles {
Some(role_list) => {
let user_roles: Vec<&str> =
role_list.iter().filter_map(|v| v.as_str()).collect();
if required_roles.iter().any(|r| user_roles.contains(&r.as_str())) {
Ok(())
} else {
Err("missing required role")
}
}
None => Err("missing roles claim"),
}
}
JwtRequirement::Scopes(required_scopes) => {
let scopes = claims
.get("scope")
.or_else(|| claims.get("scopes"))
.and_then(|v| v.as_str())
.map(|s| s.split_whitespace().collect::<Vec<&str>>())
.or_else(|| {
claims
.get("scope")
.or_else(|| claims.get("scopes"))
.and_then(|v| v.as_array())
.map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
});
match scopes {
Some(user_scopes) => {
if required_scopes.iter().any(|s| user_scopes.contains(&s.as_str())) {
Ok(())
} else {
Err("missing required scope")
}
}
None => Err("missing scope/scopes claim"),
}
}
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for JwtAuth {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
// One-time warning if aud/iss validation is not configured.
if self.validation.aud.is_none()
&& self.validation.iss.is_none()
&& !self.warned_aud_iss.swap(true, std::sync::atomic::Ordering::Relaxed)
{
tracing::warn!(
"JwtAuth: neither `aud` nor `iss` claim is validated. \
Call `.with_audience([...])` and/or `.with_issuer(...)` \
to prevent token replay across different services."
);
}
let path = req.uri().path().to_string();
let requirement = self.requirement_for_path(&path);
// If no JWT required for this route, skip validation entirely
if matches!(requirement, JwtRequirement::None) {
return next.run(req).await;
}
let auth_header = req.headers().get("authorization").and_then(|v| v.to_str().ok());
let token = match auth_header {
Some(h) if h.starts_with("Bearer ") => &h[7..],
_ => {
return Ok(json_error(
StatusCode::UNAUTHORIZED,
"missing or invalid authorization header",
))
}
};
match jsonwebtoken::decode::<serde_json::Value>(token, &self.decoding_key, &self.validation)
{
Ok(token_data) => {
if let Err(msg) = check_claims(&token_data.claims, requirement) {
return Ok(json_error(StatusCode::FORBIDDEN, msg));
}
let mut req = req;
req.extensions_mut().insert(token_data.claims);
next.run(req).await
}
Err(_) => Ok(json_error(StatusCode::UNAUTHORIZED, "invalid token")),
}
}
}
pub struct RateLimiter {
limiter: governor::RateLimiter<
governor::state::direct::NotKeyed,
governor::state::InMemoryState,
governor::clock::DefaultClock,
>,
}
impl RateLimiter {
pub fn new(duration: std::time::Duration, max_burst: u32) -> Self {
let burst = NonZeroU32::new(max_burst).unwrap_or(NonZeroU32::MIN);
let quota = governor::Quota::with_period(duration)
.expect("valid rate-limit duration")
.allow_burst(burst);
Self { limiter: governor::RateLimiter::direct(quota) }
}
pub fn per_second(max_burst: u32) -> Self {
Self::new(std::time::Duration::from_secs(1), max_burst)
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for RateLimiter {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
match self.limiter.check() {
Ok(()) => next.run(req).await,
Err(negative) => {
let clock = governor::clock::DefaultClock::default();
let now = clock.now();
let wait = negative.wait_time_from(now);
let retry_after_secs = wait.as_secs().max(1);
let mut resp = json_error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
let retry_val = HeaderValue::from_str(&retry_after_secs.to_string())
.unwrap_or_else(|_| HeaderValue::from_static("1"));
resp.headers_mut().insert("retry-after", retry_val.clone());
resp.headers_mut().insert("x-ratelimit-reset", retry_val);
Ok(resp)
}
}
}
}
/// Per-IP rate limiter using governor's keyed rate limiter.
/// Extracts client IP from connection info (requires `req.extensions().get::<SocketAddr>()`).
pub struct IpRateLimiter {
limiter: std::sync::Arc<
governor::RateLimiter<
String,
governor::state::keyed::DefaultKeyedStateStore<String>,
governor::clock::DefaultClock,
>,
>,
}
impl IpRateLimiter {
pub fn new(duration: std::time::Duration, max_burst: u32) -> Self {
let quota = governor::Quota::with_period(duration)
.expect("valid rate-limit duration for IpRateLimiter")
.allow_burst(
NonZeroU32::new(max_burst).expect("max_burst must be > 0 for IpRateLimiter"),
);
let limiter = std::sync::Arc::new(governor::RateLimiter::keyed(quota));
let limiter_clone = limiter.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
loop {
interval.tick().await;
limiter_clone.retain_recent();
}
});
Self { limiter }
}
pub fn per_second(max_burst: u32) -> Self {
Self::new(std::time::Duration::from_secs(1), max_burst)
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for IpRateLimiter {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
let ip = req
.extensions()
.get::<SocketAddr>()
.map(|a| a.ip().to_string())
.unwrap_or_else(|| "unknown".to_string());
match self.limiter.check_key(&ip) {
Ok(()) => next.run(req).await,
Err(negative) => {
let clock = governor::clock::DefaultClock::default();
let now = clock.now();
let wait = negative.wait_time_from(now);
let retry_after_secs = wait.as_secs().max(1);
let mut resp = json_error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
let retry_val = HeaderValue::from_str(&retry_after_secs.to_string())
.map_err(|e| anyhow::anyhow!("invalid retry-after: {e}"))?;
resp.headers_mut().insert("retry-after", retry_val.clone());
resp.headers_mut().insert("x-ratelimit-reset", retry_val);
Ok(resp)
}
}
}
}
// ---------------------------------------------------------------------------
// Per-route rate limiting
// ---------------------------------------------------------------------------
/// A single rate-limit rule matching a path prefix.
struct RateLimitRule {
/// Path prefix to match (e.g. "/api/search"). Empty string matches all paths.
prefix: String,
/// Optional method filter. `None` means all methods.
method: Option<Method>,
limiter: governor::RateLimiter<
governor::state::direct::NotKeyed,
governor::state::InMemoryState,
governor::clock::DefaultClock,
>,
}
/// Per-route rate limiter. Applies different rate limits to different path
/// prefixes and optionally HTTP methods.
///
/// # Example
///
/// ```ignore
/// use std::time::Duration;
///
/// let rl = PerRouteRateLimiter::new()
/// .add_rule("/api/search", None, Duration::from_secs(1), 100)
/// .add_rule("/api/export", Some(Method::POST), Duration::from_secs(1), 10);
/// ```
pub struct PerRouteRateLimiter {
rules: Vec<RateLimitRule>,
/// Fallback limiter applied when no rule matches. `None` means no limit.
fallback: Option<RateLimiter>,
}
impl PerRouteRateLimiter {
pub fn new() -> Self {
Self { rules: Vec::new(), fallback: None }
}
/// Add a rate-limit rule for a path prefix.
///
/// - `prefix`: Match paths starting with this string. Use `"/"` for all paths.
/// - `method`: Optional HTTP method filter. `None` matches all methods.
/// - `duration`: Time window for the rate limit (e.g. 1 second).
/// - `max_burst`: Maximum burst size within the time window.
pub fn add_rule(
mut self,
prefix: &str,
method: Option<Method>,
duration: Duration,
max_burst: u32,
) -> Self {
let burst = NonZeroU32::new(max_burst).unwrap_or(NonZeroU32::MIN);
let quota = governor::Quota::with_period(duration)
.expect("valid rate-limit duration for PerRouteRateLimiter")
.allow_burst(burst);
self.rules.push(RateLimitRule {
prefix: prefix.to_string(),
method,
limiter: governor::RateLimiter::direct(quota),
});
self
}
/// Set a fallback rate limiter for paths that don't match any rule.
pub fn with_fallback(mut self, limiter: RateLimiter) -> Self {
self.fallback = Some(limiter);
self
}
fn find_rule(&self, path: &str, method: &Method) -> Option<&RateLimitRule> {
self.rules
.iter()
.find(|r| path.starts_with(&r.prefix) && r.method.as_ref().is_none_or(|m| m == method))
}
}
impl Default for PerRouteRateLimiter {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for PerRouteRateLimiter {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
let path = req.uri().path().to_string();
let method = req.method().clone();
if let Some(rule) = self.find_rule(&path, &method) {
match rule.limiter.check() {
Ok(()) => next.run(req).await,
Err(negative) => {
let clock = governor::clock::DefaultClock::default();
let now = clock.now();
let wait = negative.wait_time_from(now);
let retry_after_secs = wait.as_secs().max(1);
let mut resp = json_error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
let retry_val = HeaderValue::from_str(&retry_after_secs.to_string())
.unwrap_or_else(|_| HeaderValue::from_static("1"));
resp.headers_mut().insert("retry-after", retry_val.clone());
resp.headers_mut().insert("x-ratelimit-reset", retry_val);
Ok(resp)
}
}
} else if let Some(ref fallback) = self.fallback {
// Delegate to the fallback global limiter
fallback.handle(req, next).await
} else {
// No rule matches and no fallback — allow through
next.run(req).await
}
}
}
fn json_error(status: StatusCode, msg: &str) -> Response<ResponseBody> {
let status_code: u16 = status.into();
let title = match status_code {
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
413 => "Payload Too Large",
422 => "Unprocessable Entity",
429 => "Too Many Requests",
500 => "Internal Server Error",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
_ => "Error",
};
let body = serde_json::json!({
"type": format!("https://justapi.dev/errors/{}", title.to_lowercase().replace(' ', "-")),
"title": title,
"status": status_code,
"detail": msg,
})
.to_string();
Response::builder()
.status(status)
.header("content-type", "application/problem+json")
.header("content-length", body.len().to_string())
.body(UnsyncBoxBody::new(
http_body_util::Full::new(Bytes::from(body))
.map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
))
.expect("Response::builder with valid inputs should never fail")
}
// ---------------------------------------------------------------------------
// API-key authentication (the "API-key scheme" from OpenAPI / FastAPI)
// ---------------------------------------------------------------------------
/// API-key authentication middleware.
///
/// Validates a key presented in a configurable request header (default
/// `x-api-key`) or, optionally, a query parameter. Valid keys map to a set of
/// claims (subject / roles / scopes) inserted into the request extensions for
/// downstream handlers. Per-path-prefix rules control whether a key is required
/// at all (e.g. public health endpoints vs. private `/v1/*` routes).
pub struct ApiKeyAuth {
header_name: hyper::header::HeaderName,
query_param: Option<String>,
keys: std::collections::HashMap<String, serde_json::Value>,
route_rules: Vec<(String, bool)>,
default_required: bool,
}
impl ApiKeyAuth {
/// Create an API-key authenticator reading keys from `header_name`
/// (e.g. `"x-api-key"`). No keys are valid until registered with
/// [`ApiKeyAuth::with_key`].
pub fn new(header_name: &str) -> Self {
Self {
header_name: hyper::header::HeaderName::from_bytes(header_name.as_bytes())
.expect("valid header name"),
query_param: None,
keys: std::collections::HashMap::new(),
route_rules: Vec::new(),
default_required: true,
}
}
/// Register a valid key with its associated claims (subject / roles / scopes).
pub fn with_key(mut self, key: &str, claims: serde_json::Value) -> Self {
self.keys.insert(key.to_string(), claims);
self
}
/// Also accept the key via this query parameter (in addition to the header).
pub fn with_query_param(mut self, name: &str) -> Self {
self.query_param = Some(name.to_string());
self
}
/// Require (or exempt) keys for paths starting with `path_prefix`.
pub fn require_for(mut self, path_prefix: &str, required: bool) -> Self {
self.route_rules.push((path_prefix.to_string(), required));
self
}
/// Set whether keys are required by default for paths without an explicit rule.
pub fn default_required(mut self, required: bool) -> Self {
self.default_required = required;
self
}
fn required_for_path(&self, path: &str) -> bool {
for (prefix, req) in &self.route_rules {
if path.starts_with(prefix) {
return *req;
}
}
self.default_required
}
fn extract_key<B>(&self, req: &Request<B>) -> Option<String> {
if let Some(v) = req.headers().get(&self.header_name).and_then(|v| v.to_str().ok()) {
return Some(v.to_string());
}
if let Some(qp) = &self.query_param {
if let Some(query) = req.uri().query() {
for pair in query.split('&') {
let mut it = pair.splitn(2, '=');
if let (Some(k), Some(v)) = (it.next(), it.next()) {
if k == qp {
return Some(v.to_string());
}
}
}
}
}
None
}
async fn handle_inner<B: Send + 'static>(
&self,
req: Request<B>,
next: Next<'_, B>,
) -> Result<Response<ResponseBody>> {
let path = req.uri().path().to_string();
if !self.required_for_path(&path) {
return next.run(req).await;
}
match self.extract_key(&req) {
Some(key) => {
if let Some(claims) = self.keys.get(&key) {
let mut req = req;
req.extensions_mut().insert(claims.clone());
next.run(req).await
} else {
Ok(json_error(StatusCode::UNAUTHORIZED, "invalid api key"))
}
}
None => Ok(json_error(StatusCode::UNAUTHORIZED, "missing api key")),
}
}
}
#[async_trait]
impl<B: Send + 'static> Middleware<B> for ApiKeyAuth {
async fn handle(&self, req: Request<B>, next: Next<'_, B>) -> Result<Response<ResponseBody>> {
self.handle_inner(req, next).await
}
}
// ---------------------------------------------------------------------------
// OAuth2 Password flow — token issuance
// ---------------------------------------------------------------------------
/// User validator for the OAuth2 password flow.
pub type UserValidator = Arc<dyn Fn(&str, &str) -> Option<serde_json::Value> + Send + Sync>;
/// OAuth2 Password-flow provider.
///
/// Issues signed JWTs in exchange for valid `username`/`password` credentials
/// (the Resource Owner Password Credentials Grant, RFC 6749 §4.3). The returned
/// token handler can be mounted at any path (default `/token`). Use
/// [`OAuth2Password::jwt_auth`] to obtain a pre-configured [`JwtAuth`] that
/// verifies the issued tokens.
///
/// # Example
///
/// ```ignore
/// let oauth2 = OAuth2Password::new(
/// |user, pass| {
/// if user == "alice" && pass == "secret" {
/// Some(serde_json::json!({"sub": "alice", "roles": ["user"]}))
/// } else { None }
/// },
/// jsonwebtoken::EncodingKey::from_secret(b"my_secret"),
/// jsonwebtoken::DecodingKey::from_secret(b"my_secret"),
/// );
/// // Register token endpoint + add JwtAuth middleware:
/// // server.with_oauth2_password(oauth2);
/// ```
pub struct OAuth2Password {
validate_user: UserValidator,
encoding_key: jsonwebtoken::EncodingKey,
decoding_key: jsonwebtoken::DecodingKey,
algorithm: jsonwebtoken::Algorithm,
pub(crate) token_path: String,
token_expiry: Duration,
issuer: Option<String>,
}
impl OAuth2Password {
/// Create a new OAuth2 password-flow provider.
///
/// `validate_user` is called with `(username, password)` and should return
/// `Some(claims)` on success (the `sub` claim is typically included) or
/// `None` on invalid credentials.
///
/// For symmetric (HS*) keys, the same secret bytes work for both encoding
/// and decoding. For asymmetric (RS*/ES*) algorithms, provide the private
/// key as `encoding_key` and the public key as `decoding_key`.
pub fn new(
validate_user: UserValidator,
encoding_key: jsonwebtoken::EncodingKey,
decoding_key: jsonwebtoken::DecodingKey,
) -> Self {
Self {
validate_user,
encoding_key,
decoding_key,
algorithm: jsonwebtoken::Algorithm::HS256,
token_path: "/token".to_string(),
token_expiry: Duration::from_secs(3600), // 1 hour
issuer: None,
}
}
/// Set the signing algorithm (default `HS256`).
pub fn with_algorithm(mut self, alg: jsonwebtoken::Algorithm) -> Self {
self.algorithm = alg;
self
}
/// Set the token endpoint path (default `/token`).
pub fn with_token_path(mut self, path: &str) -> Self {
self.token_path = path.to_string();
self
}
/// Set the access-token expiry (default 1 hour).
pub fn with_token_expiry(mut self, expiry: Duration) -> Self {
self.token_expiry = expiry;
self
}
/// Set the `iss` (issuer) claim included in issued tokens.
pub fn with_issuer(mut self, issuer: &str) -> Self {
self.issuer = Some(issuer.to_string());
self
}
/// Return a handler for the OAuth2 token endpoint, generic over body type
/// (works with `Incoming` in production and `Full<Bytes>` in tests).
///
/// The handler expects `POST` with `application/x-www-form-urlencoded` body
/// containing `grant_type=password`, `username`, and `password` fields.
/// On success it returns `{"access_token": "...", "token_type": "bearer"}`.
pub fn token_handler<B>(&self) -> HandlerFn<B>
where
B: http_body::Body<Data = Bytes> + Send + 'static,
B::Error: std::error::Error + Send + Sync + 'static,
{
let validate_user = self.validate_user.clone();
let encoding_key_ref = self.encoding_key.clone();
let algorithm = self.algorithm;
let token_expiry = self.token_expiry;
let issuer = self.issuer.clone();
let path = self.token_path.clone();
Arc::new(move |req: Request<B>| {
let validate_user = validate_user.clone();
let encoding_key_ref = encoding_key_ref.clone();
let algorithm = algorithm;
let token_expiry = token_expiry;
let issuer = issuer.clone();
let path = path.clone();
Box::pin(async move {
if req.method() != Method::POST {
return Ok(json_error(StatusCode::METHOD_NOT_ALLOWED, "only POST is allowed"));
}
if req.uri().path() != path {
return Ok(json_error(StatusCode::NOT_FOUND, "not found"));
}
let content_type =
req.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("");
if !content_type.starts_with("application/x-www-form-urlencoded") {
return Ok(json_error(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"expected application/x-www-form-urlencoded",
));
}
let body_bytes = req.collect().await.map_err(|e| anyhow::anyhow!(e))?.to_bytes();
let body_str = String::from_utf8_lossy(&body_bytes).to_string();
let params: HashMap<String, String> = serde_urlencoded::from_str(&body_str)
.map_err(|_| anyhow::anyhow!("bad form"))?;
let grant_type = params.get("grant_type").map(|s| s.as_str()).unwrap_or("");
if grant_type != "password" {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"unsupported grant_type, expected 'password'",
));
}
let username = params.get("username").map(|s| s.as_str()).unwrap_or("");
let password = params.get("password").map(|s| s.as_str()).unwrap_or("");
if username.is_empty() || password.is_empty() {
return Ok(json_error(
StatusCode::BAD_REQUEST,
"username and password are required",
));
}
let claims_value = match (validate_user)(username, password) {
Some(c) => c,
None => {
return Ok(json_error(
StatusCode::UNAUTHORIZED,
"invalid username or password",
))
}
};
let sub = claims_value
.get("sub")
.and_then(|v| v.as_str())
.unwrap_or(username)
.to_string();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let mut jwt_claims = serde_json::Map::new();
jwt_claims.insert("sub".to_string(), serde_json::Value::String(sub));
jwt_claims.insert(
"iat".to_string(),
serde_json::Value::Number(serde_json::Number::from(now)),
);
jwt_claims.insert(
"exp".to_string(),
serde_json::Value::Number(serde_json::Number::from(
now + token_expiry.as_secs(),
)),
);
if let Some(iss) = &issuer {
jwt_claims.insert("iss".to_string(), serde_json::Value::String(iss.clone()));
}
// Merge user claims
if let Some(obj) = claims_value.as_object() {
for (k, v) in obj {
if !["sub", "iat", "exp", "iss"].contains(&k.as_str()) {
jwt_claims.insert(k.clone(), v.clone());
}
}
}
let header = jsonwebtoken::Header::new(algorithm);
let token = jsonwebtoken::encode(
&header,
&serde_json::Value::Object(jwt_claims),
&encoding_key_ref,
)
.map_err(|e| anyhow::anyhow!("token encoding failed: {}", e))?;
let body = serde_json::json!({
"access_token": token,
"token_type": "bearer",
"expires_in": token_expiry.as_secs(),
});
let body_bytes = serde_json::to_vec(&body)?;
let resp = Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.header("content-length", body_bytes.len().to_string())
.header("cache-control", "no-store")
.body(UnsyncBoxBody::new(
http_body_util::Full::new(Bytes::from(body_bytes))
.map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
))
.unwrap();
Ok(resp)
})
})
}
/// Obtain a [`JwtAuth`] pre-configured to verify tokens issued by this
/// provider. You may add path rules via the returned builder.
pub fn jwt_auth(&self) -> JwtAuth {
let mut validation = jsonwebtoken::Validation::new(self.algorithm);
if let Some(iss) = &self.issuer {
validation.iss = Some([iss.clone()].into());
}
JwtAuth {
validation,
decoding_key: self.decoding_key.clone(),
route_rules: Vec::new(),
default_requirement: JwtRequirement::Required,
warned_aud_iss: std::sync::atomic::AtomicBool::new(false),
}
}
}
// ---------------------------------------------------------------------------
// Tests — use Request<http_body_util::Full<Bytes>> for constructability
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::json_response;
type TestBody = http_body_util::Full<Bytes>;
fn test_req(method: Method, uri: &str) -> Request<TestBody> {
Request::builder().method(method).uri(uri).body(TestBody::new(Bytes::new())).unwrap()
}
fn test_req_with_header(method: Method, uri: &str, key: &str, val: &str) -> Request<TestBody> {
let mut req = test_req(method, uri);
req.headers_mut().insert(
hyper::header::HeaderName::from_bytes(key.as_bytes()).unwrap(),
hyper::header::HeaderValue::from_str(val).unwrap(),
);
req
}
#[tokio::test]
async fn test_cors_preflight() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(Cors::permissive());
let req = test_req_with_header(Method::OPTIONS, "/hello", "origin", "https://example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
assert_eq!(resp.headers()["access-control-allow-origin"], "*");
}
#[tokio::test]
async fn test_cors_headers_added() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(Cors::permissive());
let req = test_req_with_header(Method::GET, "/hello", "origin", "https://example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.headers()["access-control-allow-origin"], "*");
}
#[tokio::test]
async fn test_security_headers() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "hi")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(SecurityHeaders::default());
let req = test_req(Method::GET, "/hello");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.headers()["x-content-type-options"], "nosniff");
assert_eq!(resp.headers()["x-frame-options"], "DENY");
}
#[tokio::test]
async fn test_jwt_missing_header() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "hi")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(JwtAuth::from_secret(b"secret"));
let req = test_req(Method::GET, "/hello");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_jwt_invalid_token() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "hi")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(JwtAuth::from_secret(b"secret"));
let req = test_req_with_header(
Method::GET,
"/hello",
"authorization",
"Bearer invalid.token.here",
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_jwt_valid_token() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "hi")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(JwtAuth::from_secret(b"secret"));
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&serde_json::json!({"sub": "123", "exp": 9999999999u64}),
&jsonwebtoken::EncodingKey::from_secret(b"secret"),
)
.unwrap();
let req = test_req_with_header(
Method::GET,
"/hello",
"authorization",
&format!("Bearer {}", token),
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_multiple_middlewares() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "hi")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(Cors::permissive());
chain.add(SecurityHeaders::default());
let req = test_req_with_header(Method::GET, "/hello", "origin", "https://example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.headers()["access-control-allow-origin"], "*");
assert_eq!(resp.headers()["x-content-type-options"], "nosniff");
}
#[tokio::test]
async fn test_middleware_chain_no_middleware() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "direct")) })
});
let chain = MiddlewareChain::new(handler);
let req = test_req(Method::GET, "/hello");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
// --- Enhanced Cors tests -------------------------------------------------
#[tokio::test]
async fn test_cors_specific_origin_allowed() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(Cors::new().allow_origin("https://example.com"));
let req = test_req_with_header(Method::GET, "/hello", "origin", "https://example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.headers()["access-control-allow-origin"], "https://example.com");
assert_eq!(resp.headers()["vary"], "Origin");
}
#[tokio::test]
async fn test_cors_specific_origin_rejected() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(Cors::new().allow_origin("https://example.com"));
let req = test_req_with_header(Method::GET, "/hello", "origin", "https://evil.com");
let resp = chain.run(req).await.unwrap();
assert!(!resp.headers().contains_key("access-control-allow-origin"));
}
#[tokio::test]
async fn test_cors_credentials() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(Cors::new().allow_origin("https://example.com").allow_credentials());
let req = test_req_with_header(Method::GET, "/hello", "origin", "https://example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.headers()["access-control-allow-credentials"], "true");
}
#[tokio::test]
async fn test_cors_expose_headers() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
Cors::new()
.allow_origin("https://example.com")
.expose_headers(&["x-custom-header", "x-trace-id"]),
);
let req = test_req_with_header(Method::GET, "/hello", "origin", "https://example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.headers()["access-control-expose-headers"], "x-custom-header, x-trace-id");
}
#[tokio::test]
async fn test_cors_preflight_with_credentials() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
Cors::new()
.allow_origin("https://app.example.com")
.allow_credentials()
.allow_methods("POST, OPTIONS")
.allow_headers("Authorization, Content-Type"),
);
let req =
test_req_with_header(Method::OPTIONS, "/hello", "origin", "https://app.example.com");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
assert_eq!(resp.headers()["access-control-allow-origin"], "https://app.example.com");
assert_eq!(resp.headers()["access-control-allow-credentials"], "true");
assert_eq!(resp.headers()["vary"], "Origin");
}
// --- Enhanced JwtAuth tests ---------------------------------------------
#[tokio::test]
async fn test_jwt_no_auth_for_public_route() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "public")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
JwtAuth::from_secret(b"secret")
.default_requirement(JwtRequirement::Required)
.require_for("/public", JwtRequirement::None),
);
// No auth header — should pass for /public
let req = test_req(Method::GET, "/public/info");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_jwt_required_for_protected_route() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "protected")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
JwtAuth::from_secret(b"secret")
.default_requirement(JwtRequirement::Required)
.require_for("/public", JwtRequirement::None),
);
// No auth header for /admin — should fail
let req = test_req(Method::GET, "/admin/data");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_jwt_roles_check() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "admin only")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
JwtAuth::from_secret(b"secret")
.default_requirement(JwtRequirement::None)
.require_for("/admin", JwtRequirement::Roles(vec!["admin".to_string()])),
);
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&serde_json::json!({"sub": "123", "roles": ["admin"], "exp": 9999999999u64}),
&jsonwebtoken::EncodingKey::from_secret(b"secret"),
)
.unwrap();
let req = test_req_with_header(
Method::GET,
"/admin/data",
"authorization",
&format!("Bearer {}", token),
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_jwt_roles_missing() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "admin only")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
JwtAuth::from_secret(b"secret")
.default_requirement(JwtRequirement::None)
.require_for("/admin", JwtRequirement::Roles(vec!["admin".to_string()])),
);
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&serde_json::json!({"sub": "123", "roles": ["user"], "exp": 9999999999u64}),
&jsonwebtoken::EncodingKey::from_secret(b"secret"),
)
.unwrap();
let req = test_req_with_header(
Method::GET,
"/admin/data",
"authorization",
&format!("Bearer {}", token),
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn test_jwt_scopes_check() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "scoped")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
JwtAuth::from_secret(b"secret")
.default_requirement(JwtRequirement::None)
.require_for("/api", JwtRequirement::Scopes(vec!["read:data".to_string()])),
);
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&serde_json::json!({"sub": "123", "scope": "read:data write:data", "exp": 9999999999u64}),
&jsonwebtoken::EncodingKey::from_secret(b"secret"),
)
.unwrap();
let req = test_req_with_header(
Method::GET,
"/api/resource",
"authorization",
&format!("Bearer {}", token),
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_jwt_scopes_missing() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "scoped")) })
});
let mut chain = MiddlewareChain::new(handler);
chain.add(
JwtAuth::from_secret(b"secret")
.default_requirement(JwtRequirement::None)
.require_for("/api", JwtRequirement::Scopes(vec!["admin:all".to_string()])),
);
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&serde_json::json!({"sub": "123", "scope": "read:data", "exp": 9999999999u64}),
&jsonwebtoken::EncodingKey::from_secret(b"secret"),
)
.unwrap();
let req = test_req_with_header(
Method::GET,
"/api/resource",
"authorization",
&format!("Bearer {}", token),
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}
// --- ApiKeyAuth tests ------------------------------------------------
fn api_chain(handler: HandlerFn<TestBody>, auth: ApiKeyAuth) -> MiddlewareChain<TestBody> {
let mut chain = MiddlewareChain::new(handler);
chain.add(auth);
chain
}
#[tokio::test]
async fn api_key_valid_header_passes() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let auth = ApiKeyAuth::new("x-api-key")
.with_key("secret-123", serde_json::json!({"sub": "user-1", "roles": ["admin"]}));
let chain = api_chain(handler, auth);
let req = test_req_with_header(Method::GET, "/v1/models", "x-api-key", "secret-123");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_missing_is_401() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let auth = ApiKeyAuth::new("x-api-key").with_key("secret-123", serde_json::json!({}));
let chain = api_chain(handler, auth);
let req = test_req(Method::GET, "/v1/models");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_invalid_is_401() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let auth = ApiKeyAuth::new("x-api-key").with_key("secret-123", serde_json::json!({}));
let chain = api_chain(handler, auth);
let req = test_req_with_header(Method::GET, "/v1/models", "x-api-key", "wrong");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_query_param_accepted() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let auth = ApiKeyAuth::new("x-api-key")
.with_query_param("api_key")
.with_key("secret-123", serde_json::json!({}));
let chain = api_chain(handler, auth);
let req = test_req(Method::GET, "/v1/models?api_key=secret-123");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_exempt_path_skips_auth() {
let handler: HandlerFn<TestBody> = Arc::new(|_req: Request<TestBody>| {
Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
});
let auth = ApiKeyAuth::new("x-api-key")
.require_for("/public", false)
.with_key("secret-123", serde_json::json!({}));
let chain = api_chain(handler, auth);
// No key on an exempt path → 200.
let req = test_req(Method::GET, "/public/health");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// No key on a protected path → 401.
let req = test_req(Method::GET, "/v1/models");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_claims_injected_to_extensions() {
let seen = Arc::new(std::sync::Mutex::new(None::<serde_json::Value>));
let seen2 = seen.clone();
let handler: HandlerFn<TestBody> = Arc::new(move |req: Request<TestBody>| {
let s = seen2.clone();
Box::pin(async move {
let claims = req.extensions().get::<serde_json::Value>().cloned();
*s.lock().unwrap() = claims;
Ok(json_response(StatusCode::OK, "ok"))
})
});
let auth = ApiKeyAuth::new("x-api-key")
.with_key("secret-123", serde_json::json!({"sub": "user-9"}));
let chain = api_chain(handler, auth);
let req = test_req_with_header(Method::GET, "/v1/models", "x-api-key", "secret-123");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let claims = seen.lock().unwrap();
assert_eq!(claims.as_ref().unwrap()["sub"], "user-9");
}
// --- OAuth2Password tests ---------------------------------------------
fn form_req(method: Method, uri: &str, form_body: &str) -> Request<TestBody> {
Request::builder()
.method(method)
.uri(uri)
.header("content-type", "application/x-www-form-urlencoded")
.body(TestBody::new(Bytes::from(form_body.to_string())))
.unwrap()
}
#[tokio::test]
async fn oauth2_non_post_returns_405() {
let oauth2 = OAuth2Password::new(
Arc::new(|_, _| Some(serde_json::json!({"sub": "test"}))),
jsonwebtoken::EncodingKey::from_secret(b"test"),
jsonwebtoken::DecodingKey::from_secret(b"test"),
);
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req = test_req(Method::GET, "/token");
let resp = handler(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}
#[tokio::test]
async fn oauth2_wrong_content_type_returns_415() {
let oauth2 = OAuth2Password::new(
Arc::new(|_, _| Some(serde_json::json!({"sub": "test"}))),
jsonwebtoken::EncodingKey::from_secret(b"test"),
jsonwebtoken::DecodingKey::from_secret(b"test"),
);
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req = Request::builder()
.method(Method::POST)
.uri("/token")
.header("content-type", "application/json")
.body(TestBody::new(Bytes::from(r#"{"a":1}"#)))
.unwrap();
let resp = handler(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
}
#[tokio::test]
async fn oauth2_bad_grant_type_returns_400() {
let oauth2 = OAuth2Password::new(
Arc::new(|_, _| Some(serde_json::json!({"sub": "test"}))),
jsonwebtoken::EncodingKey::from_secret(b"test"),
jsonwebtoken::DecodingKey::from_secret(b"test"),
);
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req = form_req(
Method::POST,
"/token",
"grant_type=client_credentials&username=alice&password=secret",
);
let resp = handler(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn oauth2_missing_credentials_returns_400() {
let oauth2 = OAuth2Password::new(
Arc::new(|_, _| Some(serde_json::json!({"sub": "test"}))),
jsonwebtoken::EncodingKey::from_secret(b"test"),
jsonwebtoken::DecodingKey::from_secret(b"test"),
);
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req = form_req(Method::POST, "/token", "grant_type=password");
let resp = handler(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn oauth2_invalid_credentials_returns_401() {
let oauth2 = OAuth2Password::new(
Arc::new(|u, p| {
if u == "alice" && p == "correct" {
Some(serde_json::json!({"sub": "alice"}))
} else {
None
}
}),
jsonwebtoken::EncodingKey::from_secret(b"test"),
jsonwebtoken::DecodingKey::from_secret(b"test"),
);
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req =
form_req(Method::POST, "/token", "grant_type=password&username=alice&password=wrong");
let resp = handler(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn oauth2_valid_credentials_returns_token() {
let oauth2 = OAuth2Password::new(
Arc::new(|u, p| {
if u == "alice" && p == "secret" {
Some(serde_json::json!({"sub": "alice", "roles": ["user"]}))
} else {
None
}
}),
jsonwebtoken::EncodingKey::from_secret(b"test"),
jsonwebtoken::DecodingKey::from_secret(b"test"),
);
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req =
form_req(Method::POST, "/token", "grant_type=password&username=alice&password=secret");
let resp = handler(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body: serde_json::Value = serde_json::from_slice(
&http_body_util::BodyExt::collect(resp.into_body()).await.unwrap().to_bytes(),
)
.unwrap();
assert!(body.get("access_token").and_then(|v| v.as_str()).is_some());
assert_eq!(body["token_type"], "bearer");
assert!(body["expires_in"].as_u64().unwrap() > 0);
}
#[tokio::test]
async fn oauth2_issued_token_verified_by_jwt_auth() {
let oauth2 = OAuth2Password::new(
Arc::new(|u, p| {
if u == "alice" && p == "secret" {
Some(serde_json::json!({"sub": "alice", "roles": ["admin"]}))
} else {
None
}
}),
jsonwebtoken::EncodingKey::from_secret(b"test_key"),
jsonwebtoken::DecodingKey::from_secret(b"test_key"),
);
// 1. Get a token from the token handler.
let handler: HandlerFn<TestBody> = oauth2.token_handler();
let req =
form_req(Method::POST, "/token", "grant_type=password&username=alice&password=secret");
let resp = handler(req).await.unwrap();
let body: serde_json::Value = serde_json::from_slice(
&http_body_util::BodyExt::collect(resp.into_body()).await.unwrap().to_bytes(),
)
.unwrap();
let token = body["access_token"].as_str().unwrap().to_string();
// 2. Create a JwtAuth from the OAuth2 provider and verify.
let jwt_auth = oauth2.jwt_auth();
let handler2: HandlerFn<TestBody> = Arc::new(|req: Request<TestBody>| {
// The JwtAuth middleware injects claims into extensions
let claims = req.extensions().get::<serde_json::Value>().cloned();
Box::pin(async move {
let body = serde_json::json!({
"claims": claims,
"ok": true,
});
Ok(json_response(StatusCode::OK, &serde_json::to_string(&body).unwrap()))
})
});
let mut chain = MiddlewareChain::new(handler2);
chain.add(jwt_auth);
let req = test_req_with_header(
Method::GET,
"/protected",
"authorization",
&format!("Bearer {}", token),
);
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
// --- Per-route rate limiter tests (Phase 55.1) ---
#[tokio::test]
async fn per_route_rate_limit_allows_matching_prefix() {
let rl = PerRouteRateLimiter::new().add_rule(
"/api/",
None,
std::time::Duration::from_secs(1),
10,
);
let handler: HandlerFn<TestBody> =
Arc::new(|_| Box::pin(async { Ok(json_response(StatusCode::OK, r#"{"ok":true}"#)) }));
let mut chain = MiddlewareChain::new(handler);
chain.add(rl);
let req = test_req(Method::GET, "/api/search");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn per_route_rate_limit_rejects_when_exceeded() {
let rl = PerRouteRateLimiter::new().add_rule(
"/api/",
None,
std::time::Duration::from_secs(1),
1,
);
let handler: HandlerFn<TestBody> =
Arc::new(|_| Box::pin(async { Ok(json_response(StatusCode::OK, r#"{"ok":true}"#)) }));
let mut chain = MiddlewareChain::new(handler);
chain.add(rl);
// First request should pass
let req = test_req(Method::GET, "/api/search");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// Second request should be rate limited
let req = test_req(Method::GET, "/api/search");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn per_route_rate_limit_different_limits_per_prefix() {
let rl = PerRouteRateLimiter::new()
.add_rule("/api/fast", None, std::time::Duration::from_secs(1), 100)
.add_rule("/api/slow", None, std::time::Duration::from_secs(1), 1);
let handler: HandlerFn<TestBody> =
Arc::new(|_| Box::pin(async { Ok(json_response(StatusCode::OK, r#"{"ok":true}"#)) }));
let mut chain = MiddlewareChain::new(handler);
chain.add(rl);
// /api/fast should allow many requests
for _ in 0..5 {
let req = test_req(Method::GET, "/api/fast");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
// /api/slow should limit after 1
let req = test_req(Method::GET, "/api/slow");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = test_req(Method::GET, "/api/slow");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn per_route_rate_limit_method_filter() {
let rl = PerRouteRateLimiter::new().add_rule(
"/api/",
Some(Method::POST),
std::time::Duration::from_secs(1),
1,
);
let handler: HandlerFn<TestBody> =
Arc::new(|_| Box::pin(async { Ok(json_response(StatusCode::OK, r#"{"ok":true}"#)) }));
let mut chain = MiddlewareChain::new(handler);
chain.add(rl);
// GET should pass (no rule matches)
let req = test_req(Method::GET, "/api/data");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// First POST should pass
let req = test_req(Method::POST, "/api/data");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// Second POST should be limited
let req = test_req(Method::POST, "/api/data");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn per_route_rate_limit_no_fallback_allows_unmatched() {
let rl = PerRouteRateLimiter::new().add_rule(
"/api/",
None,
std::time::Duration::from_secs(1),
1,
);
let handler: HandlerFn<TestBody> =
Arc::new(|_| Box::pin(async { Ok(json_response(StatusCode::OK, r#"{"ok":true}"#)) }));
let mut chain = MiddlewareChain::new(handler);
chain.add(rl);
// Unmatched path should always pass (no fallback, no rule)
for _ in 0..10 {
let req = test_req(Method::GET, "/other/path");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
}
#[tokio::test]
async fn per_route_rate_limit_fallback_applies_to_unmatched() {
let rl = PerRouteRateLimiter::new()
.add_rule("/api/", None, std::time::Duration::from_secs(1), 1)
.with_fallback(RateLimiter::new(std::time::Duration::from_secs(1), 1));
let handler: HandlerFn<TestBody> =
Arc::new(|_| Box::pin(async { Ok(json_response(StatusCode::OK, r#"{"ok":true}"#)) }));
let mut chain = MiddlewareChain::new(handler);
chain.add(rl);
// First request to unmatched path passes (uses fallback)
let req = test_req(Method::GET, "/other/path");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// Second request to unmatched path is limited by fallback
let req = test_req(Method::GET, "/other/path");
let resp = chain.run(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
}
}