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
// HTTP request and response types
use crate::body::RequestBody;
use crate::extensions::Extensions;
use crate::headers::HeaderMap;
use crate::query::{QueryPairs, QueryView, parse as parse_query};
use crate::{ByteStr, Method};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::{Arc, OnceLock};
/// Route parameters captured from the request target.
///
/// Names are `&'static str` from the compiled route pattern (see
/// [`crate::param_intern`]), so the name half of a match is free. Values are
/// `Bytes` the matchers fill with `Bytes::copy_from_slice`, so a match costs one
/// small copy per captured value. Four inline slots covers the overwhelming
/// majority of routes.
pub type RouteParams = SmallVec<[(&'static str, Bytes); 4]>;
/// Read helpers for [`RouteParams`].
///
/// The type is a `SmallVec` of pairs rather than a map, so `get` on it means
/// "index into the slice". This is the by-name lookup.
pub trait RouteParamsExt {
/// The value captured for `name`, as UTF-8.
fn get_str(&self, name: &str) -> Option<&str>;
/// The value captured for `name`, raw.
fn get_bytes(&self, name: &str) -> Option<&Bytes>;
}
impl RouteParamsExt for RouteParams {
#[inline]
fn get_str(&self, name: &str) -> Option<&str> {
self.get_bytes(name)
.and_then(|v| std::str::from_utf8(v).ok())
}
#[inline]
fn get_bytes(&self, name: &str) -> Option<&Bytes> {
self.iter().find(|(k, _)| *k == name).map(|(_, v)| v)
}
}
/// The memoized query pairs.
///
/// `OnceLock` rather than `OnceCell` because `HttpRequest` must stay `Sync`:
/// extractors hold `&HttpRequest` across an `await` inside a `Send` future, and
/// `&T: Send` requires `T: Sync`.
#[derive(Debug, Default)]
pub struct QueryCache(OnceLock<QueryPairs>);
impl Clone for QueryCache {
/// A clone starts cold.
///
/// Carrying the parsed pairs across a clone would be wrong, not merely
/// wasteful: `path` is a public field, so a caller can clone a request and
/// then change its target. A cold cache cannot answer for the wrong path.
fn clone(&self) -> Self {
Self(OnceLock::new())
}
}
/// HTTP request wrapper
///
/// The path and body are `Bytes`-backed, so cloning a request is a handful of
/// refcount bumps rather than a deep copy of the target and payload.
#[derive(Debug, Clone)]
pub struct HttpRequest {
/// The request method.
///
/// Was a `String`. An unrecognized token is carried as `Method::Other`
/// rather than rejected here; routing answers it with 404
/// ([`crate::Error::RouteNotFound`]) since no route can match the token.
pub method: Method,
/// The raw request target, query string included.
///
/// Was a `String`. A `ByteStr` so it can be a slice of the connection read
/// buffer, which it is under the default `h1-backend` feature;
/// `Deref<Target = str>` keeps `&req.path` working wherever a `&str` is
/// wanted.
pub path: ByteStr,
/// Request headers stored in a SmallVec-backed `HeaderMap`.
///
/// For typical requests (<12 headers) this is stored inline on the stack,
/// avoiding the per-request HashMap heap allocation on the read path.
/// The API is HashMap-compatible (`get`/`insert`/`iter`/`contains_key`/...),
/// with case-insensitive header name lookup.
pub headers: HeaderMap,
/// The request body.
///
/// Was a `Vec<u8>` shadowed by an optional `Bytes` that could disagree with
/// it. One field, always authoritative.
pub body: Bytes,
pub path_params: RouteParams,
/// Type-safe extensions for storing application state.
///
/// Use this to pass typed data to handlers without DI container lookups.
/// Access via the `State<T>` extractor for zero-cost state retrieval.
pub extensions: Extensions,
/// The address of the socket this request arrived on, when the serve path
/// knows it.
///
/// This is the only client identifier a handler can trust. Every address in
/// a header — `X-Forwarded-For`, `X-Real-IP`, `Forwarded` — is set by the
/// caller, so an application that rate-limits, deduplicates, or logs by
/// "client address" without this field is keyed on a value the client
/// chooses.
///
/// Behind a proxy the peer is the proxy, so this is usually the input to a
/// decision rather than the answer. [`HttpRequest::client_address`] makes
/// that decision; prefer it over reading this field and a header directly,
/// because the direction the forwarded chain grows in is easy to get
/// backwards.
///
/// `None` means the address is genuinely unknown, not `0.0.0.0`: a request
/// built by hand, by [`HttpRequest::new`], by a test, or by a transport that
/// has no socket. Callers must handle it rather than be handed a plausible
/// lie — an unwrap-shaped default is how a fabricated address ends up in an
/// audit log.
///
/// Populated by the HTTP/1.1, HTTP/2 and HTTP/3 serve paths.
pub peer: Option<SocketAddr>,
/// Parsed lazily by [`HttpRequest::query`].
query_cache: QueryCache,
}
impl HttpRequest {
/// Create a request.
///
/// Generic in the method so every existing `HttpRequest::new("GET", …)`
/// call site compiles unchanged.
#[inline]
pub fn new(method: impl Into<Method>, path: impl Into<ByteStr>) -> Self {
Self {
method: method.into(),
path: path.into(),
headers: HeaderMap::new(),
body: Bytes::new(),
path_params: RouteParams::new(),
extensions: Extensions::new(),
peer: None,
query_cache: QueryCache::default(),
}
}
/// Set the socket peer address.
///
/// Serve paths call this; handlers read [`HttpRequest::peer`]. Taking
/// `Option` rather than `SocketAddr` so a transport that only sometimes
/// knows the address does not have to branch at the call site.
#[inline]
pub fn with_peer(mut self, peer: Option<SocketAddr>) -> Self {
self.peer = peer;
self
}
/// The client address to attribute this request to, given how many reverse
/// proxies sit in front of the process.
///
/// `X-Forwarded-For` is a comma-separated list `client, proxy1, proxy2, …`
/// that each proxy **appends** to. So the rightmost hops are the ones your
/// own infrastructure added and the only ones worth believing; everything to
/// the left of them is whatever the client sent, including entries it
/// invented. The client is therefore selected `depth`-from-the-right
/// (1-indexed): with one trusted proxy, the rightmost hop is the address
/// that proxy actually observed.
///
/// Taking the *leftmost* entry instead — the obvious reading of "the first
/// one is the client" — is a spoof: a caller sends
/// `X-Forwarded-For: 198.51.100.9`, the real proxy appends the true address,
/// and the leftmost entry is the fabricated one. That defeats rate limiting
/// (rotate it per request for a fresh bucket) and abuse attribution (name a
/// victim and let them absorb it).
///
/// Every `X-Forwarded-For` field line is joined, in order, before the list
/// is split. RFC 9110 §5.3 makes a field that appears twice identical to one
/// field carrying both values comma-joined, and proxies do emit the
/// two-line form — HAProxy's `option forwardfor` and several ingress
/// configurations add their own field line rather than extending the
/// client's. Reading only the first line there would return the line the
/// *client* wrote, which is the spoof above reached by a different route:
/// the entries your infrastructure added would be on the second line and
/// never looked at.
///
/// `trusted_proxy_depth` of `0` means no proxy is trusted, so the header is
/// ignored entirely and the socket peer is used. That is the correct default
/// for a process reachable directly.
///
/// Returns `None` when the address is genuinely unknown: no peer and no
/// usable header, or a `depth` deeper than the chain actually present, which
/// means the deployment does not match the configuration and no entry in the
/// list can be trusted. Callers must handle it rather than be handed a
/// plausible lie.
///
/// Mirrors `forwarded_ip_at_depth` in `armature-ratelimit`, which needs the
/// same rule; this is the shared implementation now that the peer is
/// available here.
///
/// # Example
///
/// ```
/// use armature_core::HttpRequest;
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let proxy = SocketAddr::from(([10, 0, 0, 1], 5555));
/// let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy));
/// // A client that tried to pass itself off as 198.51.100.9; the real proxy
/// // appended what it actually saw.
/// req.headers.insert("X-Forwarded-For", "198.51.100.9, 203.0.113.7");
///
/// // One trusted proxy: the rightmost hop is what it observed.
/// assert_eq!(
/// req.client_address(1),
/// Some(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)))
/// );
///
/// // No proxy trusted: the header is ignored and the socket wins.
/// assert_eq!(req.client_address(0), Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));
/// ```
pub fn client_address(&self, trusted_proxy_depth: usize) -> Option<IpAddr> {
if trusted_proxy_depth == 0 {
return self.peer.map(|peer| peer.ip());
}
// Across every field line, not just the first. A repeated field is one
// list (RFC 9110 §5.3), and a proxy that adds its own line instead of
// extending the client's puts the only entries worth believing on a
// line `get` would never reach. Splitting each line and chaining them is
// the same sequence joining them with commas would produce, without the
// intermediate `String`.
// Empty elements are kept rather than filtered, which looks like
// sloppiness and is the opposite. Discarding them shortens the list,
// and since the entry is chosen by counting from the *right*, a shorter
// list slides the index one position further left — onto an entry the
// client supplied. A malformed or empty hop means the chain is not the
// one the deployment was configured for, and the safe answer to that is
// no answer: the empty string fails `parse` below and the function
// returns `None`.
let hops: Vec<&str> = self
.headers
.get_all("X-Forwarded-For")
.into_iter()
.flat_map(|line| line.split(','))
.map(str::trim)
.collect();
// Counting from the right. A depth deeper than the chain present means
// the request did not traverse the proxies it was configured to, so
// there is no entry here anyone put there on purpose.
let index = hops.len().checked_sub(trusted_proxy_depth)?;
hops.get(index)?.parse().ok()
}
/// Create a new request with pre-allocated extensions capacity.
#[inline]
pub fn with_extensions_capacity(
method: impl Into<Method>,
path: impl Into<ByteStr>,
capacity: usize,
) -> Self {
Self {
method: method.into(),
path: path.into(),
headers: HeaderMap::new(),
body: Bytes::new(),
path_params: RouteParams::new(),
extensions: Extensions::with_capacity(capacity),
peer: None,
query_cache: QueryCache::default(),
}
}
/// Create a new request with a Bytes body (zero-copy).
///
/// This is the most efficient way to create a request from Hyper's body,
/// as it avoids copying the body data.
#[inline]
pub fn with_bytes_body(
method: impl Into<Method>,
path: impl Into<ByteStr>,
body: Bytes,
) -> Self {
Self {
method: method.into(),
path: path.into(),
headers: HeaderMap::new(),
body,
path_params: RouteParams::new(),
extensions: Extensions::new(),
peer: None,
query_cache: QueryCache::default(),
}
}
/// Set the body (zero-copy).
#[inline]
pub fn set_body_bytes(&mut self, bytes: Bytes) {
self.body = bytes;
}
/// The body as `Bytes`. A refcount bump, not a copy.
#[inline]
pub fn body_bytes(&self) -> Bytes {
self.body.clone()
}
/// The body as a byte slice.
#[inline]
pub fn body_slice(&self) -> &[u8] {
&self.body
}
/// The body as a byte slice.
#[inline]
pub fn body_ref(&self) -> &[u8] {
&self.body
}
/// The request target as a string, query string included.
#[inline]
pub fn path_str(&self) -> &str {
self.path.as_str()
}
/// The request target with any query string removed.
///
/// This is what routing matches on, and what most callers mean when they
/// say "the path" — `path`/`path_str` are the raw target, which is what the
/// query is parsed out of.
#[inline]
pub fn path_only(&self) -> &str {
self.path
.split_once('?')
.map_or(self.path.as_str(), |(p, _)| p)
}
/// Get the body as a RequestBody (zero-copy wrapper).
#[inline]
pub fn request_body(&self) -> RequestBody {
RequestBody::from_bytes(self.body_bytes())
}
/// Whether the body holds anything.
///
/// Kept for call-site compatibility from when the body could live in either
/// of two fields; it is always `Bytes` now.
#[inline]
pub fn has_bytes_body(&self) -> bool {
!self.body.is_empty()
}
/// The method as a string, for logging and for code that compares tokens.
#[inline]
pub fn method_str(&self) -> &str {
self.method.as_str()
}
/// Set the body from a `Vec<u8>`, taking over its allocation.
#[inline]
pub fn set_body(&mut self, body: Vec<u8>) {
self.body = Bytes::from(body);
}
/// Create a request from all parts (for compatibility in tests).
#[inline]
pub fn from_parts(
method: impl Into<Method>,
path: impl Into<ByteStr>,
headers: HashMap<String, String>,
body: Vec<u8>,
path_params: HashMap<String, String>,
query_params: HashMap<String, String>,
) -> Self {
// Names are interned rather than borrowed: `from_parts` is a
// compatibility shim taking an owned map, so there is no route pattern
// to borrow a `&'static str` from.
let path_params: RouteParams = path_params
.into_iter()
.map(|(k, v)| (crate::param_intern::intern(&k), Bytes::from(v)))
.collect();
// `query_params` is accepted for source compatibility and ignored: the
// query now comes from `path`, parsed on demand. Callers that need one
// honoured should put it in the path.
let _ = query_params;
Self {
method: method.into(),
path: path.into(),
headers: headers.into(),
body: Bytes::from(body),
path_params,
extensions: Extensions::new(),
// This constructor builds a request from parts a caller supplies,
// so there is no socket to name. `with_peer` sets one.
peer: None,
query_cache: QueryCache::default(),
}
}
/// Insert a typed value into request extensions.
///
/// Use this to pass application state to handlers.
///
/// # Example
///
/// ```rust,ignore
/// let mut request = HttpRequest::new("GET", "/");
/// request.insert_extension(app_state);
/// ```
#[inline]
pub fn insert_extension<T: Send + Sync + 'static>(&mut self, value: T) {
self.extensions.insert(value);
}
/// Insert an Arc-wrapped value into request extensions.
///
/// This is more efficient when you already have an Arc.
#[inline]
pub fn insert_extension_arc<T: Send + Sync + 'static>(&mut self, value: Arc<T>) {
self.extensions.insert_arc(value);
}
/// Get a reference to a typed extension.
///
/// Returns `None` if no value of this type exists.
#[inline]
pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.extensions.get::<T>()
}
/// Get an Arc reference to a typed extension.
#[inline]
pub fn extension_arc<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
self.extensions.get_arc::<T>()
}
/// Parse the request body as JSON.
///
/// With the `simd-json` feature enabled, this uses SIMD-accelerated parsing
/// which can be 2-3x faster on modern x86_64 CPUs.
///
/// # Example
///
/// ```rust,ignore
/// let user: CreateUser = request.json()?;
/// ```
#[inline]
pub fn json<T: for<'de> Deserialize<'de>>(&self) -> Result<T, crate::Error> {
crate::json::from_slice(self.body_ref())
.map_err(|e| crate::Error::Deserialization(e.to_string()))
}
/// Parse URL-encoded form data
pub fn form<T: for<'de> Deserialize<'de>>(&self) -> Result<T, crate::Error> {
crate::form::parse_form(self.body_ref())
}
/// Parse URL-encoded form data into a HashMap
pub fn form_map(&self) -> Result<HashMap<String, String>, crate::Error> {
crate::form::parse_form_map(self.body_ref())
}
/// Parse multipart form data
pub fn multipart(&self) -> Result<Vec<crate::form::FormField>, crate::Error> {
// One lookup: header names intern case-insensitively, so the
// lowercased retry was always redundant.
let content_type = self
.headers
.get("Content-Type")
.ok_or_else(|| crate::Error::BadRequest("Missing Content-Type header".to_string()))?;
let parser = crate::form::MultipartParser::from_content_type(content_type)?;
parser.parse(self.body_ref())
}
/// A captured route parameter, as UTF-8.
#[inline]
pub fn param(&self, name: &str) -> Option<&str> {
self.param_bytes(name)
.and_then(|v| std::str::from_utf8(v).ok())
}
/// A captured route parameter, raw.
#[inline]
pub fn param_bytes(&self, name: &str) -> Option<&Bytes> {
self.path_params
.iter()
.find(|(k, _)| *k == name)
.map(|(_, v)| v)
}
/// Add one captured route parameter, interning its name.
///
/// The router uses [`HttpRequest::set_params`] with names already interned
/// at registration; this is for callers assembling a request by hand. The
/// interner is hard-capped ([`crate::param_intern::MAX_INTERNED`]), so
/// feeding this a request-derived name cannot grow the process without
/// bound — past the cap the name resolves to
/// [`crate::param_intern::OVERFLOW_NAME`] and the parameter is no longer
/// retrievable by its own name.
pub fn push_param(&mut self, name: &str, value: impl Into<Bytes>) {
self.path_params
.push((crate::param_intern::intern(name), value.into()));
}
/// Replace the captured parameters. Called by the router.
#[inline]
pub fn set_params(&mut self, params: RouteParams) {
self.path_params = params;
}
/// The raw query string, without the `?`.
#[inline]
pub fn query_string(&self) -> Option<&str> {
self.path.as_str().split_once('?').map(|(_, q)| q)
}
/// A parsed view of the query string.
///
/// Parses on the first call and memoizes; a handler that never calls this
/// pays nothing. Note the shape change: this used to take a name and return
/// one value — that accessor is now [`HttpRequest::query_param`].
#[inline]
pub fn query(&self) -> QueryView<'_> {
let pairs = self
.query_cache
.0
.get_or_init(|| match self.query_string() {
Some(q) => parse_query(q),
None => QueryPairs::new(),
});
QueryView::new(pairs)
}
/// Append a query parameter to the target, percent-encoding both sides.
///
/// The query lives in `path` now, so this is how a caller adds one without
/// hand-assembling the target. Any memoized parse is discarded, since the
/// target it was parsed from no longer describes this request.
pub fn push_query_param(&mut self, name: impl AsRef<str>, value: impl AsRef<str>) {
let pair = [(name.as_ref(), value.as_ref())];
let Ok(encoded) = serde_urlencoded::to_string(pair) else {
return;
};
let separator = if self.path.contains('?') { '&' } else { '?' };
self.path = ByteStr::from(format!("{}{separator}{encoded}", self.path.as_str()));
self.query_cache = QueryCache::default();
}
/// The first query value for `name`.
#[inline]
pub fn query_param(&self, name: &str) -> Option<&str> {
self.query().get(name)
}
}
/// Lazy-initialized HashMap that doesn't allocate until first insert.
///
/// This provides the same API as HashMap but with zero allocation cost
/// for empty maps.
#[derive(Debug, Clone, Default)]
pub struct LazyHeaders {
inner: Option<HashMap<String, String>>,
}
impl LazyHeaders {
/// Create a new empty LazyHeaders (no allocation).
#[inline(always)]
pub const fn new() -> Self {
Self { inner: None }
}
/// Create with pre-allocated capacity.
#[inline]
pub fn with_capacity(cap: usize) -> Self {
Self {
inner: Some(HashMap::with_capacity(cap)),
}
}
/// Insert a key-value pair.
#[inline]
pub fn insert(&mut self, key: String, value: String) -> Option<String> {
self.inner
.get_or_insert_with(HashMap::new)
.insert(key, value)
}
/// Get a value by key.
#[inline]
pub fn get(&self, key: &str) -> Option<&String> {
self.inner.as_ref()?.get(key)
}
/// Check if key exists.
#[inline]
pub fn contains_key(&self, key: &str) -> bool {
self.inner.as_ref().is_some_and(|m| m.contains_key(key))
}
/// Get number of headers.
#[inline]
pub fn len(&self) -> usize {
self.inner.as_ref().map_or(0, |m| m.len())
}
/// Check if empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.as_ref().is_none_or(|m| m.is_empty())
}
/// Iterate over headers.
#[inline]
pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
self.inner.iter().flat_map(|m| m.iter())
}
/// Convert to HashMap (for compatibility).
#[inline]
pub fn to_hashmap(&self) -> HashMap<String, String> {
self.inner.clone().unwrap_or_default()
}
/// Remove a header by key.
#[inline]
pub fn remove(&mut self, key: &str) -> Option<String> {
self.inner.as_mut()?.remove(key)
}
/// Get an entry for in-place manipulation.
#[inline]
pub fn entry(&mut self, key: String) -> std::collections::hash_map::Entry<'_, String, String> {
self.inner.get_or_insert_with(HashMap::new).entry(key)
}
/// Extend with headers from an iterator.
#[inline]
pub fn extend<I: IntoIterator<Item = (String, String)>>(&mut self, iter: I) {
let map = self.inner.get_or_insert_with(HashMap::new);
map.extend(iter);
}
/// Clear all headers.
#[inline]
pub fn clear(&mut self) {
if let Some(ref mut map) = self.inner {
map.clear();
}
}
/// Clone the inner HashMap if present.
#[inline]
pub fn clone_inner(&self) -> Option<HashMap<String, String>> {
self.inner.clone()
}
}
impl From<HashMap<String, String>> for LazyHeaders {
#[inline]
fn from(map: HashMap<String, String>) -> Self {
Self { inner: Some(map) }
}
}
impl From<LazyHeaders> for HashMap<String, String> {
#[inline]
fn from(lazy: LazyHeaders) -> Self {
lazy.inner.unwrap_or_default()
}
}
// Allow iteration
impl<'a> IntoIterator for &'a LazyHeaders {
type Item = (&'a String, &'a String);
type IntoIter = std::iter::Flatten<std::option::Iter<'a, HashMap<String, String>>>;
fn into_iter(self) -> Self::IntoIter {
self.inner.iter().flatten()
}
}
/// HTTP response wrapper
///
/// The body is `Bytes`, so handing a response to the writer — or cloning one out
/// of a cache — is a refcount bump rather than a copy. Build one from an
/// existing buffer with `with_bytes_body()`.
///
/// ## Performance Note
///
/// Response creation is optimized for minimal allocation:
/// - `headers` uses `LazyHeaders` which doesn't allocate until first insert
/// - `body` is an empty `Bytes` until set, which doesn't allocate
/// - Use `FastResponse` from `armature_core::fast_response` for even faster creation
#[derive(Debug)]
pub struct HttpResponse {
pub status: u16,
/// Response headers with lazy allocation.
pub headers: LazyHeaders,
/// Set-Cookie headers (supports multiple cookies per response).
pub cookies: Vec<String>,
/// The response body.
///
/// Was a `Vec<u8>` shadowed by an optional `Bytes`. One field, always
/// authoritative.
pub body: Bytes,
}
/// Default pre-allocated response buffer size (512 bytes).
pub const DEFAULT_RESPONSE_CAPACITY: usize = 512;
impl HttpResponse {
/// Create a new response with the given status code.
///
/// This is optimized for minimal allocation - headers use `LazyHeaders`
/// which doesn't allocate until first insert, and body uses `Vec::new()`
/// which is zero-cost.
#[inline(always)]
pub fn new(status: u16) -> Self {
Self {
status,
headers: LazyHeaders::new(),
cookies: Vec::new(),
body: Bytes::new(),
}
}
/// Create a new response with pre-allocated header capacity.
///
/// The `capacity` argument is retained for source compatibility but no
/// longer reserves body space: `Bytes` is handed a finished buffer rather
/// than grown in place.
///
/// # Example
///
/// ```rust,ignore
/// let response = HttpResponse::with_capacity(200, 512);
/// ```
#[inline]
pub fn with_capacity(status: u16, _capacity: usize) -> Self {
Self {
status,
headers: LazyHeaders::with_capacity(8),
cookies: Vec::new(),
body: Bytes::new(),
}
}
/// Create a 200 OK response.
#[inline(always)]
pub fn ok() -> Self {
Self::new(200)
}
/// Create a 200 OK response with pre-allocated buffer (512 bytes default).
#[inline]
pub fn ok_preallocated() -> Self {
Self::with_capacity(200, DEFAULT_RESPONSE_CAPACITY)
}
/// Create a 201 Created response.
#[inline(always)]
pub fn created() -> Self {
Self::new(201)
}
/// Create a 204 No Content response.
#[inline(always)]
pub fn no_content() -> Self {
Self::new(204)
}
/// Create a 400 Bad Request response.
#[inline(always)]
pub fn bad_request() -> Self {
Self::new(400)
}
/// Create a 404 Not Found response.
#[inline(always)]
pub fn not_found() -> Self {
Self::new(404)
}
/// Create a 500 Internal Server Error response.
#[inline(always)]
pub fn internal_server_error() -> Self {
Self::new(500)
}
/// Set the body from a `Vec<u8>`, taking over its allocation.
pub fn with_body(mut self, body: Vec<u8>) -> Self {
self.body = Bytes::from(body);
self
}
/// Set the body using Bytes (zero-copy).
///
/// This is the most efficient way to set response body data,
/// as it can be passed directly to Hyper without copying.
#[inline]
pub fn with_bytes_body(mut self, bytes: Bytes) -> Self {
self.body = bytes;
self
}
/// Set the body from a static byte slice (zero-copy).
#[inline]
pub fn with_static_body(mut self, body: &'static [u8]) -> Self {
self.body = Bytes::from_static(body);
self
}
/// The body as `Bytes`. A refcount bump, not a copy.
#[inline]
pub fn body_bytes(&self) -> Bytes {
self.body.clone()
}
/// Consume the response and return the body.
#[inline]
pub fn into_body_bytes(self) -> Bytes {
self.body
}
/// The body as a byte slice.
#[inline]
pub fn body_slice(&self) -> &[u8] {
&self.body
}
/// The body as a byte slice.
#[inline]
pub fn body_ref(&self) -> &[u8] {
&self.body
}
/// The body length in bytes.
#[inline]
pub fn body_len(&self) -> usize {
self.body.len()
}
/// Whether the body holds anything.
///
/// Kept for call-site compatibility from when the body could live in either
/// of two fields; it is always `Bytes` now.
#[inline]
pub fn has_bytes_body(&self) -> bool {
!self.body.is_empty()
}
/// Serialize a value as JSON and set it as the response body.
///
/// With the `simd-json` feature enabled, this uses SIMD-accelerated serialization
/// which can be 1.5-2x faster on modern x86_64 CPUs.
///
/// The body is stored as `Bytes` for zero-copy passthrough to Hyper.
///
/// # Example
///
/// ```rust,ignore
/// HttpResponse::ok().with_json(&user)?
/// ```
#[inline]
pub fn with_json<T: Serialize>(mut self, value: &T) -> Result<Self, crate::Error> {
let vec =
crate::json::to_vec(value).map_err(|e| crate::Error::Serialization(e.to_string()))?;
self.body = Bytes::from(vec);
self.headers
.insert("Content-Type".to_string(), "application/json".to_string());
Ok(self)
}
pub fn with_header(mut self, key: String, value: String) -> Self {
self.headers.insert(key, value);
self
}
/// Set multiple headers from a HashMap.
#[inline]
pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
self.headers = LazyHeaders::from(headers);
self
}
/// Create a response with status and headers (for CORS preflight, etc.).
#[inline]
pub fn with_status_and_headers(status: u16, headers: HashMap<String, String>) -> Self {
Self {
status,
headers: LazyHeaders::from(headers),
cookies: Vec::new(),
body: Bytes::new(),
}
}
/// Create a response with all components (for compatibility).
///
/// This is useful when you need to construct a response with all parts at once.
#[inline]
pub fn from_parts(status: u16, headers: HashMap<String, String>, body: Vec<u8>) -> Self {
Self {
status,
headers: LazyHeaders::from(headers),
cookies: Vec::new(),
body: Bytes::from(body),
}
}
// ============================================================================
// Convenience Methods for Common Response Types
// ============================================================================
/// Create an accepted response (202).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::accepted();
/// assert_eq!(response.status, 202);
/// ```
pub fn accepted() -> Self {
Self::new(202)
}
/// Create an unauthorized response (401).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::unauthorized();
/// assert_eq!(response.status, 401);
/// ```
pub fn unauthorized() -> Self {
Self::new(401)
}
/// Create a forbidden response (403).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::forbidden();
/// assert_eq!(response.status, 403);
/// ```
pub fn forbidden() -> Self {
Self::new(403)
}
/// Create a conflict response (409).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::conflict();
/// assert_eq!(response.status, 409);
/// ```
pub fn conflict() -> Self {
Self::new(409)
}
/// Create a service unavailable response (503).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::service_unavailable();
/// assert_eq!(response.status, 503);
/// ```
pub fn service_unavailable() -> Self {
Self::new(503)
}
/// Shorthand for creating a JSON response with 200 OK status.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// use serde_json::json;
///
/// let response = HttpResponse::json(&json!({"message": "Hello"})).unwrap();
/// assert_eq!(response.status, 200);
/// ```
pub fn json<T: Serialize>(value: &T) -> Result<Self, crate::Error> {
Self::ok().with_json(value)
}
/// Create an HTML response with 200 OK status.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::html("<h1>Hello</h1>");
/// assert_eq!(response.status, 200);
/// assert_eq!(response.headers.get("Content-Type"), Some(&"text/html; charset=utf-8".to_string()));
/// ```
pub fn html(content: impl Into<String>) -> Self {
Self::ok()
.with_header(
"Content-Type".to_string(),
"text/html; charset=utf-8".to_string(),
)
.with_body(content.into().into_bytes())
}
/// Create a plain text response with 200 OK status.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::text("Hello, World!");
/// assert_eq!(response.status, 200);
/// assert_eq!(response.headers.get("Content-Type"), Some(&"text/plain; charset=utf-8".to_string()));
/// ```
pub fn text(content: impl Into<String>) -> Self {
Self::ok()
.with_header(
"Content-Type".to_string(),
"text/plain; charset=utf-8".to_string(),
)
.with_body(content.into().into_bytes())
}
/// Create a redirect response (302 Found).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::redirect("https://example.com");
/// assert_eq!(response.status, 302);
/// assert_eq!(response.headers.get("Location"), Some(&"https://example.com".to_string()));
/// ```
pub fn redirect(url: impl Into<String>) -> Self {
Self::new(302).with_header("Location".to_string(), url.into())
}
/// Create a permanent redirect response (301 Moved Permanently).
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::redirect_permanent("https://example.com");
/// assert_eq!(response.status, 301);
/// ```
pub fn redirect_permanent(url: impl Into<String>) -> Self {
Self::new(301).with_header("Location".to_string(), url.into())
}
/// Create a see other redirect response (303 See Other).
/// Useful after a POST request to redirect to a GET.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::see_other("/success");
/// assert_eq!(response.status, 303);
/// ```
pub fn see_other(url: impl Into<String>) -> Self {
Self::new(303).with_header("Location".to_string(), url.into())
}
/// Alias for no_content() - returns 204 with empty body.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::empty();
/// assert_eq!(response.status, 204);
/// ```
pub fn empty() -> Self {
Self::no_content()
}
/// Set the Content-Type header.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::ok().content_type("application/xml");
/// assert_eq!(response.headers.get("Content-Type"), Some(&"application/xml".to_string()));
/// ```
pub fn content_type(self, content_type: impl Into<String>) -> Self {
self.with_header("Content-Type".to_string(), content_type.into())
}
/// Set the Cache-Control header.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::ok().cache_control("max-age=3600");
/// ```
pub fn cache_control(self, directive: impl Into<String>) -> Self {
self.with_header("Cache-Control".to_string(), directive.into())
}
/// Mark the response as not cacheable.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::ok().no_cache();
/// ```
pub fn no_cache(self) -> Self {
self.cache_control("no-store, no-cache, must-revalidate")
}
/// Set a cookie on the response. Can be called multiple times to set
/// multiple cookies — each produces a separate `Set-Cookie` header.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::ok()
/// .cookie("session", "abc123; HttpOnly; Secure")
/// .cookie("theme", "dark; Path=/");
/// ```
pub fn cookie(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.cookies
.push(format!("{}={}", name.into(), value.into()));
self
}
/// Clear a cookie by setting it with an expired Max-Age.
///
/// # Example
/// ```
/// use armature_core::HttpResponse;
/// let response = HttpResponse::ok().clear_cookie("session", "/");
/// ```
pub fn clear_cookie(mut self, name: impl Into<String>, path: impl Into<String>) -> Self {
self.cookies
.push(format!("{}=; Path={}; Max-Age=0", name.into(), path.into(),));
self
}
/// Get the response body as a string (lossy UTF-8 conversion).
pub fn body_string(&self) -> String {
String::from_utf8_lossy(self.body_ref()).to_string()
}
/// Check if the response is successful (2xx status code).
pub fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
/// Check if the response is a redirect (3xx status code).
pub fn is_redirect(&self) -> bool {
(300..400).contains(&self.status)
}
/// Check if the response is a client error (4xx status code).
pub fn is_client_error(&self) -> bool {
(400..500).contains(&self.status)
}
/// Check if the response is a server error (5xx status code).
pub fn is_server_error(&self) -> bool {
(500..600).contains(&self.status)
}
}
/// JSON response helper
#[derive(Debug)]
pub struct Json<T: Serialize>(pub T);
impl<T: Serialize> Json<T> {
pub fn into_response(self) -> Result<HttpResponse, crate::Error> {
HttpResponse::ok().with_json(&self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `10.0.0.1:5555` — stands in for a reverse proxy.
fn proxy() -> SocketAddr {
SocketAddr::from(([10, 0, 0, 1], 5555))
}
/// An empty hop must not shorten the chain. The entry is selected by
/// counting from the right, so dropping one slides the index left — onto an
/// entry the client wrote. Failing closed is the only safe answer to a
/// chain that does not match the deployment.
#[test]
fn an_empty_hop_fails_closed_rather_than_sliding_the_index() {
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
// A misconfigured intermediary emits an empty element after the
// client's value. With the empty entry discarded, depth 1 would land on
// the client's own entry and return it as the trusted address.
req.headers.insert("X-Forwarded-For", "198.51.100.9, ");
assert_eq!(
req.client_address(1),
None,
"a chain containing an unusable hop must yield no address, not the \
entry next to it"
);
// The positive control: the same chain with the empty element filled in
// does resolve, and to the hop the empty one stood in for. Without this,
// a future change that made every multi-entry chain return `None` would
// keep the assertion above passing and this test's name would be a lie.
let mut intact = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
intact
.headers
.insert("X-Forwarded-For", "198.51.100.9, 203.0.113.7");
assert_eq!(
intact.client_address(1),
ip("203.0.113.7"),
"the empty hop is why the address is None; a chain of the same \
shape without it must still resolve"
);
}
#[test]
fn a_hand_built_request_has_no_peer() {
// `None` rather than an unspecified address: a caller must be able to
// tell "nobody told me" from "the client is 0.0.0.0".
assert_eq!(HttpRequest::new("GET", "/").peer, None);
assert_eq!(
HttpRequest::with_extensions_capacity("GET", "/", 4).peer,
None
);
}
#[test]
fn with_peer_survives_a_clone() {
// Requests are cloned freely on the serve path; an attribution that
// silently reset would be worse than none.
let req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
assert_eq!(req.clone().peer, Some(proxy()));
}
fn ip(s: &str) -> Option<IpAddr> {
Some(s.parse().unwrap())
}
#[test]
fn a_prepended_forwarded_entry_cannot_impersonate_the_client() {
// The attack the depth-from-the-right rule exists to stop: the caller
// sent the first entry itself, and the real proxy appended the second.
// Reading left-to-right would return the fabrication.
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers
.insert("X-Forwarded-For", "198.51.100.9, 203.0.113.7");
assert_eq!(req.client_address(1), ip("203.0.113.7"));
}
#[test]
fn depth_counts_proxies_from_the_right() {
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers.insert(
"X-Forwarded-For",
"198.51.100.9, 203.0.113.7, 192.0.2.4, 192.0.2.5",
);
assert_eq!(req.client_address(1), ip("192.0.2.5"));
assert_eq!(req.client_address(2), ip("192.0.2.4"));
assert_eq!(req.client_address(3), ip("203.0.113.7"));
}
#[test]
fn a_chain_split_across_two_field_lines_is_still_one_chain() {
// The h1 serve path appends repeated fields rather than collapsing them
// to the last, and a proxy that runs HAProxy's `option forwardfor` adds
// its own `X-Forwarded-For` line instead of extending the client's. Both
// lines are one list (RFC 9110 §5.3): reading only the first would hand
// back the entry the client invented.
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers.append("X-Forwarded-For", "198.51.100.9");
req.headers.append("X-Forwarded-For", "203.0.113.7");
assert_eq!(req.client_address(1), ip("203.0.113.7"));
assert_eq!(req.client_address(2), ip("198.51.100.9"));
// Two hops present, three configured: the deployment disagrees with
// itself and nothing here is trustworthy.
assert_eq!(req.client_address(3), None);
}
#[test]
fn the_joined_and_the_split_form_select_identically() {
// The other half of §5.3. The single-line form must keep behaving
// exactly as it always has, and the two forms must not disagree at any
// depth — otherwise attribution depends on how a proxy happened to
// write the field.
let mut one = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
one.headers
.insert("X-Forwarded-For", "198.51.100.9, 203.0.113.7, 192.0.2.4");
let mut split = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
split.headers.append("X-Forwarded-For", "198.51.100.9");
split
.headers
.append("X-Forwarded-For", "203.0.113.7, 192.0.2.4");
for depth in 0..=4 {
assert_eq!(
one.client_address(depth),
split.client_address(depth),
"the two spellings of one chain disagree at depth {depth}"
);
}
assert_eq!(one.client_address(1), ip("192.0.2.4"));
assert_eq!(one.client_address(2), ip("203.0.113.7"));
assert_eq!(one.client_address(3), ip("198.51.100.9"));
}
#[test]
fn depth_zero_ignores_the_header_entirely() {
// A process reachable directly. Anything in the header is the caller's
// invention, so the socket is the only answer.
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers.insert("X-Forwarded-For", "198.51.100.9");
assert_eq!(req.client_address(0), ip("10.0.0.1"));
}
#[test]
fn a_depth_deeper_than_the_chain_trusts_nothing() {
// Configured for two proxies, one hop present: the request did not come
// the way the deployment says it does. Every entry is then suspect, and
// falling back to the peer would attribute every client to the proxy.
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers.insert("X-Forwarded-For", "198.51.100.9");
assert_eq!(req.client_address(2), None);
}
#[test]
fn a_missing_or_empty_header_at_depth_is_unknown() {
for value in ["", " ", " , "] {
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers.insert("X-Forwarded-For", value);
assert_eq!(
req.client_address(1),
None,
"{value:?} names no hop, so there is nothing to attribute to"
);
}
let bare = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
assert_eq!(bare.client_address(1), None);
}
#[test]
fn a_hop_that_is_not_an_address_is_unknown_rather_than_guessed() {
let mut req = HttpRequest::new("GET", "/").with_peer(Some(proxy()));
req.headers.insert("X-Forwarded-For", "not-an-address");
assert_eq!(req.client_address(1), None);
}
#[test]
fn nothing_to_go_on_is_none_rather_than_a_placeholder() {
assert_eq!(HttpRequest::new("GET", "/").client_address(0), None);
}
#[test]
fn an_ipv6_peer_survives_the_round_trip() {
let req = HttpRequest::new("GET", "/").with_peer(Some(SocketAddr::from((
[0x2001, 0xdb8, 0, 0, 0, 0, 0, 1],
443,
))));
assert_eq!(req.client_address(0), ip("2001:db8::1"));
}
#[test]
fn new_accepts_str_and_string_and_method() {
// All three forms must compile: existing call sites pass a String, and
// new code should be able to pass a Method directly.
let a = HttpRequest::new("GET", "/a".to_string());
let b = HttpRequest::new("POST", "/b".to_string());
let c = HttpRequest::new(Method::Put, "/c".to_string());
assert_eq!(a.method, Method::Get);
assert_eq!(b.method, Method::Post);
assert_eq!(c.method, Method::Put);
}
#[test]
fn from_parts_ignores_query_params_entirely() {
// The argument is kept for source compatibility only — the query comes
// from the target now. Pinned so a caller still passing a map can't
// silently depend on it being honoured.
let mut query = HashMap::new();
query.insert("page".to_string(), "2".to_string());
let req = HttpRequest::from_parts(
"GET",
"/items",
HashMap::new(),
Vec::new(),
HashMap::new(),
query,
);
assert_eq!(req.query_string(), None);
assert_eq!(req.query_param("page"), None);
assert_eq!(req.query().len(), 0);
}
#[test]
fn with_capacity_ignores_its_capacity_argument() {
// `Bytes` is handed a finished buffer rather than grown in place, so
// there is no body capacity to reserve. Any two capacities must produce
// indistinguishable responses.
let small = HttpResponse::with_capacity(200, 0);
let large = HttpResponse::with_capacity(200, 1 << 20);
assert_eq!(small.status, large.status);
assert_eq!(small.body.len(), large.body.len());
assert!(small.body.is_empty());
assert_eq!(small.headers.len(), large.headers.len());
}
#[test]
fn params_read_back_as_str_and_bytes() {
let mut req = HttpRequest::new("GET", "/users/42/posts/7");
let mut params = RouteParams::new();
params.push((
crate::param_intern::intern("user_id"),
Bytes::from_static(b"42"),
));
params.push((
crate::param_intern::intern("post_id"),
Bytes::from_static(b"7"),
));
req.set_params(params);
assert_eq!(req.param("user_id"), Some("42"));
assert_eq!(req.param("post_id"), Some("7"));
assert_eq!(req.param("nope"), None);
assert_eq!(req.param_bytes("user_id").map(|b| b.len()), Some(2));
assert_eq!(
req.param("user_id").and_then(|v| v.parse::<u32>().ok()),
Some(42)
);
}
#[test]
fn four_params_stay_inline() {
let mut params = RouteParams::new();
for name in ["a", "b", "c", "d"] {
params.push((crate::param_intern::intern(name), Bytes::from_static(b"x")));
}
assert!(!params.spilled(), "four params must not allocate");
}
#[test]
fn path_is_a_bytestr_and_still_compares_and_prints_as_a_str() {
let req = HttpRequest::new("GET", "/users/42?a=1");
assert_eq!(req.path_str(), "/users/42?a=1");
assert!(req.path == "/users/42?a=1");
assert_eq!(format!("{}", req.path), "/users/42?a=1");
// Deref<Target = str> keeps the `&str` surface intact.
assert!(req.path.starts_with("/users"));
}
#[test]
fn request_body_is_bytes_and_the_shadow_field_is_gone() {
let mut req = HttpRequest::new("POST", "/x");
req.set_body(b"hello".to_vec());
assert_eq!(req.body_slice(), b"hello");
// The old two-field arrangement could disagree with itself; one field
// cannot.
assert_eq!(req.body_bytes(), Bytes::from_static(b"hello"));
assert!(req.has_bytes_body());
req.set_body_bytes(Bytes::from_static(b"world"));
assert_eq!(req.body_slice(), b"world");
assert_eq!(req.body_ref(), b"world");
}
#[test]
fn cloning_a_body_does_not_copy_it() {
let big = Bytes::from(vec![7u8; 64 * 1024]);
let mut req = HttpRequest::new("POST", "/x");
req.set_body_bytes(big.clone());
let copy = req.clone();
// Same allocation, reached from two requests: the whole point of Bytes.
assert_eq!(copy.body.as_ptr(), req.body.as_ptr());
}
#[test]
fn response_body_is_bytes() {
let mut resp = HttpResponse::new(200);
resp.body = Bytes::from_static(b"{}");
assert_eq!(resp.body_slice(), b"{}");
assert_eq!(resp.body_len(), 2);
}
#[test]
fn method_compares_against_str_and_reports_itself_as_str() {
let req = HttpRequest::new("DELETE", "/x".to_string());
assert!(req.method == "DELETE");
assert!(req.method != "GET");
assert_eq!(req.method_str(), "DELETE");
// An unknown token survives intact rather than being coerced.
let odd = HttpRequest::new("PURGE", "/x".to_string());
assert_eq!(odd.method_str(), "PURGE");
assert!(odd.method == "PURGE");
}
#[test]
fn test_http_request_new() {
let req = HttpRequest::new("GET", "/test".to_string());
assert_eq!(req.method, "GET");
assert_eq!(req.path, "/test");
assert!(req.headers.is_empty());
assert!(req.body.is_empty());
}
#[test]
fn test_http_request_with_body() {
let mut req = HttpRequest::new("POST", "/api".to_string());
req.body = Bytes::from(vec![1, 2, 3, 4]);
assert_eq!(req.body.len(), 4);
}
#[test]
fn test_http_request_json_deserialization() {
#[derive(Deserialize, Debug, PartialEq)]
struct TestData {
name: String,
age: u32,
}
let mut req = HttpRequest::new("POST", "/api".to_string());
req.body = Bytes::from(
serde_json::to_vec(&serde_json::json!({
"name": "John",
"age": 30
}))
.unwrap(),
);
let data: TestData = req.json().unwrap();
assert_eq!(data.name, "John");
assert_eq!(data.age, 30);
}
#[test]
fn test_http_request_param() {
let mut req = HttpRequest::new("GET", "/users/123".to_string());
req.push_param("id", "123");
assert_eq!(req.param("id"), Some("123"));
assert_eq!(req.param("name"), None);
}
#[test]
fn test_http_request_query() {
let req = HttpRequest::new("GET", "/users?sort=asc");
assert_eq!(req.query_param("sort"), Some("asc"));
assert_eq!(req.query_param("limit"), None);
}
#[test]
fn test_http_request_clone() {
let req1 = HttpRequest::new("GET", "/test".to_string());
let req2 = req1.clone();
assert_eq!(req1.method, req2.method);
assert_eq!(req1.path, req2.path);
}
#[test]
fn test_http_response_ok() {
let res = HttpResponse::ok();
assert_eq!(res.status, 200);
}
#[test]
fn test_http_response_created() {
let res = HttpResponse::created();
assert_eq!(res.status, 201);
}
#[test]
fn test_http_response_no_content() {
let res = HttpResponse::no_content();
assert_eq!(res.status, 204);
}
#[test]
fn test_http_response_bad_request() {
let res = HttpResponse::bad_request();
assert_eq!(res.status, 400);
}
#[test]
fn test_http_response_not_found() {
let res = HttpResponse::not_found();
assert_eq!(res.status, 404);
}
#[test]
fn test_http_response_internal_server_error() {
let res = HttpResponse::internal_server_error();
assert_eq!(res.status, 500);
}
#[test]
fn test_http_response_with_body() {
let body = b"Hello, World!".to_vec();
let res = HttpResponse::ok().with_body(body.clone());
assert_eq!(res.body, body);
}
#[test]
fn test_http_response_with_json() {
#[derive(Serialize)]
struct TestData {
message: String,
}
let data = TestData {
message: "test".to_string(),
};
let res = HttpResponse::ok().with_json(&data).unwrap();
assert!(!res.body_ref().is_empty());
assert_eq!(
res.headers.get("Content-Type"),
Some(&"application/json".to_string())
);
}
#[test]
fn test_http_response_with_header() {
let res = HttpResponse::ok().with_header("X-Custom".to_string(), "value".to_string());
assert_eq!(res.headers.get("X-Custom"), Some(&"value".to_string()));
}
#[test]
fn test_http_response_multiple_headers() {
let res = HttpResponse::ok()
.with_header("X-Header-1".to_string(), "value1".to_string())
.with_header("X-Header-2".to_string(), "value2".to_string());
assert_eq!(res.headers.len(), 2);
}
#[test]
fn test_json_helper() {
#[derive(Serialize)]
struct Data {
value: i32,
}
let json = Json(Data { value: 42 });
let response = json.into_response().unwrap();
assert_eq!(response.status, 200);
assert!(!response.body_ref().is_empty());
}
#[test]
fn test_http_request_with_headers() {
let mut req = HttpRequest::new("GET", "/api".to_string());
req.headers
.insert("Authorization", "Bearer token".to_string());
req.headers
.insert("Content-Type", "application/json".to_string());
assert_eq!(req.headers.len(), 2);
}
#[test]
fn test_http_request_from_parts_headermap_roundtrip() {
// `from_parts` still takes a HashMap for backwards compatibility, but
// now stores headers in a `HeaderMap`. Lookups must be case-insensitive.
let mut headers = HashMap::new();
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("X-Custom".to_string(), "abc".to_string());
let req = HttpRequest::from_parts(
"GET",
"/api".to_string(),
headers,
Vec::new(),
HashMap::new(),
HashMap::new(),
);
assert_eq!(req.headers.len(), 2);
// Case-insensitive lookup via HeaderMap.
assert_eq!(req.headers.get("content-type"), Some("application/json"));
assert_eq!(req.headers.get("Content-Type"), Some("application/json"));
assert!(req.headers.contains_key("x-custom"));
}
#[test]
fn test_http_request_json_invalid() {
#[derive(Deserialize)]
#[allow(dead_code)]
struct TestData {
name: String,
}
let mut req = HttpRequest::new("POST", "/api".to_string());
req.body = Bytes::from_static(b"invalid json");
let result: Result<TestData, crate::Error> = req.json();
assert!(result.is_err());
}
#[test]
fn test_http_response_new_custom_status() {
let res = HttpResponse::new(418); // I'm a teapot
assert_eq!(res.status, 418);
}
#[test]
fn test_http_response_with_json_complex() {
#[derive(Serialize)]
struct ComplexData {
nested: Vec<HashMap<String, i32>>,
}
let mut map = HashMap::new();
map.insert("key".to_string(), 123);
let data = ComplexData { nested: vec![map] };
let res = HttpResponse::ok().with_json(&data);
assert!(res.is_ok());
}
}