http-acl 0.13.0

An ACL for HTTP requests.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
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
//! Contains the [`HttpAcl`], [`HttpAclBuilder`],
//! and related types.
//!
//! Each category an [`HttpAcl`] checks (scheme, method, host, port, IP, header, URL
//! path) is evaluated the same way: the allow-list is checked first, then the
//! deny-list, and if neither matches, the category's configured default (set via
//! e.g. [`HttpAclBuilder::host_acl_default`]) decides the outcome. The allow-list
//! always wins over the deny-list, so a broad allow entry can shadow a narrower deny
//! entry in the same category. Every check returns an [`AclClassification`] rather
//! than a plain `bool`, so callers can tell *why* something was allowed or denied;
//! use [`AclClassification::is_allowed`]/[`AclClassification::is_denied`] where only
//! the outcome matters.

#[cfg(feature = "hashbrown")]
use hashbrown::{HashMap, HashSet, hash_map::Entry};
#[cfg(not(feature = "hashbrown"))]
use std::collections::{HashMap, HashSet, hash_map::Entry};
use std::hash::Hash;
use std::net::{IpAddr, SocketAddr};
use std::ops::RangeInclusive;
use std::sync::Arc;

use matchit::Router;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{
    error::AddError,
    mutation::{ModifyRequestFn, ModifyResponseFn, RequestMutation, ResponseMutation},
    utils::{
        self, IntoIpRange,
        authority::Authority,
        host_pattern::{HostPattern, is_wildcard_host},
    },
};

/// A function that validates an HTTP request against an ACL.
///
/// Called by [`HttpAcl::is_valid`] with the request's scheme, authority (host and
/// port), headers, and optional body, in that order. It is the only hook for checks
/// that don't fit the built-in categories (e.g. inspecting the body, or applying
/// custom cross-field logic). Return [`AclClassification::DeniedUserAcl`] or
/// [`AclClassification::Denied`] to reject the request, or
/// [`AclClassification::AllowedDefault`] to let it through.
///
/// A `ValidateFn` is attached via [`HttpAclBuilder::build_full`] or
/// [`HttpAclBuilder::try_build_full`] rather than a dedicated builder setter, since
/// it is typically a closure that captures state from outside the builder.
pub type ValidateFn = Arc<
    dyn for<'h> Fn(
            &str,
            &Authority,
            Box<dyn Iterator<Item = (&'h str, &'h str)> + Send + Sync + 'h>,
            Option<&[u8]>,
        ) -> AclClassification
        + Send
        + Sync,
>;

#[derive(Clone)]
/// Represents an HTTP ACL.
///
/// Built via [`HttpAcl::builder`] (an [`HttpAclBuilder`]) rather than constructed
/// directly. Once built, an `HttpAcl` is immutable; the various `is_*_allowed`
/// methods check a single aspect of a request (scheme, method, host, port, IP,
/// header, or URL path) and return an [`AclClassification`]. See the module-level
/// documentation for how allow-lists, deny-lists, and per-category defaults combine.
pub struct HttpAcl {
    allow_http: bool,
    allow_https: bool,
    allowed_methods: HashSet<HttpRequestMethod>,
    denied_methods: HashSet<HttpRequestMethod>,
    allowed_hosts: HashSet<Box<str>>,
    denied_hosts: HashSet<Box<str>>,
    allowed_host_patterns: Box<[HostPattern]>,
    denied_host_patterns: Box<[HostPattern]>,
    allowed_port_ranges: Box<[RangeInclusive<u16>]>,
    denied_port_ranges: Box<[RangeInclusive<u16>]>,
    allowed_ip_ranges: Box<[RangeInclusive<IpAddr>]>,
    denied_ip_ranges: Box<[RangeInclusive<IpAddr>]>,
    static_dns_mapping: HashMap<Box<str>, SocketAddr>,
    trusted_static_dns_mapping: HashMap<Box<str>, SocketAddr>,
    allowed_headers: HashMap<Box<str>, Option<Box<str>>>,
    denied_headers: HashMap<Box<str>, Option<Box<str>>>,
    allowed_url_paths_router: Router<()>,
    denied_url_paths_router: Router<()>,
    validate_fn: Option<ValidateFn>,
    modify_request_fn: Option<ModifyRequestFn>,
    modify_response_fn: Option<ModifyResponseFn>,
    allow_non_global_ip_ranges: bool,
    method_acl_default: bool,
    host_acl_default: bool,
    port_acl_default: bool,
    ip_acl_default: bool,
    header_acl_default: bool,
    url_path_acl_default: bool,
}

impl std::fmt::Debug for HttpAcl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpAcl")
            .field("allow_http", &self.allow_http)
            .field("allow_https", &self.allow_https)
            .field("allowed_methods", &self.allowed_methods)
            .field("denied_methods", &self.denied_methods)
            .field("allowed_hosts", &self.allowed_hosts)
            .field("denied_hosts", &self.denied_hosts)
            .field("allowed_port_ranges", &self.allowed_port_ranges)
            .field("denied_port_ranges", &self.denied_port_ranges)
            .field("allowed_ip_ranges", &self.allowed_ip_ranges)
            .field("denied_ip_ranges", &self.denied_ip_ranges)
            .field("static_dns_mapping", &self.static_dns_mapping)
            .field(
                "trusted_static_dns_mapping",
                &self.trusted_static_dns_mapping,
            )
            .field("allowed_headers", &self.allowed_headers)
            .field("denied_headers", &self.denied_headers)
            .field(
                "allow_non_global_ip_ranges",
                &self.allow_non_global_ip_ranges,
            )
            .field("method_acl_default", &self.method_acl_default)
            .field("host_acl_default", &self.host_acl_default)
            .field("port_acl_default", &self.port_acl_default)
            .field("ip_acl_default", &self.ip_acl_default)
            .field("header_acl_default", &self.header_acl_default)
            .field("url_path_acl_default", &self.url_path_acl_default)
            .finish()
    }
}

impl PartialEq for HttpAcl {
    fn eq(&self, other: &Self) -> bool {
        self.allow_http == other.allow_http
            && self.allow_https == other.allow_https
            && self.allowed_methods == other.allowed_methods
            && self.denied_methods == other.denied_methods
            && self.allowed_hosts == other.allowed_hosts
            && self.denied_hosts == other.denied_hosts
            && self.allowed_port_ranges == other.allowed_port_ranges
            && self.denied_port_ranges == other.denied_port_ranges
            && self.allowed_ip_ranges == other.allowed_ip_ranges
            && self.denied_ip_ranges == other.denied_ip_ranges
            && self.static_dns_mapping == other.static_dns_mapping
            && self.trusted_static_dns_mapping == other.trusted_static_dns_mapping
            && self.allowed_headers == other.allowed_headers
            && self.denied_headers == other.denied_headers
            && self.allow_non_global_ip_ranges == other.allow_non_global_ip_ranges
            && self.method_acl_default == other.method_acl_default
            && self.host_acl_default == other.host_acl_default
            && self.port_acl_default == other.port_acl_default
            && self.ip_acl_default == other.ip_acl_default
            && self.header_acl_default == other.header_acl_default
            && self.url_path_acl_default == other.url_path_acl_default
    }
}

impl std::default::Default for HttpAcl {
    fn default() -> Self {
        Self {
            allow_http: true,
            allow_https: true,
            allowed_methods: [
                HttpRequestMethod::CONNECT,
                HttpRequestMethod::DELETE,
                HttpRequestMethod::GET,
                HttpRequestMethod::HEAD,
                HttpRequestMethod::OPTIONS,
                HttpRequestMethod::PATCH,
                HttpRequestMethod::POST,
                HttpRequestMethod::PUT,
                HttpRequestMethod::TRACE,
            ]
            .into_iter()
            .collect(),
            denied_methods: HashSet::new(),
            allowed_hosts: HashSet::new(),
            denied_hosts: HashSet::new(),
            allowed_host_patterns: Box::new([]),
            denied_host_patterns: Box::new([]),
            allowed_port_ranges: vec![80..=80, 443..=443].into_boxed_slice(),
            denied_port_ranges: Vec::new().into_boxed_slice(),
            allowed_ip_ranges: Vec::new().into_boxed_slice(),
            denied_ip_ranges: Vec::new().into_boxed_slice(),
            static_dns_mapping: HashMap::new(),
            trusted_static_dns_mapping: HashMap::new(),
            allowed_headers: HashMap::new(),
            denied_headers: HashMap::new(),
            allowed_url_paths_router: Router::new(),
            denied_url_paths_router: Router::new(),
            validate_fn: None,
            modify_request_fn: None,
            modify_response_fn: None,
            allow_non_global_ip_ranges: false,
            method_acl_default: false,
            host_acl_default: false,
            port_acl_default: false,
            ip_acl_default: false,
            header_acl_default: true,
            url_path_acl_default: true,
        }
    }
}

impl HttpAcl {
    /// Returns a new [`HttpAclBuilder`].
    pub fn builder() -> HttpAclBuilder {
        HttpAclBuilder::new()
    }

    /// Returns whether the scheme is allowed.
    ///
    /// Unlike the other `is_*_allowed` methods, this is a plain per-scheme flag (set
    /// via [`HttpAclBuilder::http`]/[`HttpAclBuilder::https`]) rather than an
    /// allow/deny/default check, so it only ever returns
    /// [`AclClassification::AllowedUserAcl`] or [`AclClassification::DeniedUserAcl`].
    /// Any scheme other than `"http"`/`"https"` is denied.
    pub fn is_scheme_allowed(&self, scheme: &str) -> AclClassification {
        if scheme == "http" && self.allow_http || scheme == "https" && self.allow_https {
            AclClassification::AllowedUserAcl
        } else {
            AclClassification::DeniedUserAcl
        }
    }

    /// Returns whether the method is allowed.
    ///
    /// Note: If you pass a string ensure it is uppercased first.
    pub fn is_method_allowed(&self, method: impl Into<HttpRequestMethod>) -> AclClassification {
        let method = method.into();
        if self.allowed_methods.contains(&method) {
            AclClassification::AllowedUserAcl
        } else if self.denied_methods.contains(&method) {
            AclClassification::DeniedUserAcl
        } else if self.method_acl_default {
            AclClassification::AllowedDefault
        } else {
            AclClassification::DeniedDefault
        }
    }

    /// Returns whether the host is allowed.
    ///
    /// Hosts may be exact hostnames or wildcard patterns (see
    /// [`HttpAclBuilder::add_allowed_host`] for the wildcard syntax).
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn is_host_allowed(&self, host: &str) -> AclClassification {
        if self.allowed_hosts.contains(host)
            || self.allowed_host_patterns.iter().any(|p| p.matches(host))
        {
            AclClassification::AllowedUserAcl
        } else if self.denied_hosts.contains(host)
            || self.denied_host_patterns.iter().any(|p| p.matches(host))
        {
            AclClassification::DeniedUserAcl
        } else if self.host_acl_default {
            AclClassification::AllowedDefault
        } else {
            AclClassification::DeniedDefault
        }
    }

    /// Returns whether the port is allowed.
    pub fn is_port_allowed(&self, port: u16) -> AclClassification {
        if Self::is_port_in_ranges(port, &self.allowed_port_ranges) {
            AclClassification::AllowedUserAcl
        } else if Self::is_port_in_ranges(port, &self.denied_port_ranges) {
            AclClassification::DeniedUserAcl
        } else if self.port_acl_default {
            AclClassification::AllowedDefault
        } else {
            AclClassification::DeniedDefault
        }
    }

    /// Returns whether an IP is allowed.
    ///
    /// A non-global IP (private, loopback, link-local, and other special-use
    /// addresses) is denied with [`AclClassification::DeniedNotGlobal`] before the
    /// allow/deny lists are even checked, unless
    /// [`HttpAclBuilder::non_global_ip_ranges`] was set to `true`.
    pub fn is_ip_allowed(&self, ip: &IpAddr) -> AclClassification {
        if !utils::ip::is_global_ip(ip) && !self.allow_non_global_ip_ranges {
            AclClassification::DeniedNotGlobal
        } else if Self::is_ip_in_ranges(ip, &self.allowed_ip_ranges) {
            AclClassification::AllowedUserAcl
        } else if Self::is_ip_in_ranges(ip, &self.denied_ip_ranges) {
            AclClassification::DeniedUserAcl
        } else if self.ip_acl_default {
            AclClassification::AllowedDefault
        } else {
            AclClassification::DeniedDefault
        }
    }

    /// Resolve a static DNS mapping.
    ///
    /// The returned address is still subject to the IP and port ACL - callers must
    /// check it with [`Self::is_ip_allowed`] and [`Self::is_port_allowed`] themselves.
    /// Use [`Self::resolve_trusted_static_dns_mapping`] for mappings that should
    /// bypass those checks entirely.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn resolve_static_dns_mapping(&self, host: &str) -> Option<SocketAddr> {
        self.static_dns_mapping.get(host).copied()
    }

    /// Resolve a trusted static DNS mapping.
    ///
    /// Unlike [`Self::resolve_static_dns_mapping`], the returned address is meant to
    /// bypass the IP and port ACL entirely - only use this for mappings you trust
    /// regardless of what the ACL would otherwise say (e.g. pinning a hostname to an
    /// internal address on purpose).
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn resolve_trusted_static_dns_mapping(&self, host: &str) -> Option<SocketAddr> {
        self.trusted_static_dns_mapping.get(host).copied()
    }

    /// Returns whether a header is allowed.
    ///
    /// Note: Header names are case-insensitive, but this function assumes the caller provides them in a consistent case.
    pub fn is_header_allowed(&self, header_name: &str, header_value: &str) -> AclClassification {
        if let Some(allowed_value) = self.allowed_headers.get(header_name) {
            if allowed_value.as_deref() == Some(header_value) || allowed_value.is_none() {
                AclClassification::AllowedUserAcl
            } else {
                AclClassification::DeniedUserAcl
            }
        } else if let Some(denied_value) = self.denied_headers.get(header_name) {
            if denied_value.as_deref() == Some(header_value) || denied_value.is_none() {
                AclClassification::DeniedUserAcl
            } else {
                AclClassification::AllowedUserAcl
            }
        } else if self.header_acl_default {
            AclClassification::AllowedDefault
        } else {
            AclClassification::DeniedDefault
        }
    }

    /// Returns whether a URL path is allowed.
    ///
    /// Note: The URL path should be percent-decoded before passing it to this function.
    pub fn is_url_path_allowed(&self, url_path: &str) -> AclClassification {
        if self.allowed_url_paths_router.at(url_path).is_ok() {
            AclClassification::AllowedUserAcl
        } else if self.denied_url_paths_router.at(url_path).is_ok() {
            AclClassification::DeniedUserAcl
        } else if self.url_path_acl_default {
            AclClassification::AllowedDefault
        } else {
            AclClassification::DeniedDefault
        }
    }

    /// Runs the [`ValidateFn`] attached to this ACL, if any, against a request.
    ///
    /// Returns [`AclClassification::AllowedDefault`] when no `ValidateFn` was
    /// attached (the default for an `HttpAcl` built without one), so calling this is
    /// always safe even if you never configured custom validation.
    pub fn is_valid<'h>(
        &self,
        scheme: &str,
        authority: &Authority,
        headers: impl Iterator<Item = (&'h str, &'h str)> + Send + Sync + 'h,
        body: Option<&[u8]>,
    ) -> AclClassification {
        if let Some(validate_fn) = &self.validate_fn {
            validate_fn(scheme, authority, Box::new(headers), body)
        } else {
            AclClassification::AllowedDefault
        }
    }

    /// Returns whether a [`ModifyRequestFn`] is attached to this ACL.
    ///
    /// Cheap (a single field read). Check this before doing any work to make a
    /// request's body/headers available for mutation (e.g. buffering a streaming
    /// body), so that omitting a `ModifyRequestFn` costs nothing at request time.
    pub fn has_modify_request(&self) -> bool {
        self.modify_request_fn.is_some()
    }

    /// Returns whether a [`ModifyResponseFn`] is attached to this ACL.
    ///
    /// See [`Self::has_modify_request`] - same rationale, for the response side.
    pub fn has_modify_response(&self) -> bool {
        self.modify_response_fn.is_some()
    }

    /// Runs the [`ModifyRequestFn`] attached to this ACL, if any, against
    /// `mutation`, mutating it in place.
    ///
    /// Does nothing when no `ModifyRequestFn` was attached, so calling this is
    /// always safe even if you never configured one - though see
    /// [`Self::has_modify_request`] if you want to skip preparing `mutation` at all
    /// in that case.
    pub fn modify_request(
        &self,
        scheme: &str,
        authority: &Authority,
        mutation: &mut RequestMutation,
    ) {
        if let Some(modify_request_fn) = &self.modify_request_fn {
            modify_request_fn(scheme, authority, mutation);
        }
    }

    /// Runs the [`ModifyResponseFn`] attached to this ACL, if any, against
    /// `mutation`, mutating it in place. See [`Self::modify_request`].
    pub fn modify_response(
        &self,
        scheme: &str,
        authority: &Authority,
        mutation: &mut ResponseMutation,
    ) {
        if let Some(modify_response_fn) = &self.modify_response_fn {
            modify_response_fn(scheme, authority, mutation);
        }
    }

    /// Checks if an ip is in a list of ip ranges.
    fn is_ip_in_ranges(ip: &IpAddr, ranges: &[RangeInclusive<IpAddr>]) -> bool {
        ranges.iter().any(|range| range.contains(ip))
    }

    /// Checks if a port is in a list of port ranges.
    fn is_port_in_ranges(port: u16, ranges: &[RangeInclusive<u16>]) -> bool {
        ranges.iter().any(|range| range.contains(&port))
    }
}

/// Represents the outcome of an ACL check, and why it was reached.
///
/// Every `is_*_allowed` method on [`HttpAcl`] returns one of these instead of a plain
/// `bool`, so the reason for an outcome is preserved for logging or error messages.
/// Use [`Self::is_allowed`] or [`Self::is_denied`] to collapse it to a `bool` once you
/// only care about the outcome.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AclClassification {
    /// The entity is allowed according to the allowed ACL.
    AllowedUserAcl,
    /// The entity is allowed because the default is to allow if no ACL match is found.
    AllowedDefault,
    /// The entity is denied according to the denied ACL.
    DeniedUserAcl,
    /// The entity is denied because the default is to deny if no ACL match is found.
    DeniedDefault,
    /// The entity is denied for a custom reason.
    ///
    /// Not produced by any built-in check; this exists for a [`ValidateFn`] to return
    /// a denial with a human-readable explanation of its own.
    Denied(String),
    /// The IP is denied because it is not global.
    DeniedNotGlobal,
}

impl std::fmt::Display for AclClassification {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AclClassification::AllowedUserAcl => {
                write!(f, "The entity is allowed according to the allowed ACL.")
            }
            AclClassification::AllowedDefault => write!(
                f,
                "The entity is allowed because the default is to allow if no ACL match is found."
            ),
            AclClassification::DeniedUserAcl => {
                write!(f, "The entity is denied according to the denied ACL.")
            }
            AclClassification::DeniedNotGlobal => {
                write!(f, "The ip is denied because it is not global.")
            }
            AclClassification::DeniedDefault => write!(
                f,
                "The entity is denied because the default is to deny if no ACL match is found."
            ),
            AclClassification::Denied(reason) => {
                write!(f, "The entity is denied because {reason}.")
            }
        }
    }
}

impl AclClassification {
    /// Returns whether the classification is allowed.
    pub fn is_allowed(&self) -> bool {
        matches!(
            self,
            AclClassification::AllowedUserAcl | AclClassification::AllowedDefault
        )
    }

    /// Returns whether the classification is denied.
    pub fn is_denied(&self) -> bool {
        matches!(
            self,
            AclClassification::DeniedUserAcl
                | AclClassification::Denied(_)
                | AclClassification::DeniedDefault
                | AclClassification::DeniedNotGlobal
        )
    }
}

/// Represents an HTTP request method.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum HttpRequestMethod {
    /// The CONNECT method.
    CONNECT,
    /// The DELETE method.
    DELETE,
    /// The GET method.
    GET,
    /// The HEAD method.
    HEAD,
    /// The OPTIONS method.
    OPTIONS,
    /// The PATCH method.
    PATCH,
    /// The POST method.
    POST,
    /// The PUT method.
    PUT,
    /// The TRACE method.
    TRACE,
    /// Any other method.
    OTHER(Box<str>),
}

impl From<&str> for HttpRequestMethod {
    fn from(method: &str) -> Self {
        match method {
            "CONNECT" => HttpRequestMethod::CONNECT,
            "DELETE" => HttpRequestMethod::DELETE,
            "GET" => HttpRequestMethod::GET,
            "HEAD" => HttpRequestMethod::HEAD,
            "OPTIONS" => HttpRequestMethod::OPTIONS,
            "PATCH" => HttpRequestMethod::PATCH,
            "POST" => HttpRequestMethod::POST,
            "PUT" => HttpRequestMethod::PUT,
            "TRACE" => HttpRequestMethod::TRACE,
            _ => HttpRequestMethod::OTHER(method.into()),
        }
    }
}

impl HttpRequestMethod {
    /// Return the method as a `&str`.
    pub fn as_str(&self) -> &str {
        match self {
            HttpRequestMethod::CONNECT => "CONNECT",
            HttpRequestMethod::DELETE => "DELETE",
            HttpRequestMethod::GET => "GET",
            HttpRequestMethod::HEAD => "HEAD",
            HttpRequestMethod::OPTIONS => "OPTIONS",
            HttpRequestMethod::PATCH => "PATCH",
            HttpRequestMethod::POST => "POST",
            HttpRequestMethod::PUT => "PUT",
            HttpRequestMethod::TRACE => "TRACE",
            HttpRequestMethod::OTHER(other) => other,
        }
    }
}

/// The runtime hooks attached to an [`HttpAcl`] at build time, via
/// [`HttpAclBuilder::build_full`]/[`HttpAclBuilder::try_build_full`].
///
/// Each field is typically a closure that captures state from outside the builder
/// (a database handle, a secret, and so on), which is why these aren't set through
/// dedicated builder setter methods the way most of [`HttpAclBuilder`]'s other
/// configuration is.
#[derive(Clone, Default)]
pub struct HttpAclHooks {
    /// See [`ValidateFn`].
    pub validate_fn: Option<ValidateFn>,
    /// See [`ModifyRequestFn`].
    pub modify_request_fn: Option<ModifyRequestFn>,
    /// See [`ModifyResponseFn`].
    pub modify_response_fn: Option<ModifyResponseFn>,
}

/// A builder for [`HttpAcl`].
///
/// Most categories (methods, hosts, port ranges, IP ranges, headers, URL paths,
/// static DNS mappings) follow the same set of methods: `add_allowed_*`/
/// `add_denied_*` to add a single entry, `remove_allowed_*`/`remove_denied_*` to
/// remove one, `allowed_*`/`denied_*` to replace the whole list at once, and
/// `clear_allowed_*`/`clear_denied_*` to empty it. The fallible variants return
/// [`AddError`] rather than panicking, e.g. when an entry is already present on the
/// opposite list, so a host (or header, port range, and so on) can never end up
/// allowed and denied at the same time.
///
/// Call [`Self::build`] or [`Self::try_build`] to finish. Only the latter validates
/// the finished configuration (uniqueness, overlaps, non-global IP ranges); see
/// their docs for when each applies.
#[derive(Default, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct HttpAclBuilder {
    allow_http: bool,
    allow_https: bool,
    allowed_methods: Vec<HttpRequestMethod>,
    denied_methods: Vec<HttpRequestMethod>,
    allowed_hosts: Vec<String>,
    denied_hosts: Vec<String>,
    #[cfg_attr(feature = "serde", serde(skip))]
    allowed_host_patterns: Vec<HostPattern>,
    #[cfg_attr(feature = "serde", serde(skip))]
    denied_host_patterns: Vec<HostPattern>,
    allowed_port_ranges: Vec<RangeInclusive<u16>>,
    denied_port_ranges: Vec<RangeInclusive<u16>>,
    allowed_ip_ranges: Vec<RangeInclusive<IpAddr>>,
    denied_ip_ranges: Vec<RangeInclusive<IpAddr>>,
    static_dns_mapping: HashMap<String, SocketAddr>,
    trusted_static_dns_mapping: HashMap<String, SocketAddr>,
    allowed_headers: HashMap<String, Option<String>>,
    denied_headers: HashMap<String, Option<String>>,
    allowed_url_paths: Vec<String>,
    #[cfg_attr(feature = "serde", serde(skip))]
    allowed_url_paths_router: Router<()>,
    denied_url_paths: Vec<String>,
    #[cfg_attr(feature = "serde", serde(skip))]
    denied_url_paths_router: Router<()>,
    allow_non_global_ip_ranges: bool,
    method_acl_default: bool,
    host_acl_default: bool,
    port_acl_default: bool,
    ip_acl_default: bool,
    header_acl_default: bool,
    url_path_acl_default: bool,
}

impl std::fmt::Debug for HttpAclBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpAclBuilder")
            .field("allow_http", &self.allow_http)
            .field("allow_https", &self.allow_https)
            .field("allowed_methods", &self.allowed_methods)
            .field("denied_methods", &self.denied_methods)
            .field("allowed_hosts", &self.allowed_hosts)
            .field("denied_hosts", &self.denied_hosts)
            .field("allowed_port_ranges", &self.allowed_port_ranges)
            .field("denied_port_ranges", &self.denied_port_ranges)
            .field("allowed_ip_ranges", &self.allowed_ip_ranges)
            .field("denied_ip_ranges", &self.denied_ip_ranges)
            .field("static_dns_mapping", &self.static_dns_mapping)
            .field(
                "trusted_static_dns_mapping",
                &self.trusted_static_dns_mapping,
            )
            .field("allowed_headers", &self.allowed_headers)
            .field("denied_headers", &self.denied_headers)
            .field("allowed_url_paths", &self.allowed_url_paths)
            .field("denied_url_paths", &self.denied_url_paths)
            .field(
                "allow_non_global_ip_ranges",
                &self.allow_non_global_ip_ranges,
            )
            .field("method_acl_default", &self.method_acl_default)
            .field("host_acl_default", &self.host_acl_default)
            .field("port_acl_default", &self.port_acl_default)
            .field("ip_acl_default", &self.ip_acl_default)
            .field("header_acl_default", &self.header_acl_default)
            .field("url_path_acl_default", &self.url_path_acl_default)
            .finish()
    }
}

impl PartialEq for HttpAclBuilder {
    fn eq(&self, other: &Self) -> bool {
        self.allow_http == other.allow_http
            && self.allow_https == other.allow_https
            && self.allowed_methods == other.allowed_methods
            && self.denied_methods == other.denied_methods
            && self.allowed_hosts == other.allowed_hosts
            && self.denied_hosts == other.denied_hosts
            && self.allowed_port_ranges == other.allowed_port_ranges
            && self.denied_port_ranges == other.denied_port_ranges
            && self.allowed_ip_ranges == other.allowed_ip_ranges
            && self.denied_ip_ranges == other.denied_ip_ranges
            && self.static_dns_mapping == other.static_dns_mapping
            && self.trusted_static_dns_mapping == other.trusted_static_dns_mapping
            && self.allowed_headers == other.allowed_headers
            && self.denied_headers == other.denied_headers
            && self.allowed_url_paths == other.allowed_url_paths
            && self.denied_url_paths == other.denied_url_paths
            && self.allow_non_global_ip_ranges == other.allow_non_global_ip_ranges
            && self.method_acl_default == other.method_acl_default
            && self.host_acl_default == other.host_acl_default
            && self.port_acl_default == other.port_acl_default
            && self.ip_acl_default == other.ip_acl_default
            && self.header_acl_default == other.header_acl_default
            && self.url_path_acl_default == other.url_path_acl_default
    }
}

impl HttpAclBuilder {
    /// Create a new [`HttpAclBuilder`].
    pub fn new() -> Self {
        Self {
            allow_http: true,
            allow_https: true,
            allowed_methods: vec![
                HttpRequestMethod::CONNECT,
                HttpRequestMethod::DELETE,
                HttpRequestMethod::GET,
                HttpRequestMethod::HEAD,
                HttpRequestMethod::OPTIONS,
                HttpRequestMethod::PATCH,
                HttpRequestMethod::POST,
                HttpRequestMethod::PUT,
                HttpRequestMethod::TRACE,
            ],
            denied_methods: Vec::new(),
            allowed_hosts: Vec::new(),
            denied_hosts: Vec::new(),
            allowed_host_patterns: Vec::new(),
            denied_host_patterns: Vec::new(),
            allowed_port_ranges: vec![80..=80, 443..=443],
            denied_port_ranges: Vec::new(),
            allowed_ip_ranges: Vec::new(),
            denied_ip_ranges: Vec::new(),
            allowed_headers: HashMap::new(),
            denied_headers: HashMap::new(),
            allowed_url_paths: Vec::new(),
            allowed_url_paths_router: Router::new(),
            denied_url_paths: Vec::new(),
            denied_url_paths_router: Router::new(),
            allow_non_global_ip_ranges: false,
            static_dns_mapping: HashMap::new(),
            trusted_static_dns_mapping: HashMap::new(),
            method_acl_default: false,
            host_acl_default: false,
            port_acl_default: false,
            ip_acl_default: false,
            header_acl_default: true,
            url_path_acl_default: true,
        }
    }

    /// Sets whether HTTP is allowed.
    pub fn http(mut self, allow: bool) -> Self {
        self.allow_http = allow;
        self
    }

    /// Sets whether HTTPS is allowed.
    pub fn https(mut self, allow: bool) -> Self {
        self.allow_https = allow;
        self
    }

    /// Sets whether non-global IP ranges are allowed.
    ///
    /// Non-global IP ranges include private, loopback, link-local, and other special-use addresses.
    pub fn non_global_ip_ranges(mut self, allow: bool) -> Self {
        self.allow_non_global_ip_ranges = allow;
        self
    }

    /// Set default action for HTTP methods if no ACL match is found.
    pub fn method_acl_default(mut self, allow: bool) -> Self {
        self.method_acl_default = allow;
        self
    }

    /// Set default action for hosts if no ACL match is found.
    pub fn host_acl_default(mut self, allow: bool) -> Self {
        self.host_acl_default = allow;
        self
    }

    /// Set default action for ports if no ACL match is found.
    pub fn port_acl_default(mut self, allow: bool) -> Self {
        self.port_acl_default = allow;
        self
    }

    /// Set default action for IPs if no ACL match is found.
    pub fn ip_acl_default(mut self, allow: bool) -> Self {
        self.ip_acl_default = allow;
        self
    }

    /// Set default action for headers if no ACL match is found.
    pub fn header_acl_default(mut self, allow: bool) -> Self {
        self.header_acl_default = allow;
        self
    }

    /// Set default action for URL paths if no ACL match is found.
    pub fn url_path_acl_default(mut self, allow: bool) -> Self {
        self.url_path_acl_default = allow;
        self
    }

    /// Adds a method to the allowed methods.
    ///
    /// Note: If you pass a string ensure it is uppercased first.
    pub fn add_allowed_method(
        mut self,
        method: impl Into<HttpRequestMethod>,
    ) -> Result<Self, AddError> {
        let method = method.into();
        if self.denied_methods.contains(&method) {
            Err(AddError::AlreadyDeniedMethod(method))
        } else if self.allowed_methods.contains(&method) {
            Err(AddError::AlreadyAllowedMethod(method))
        } else {
            self.allowed_methods.push(method);
            Ok(self)
        }
    }

    /// Removes a method from the allowed methods.
    ///
    /// Note: If you pass a string ensure it is uppercased first.
    pub fn remove_allowed_method(mut self, method: impl Into<HttpRequestMethod>) -> Self {
        let method = method.into();
        self.allowed_methods.retain(|m| m != &method);
        self
    }

    /// Sets the allowed methods.
    ///
    /// Note: If you pass strings ensure they are uppercased first.
    pub fn allowed_methods(
        mut self,
        methods: Vec<impl Into<HttpRequestMethod>>,
    ) -> Result<Self, AddError> {
        let methods = methods.into_iter().map(|m| m.into()).collect::<Vec<_>>();

        for method in &methods {
            if self.denied_methods.contains(method) {
                return Err(AddError::AlreadyDeniedMethod(method.clone()));
            }
        }
        self.allowed_methods = methods;
        Ok(self)
    }

    /// Clears the allowed methods.
    pub fn clear_allowed_methods(mut self) -> Self {
        self.allowed_methods.clear();
        self
    }

    /// Adds a method to the denied methods.
    ///
    /// Note: If you pass a string ensure it is uppercased first.
    pub fn add_denied_method(
        mut self,
        method: impl Into<HttpRequestMethod>,
    ) -> Result<Self, AddError> {
        let method = method.into();
        if self.allowed_methods.contains(&method) {
            Err(AddError::AlreadyAllowedMethod(method))
        } else if self.denied_methods.contains(&method) {
            Err(AddError::AlreadyDeniedMethod(method))
        } else {
            self.denied_methods.push(method);
            Ok(self)
        }
    }

    /// Removes a method from the denied methods.
    ///
    /// Note: If you pass a string ensure it is uppercased first.
    pub fn remove_denied_method(mut self, method: impl Into<HttpRequestMethod>) -> Self {
        let method = method.into();
        self.denied_methods.retain(|m| m != &method);
        self
    }

    /// Sets the denied methods.
    ///
    /// Note: If you pass strings ensure they are uppercased first.
    pub fn denied_methods(
        mut self,
        methods: Vec<impl Into<HttpRequestMethod>>,
    ) -> Result<Self, AddError> {
        let methods = methods.into_iter().map(|m| m.into()).collect::<Vec<_>>();

        for method in &methods {
            if self.allowed_methods.contains(method) {
                return Err(AddError::AlreadyAllowedMethod(method.clone()));
            }
        }
        self.denied_methods = methods;
        Ok(self)
    }

    /// Clears the denied methods.
    pub fn clear_denied_methods(mut self) -> Self {
        self.denied_methods.clear();
        self
    }

    /// Adds a host to the allowed hosts.
    ///
    /// `host` may be an exact hostname, or a wildcard pattern where each label
    /// (dot-separated segment) is either literal or one of:
    ///
    /// - `?` - matches exactly one label (e.g. `?.example.com` matches `foo.example.com`
    ///   but not `foo.bar.example.com` or bare `example.com`).
    /// - `*` - matches one or more labels (e.g. `*.example.com` matches `foo.example.com`
    ///   and `foo.bar.example.com`, but not bare `example.com`).
    ///
    /// A wildcard must occupy an entire label; `foo*.example.com` is not a valid pattern.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn add_allowed_host(mut self, host: String) -> Result<Self, AddError> {
        let pattern = Self::validate_host_or_pattern(&host)?;

        if self.denied_hosts.contains(&host) {
            return Err(AddError::AlreadyDeniedHost(host));
        }
        if self.allowed_hosts.contains(&host) {
            return Err(AddError::AlreadyAllowedHost(host));
        }

        if let Some(pattern) = pattern {
            self.allowed_host_patterns.push(pattern);
        }
        self.allowed_hosts.push(host);
        Ok(self)
    }

    /// Removes a host from the allowed hosts.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn remove_allowed_host(mut self, host: String) -> Self {
        self.allowed_hosts.retain(|h| h != &host);
        self.allowed_host_patterns = Self::compile_host_patterns(&self.allowed_hosts);
        self
    }

    /// Sets the allowed hosts.
    ///
    /// See [`Self::add_allowed_host`] for the wildcard pattern syntax.
    ///
    /// Note: The hosts should be in their canonical form (lowercase, punycode for IDN).
    pub fn allowed_hosts(mut self, hosts: Vec<String>) -> Result<Self, AddError> {
        let mut patterns = Vec::new();
        for host in &hosts {
            if let Some(pattern) = Self::validate_host_or_pattern(host)? {
                patterns.push(pattern);
            }
            if self.denied_hosts.contains(host) {
                return Err(AddError::AlreadyDeniedHost(host.clone()));
            }
        }
        self.allowed_host_patterns = patterns;
        self.allowed_hosts = hosts;
        Ok(self)
    }

    /// Clears the allowed hosts.
    pub fn clear_allowed_hosts(mut self) -> Self {
        self.allowed_hosts.clear();
        self.allowed_host_patterns.clear();
        self
    }

    /// Adds a host to the denied hosts.
    ///
    /// See [`Self::add_allowed_host`] for the wildcard pattern syntax.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn add_denied_host(mut self, host: String) -> Result<Self, AddError> {
        let pattern = Self::validate_host_or_pattern(&host)?;

        if self.allowed_hosts.contains(&host) {
            return Err(AddError::AlreadyAllowedHost(host));
        }
        if self.denied_hosts.contains(&host) {
            return Err(AddError::AlreadyDeniedHost(host));
        }

        if let Some(pattern) = pattern {
            self.denied_host_patterns.push(pattern);
        }
        self.denied_hosts.push(host);
        Ok(self)
    }

    /// Removes a host from the denied hosts.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn remove_denied_host(mut self, host: String) -> Self {
        self.denied_hosts.retain(|h| h != &host);
        self.denied_host_patterns = Self::compile_host_patterns(&self.denied_hosts);
        self
    }

    /// Sets the denied hosts.
    ///
    /// See [`Self::add_allowed_host`] for the wildcard pattern syntax.
    ///
    /// Note: The hosts should be in their canonical form (lowercase, punycode for IDN).
    pub fn denied_hosts(mut self, hosts: Vec<String>) -> Result<Self, AddError> {
        let mut patterns = Vec::new();
        for host in &hosts {
            if let Some(pattern) = Self::validate_host_or_pattern(host)? {
                patterns.push(pattern);
            }
            if self.allowed_hosts.contains(host) {
                return Err(AddError::AlreadyAllowedHost(host.clone()));
            }
        }
        self.denied_host_patterns = patterns;
        self.denied_hosts = hosts;
        Ok(self)
    }

    /// Clears the denied hosts.
    pub fn clear_denied_hosts(mut self) -> Self {
        self.denied_hosts.clear();
        self.denied_host_patterns.clear();
        self
    }

    /// Validates a host string, returning its compiled [`HostPattern`] if it is a
    /// wildcard pattern, or `None` if it's a literal host.
    fn validate_host_or_pattern(host: &str) -> Result<Option<HostPattern>, AddError> {
        if is_wildcard_host(host) {
            match HostPattern::parse(host) {
                Some(pattern) => Ok(Some(pattern)),
                None => Err(AddError::InvalidEntity(host.to_string())),
            }
        } else if utils::authority::is_valid_host(host) {
            Ok(None)
        } else {
            Err(AddError::InvalidEntity(host.to_string()))
        }
    }

    /// Compiles the wildcard patterns out of a list of (already-validated) host strings.
    fn compile_host_patterns(hosts: &[String]) -> Vec<HostPattern> {
        hosts
            .iter()
            .filter(|h| is_wildcard_host(h))
            .filter_map(|h| HostPattern::parse(h))
            .collect()
    }

    /// Adds a port range to the allowed port ranges.
    pub fn add_allowed_port_range(
        mut self,
        port_range: RangeInclusive<u16>,
    ) -> Result<Self, AddError> {
        if self.denied_port_ranges.contains(&port_range) {
            Err(AddError::AlreadyDeniedPortRange(port_range))
        } else if self.allowed_port_ranges.contains(&port_range) {
            Err(AddError::AlreadyAllowedPortRange(port_range))
        } else if utils::range_overlaps(&self.allowed_port_ranges, &port_range, None)
            || utils::range_overlaps(&self.denied_port_ranges, &port_range, None)
        {
            Err(AddError::Overlaps(format!("{port_range:?}")))
        } else {
            self.allowed_port_ranges.push(port_range);
            Ok(self)
        }
    }

    /// Removes a port range from the allowed port ranges.
    pub fn remove_allowed_port_range(mut self, port_range: RangeInclusive<u16>) -> Self {
        self.allowed_port_ranges.retain(|p| p != &port_range);
        self
    }

    /// Sets the allowed port ranges.
    pub fn allowed_port_ranges(
        mut self,
        port_ranges: Vec<RangeInclusive<u16>>,
    ) -> Result<Self, AddError> {
        for (i, port_range) in port_ranges.iter().enumerate() {
            if self.denied_port_ranges.contains(port_range) {
                return Err(AddError::AlreadyDeniedPortRange(port_range.clone()));
            } else if utils::range_overlaps(&port_ranges, port_range, Some(i))
                || utils::range_overlaps(&self.denied_port_ranges, port_range, None)
            {
                return Err(AddError::Overlaps(format!("{port_range:?}")));
            }
        }
        self.allowed_port_ranges = port_ranges;
        Ok(self)
    }

    /// Clears the allowed port ranges.
    pub fn clear_allowed_port_ranges(mut self) -> Self {
        self.allowed_port_ranges.clear();
        self
    }

    /// Adds a port range to the denied port ranges.
    pub fn add_denied_port_range(
        mut self,
        port_range: RangeInclusive<u16>,
    ) -> Result<Self, AddError> {
        if self.allowed_port_ranges.contains(&port_range) {
            Err(AddError::AlreadyAllowedPortRange(port_range))
        } else if self.denied_port_ranges.contains(&port_range) {
            Err(AddError::AlreadyDeniedPortRange(port_range))
        } else if utils::range_overlaps(&self.allowed_port_ranges, &port_range, None)
            || utils::range_overlaps(&self.denied_port_ranges, &port_range, None)
        {
            Err(AddError::Overlaps(format!("{port_range:?}")))
        } else {
            self.denied_port_ranges.push(port_range);
            Ok(self)
        }
    }

    /// Removes a port range from the denied port ranges.
    pub fn remove_denied_port_range(mut self, port_range: RangeInclusive<u16>) -> Self {
        self.denied_port_ranges.retain(|p| p != &port_range);
        self
    }

    /// Sets the denied port ranges.
    pub fn denied_port_ranges(
        mut self,
        port_ranges: Vec<RangeInclusive<u16>>,
    ) -> Result<Self, AddError> {
        for (i, port_range) in port_ranges.iter().enumerate() {
            if self.allowed_port_ranges.contains(port_range) {
                return Err(AddError::AlreadyAllowedPortRange(port_range.clone()));
            } else if utils::range_overlaps(&port_ranges, port_range, Some(i))
                || utils::range_overlaps(&self.allowed_port_ranges, port_range, None)
            {
                return Err(AddError::Overlaps(format!("{port_range:?}")));
            }
        }
        self.denied_port_ranges = port_ranges;
        Ok(self)
    }

    /// Clears the denied port ranges.
    pub fn clear_denied_port_ranges(mut self) -> Self {
        self.denied_port_ranges.clear();
        self
    }

    /// Adds an IP range to the allowed IP ranges.
    pub fn add_allowed_ip_range<Ip: IntoIpRange>(mut self, ip_range: Ip) -> Result<Self, AddError> {
        let ip_range = ip_range
            .into_range()
            .ok_or_else(|| AddError::InvalidEntity("Invalid IP range".to_string()))?;
        if self.denied_ip_ranges.contains(&ip_range) {
            return Err(AddError::AlreadyDeniedIpRange(ip_range));
        } else if self.allowed_ip_ranges.contains(&ip_range) {
            return Err(AddError::AlreadyAllowedIpRange(ip_range));
        } else if utils::range_overlaps(&self.allowed_ip_ranges, &ip_range, None)
            || utils::range_overlaps(&self.denied_ip_ranges, &ip_range, None)
        {
            return Err(AddError::Overlaps(format!("{ip_range:?}")));
        }
        self.allowed_ip_ranges.push(ip_range);
        Ok(self)
    }

    /// Removes an IP range from the allowed IP ranges.
    pub fn remove_allowed_ip_range<Ip: IntoIpRange>(
        mut self,
        ip_range: Ip,
    ) -> Result<Self, AddError> {
        let ip_range = ip_range
            .into_range()
            .ok_or_else(|| AddError::InvalidEntity("Invalid IP range".to_string()))?;
        self.allowed_ip_ranges.retain(|ip| ip != &ip_range);
        Ok(self)
    }

    /// Sets the allowed IP ranges.
    pub fn allowed_ip_ranges<Ip: IntoIpRange>(
        mut self,
        ip_ranges: Vec<Ip>,
    ) -> Result<Self, AddError> {
        let ip_ranges = ip_ranges
            .into_iter()
            .map(|ip| ip.into_range())
            .collect::<Option<Vec<_>>>()
            .ok_or_else(|| AddError::InvalidEntity("Invalid IP range".to_string()))?;
        for (i, ip_range) in ip_ranges.iter().enumerate() {
            if self.denied_ip_ranges.contains(ip_range) {
                return Err(AddError::AlreadyDeniedIpRange(ip_range.clone()));
            } else if utils::range_overlaps(&ip_ranges, ip_range, Some(i))
                || utils::range_overlaps(&self.denied_ip_ranges, ip_range, None)
            {
                return Err(AddError::Overlaps(format!("{ip_range:?}")));
            }
        }
        self.allowed_ip_ranges = ip_ranges;
        Ok(self)
    }

    /// Clears the allowed IP ranges.
    pub fn clear_allowed_ip_ranges(mut self) -> Self {
        self.allowed_ip_ranges.clear();
        self
    }

    /// Adds an IP range to the denied IP ranges.
    pub fn add_denied_ip_range<Ip: IntoIpRange>(mut self, ip_range: Ip) -> Result<Self, AddError> {
        let ip_range = ip_range
            .into_range()
            .ok_or_else(|| AddError::InvalidEntity("Invalid IP range".to_string()))?;
        if self.allowed_ip_ranges.contains(&ip_range) {
            return Err(AddError::AlreadyAllowedIpRange(ip_range));
        } else if self.denied_ip_ranges.contains(&ip_range) {
            return Err(AddError::AlreadyDeniedIpRange(ip_range));
        } else if utils::range_overlaps(&self.allowed_ip_ranges, &ip_range, None)
            || utils::range_overlaps(&self.denied_ip_ranges, &ip_range, None)
        {
            return Err(AddError::Overlaps(format!("{ip_range:?}")));
        }
        self.denied_ip_ranges.push(ip_range);
        Ok(self)
    }

    /// Removes an IP range from the denied IP ranges.
    pub fn remove_denied_ip_range<Ip: IntoIpRange>(
        mut self,
        ip_range: Ip,
    ) -> Result<Self, AddError> {
        let ip_range = ip_range
            .into_range()
            .ok_or_else(|| AddError::InvalidEntity("Invalid IP range".to_string()))?;
        self.denied_ip_ranges.retain(|ip| ip != &ip_range);
        Ok(self)
    }

    /// Sets the denied IP ranges.
    pub fn denied_ip_ranges<Ip: IntoIpRange>(
        mut self,
        ip_ranges: Vec<Ip>,
    ) -> Result<Self, AddError> {
        let ip_ranges = ip_ranges
            .into_iter()
            .map(|ip| ip.into_range())
            .collect::<Option<Vec<_>>>()
            .ok_or_else(|| AddError::InvalidEntity("Invalid IP range".to_string()))?;
        for (i, ip_range) in ip_ranges.iter().enumerate() {
            if self.allowed_ip_ranges.contains(ip_range) {
                return Err(AddError::AlreadyAllowedIpRange(ip_range.clone()));
            } else if utils::range_overlaps(&ip_ranges, ip_range, Some(i))
                || utils::range_overlaps(&self.allowed_ip_ranges, ip_range, None)
            {
                return Err(AddError::Overlaps(format!("{ip_range:?}")));
            }
        }
        self.denied_ip_ranges = ip_ranges;
        Ok(self)
    }

    /// Clears the denied IP ranges.
    pub fn clear_denied_ip_ranges(mut self) -> Self {
        self.denied_ip_ranges.clear();
        self
    }

    /// Add a static DNS mapping.
    ///
    /// The resolved address is still subject to the IP and port ACL. Use
    /// [`Self::add_trusted_static_dns_mapping`] for a mapping that should bypass
    /// those checks entirely.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn add_static_dns_mapping(
        mut self,
        host: String,
        sock_addr: SocketAddr,
    ) -> Result<Self, AddError> {
        if !utils::authority::is_valid_host(&host) {
            return Err(AddError::InvalidEntity(host));
        }
        if self.trusted_static_dns_mapping.contains_key(&host) {
            return Err(AddError::AlreadyPresentTrustedStaticDnsMapping(
                host, sock_addr,
            ));
        }
        if let Entry::Vacant(e) = self.static_dns_mapping.entry(host.clone()) {
            e.insert(sock_addr);
            Ok(self)
        } else {
            Err(AddError::AlreadyPresentStaticDnsMapping(host, sock_addr))
        }
    }

    /// Removes a static DNS mapping.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn remove_static_dns_mapping(mut self, host: &str) -> Self {
        self.static_dns_mapping.remove(host);
        self
    }

    /// Sets the static DNS mappings.
    ///
    /// Note: The hosts should be in their canonical form (lowercase, punycode for IDN).
    pub fn static_dns_mappings(
        mut self,
        mappings: HashMap<String, SocketAddr>,
    ) -> Result<Self, AddError> {
        for (host, ip) in &mappings {
            if !utils::authority::is_valid_host(host) {
                return Err(AddError::InvalidEntity(host.clone()));
            }
            if self.trusted_static_dns_mapping.contains_key(host) {
                return Err(AddError::AlreadyPresentTrustedStaticDnsMapping(
                    host.clone(),
                    *ip,
                ));
            }
            if self.static_dns_mapping.contains_key(host) {
                return Err(AddError::AlreadyPresentStaticDnsMapping(host.clone(), *ip));
            }
            self.static_dns_mapping.insert(host.to_string(), *ip);
        }
        Ok(self)
    }

    /// Clears the static DNS mappings.
    pub fn clear_static_dns_mappings(mut self) -> Self {
        self.static_dns_mapping.clear();
        self
    }

    /// Add a trusted static DNS mapping.
    ///
    /// Unlike [`Self::add_static_dns_mapping`], the resolved address is meant to
    /// bypass the IP and port ACL entirely - only use this for mappings you trust
    /// regardless of what the ACL would otherwise say (e.g. pinning a hostname to an
    /// internal address on purpose).
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn add_trusted_static_dns_mapping(
        mut self,
        host: String,
        sock_addr: SocketAddr,
    ) -> Result<Self, AddError> {
        if !utils::authority::is_valid_host(&host) {
            return Err(AddError::InvalidEntity(host));
        }
        if self.static_dns_mapping.contains_key(&host) {
            return Err(AddError::AlreadyPresentStaticDnsMapping(host, sock_addr));
        }
        if let Entry::Vacant(e) = self.trusted_static_dns_mapping.entry(host.clone()) {
            e.insert(sock_addr);
            Ok(self)
        } else {
            Err(AddError::AlreadyPresentTrustedStaticDnsMapping(
                host, sock_addr,
            ))
        }
    }

    /// Removes a trusted static DNS mapping.
    ///
    /// Note: The host should be in its canonical form (lowercase, punycode for IDN).
    pub fn remove_trusted_static_dns_mapping(mut self, host: &str) -> Self {
        self.trusted_static_dns_mapping.remove(host);
        self
    }

    /// Sets the trusted static DNS mappings.
    ///
    /// Note: The hosts should be in their canonical form (lowercase, punycode for IDN).
    pub fn trusted_static_dns_mappings(
        mut self,
        mappings: HashMap<String, SocketAddr>,
    ) -> Result<Self, AddError> {
        for (host, ip) in &mappings {
            if !utils::authority::is_valid_host(host) {
                return Err(AddError::InvalidEntity(host.clone()));
            }
            if self.static_dns_mapping.contains_key(host) {
                return Err(AddError::AlreadyPresentStaticDnsMapping(host.clone(), *ip));
            }
            if self.trusted_static_dns_mapping.contains_key(host) {
                return Err(AddError::AlreadyPresentTrustedStaticDnsMapping(
                    host.clone(),
                    *ip,
                ));
            }
            self.trusted_static_dns_mapping
                .insert(host.to_string(), *ip);
        }
        Ok(self)
    }

    /// Clears the trusted static DNS mappings.
    pub fn clear_trusted_static_dns_mappings(mut self) -> Self {
        self.trusted_static_dns_mapping.clear();
        self
    }

    /// Adds a header to the allowed headers.
    ///
    /// If `value` is `None`, any value for the header is allowed.
    ///
    /// Note: Ensure header names are lowercased.
    pub fn add_allowed_header(
        mut self,
        header: String,
        value: Option<String>,
    ) -> Result<Self, AddError> {
        if self.denied_headers.contains_key(&header) {
            Err(AddError::AlreadyDeniedHeader(header, value.clone()))
        } else if let Entry::Vacant(e) = self.allowed_headers.entry(header.clone()) {
            e.insert(value);
            Ok(self)
        } else {
            Err(AddError::AlreadyAllowedHeader(header, value))
        }
    }

    /// Removes a header from the allowed headers.
    ///
    /// Note: Ensure header names are lowercased.
    pub fn remove_allowed_header(mut self, header: &str) -> Self {
        self.allowed_headers.remove(header);
        self
    }

    /// Sets the allowed headers.
    ///
    /// Note: Ensure header names are lowercased.
    pub fn allowed_headers(
        mut self,
        headers: HashMap<String, Option<String>>,
    ) -> Result<Self, AddError> {
        for (header, value) in &headers {
            if self.denied_headers.contains_key(header) {
                return Err(AddError::AlreadyDeniedHeader(header.clone(), value.clone()));
            }
        }
        self.allowed_headers = headers;
        Ok(self)
    }

    /// Clears the allowed headers.
    pub fn clear_allowed_headers(mut self) -> Self {
        self.allowed_headers.clear();
        self
    }

    /// Adds a header to the denied headers.
    ///
    /// If `value` is `None`, any value for the header is denied.
    ///
    /// Note: Ensure header names are lowercased.
    pub fn add_denied_header(
        mut self,
        header: String,
        value: Option<String>,
    ) -> Result<Self, AddError> {
        if self.allowed_headers.contains_key(&header) {
            Err(AddError::AlreadyAllowedHeader(header, value.clone()))
        } else if let Entry::Vacant(e) = self.denied_headers.entry(header.clone()) {
            e.insert(value);
            Ok(self)
        } else {
            Err(AddError::AlreadyDeniedHeader(header, value))
        }
    }

    /// Removes a header from the denied headers.
    ///
    /// Note: Ensure header names are lowercased.
    pub fn remove_denied_header(mut self, header: &str) -> Self {
        self.denied_headers.remove(header);
        self
    }

    /// Sets the denied headers.
    ///
    /// Note: Ensure header names are lowercased.
    pub fn denied_headers(
        mut self,
        headers: HashMap<String, Option<String>>,
    ) -> Result<Self, AddError> {
        for (header, value) in &headers {
            if self.allowed_headers.contains_key(header) {
                return Err(AddError::AlreadyAllowedHeader(
                    header.clone(),
                    value.clone(),
                ));
            }
        }
        self.denied_headers = headers;
        Ok(self)
    }

    /// Clears the denied headers.
    pub fn clear_denied_headers(mut self) -> Self {
        self.denied_headers.clear();
        self
    }

    /// Adds a URL path to the allowed URL paths.
    ///
    /// Note: URL paths should start with a '/' and be properly URL-encoded.
    pub fn add_allowed_url_path(mut self, url_path: String) -> Result<Self, AddError> {
        if self.denied_url_paths.contains(&url_path)
            || self.denied_url_paths_router.at(&url_path).is_ok()
        {
            Err(AddError::AlreadyDeniedUrlPath(url_path))
        } else if self.allowed_url_paths.contains(&url_path)
            || self.allowed_url_paths_router.at(&url_path).is_ok()
        {
            Err(AddError::AlreadyAllowedUrlPath(url_path))
        } else {
            self.allowed_url_paths.push(url_path.clone());
            self.allowed_url_paths_router
                .insert(url_path, ())
                .map_err(|_| AddError::InvalidEntity("Invalid URL path".to_string()))?;
            Ok(self)
        }
    }

    /// Removes a URL path from the allowed URL paths.
    ///
    /// Note: URL paths should start with a '/' and be properly URL-encoded.
    pub fn remove_allowed_url_path(mut self, url_path: &str) -> Self {
        self.allowed_url_paths.retain(|p| p != url_path);
        self.allowed_url_paths_router = {
            let mut router = Router::new();
            for url_path in &self.allowed_url_paths {
                router
                    .insert(url_path.clone(), ())
                    .expect("failed to insert url path");
            }
            router
        };
        self
    }

    /// Sets the allowed URL paths.
    ///
    /// Note: URL paths should start with a '/' and be properly URL-encoded.
    pub fn allowed_url_paths(mut self, url_paths: Vec<String>) -> Result<Self, AddError> {
        for url_path in &url_paths {
            if self.denied_url_paths.contains(url_path)
                || self.denied_url_paths_router.at(url_path).is_ok()
            {
                return Err(AddError::AlreadyDeniedUrlPath(url_path.clone()));
            }
        }
        self.allowed_url_paths_router = Router::new();
        for url_path in &url_paths {
            self.allowed_url_paths_router
                .insert(url_path.clone(), ())
                .map_err(|_| AddError::InvalidEntity(format!("Invalid URL path: {url_path}")))?;
        }
        self.allowed_url_paths = url_paths;
        Ok(self)
    }

    /// Clears the allowed URL paths.
    pub fn clear_allowed_url_paths(mut self) -> Self {
        self.allowed_url_paths.clear();
        self.allowed_url_paths_router = Router::new();
        self
    }

    /// Adds a URL path to the denied URL paths.
    ///
    /// Note: URL paths should start with a '/' and be properly URL-encoded.
    pub fn add_denied_url_path(mut self, url_path: String) -> Result<Self, AddError> {
        if self.allowed_url_paths.contains(&url_path)
            || self.allowed_url_paths_router.at(&url_path).is_ok()
        {
            Err(AddError::AlreadyAllowedUrlPath(url_path))
        } else if self.denied_url_paths.contains(&url_path)
            || self.denied_url_paths_router.at(&url_path).is_ok()
        {
            Err(AddError::AlreadyDeniedUrlPath(url_path))
        } else {
            self.denied_url_paths.push(url_path.clone());
            self.denied_url_paths_router
                .insert(url_path, ())
                .map_err(|_| AddError::InvalidEntity("Invalid URL path".to_string()))?;
            Ok(self)
        }
    }

    /// Removes a URL path from the denied URL paths.
    ///
    /// Note: URL paths should start with a '/' and be properly URL-encoded.
    pub fn remove_denied_url_path(mut self, url_path: &str) -> Self {
        self.denied_url_paths.retain(|p| p != url_path);
        self.denied_url_paths_router = {
            let mut router = Router::new();
            for url_path in &self.denied_url_paths {
                router
                    .insert(url_path.clone(), ())
                    .expect("failed to insert url path");
            }
            router
        };
        self
    }

    /// Sets the denied URL paths.
    ///
    /// Note: URL paths should start with a '/' and be properly URL-encoded.
    pub fn denied_url_paths(mut self, url_paths: Vec<String>) -> Result<Self, AddError> {
        for url_path in &url_paths {
            if self.allowed_url_paths.contains(url_path)
                || self.allowed_url_paths_router.at(url_path).is_ok()
            {
                return Err(AddError::AlreadyAllowedUrlPath(url_path.clone()));
            }
        }
        self.denied_url_paths_router = Router::new();
        for url_path in &url_paths {
            self.denied_url_paths_router
                .insert(url_path.clone(), ())
                .map_err(|_| AddError::InvalidEntity(format!("Invalid URL path: {url_path}")))?;
        }
        self.denied_url_paths = url_paths;
        Ok(self)
    }

    /// Clears the denied URL paths.
    pub fn clear_denied_url_paths(mut self) -> Self {
        self.denied_url_paths.clear();
        self.denied_url_paths_router = Router::new();
        self
    }

    /// Builds the [`HttpAcl`], without any [`HttpAclHooks`] attached.
    ///
    /// This does not validate the configuration (uniqueness, overlaps, non-global IP
    /// ranges); use [`Self::try_build`] instead if the builder wasn't assembled
    /// entirely through this type's own fallible `add_*`/`allowed_*`/`denied_*`
    /// methods, e.g. if it was deserialized. See [`Self::try_build`] for details.
    pub fn build(self) -> HttpAcl {
        self.build_full(HttpAclHooks::default())
    }

    /// Builds the [`HttpAcl`] with the given [`HttpAclHooks`] attached.
    ///
    /// This is the only way to attach a `ValidateFn`, `ModifyRequestFn`, or
    /// `ModifyResponseFn`; there is no dedicated builder setter for any of them.
    /// Like [`Self::build`], this does not validate the configuration; use
    /// [`Self::try_build_full`] for that.
    pub fn build_full(self, hooks: HttpAclHooks) -> HttpAcl {
        HttpAcl {
            allow_http: self.allow_http,
            allow_https: self.allow_https,
            allowed_methods: self.allowed_methods.into_iter().collect(),
            denied_methods: self.denied_methods.into_iter().collect(),
            allowed_hosts: self
                .allowed_hosts
                .into_iter()
                .filter(|h| !is_wildcard_host(h))
                .map(|x| x.into_boxed_str())
                .collect(),
            denied_hosts: self
                .denied_hosts
                .into_iter()
                .filter(|h| !is_wildcard_host(h))
                .map(|x| x.into_boxed_str())
                .collect(),
            allowed_host_patterns: self.allowed_host_patterns.into_boxed_slice(),
            denied_host_patterns: self.denied_host_patterns.into_boxed_slice(),
            allowed_port_ranges: self.allowed_port_ranges.into_boxed_slice(),
            denied_port_ranges: self.denied_port_ranges.into_boxed_slice(),
            allowed_ip_ranges: self.allowed_ip_ranges.into_boxed_slice(),
            denied_ip_ranges: self.denied_ip_ranges.into_boxed_slice(),
            allowed_headers: self
                .allowed_headers
                .into_iter()
                .map(|(k, v)| (k.into_boxed_str(), v.map(|s| s.into_boxed_str())))
                .collect(),
            denied_headers: self
                .denied_headers
                .into_iter()
                .map(|(k, v)| (k.into_boxed_str(), v.map(|s| s.into_boxed_str())))
                .collect(),
            allowed_url_paths_router: self.allowed_url_paths_router,
            denied_url_paths_router: self.denied_url_paths_router,
            static_dns_mapping: self
                .static_dns_mapping
                .into_iter()
                .map(|(k, v)| (k.into_boxed_str(), v))
                .collect(),
            trusted_static_dns_mapping: self
                .trusted_static_dns_mapping
                .into_iter()
                .map(|(k, v)| (k.into_boxed_str(), v))
                .collect(),
            validate_fn: hooks.validate_fn,
            modify_request_fn: hooks.modify_request_fn,
            modify_response_fn: hooks.modify_response_fn,
            allow_non_global_ip_ranges: self.allow_non_global_ip_ranges,
            method_acl_default: self.method_acl_default,
            host_acl_default: self.host_acl_default,
            port_acl_default: self.port_acl_default,
            ip_acl_default: self.ip_acl_default,
            header_acl_default: self.header_acl_default,
            url_path_acl_default: self.url_path_acl_default,
        }
    }

    /// Builds the [`HttpAcl`] with the given [`HttpAclHooks`] attached, validating
    /// the configuration first.
    ///
    /// Checks each category for unique entries, non-overlapping ranges, and no host
    /// (or port range, IP range, header, and so on) present on both the allowed and
    /// denied lists, returning [`AddError`] on the first problem found. It also
    /// enforces that IP ranges are global unless [`Self::non_global_ip_ranges`] was
    /// set to `true`, which [`Self::add_allowed_ip_range`]/
    /// [`Self::add_denied_ip_range`] do not check themselves.
    ///
    /// Prefer this over [`Self::build_full`] whenever the builder wasn't assembled
    /// entirely through this type's own fallible methods, most notably a builder
    /// deserialized from an untrusted source: deserialization writes fields directly
    /// and bypasses the checks each `add_*` method normally performs, so this is also
    /// what rebuilds the URL path routers and wildcard host patterns skipped for that
    /// reason.
    pub fn try_build_full(mut self, hooks: HttpAclHooks) -> Result<HttpAcl, AddError> {
        if !utils::has_unique_elements(&self.allowed_methods) {
            return Err(AddError::NotUnique(
                "Allowed methods must be unique.".to_string(),
            ));
        }
        for method in &self.allowed_methods {
            if self.denied_methods.contains(method) {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "Method `{}`",
                    method.as_str()
                )));
            }
        }
        if !utils::has_unique_elements(&self.denied_methods) {
            return Err(AddError::NotUnique(
                "Denied methods must be unique.".to_string(),
            ));
        }
        for method in &self.denied_methods {
            if self.allowed_methods.contains(method) {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "Method `{}`",
                    method.as_str()
                )));
            }
        }
        if !utils::has_unique_elements(&self.allowed_hosts) {
            return Err(AddError::NotUnique(
                "Allowed hosts must be unique.".to_string(),
            ));
        }
        for host in &self.allowed_hosts {
            if is_wildcard_host(host) {
                match HostPattern::parse(host) {
                    Some(pattern) => {
                        if !self.allowed_host_patterns.contains(&pattern) {
                            self.allowed_host_patterns.push(pattern);
                        }
                    }
                    None => return Err(AddError::InvalidEntity(host.to_string())),
                }
            } else if !utils::authority::is_valid_host(host) {
                return Err(AddError::InvalidEntity(host.to_string()));
            }
            if self.denied_hosts.contains(host) {
                return Err(AddError::BothAllowedAndDenied(format!("Host `{host}`")));
            }
        }
        if !utils::has_unique_elements(&self.denied_hosts) {
            return Err(AddError::NotUnique(
                "Denied hosts must be unique.".to_string(),
            ));
        }
        for host in &self.denied_hosts {
            if is_wildcard_host(host) {
                match HostPattern::parse(host) {
                    Some(pattern) => {
                        if !self.denied_host_patterns.contains(&pattern) {
                            self.denied_host_patterns.push(pattern);
                        }
                    }
                    None => return Err(AddError::InvalidEntity(host.to_string())),
                }
            } else if !utils::authority::is_valid_host(host) {
                return Err(AddError::InvalidEntity(host.to_string()));
            }
            if self.allowed_hosts.contains(host) {
                return Err(AddError::BothAllowedAndDenied(format!("Host `{host}`")));
            }
        }
        if !utils::has_unique_elements(&self.allowed_port_ranges) {
            return Err(AddError::NotUnique(
                "Allowed port ranges must be unique.".to_string(),
            ));
        }
        if utils::has_overlapping_ranges(&self.allowed_port_ranges) {
            return Err(AddError::Overlaps(
                "Allowed port ranges must not overlap.".to_string(),
            ));
        }
        for port_range in &self.allowed_port_ranges {
            if self.denied_port_ranges.contains(port_range) {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "Port range `{port_range:?}`"
                )));
            }
        }
        if !utils::has_unique_elements(&self.denied_port_ranges) {
            return Err(AddError::NotUnique(
                "Denied port ranges must be unique.".to_string(),
            ));
        }
        if utils::has_overlapping_ranges(&self.denied_port_ranges) {
            return Err(AddError::Overlaps(
                "Denied port ranges must not overlap.".to_string(),
            ));
        }
        for port_range in &self.denied_port_ranges {
            if self.allowed_port_ranges.contains(port_range) {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "Port range `{port_range:?}`"
                )));
            }
        }
        if !utils::has_unique_elements(&self.allowed_ip_ranges) {
            return Err(AddError::NotUnique(
                "Allowed IP ranges must be unique.".to_string(),
            ));
        }
        if utils::has_overlapping_ranges(&self.allowed_ip_ranges) {
            return Err(AddError::Overlaps(
                "Allowed IP ranges must not overlap.".to_string(),
            ));
        }
        for ip_range in &self.allowed_ip_ranges {
            if self.denied_ip_ranges.contains(ip_range) {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "IP range `{ip_range:?}`"
                )));
            }

            if (!utils::ip::is_global_ip(ip_range.start())
                || !utils::ip::is_global_ip(ip_range.end()))
                && !self.allow_non_global_ip_ranges
            {
                return Err(AddError::NonGlobalIpRange(ip_range.clone()));
            }
        }
        if !utils::has_unique_elements(&self.denied_ip_ranges) {
            return Err(AddError::NotUnique(
                "Denied IP ranges must be unique.".to_string(),
            ));
        }
        if utils::has_overlapping_ranges(&self.denied_ip_ranges) {
            return Err(AddError::Overlaps(
                "Denied IP ranges must not overlap.".to_string(),
            ));
        }
        for ip_range in &self.denied_ip_ranges {
            if self.allowed_ip_ranges.contains(ip_range) {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "IP range `{ip_range:?}`"
                )));
            }

            if (!utils::ip::is_global_ip(ip_range.start())
                || !utils::ip::is_global_ip(ip_range.end()))
                && !self.allow_non_global_ip_ranges
            {
                return Err(AddError::NonGlobalIpRange(ip_range.clone()));
            }
        }
        if !utils::has_unique_elements(&self.static_dns_mapping) {
            return Err(AddError::NotUnique(
                "Static DNS mapping must be unique.".to_string(),
            ));
        }
        for (host, addr) in &self.static_dns_mapping {
            if !utils::authority::is_valid_host(host) {
                return Err(AddError::InvalidEntity(host.to_string()));
            }
            if self.trusted_static_dns_mapping.contains_key(host) {
                return Err(AddError::AlreadyPresentTrustedStaticDnsMapping(
                    host.to_string(),
                    *addr,
                ));
            }
        }
        if !utils::has_unique_elements(&self.trusted_static_dns_mapping) {
            return Err(AddError::NotUnique(
                "Trusted static DNS mapping must be unique.".to_string(),
            ));
        }
        for host in self.trusted_static_dns_mapping.keys() {
            if !utils::authority::is_valid_host(host) {
                return Err(AddError::InvalidEntity(host.to_string()));
            }
        }
        if !utils::has_unique_elements(&self.allowed_url_paths) {
            return Err(AddError::NotUnique(
                "Allowed URL paths must be unique.".to_string(),
            ));
        }
        for url_path in &self.allowed_url_paths {
            if self.denied_url_paths.contains(url_path)
                || self.denied_url_paths_router.at(url_path).is_ok()
            {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "URL path `{url_path}`"
                )));
            } else if self.allowed_url_paths_router.at(url_path).is_err() {
                self.allowed_url_paths_router
                    .insert(url_path.clone(), ())
                    .map_err(|_| {
                        AddError::InvalidEntity(format!(
                            "Failed to insert allowed URL path `{url_path}`."
                        ))
                    })?;
            }
        }
        if !utils::has_unique_elements(&self.denied_url_paths) {
            return Err(AddError::NotUnique(
                "Denied URL paths must be unique.".to_string(),
            ));
        }
        for url_path in &self.denied_url_paths {
            if self.allowed_url_paths.contains(url_path)
                || self.allowed_url_paths_router.at(url_path).is_ok()
            {
                return Err(AddError::BothAllowedAndDenied(format!(
                    "URL path `{url_path}`"
                )));
            } else if self.denied_url_paths_router.at(url_path).is_err() {
                self.denied_url_paths_router
                    .insert(url_path.clone(), ())
                    .map_err(|_| {
                        AddError::InvalidEntity(format!(
                            "Failed to insert denied URL path `{url_path}`."
                        ))
                    })?;
            }
        }
        Ok(self.build_full(hooks))
    }

    /// Builds the [`HttpAcl`], without any [`HttpAclHooks`] attached, validating
    /// the configuration first. See [`Self::try_build_full`] for what is validated
    /// and when to prefer this over [`Self::build`].
    pub fn try_build(self) -> Result<HttpAcl, AddError> {
        self.try_build_full(HttpAclHooks::default())
    }
}