shoes 0.3.2

A multi-protocol proxy server.
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
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
use log::{debug, error};
use lru::LruCache;
use parking_lot::RwLock;
use std::hash::Hash;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::num::NonZeroUsize;
use std::sync::Arc;

use crate::address::{Address, NetLocation, ResolvedLocation};
use crate::address::{AddressMask, NetLocationMask};
use crate::client_proxy_chain::ClientChainGroup;
use crate::resolver::{Resolver, resolve_location};

/// Cache key for routing decisions.
/// We cache based on the destination address and port.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum RoutingCacheKey {
    /// Hostname destination (e.g., "example.com:443")
    Hostname { hostname: String, port: u16 },
    /// IPv4 destination
    Ipv4 { addr: Ipv4Addr, port: u16 },
    /// IPv6 destination
    Ipv6 { addr: Ipv6Addr, port: u16 },
}

impl RoutingCacheKey {
    fn from_location(location: &NetLocation) -> Self {
        match location.address() {
            Address::Hostname(hostname) => RoutingCacheKey::Hostname {
                hostname: hostname
                    .strip_suffix('.')
                    .unwrap_or(hostname)
                    .to_ascii_lowercase(),
                port: location.port(),
            },
            Address::Ipv4(addr) => RoutingCacheKey::Ipv4 {
                addr: *addr,
                port: location.port(),
            },
            Address::Ipv6(addr) => RoutingCacheKey::Ipv6 {
                addr: *addr,
                port: location.port(),
            },
        }
    }
}

/// Cached routing decision.
#[derive(Debug, Clone, Copy)]
pub(crate) enum CachedDecision {
    /// Index into the rules Vec for an Allow decision
    Allow(usize),
    /// Block decision
    Block,
}

/// LRU cache for routing decisions.
/// Uses RwLock for concurrent access - reads use peek() which doesn't require mutable access.
pub struct RoutingCache {
    inner: RwLock<LruCache<RoutingCacheKey, CachedDecision>>,
}

impl std::fmt::Debug for RoutingCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cache = self.inner.read();
        f.debug_struct("RoutingCache")
            .field("len", &cache.len())
            .field("cap", &cache.cap())
            .finish()
    }
}

impl RoutingCache {
    /// Default cache capacity
    pub const DEFAULT_CAPACITY: usize = 10_000;

    /// Create a new routing cache with the specified capacity.
    pub fn new(capacity: usize) -> Self {
        let cap = NonZeroUsize::new(capacity).unwrap_or(NonZeroUsize::new(1).unwrap());
        Self {
            inner: RwLock::new(LruCache::new(cap)),
        }
    }

    /// Look up a cached decision.
    /// Uses peek() which doesn't update LRU order (avoids write lock).
    #[inline]
    pub fn get(&self, location: &NetLocation) -> Option<CachedDecision> {
        let key = RoutingCacheKey::from_location(location);
        self.inner.read().peek(&key).copied()
    }

    /// Insert a decision into the cache.
    #[inline]
    pub fn insert(&self, location: &NetLocation, decision: CachedDecision) {
        let key = RoutingCacheKey::from_location(location);
        self.inner.write().put(key, decision);
    }

    #[cfg(test)]
    fn clear(&self) {
        self.inner.write().clear();
    }

    #[cfg(test)]
    fn len(&self) -> usize {
        self.inner.read().len()
    }

    #[cfg(test)]
    fn is_empty(&self) -> bool {
        self.inner.read().is_empty()
    }
}

#[derive(Debug)]
pub struct ConnectRule {
    pub masks: Vec<NetLocationMask>,
    pub action: ConnectAction,
}

impl ConnectRule {
    pub fn new(masks: Vec<NetLocationMask>, action: ConnectAction) -> Self {
        Self { masks, action }
    }
}

#[derive(Debug)]
pub enum ConnectAction {
    Allow {
        override_address: Option<NetLocation>,
        /// The chain group for this rule - multiple chains for round-robin selection.
        chain_group: ClientChainGroup,
    },
    Block,
}

impl ConnectAction {
    pub fn new_allow(override_address: Option<NetLocation>, chain_group: ClientChainGroup) -> Self {
        ConnectAction::Allow {
            override_address,
            chain_group,
        }
    }

    pub fn new_block() -> Self {
        ConnectAction::Block
    }

    /// Convert this action to a decision.
    ///
    /// Takes ownership of the location. If there's an override_address, a new
    /// ResolvedLocation is created (the resolved_addr doesn't apply to a different
    /// destination). Otherwise, the original location is passed through, preserving
    /// any resolution that was done during rule matching.
    pub fn to_decision(&self, location: ResolvedLocation) -> ConnectDecision<'_> {
        match self {
            ConnectAction::Allow {
                override_address,
                chain_group,
            } => {
                let remote_location = match override_address {
                    Some(l) => {
                        // Override address - create fresh location (resolved_addr doesn't apply)
                        let new_loc = if l.port() > 0 {
                            l.clone()
                        } else {
                            // If port of 0 is specified, take the requested port.
                            NetLocation::new(l.address().clone(), location.location().port())
                        };
                        new_loc.into()
                    }
                    None => {
                        // No override - pass through with any resolution intact
                        location
                    }
                };
                ConnectDecision::Allow {
                    chain_group,
                    remote_location,
                }
            }
            ConnectAction::Block => ConnectDecision::Block,
        }
    }
}

/// Threshold for enabling cache based on rule count.
/// If rule count exceeds this value, caching is enabled even without DNS resolution.
const CACHE_RULE_THRESHOLD: usize = 16;

// TODO: Replace linear rule matching with radix set/trie
#[derive(Debug)]
pub struct ClientProxySelector {
    rules: Vec<ConnectRule>,
    /// If false, hostname rules will not trigger DNS resolution to match against IP-based
    /// destinations. This is useful when a huge blocklist or rule list is provided.
    /// However, this means that the user needs to make sure DNS resolutions are not done
    /// manually before hitting the server. Default is false (don't resolve).
    resolve_rule_hostnames: bool,
    /// LRU cache for routing decisions. Speeds up repeated lookups for the same destination.
    /// None if caching is disabled (few rules and no DNS resolution).
    cache: Option<RoutingCache>,
    has_ip_rules: bool,
    has_hostname_rules: bool,
}

#[derive(Debug)]
pub enum ConnectDecision<'a> {
    Allow {
        chain_group: &'a ClientChainGroup,
        remote_location: ResolvedLocation,
    },
    Block,
}

impl ClientProxySelector {
    pub fn new(rules: Vec<ConnectRule>) -> Self {
        Self::with_options(rules, false)
    }

    /// Create a new ClientProxySelector with configurable hostname resolution behavior.
    ///
    /// # Arguments
    /// * `rules` - The list of routing rules
    /// * `resolve_rule_hostnames` - If true, hostname rules will be resolved via DNS to match
    ///   against IP-based destinations. If false (default), hostname rules only match hostname
    ///   destinations directly. Setting this to false is more performant for large rule sets.
    pub fn with_options(rules: Vec<ConnectRule>, resolve_rule_hostnames: bool) -> Self {
        Self::with_options_and_cache_size(
            rules,
            resolve_rule_hostnames,
            RoutingCache::DEFAULT_CAPACITY,
        )
    }

    /// Create a new ClientProxySelector with configurable hostname resolution and cache size.
    ///
    /// # Arguments
    /// * `rules` - The list of routing rules
    /// * `resolve_rule_hostnames` - If true, hostname rules will be resolved via DNS to match
    ///   against IP-based destinations. If false (default), hostname rules only match hostname
    ///   destinations directly.
    /// * `cache_capacity` - Maximum number of routing decisions to cache. Set to 0 to disable caching.
    ///
    /// # Caching behavior
    /// Caching is automatically enabled when:
    /// - `resolve_rule_hostnames` is true (DNS lookups are expensive), OR
    /// - Rule count exceeds `CACHE_RULE_THRESHOLD` (16)
    ///
    /// For simple configurations with few rules and no DNS resolution, caching is disabled
    /// as the overhead of cache key construction exceeds the cost of linear rule matching.
    pub fn with_options_and_cache_size(
        rules: Vec<ConnectRule>,
        resolve_rule_hostnames: bool,
        cache_capacity: usize,
    ) -> Self {
        // Enable caching if:
        // 1. DNS resolution is enabled (expensive operation), OR
        // 2. Many rules (linear scan becomes expensive)
        let cache = if cache_capacity != 0
            && (resolve_rule_hostnames || rules.len() > CACHE_RULE_THRESHOLD)
        {
            Some(RoutingCache::new(cache_capacity))
        } else {
            None
        };

        let has_ip_rules = rules.iter().flat_map(|rule| &rule.masks).any(|mask| {
            mask.address_mask.netmask != 0 && mask.address_mask.address.hostname().is_none()
        });
        let has_hostname_rules = rules.iter().flat_map(|rule| &rule.masks).any(|mask| {
            mask.address_mask.netmask != 0 && mask.address_mask.address.hostname().is_some()
        });
        Self {
            rules,
            resolve_rule_hostnames,
            cache,
            has_ip_rules,
            has_hostname_rules,
        }
    }

    /// Judge a connection request, using the cache for faster repeated lookups.
    ///
    /// Takes ownership of `location` because:
    /// 1. Rule matching may resolve the hostname and cache it in the location
    /// 2. Rules may override the destination entirely
    ///
    /// The returned `ConnectDecision` contains the (possibly resolved/modified) location.
    ///
    /// Note: Caching is only enabled when `resolve_rule_hostnames` is true or there are
    /// more than 16 rules. For simple configurations, direct rule matching is faster.
    #[inline]
    pub async fn judge<'a>(
        &'a self,
        location: ResolvedLocation,
        resolver: &Arc<dyn Resolver>,
    ) -> std::io::Result<ConnectDecision<'a>> {
        // Derive resolved_ip from any pre-resolved address
        let resolved_ip = location.resolved_addr().map(|addr| ip_to_u128(addr.ip()));
        // DNS-dependent decisions must validate the address used for this connection,
        // not a hostname-only decision from a previous resolution.
        let dns_dependent = if location.location().address().hostname().is_some() {
            self.has_ip_rules
        } else {
            self.resolve_rule_hostnames && self.has_hostname_rules
        };
        if dns_dependent {
            return self.judge_uncached(location, resolved_ip, resolver).await;
        }

        // If caching is disabled, go directly to rule matching
        let cache = match &self.cache {
            Some(c) => c,
            None => {
                return self.judge_uncached(location, resolved_ip, resolver).await;
            }
        };

        // Fast path: check cache first
        // Note: cached decisions don't include resolved_addr, so we pass through the location
        if let Some(cached) = cache.get(location.location()) {
            return Ok(self.cached_to_decision(cached, location));
        }

        // Slow path: full rule matching (may resolve and update the location)
        let mut location = location;
        match match_rule(
            &self.rules,
            &mut location,
            resolved_ip,
            resolver,
            self.resolve_rule_hostnames,
        )
        .await?
        {
            Some(rule_index) => {
                // Cache the result
                cache.insert(location.location(), CachedDecision::Allow(rule_index));
                Ok(self.rules[rule_index].action.to_decision(location))
            }
            None => {
                // Cache the block decision
                cache.insert(location.location(), CachedDecision::Block);
                Ok(ConnectDecision::Block)
            }
        }
    }

    /// Judge without using the cache. Useful for testing or when cache bypass is needed.
    #[inline]
    pub async fn judge_uncached<'a>(
        &'a self,
        location: ResolvedLocation,
        resolved_ip: Option<u128>,
        resolver: &Arc<dyn Resolver>,
    ) -> std::io::Result<ConnectDecision<'a>> {
        let mut location = location;
        match match_rule(
            &self.rules,
            &mut location,
            resolved_ip,
            resolver,
            self.resolve_rule_hostnames,
        )
        .await?
        {
            Some(rule_index) => Ok(self.rules[rule_index].action.to_decision(location)),
            None => Ok(ConnectDecision::Block),
        }
    }

    /// Convert a cached decision back to a ConnectDecision.
    #[inline]
    fn cached_to_decision(
        &self,
        cached: CachedDecision,
        location: ResolvedLocation,
    ) -> ConnectDecision<'_> {
        match cached {
            CachedDecision::Allow(rule_index) => {
                self.rules[rule_index].action.to_decision(location)
            }
            CachedDecision::Block => ConnectDecision::Block,
        }
    }

    #[cfg(test)]
    fn cache_size(&self) -> usize {
        self.cache.as_ref().map_or(0, |c| c.len())
    }

    #[cfg(test)]
    fn clear_cache(&self) {
        if let Some(cache) = &self.cache {
            cache.clear();
        }
    }

    #[cfg(test)]
    fn is_cache_enabled(&self) -> bool {
        self.cache.is_some()
    }
}

#[inline]
fn ip_to_u128(ip: IpAddr) -> u128 {
    match ip {
        IpAddr::V4(addr) => ipv4_to_u128(addr),
        IpAddr::V6(addr) => ipv6_to_u128(addr),
    }
}

#[inline]
fn ipv4_to_u128(ip: Ipv4Addr) -> u128 {
    ipv6_to_u128(ip.to_ipv6_mapped())
}

#[inline]
fn ipv6_to_u128(ip: Ipv6Addr) -> u128 {
    u128::from(ip)
}

#[inline]
fn matches_domain(base_domain: &str, hostname: &str) -> bool {
    let base_domain = base_domain.strip_suffix('.').unwrap_or(base_domain);
    let hostname = hostname.strip_suffix('.').unwrap_or(hostname);
    if hostname.len() >= base_domain.len()
        && hostname
            .get(hostname.len() - base_domain.len()..)
            .is_some_and(|suffix| suffix.eq_ignore_ascii_case(base_domain))
    {
        let hostname_len = hostname.len();
        let base_domain_len = base_domain.len();
        if hostname_len == base_domain_len {
            true
        } else {
            // hostname_len > base_domain_len since hostname ends with base_domain.
            hostname.as_bytes()[hostname_len - base_domain_len - 1] == b'.'
        }
    } else {
        false
    }
}

/// Returns the index of the matching rule.
/// During matching, may resolve the location's address and cache it in `location`.
#[inline]
async fn match_rule(
    rules: &[ConnectRule],
    location: &mut ResolvedLocation,
    mut resolved_ip: Option<u128>,
    resolver: &Arc<dyn Resolver>,
    resolve_rule_hostnames: bool,
) -> std::io::Result<Option<usize>> {
    for (rule_index, rule) in rules.iter().enumerate() {
        for mask in rule.masks.iter() {
            match match_mask(
                mask,
                location,
                &mut resolved_ip,
                resolver,
                resolve_rule_hostnames,
            )
            .await
            {
                Ok(is_match) => {
                    if is_match {
                        debug!(
                            "Found matching mask for {} -> {mask:?}",
                            location.location()
                        );
                        return Ok(Some(rule_index));
                    }
                }
                Err(MatchMaskError::Fatal(e)) => {
                    return Err(std::io::Error::other(format!(
                        "fatal error while matching mask for {}: {e}",
                        location.location()
                    )));
                }
                Err(MatchMaskError::NonFatal(e)) => {
                    error!(
                        "Non-fatal error while trying to match mask for {}: {e}",
                        location.location()
                    );
                }
            }
        }
    }
    Ok(None)
}

enum MatchMaskError {
    NonFatal(std::io::Error),
    Fatal(std::io::Error),
}

// Helper function for testing - exposed for unit tests
#[cfg(test)]
pub fn matches_domain_for_test(base_domain: &str, hostname: &str) -> bool {
    matches_domain(base_domain, hostname)
}

/// Match a single mask against the location.
/// Updates `resolved_ip` and `location.resolved_addr` if DNS resolution is performed.
#[inline]
async fn match_mask(
    location_mask: &NetLocationMask,
    location: &mut ResolvedLocation,
    resolved_ip: &mut Option<u128>,
    resolver: &Arc<dyn Resolver>,
    resolve_rule_hostnames: bool,
) -> std::result::Result<bool, MatchMaskError> {
    let NetLocationMask {
        address_mask: AddressMask { address, netmask },
        port,
    } = location_mask;

    let netmask = *netmask;
    let port = *port;

    if port > 0 && port != location.location().port() {
        return Ok(false);
    }

    if netmask == 0 {
        return Ok(true);
    }

    if let Some(hostname) = address.hostname() {
        if let Some(remote_hostname) = location.location().address().hostname() {
            return Ok(matches_domain(hostname, remote_hostname));
        }

        // We don't care about netmasks when hostnames are provided, so we can do direct matching
        // without resolving when both the remote location and the provided rule address are hostnames,
        // and simply return if it doesn't match.
        if !resolve_rule_hostnames {
            return Ok(false);
        }
    }

    // Need to get resolved IP for matching
    let masked_ip = match resolved_ip {
        Some(ip) => *ip,
        None => {
            // Resolve the destination lazily - this caches in `location`
            let socket_addr = resolve_location(location, resolver)
                .await
                .map_err(MatchMaskError::Fatal)?;
            let ip = ip_to_u128(socket_addr.ip());
            resolved_ip.replace(ip);
            ip
        }
    } & netmask;

    match address {
        Address::Ipv4(ip_addr) => {
            let mask = ipv4_to_u128(*ip_addr) & netmask;
            if mask == masked_ip {
                return Ok(true);
            }
        }
        Address::Ipv6(ip_addr) => {
            let mask = ipv6_to_u128(*ip_addr) & netmask;
            if mask == masked_ip {
                return Ok(true);
            }
        }
        Address::Hostname(_) => {
            // non-fatal error when the rule address cannot be resolved.
            // TODO: could this be cached?
            let socket_addrs = resolver
                .resolve_location(&NetLocation::new(address.clone(), port))
                .await
                .map_err(MatchMaskError::NonFatal)?;
            for socket_addr in socket_addrs {
                let mask = ip_to_u128(socket_addr.ip()) & netmask;
                if mask == masked_ip {
                    return Ok(true);
                }
            }
        }
    }

    Ok(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolver::Resolver;
    use std::future::Future;
    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
    use std::pin::Pin;

    #[tokio::test]
    async fn cached_route_rechecks_changed_ip() {
        let selector = ClientProxySelector::with_options(
            vec![
                block_rule(vec!["127.0.0.0/8"]),
                allow_rule(vec!["0.0.0.0/0"], "direct"),
            ],
            true,
        );
        let resolver = mock_resolver();
        let hostname = NetLocation::from_str("example.com:443", None).unwrap();
        let public =
            ResolvedLocation::with_resolved(hostname.clone(), "1.1.1.1:443".parse().unwrap());
        assert!(matches!(
            selector.judge(public, &resolver).await.unwrap(),
            ConnectDecision::Allow { .. }
        ));
        let private = ResolvedLocation::with_resolved(hostname, "127.0.0.1:443".parse().unwrap());
        assert!(matches!(
            selector.judge(private, &resolver).await.unwrap(),
            ConnectDecision::Block
        ));
    }

    #[tokio::test]
    async fn domain_rules_agree_with_cache_on_case_and_root_dot() {
        for capacity in [0, 10] {
            let selector = ClientProxySelector::with_options_and_cache_size(
                vec![
                    block_rule(vec!["Blocked.Example."]),
                    allow_rule(vec!["0.0.0.0/0"], "direct"),
                ],
                true,
                capacity,
            );
            for name in [
                "BLOCKED.example:443",
                "blocked.EXAMPLE.:443",
                "sub.blocked.example:443",
            ] {
                let destination = NetLocation::from_str(name, None).unwrap();
                assert!(matches!(
                    selector
                        .judge(destination.into(), &mock_resolver())
                        .await
                        .unwrap(),
                    ConnectDecision::Block
                ));
            }
            if capacity == 0 {
                assert!(!selector.is_cache_enabled());
            }
        }
    }

    /// A mock resolver for testing that returns predefined results
    #[derive(Debug)]
    struct MockResolver {
        mappings: std::collections::HashMap<String, Vec<SocketAddr>>,
    }

    impl MockResolver {
        fn new() -> Self {
            Self {
                mappings: std::collections::HashMap::new(),
            }
        }
    }

    impl Resolver for MockResolver {
        fn resolve_location(
            &self,
            location: &NetLocation,
        ) -> Pin<Box<dyn Future<Output = std::io::Result<Vec<SocketAddr>>> + Send>> {
            let key = format!("{}:{}", location.address(), location.port());
            let result = self.mappings.get(&key).cloned();
            Box::pin(async move {
                result.ok_or_else(|| {
                    std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        format!("No mock mapping for {}", key),
                    )
                })
            })
        }
    }

    /// Helper to create a mock resolver as Arc<dyn Resolver>
    fn mock_resolver() -> Arc<dyn Resolver> {
        Arc::new(MockResolver::new())
    }

    /// Create a mock ClientChainGroup for testing (single chain with direct connector)
    fn mock_chain_group() -> ClientChainGroup {
        use crate::resolver::NativeResolver;
        use crate::tcp::chain_builder::build_client_chain_group;
        let resolver: Arc<dyn Resolver> = Arc::new(NativeResolver::new());
        build_client_chain_group(crate::option_util::NoneOrSome::None, resolver)
    }

    /// Helper to create an allow rule (for rule matching tests)
    fn allow_rule(masks: Vec<&str>, _proxy_name: &str) -> ConnectRule {
        let masks: Vec<NetLocationMask> = masks
            .into_iter()
            .map(|s| NetLocationMask::from(s).unwrap())
            .collect();
        // For tests, we just use a mock chain group since we're testing rule matching
        ConnectRule::new(masks, ConnectAction::new_allow(None, mock_chain_group()))
    }

    /// Helper to create an allow rule with multiple proxies (for rule matching tests)
    fn allow_rule_multi(masks: Vec<&str>, _proxy_names: Vec<&str>) -> ConnectRule {
        let masks: Vec<NetLocationMask> = masks
            .into_iter()
            .map(|s| NetLocationMask::from(s).unwrap())
            .collect();
        // For tests, we just use a mock chain group since we're testing rule matching
        ConnectRule::new(masks, ConnectAction::new_allow(None, mock_chain_group()))
    }

    /// Helper to create a block rule
    fn block_rule(masks: Vec<&str>) -> ConnectRule {
        let masks: Vec<NetLocationMask> = masks
            .into_iter()
            .map(|s| NetLocationMask::from(s).unwrap())
            .collect();
        ConnectRule::new(masks, ConnectAction::new_block())
    }

    /// Helper to create an allow rule with address override
    fn allow_rule_with_override(
        masks: Vec<&str>,
        _proxy_name: &str,
        override_addr: &str,
    ) -> ConnectRule {
        let masks: Vec<NetLocationMask> = masks
            .into_iter()
            .map(|s| NetLocationMask::from(s).unwrap())
            .collect();
        let override_location = NetLocation::from_str(override_addr, Some(0)).unwrap();
        ConnectRule::new(
            masks,
            ConnectAction::new_allow(Some(override_location), mock_chain_group()),
        )
    }

    #[test]
    fn test_matches_domain_exact_match() {
        assert!(matches_domain_for_test("example.com", "example.com"));
        assert!(matches_domain_for_test("foo.bar.com", "foo.bar.com"));
    }

    #[test]
    fn test_matches_domain_subdomain_match() {
        assert!(matches_domain_for_test("example.com", "www.example.com"));
        assert!(matches_domain_for_test(
            "example.com",
            "sub.www.example.com"
        ));
        assert!(matches_domain_for_test("bar.com", "foo.bar.com"));
    }

    #[test]
    fn test_matches_domain_no_match_different_domain() {
        assert!(!matches_domain_for_test("example.com", "notexample.com"));
        assert!(!matches_domain_for_test("example.com", "example.org"));
        assert!(!matches_domain_for_test("foo.com", "bar.com"));
    }

    #[test]
    fn test_matches_domain_no_match_partial_suffix() {
        // "malicious-example.com" ends with "example.com" as a string,
        // but it's not a subdomain
        assert!(!matches_domain_for_test(
            "example.com",
            "malicious-example.com"
        ));
        assert!(!matches_domain_for_test("example.com", "fakeexample.com"));
        assert!(!matches_domain_for_test("bar.com", "foobar.com"));
    }

    #[test]
    fn test_matches_domain_no_match_base_longer() {
        assert!(!matches_domain_for_test("www.example.com", "example.com"));
        assert!(!matches_domain_for_test("sub.example.com", "example.com"));
    }

    #[test]
    fn test_matches_domain_empty_strings() {
        assert!(!matches_domain_for_test("example.com", ""));
        assert!(!matches_domain_for_test("", "example.com"));
        assert!(matches_domain_for_test("", "")); // Both empty matches
    }

    #[test]
    fn test_matches_domain_single_label() {
        assert!(matches_domain_for_test("localhost", "localhost"));
        assert!(!matches_domain_for_test("localhost", "notlocalhost"));
        assert!(!matches_domain_for_test("host", "localhost")); // partial suffix
    }

    #[tokio::test]
    async fn test_ipv4_exact_match() {
        let rules = vec![
            allow_rule(vec!["192.168.1.1/32"], "proxy1"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow, got Block"),
        }
    }

    #[tokio::test]
    async fn test_ipv4_exact_match_no_match() {
        let rules = vec![
            allow_rule(vec!["192.168.1.1/32"], "proxy1"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Different IP should fall through to default
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 2)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow, got Block"),
        }
    }

    #[tokio::test]
    async fn test_ipv4_cidr_24() {
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "lan"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // All addresses in 192.168.1.0/24 should match
        for last_octet in [0u8, 1, 100, 254, 255] {
            let location =
                NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, last_octet)), 80);
            let decision = selector.judge(location.into(), &resolver).await.unwrap();
            match decision {
                ConnectDecision::Allow { .. } => {}
                ConnectDecision::Block => panic!("Expected Allow for 192.168.1.{}", last_octet),
            }
        }

        // Address outside the range should not match
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 2, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_ipv4_cidr_16() {
        let rules = vec![
            allow_rule(vec!["10.0.0.0/8"], "private_a"),
            allow_rule(vec!["172.16.0.0/12"], "private_b"),
            allow_rule(vec!["192.168.0.0/16"], "private_c"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Test 10.0.0.0/8 range
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 255, 255, 255)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Test 172.16.0.0/12 range (172.16.0.0 - 172.31.255.255)
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(172, 20, 5, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Test 192.168.0.0/16 range
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 100, 50)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Public IP should go to default
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(8, 8, 8, 8)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_ipv4_localhost() {
        let rules = vec![
            allow_rule(vec!["127.0.0.0/8"], "loopback"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(127, 0, 0, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // 127.x.x.x should all match loopback
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(127, 255, 255, 255)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_ipv6_exact_match() {
        let rules = vec![
            allow_rule(vec!["::1/128"], "loopback"),
            allow_rule(vec!["::/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv6(Ipv6Addr::LOCALHOST), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_ipv6_cidr() {
        let rules = vec![
            allow_rule(vec!["fe80::/10"], "link_local"),
            allow_rule(vec!["fc00::/7"], "unique_local"),
            allow_rule(vec!["::/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Link-local address
        let location = NetLocation::new(Address::Ipv6("fe80::1".parse().unwrap()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Unique local address (fc00::/7 covers fc00:: and fd00::)
        let location = NetLocation::new(Address::Ipv6("fd00::1234".parse().unwrap()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Global unicast should go to default
        let location = NetLocation::new(Address::Ipv6("2001:db8::1".parse().unwrap()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_hostname_exact_match() {
        let rules = vec![
            allow_rule(vec!["example.com"], "example_proxy"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Hostname("example.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_hostname_subdomain_match() {
        let rules = vec![
            allow_rule(vec!["example.com"], "example_proxy"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Subdomain should match
        let location = NetLocation::new(Address::Hostname("www.example.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Deep subdomain should match
        let location = NetLocation::new(Address::Hostname("sub.www.example.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_hostname_no_false_subdomain_match() {
        // malicious-example.com should NOT match example.com rule
        let rules = vec![
            allow_rule(vec!["example.com"], "example_proxy"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Hostname("malicious-example.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        let location = NetLocation::new(Address::Hostname("fakeexample.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_hostname_different_tld() {
        let rules = vec![
            allow_rule(vec!["example.com"], "example_proxy"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Different TLD should not match
        let location = NetLocation::new(Address::Hostname("example.org".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_port_specific_rule() {
        let rules = vec![
            allow_rule(vec!["0.0.0.0/0:443"], "https_proxy"),
            allow_rule(vec!["0.0.0.0/0:80"], "http_proxy"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Port 443 should match https_proxy
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 443);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Port 80 should match http_proxy
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Other ports should go to default
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 8080);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_port_with_ip_restriction() {
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24:22"], "ssh_lan"),
            allow_rule(vec!["0.0.0.0/0:22"], "ssh_default"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // LAN SSH should match ssh_lan
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 100)), 22);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // External SSH should match ssh_default
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(8, 8, 8, 8)), 22);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // LAN HTTP should go to default (not ssh_lan because port doesn't match)
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 100)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_first_rule_wins() {
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "specific"),
            allow_rule(vec!["192.168.0.0/16"], "less_specific"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // 192.168.1.x should match the first (more specific) rule
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // 192.168.2.x should match the second rule
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 2, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_rule_order_matters_security() {
        // SECURITY: If a block rule comes after an allow rule for overlapping ranges,
        // the allow rule takes precedence
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "allowed"),
            block_rule(vec!["192.168.0.0/16"]),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // 192.168.1.x matches the allow rule first
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow for 192.168.1.1"),
        }

        // 192.168.2.x should be blocked
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 2, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block for 192.168.2.1"),
            ConnectDecision::Block => {} // Expected
        }
    }

    #[tokio::test]
    async fn test_block_rule() {
        let rules = vec![
            block_rule(vec!["192.168.1.0/24"]),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Blocked range
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block"),
            ConnectDecision::Block => {} // Expected
        }

        // Non-blocked range
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(8, 8, 8, 8)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_block_hostname() {
        let rules = vec![
            block_rule(vec!["blocked.com"]),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Blocked hostname
        let location = NetLocation::new(Address::Hostname("blocked.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block for blocked.com"),
            ConnectDecision::Block => {} // Expected
        }

        // Subdomain of blocked hostname should also be blocked
        let location = NetLocation::new(Address::Hostname("www.blocked.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block for www.blocked.com"),
            ConnectDecision::Block => {} // Expected
        }
    }

    #[tokio::test]
    async fn test_no_default_rule_blocks() {
        let rules = vec![allow_rule(vec!["192.168.1.0/24"], "lan")];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Non-matching address with no default rule should block
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(8, 8, 8, 8)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block when no default rule"),
            ConnectDecision::Block => {} // Expected
        }
    }

    #[tokio::test]
    async fn test_round_robin_proxy_selection() {
        // Note: Since ClientProxyChain now handles round-robin internally,
        // we just verify that multiple calls succeed. Actual round-robin testing
        // is done at the ClientProxyChain level.
        let rules = vec![allow_rule_multi(
            vec!["0.0.0.0/0"],
            vec!["proxy1", "proxy2", "proxy3"],
        )];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        for _ in 0..6 {
            let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);
            let decision = selector.judge(location.into(), &resolver).await.unwrap();
            match decision {
                ConnectDecision::Allow { .. } => {
                    // Round-robin selection now happens in ClientProxyChain
                }
                ConnectDecision::Block => panic!("Expected Allow"),
            }
        }
    }

    #[tokio::test]
    async fn test_single_proxy_no_rotation() {
        let rules = vec![allow_rule(vec!["0.0.0.0/0"], "only_proxy")];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        for _ in 0..5 {
            let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);
            let decision = selector.judge(location.into(), &resolver).await.unwrap();
            match decision {
                ConnectDecision::Allow { .. } => {}
                ConnectDecision::Block => panic!("Expected Allow"),
            }
        }
    }

    #[tokio::test]
    async fn test_address_override() {
        let rules = vec![allow_rule_with_override(
            vec!["0.0.0.0/0"],
            "proxy",
            "10.0.0.1:8080",
        )];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 443);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow {
                remote_location, ..
            } => {
                assert_eq!(remote_location.address().to_string(), "10.0.0.1");
                assert_eq!(remote_location.port(), 8080);
            }
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_address_override_preserve_port() {
        // Override with port 0 should preserve the original port
        let rules = vec![allow_rule_with_override(
            vec!["0.0.0.0/0"],
            "proxy",
            "10.0.0.1:0",
        )];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 443);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow {
                remote_location, ..
            } => {
                assert_eq!(remote_location.address().to_string(), "10.0.0.1");
                assert_eq!(remote_location.port(), 443); // Original port preserved
            }
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_multiple_masks_in_rule() {
        let rules = vec![
            allow_rule(
                vec!["192.168.1.0/24", "192.168.2.0/24", "10.0.0.0/8"],
                "internal",
            ),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // All three ranges should match "internal"
        for ip in [
            Ipv4Addr::new(192, 168, 1, 1),
            Ipv4Addr::new(192, 168, 2, 100),
            Ipv4Addr::new(10, 50, 50, 50),
        ] {
            let location = NetLocation::new(Address::Ipv4(ip), 80);
            let decision = selector.judge(location.into(), &resolver).await.unwrap();
            match decision {
                ConnectDecision::Allow { .. } => {
                    // assertion removed - client_proxy no longer available
                }
                ConnectDecision::Block => panic!("Expected Allow for {}", ip),
            }
        }

        // Other IPs should go to default
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(8, 8, 8, 8)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_multiple_hostnames_in_rule() {
        let rules = vec![
            allow_rule(
                vec!["google.com", "youtube.com", "gmail.com"],
                "google_proxy",
            ),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        for hostname in [
            "google.com",
            "www.google.com",
            "youtube.com",
            "mail.gmail.com",
        ] {
            let location = NetLocation::new(Address::Hostname(hostname.to_string()), 80);
            let decision = selector.judge(location.into(), &resolver).await.unwrap();
            match decision {
                ConnectDecision::Allow { .. } => {
                    // assertion removed - client_proxy no longer available
                }
                ConnectDecision::Block => panic!("Expected Allow for {}", hostname),
            }
        }
    }

    #[tokio::test]
    async fn test_empty_rules_blocks_all() {
        let rules: Vec<ConnectRule> = vec![];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block with empty rules"),
            ConnectDecision::Block => {} // Expected
        }
    }

    #[tokio::test]
    async fn test_ipv4_mapped_ipv6() {
        // IPv4-mapped IPv6 addresses (::ffff:192.168.1.1) should be handled correctly
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "lan"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Regular IPv4
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_broadcast_and_special_addresses() {
        let rules = vec![
            block_rule(vec!["255.255.255.255/32"]), // Broadcast
            block_rule(vec!["0.0.0.0/32"]),         // Unspecified
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Broadcast should be blocked
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::BROADCAST), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block for broadcast"),
            ConnectDecision::Block => {} // Expected
        }

        // Unspecified should be blocked
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::UNSPECIFIED), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => panic!("Expected Block for unspecified"),
            ConnectDecision::Block => {} // Expected
        }
    }

    #[tokio::test]
    async fn test_case_sensitivity_hostname() {
        let rules = vec![
            allow_rule(vec!["Example.COM"], "example_proxy"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Note: DNS hostnames are case-insensitive by spec, but our implementation
        // does case-sensitive matching. This test documents current behavior.
        let location = NetLocation::new(Address::Hostname("example.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {
                // Current behavior: case-sensitive, so this goes to default
                // If we want case-insensitive, this should be "example_proxy"
            }
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_concurrent_access_round_robin() {
        // Test that concurrent access to round-robin is safe (uses AtomicU32)
        use std::sync::Arc as StdArc;

        let rules = vec![allow_rule_multi(
            vec!["0.0.0.0/0"],
            vec!["p1", "p2", "p3", "p4"],
        )];
        let selector = StdArc::new(ClientProxySelector::new(rules));
        let resolver = mock_resolver();

        let mut handles = vec![];
        for _ in 0..10 {
            let selector = selector.clone();
            let resolver = resolver.clone();
            handles.push(tokio::spawn(async move {
                let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);
                let _ = selector.judge(location.into(), &resolver).await;
            }));
        }

        for handle in handles {
            handle.await.unwrap();
        }
        // If we got here without panic, concurrent access is safe
    }

    #[tokio::test]
    async fn test_localhost_bypass() {
        // Common pattern: bypass proxy for localhost
        // Note: With resolve_rule_hostnames=false (default), hostname destinations
        // won't match IP rules unless the hostname rule comes first.
        let rules = vec![
            allow_rule(vec!["localhost"], "direct_host"), // Hostname rule first
            allow_rule_with_override(vec!["127.0.0.0/8"], "direct", "127.0.0.1:0"),
            allow_rule(vec!["0.0.0.0/0"], "proxy"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // 127.0.0.1 should use direct (matches IP rule)
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // localhost hostname should use direct_host (matches hostname rule)
        let location = NetLocation::new(Address::Hostname("localhost".to_string()), 8080);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_mixed_ip_and_hostname_rules() {
        // Note: With resolve_rule_hostnames=false (default), hostname destinations
        // encountering IP rules will attempt to resolve the hostname. To avoid this,
        // place hostname rules before IP rules, or use resolve_rule_hostnames=true
        // with proper DNS mock mappings.
        let rules = vec![
            block_rule(vec!["malware.com"]),
            allow_rule(vec!["trusted.com"], "trusted"), // Hostname rules before IP rules
            allow_rule(vec!["192.168.0.0/16"], "lan"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        let resolver = mock_resolver();

        // Malware hostname blocked
        let location = NetLocation::new(Address::Hostname("malware.com".to_string()), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        assert!(matches!(decision, ConnectDecision::Block));

        // LAN IP allowed through lan proxy
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Trusted hostname allowed through trusted proxy
        let location = NetLocation::new(Address::Hostname("api.trusted.com".to_string()), 443);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[test]
    fn test_routing_cache_key_from_location_hostname() {
        let location = NetLocation::new(Address::Hostname("Example.COM".to_string()), 443);
        let key = RoutingCacheKey::from_location(&location);
        match key {
            RoutingCacheKey::Hostname { hostname, port } => {
                assert_eq!(hostname, "example.com"); // Should be lowercased
                assert_eq!(port, 443);
            }
            _ => panic!("Expected Hostname key"),
        }
    }

    #[test]
    fn test_routing_cache_key_from_location_ipv4() {
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let key = RoutingCacheKey::from_location(&location);
        match key {
            RoutingCacheKey::Ipv4 { addr, port } => {
                assert_eq!(addr, Ipv4Addr::new(192, 168, 1, 1));
                assert_eq!(port, 80);
            }
            _ => panic!("Expected Ipv4 key"),
        }
    }

    #[test]
    fn test_routing_cache_key_from_location_ipv6() {
        let location = NetLocation::new(Address::Ipv6(Ipv6Addr::LOCALHOST), 8080);
        let key = RoutingCacheKey::from_location(&location);
        match key {
            RoutingCacheKey::Ipv6 { addr, port } => {
                assert_eq!(addr, Ipv6Addr::LOCALHOST);
                assert_eq!(port, 8080);
            }
            _ => panic!("Expected Ipv6 key"),
        }
    }

    #[test]
    fn test_routing_cache_basic_operations() {
        let cache = RoutingCache::new(100);
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);

        // Initially no entry
        assert!(cache.get(&location).is_none());

        // Insert and retrieve
        cache.insert(&location, CachedDecision::Allow(5));
        assert_eq!(cache.len(), 1);

        let cached = cache.get(&location);
        assert!(cached.is_some());
        match cached.unwrap() {
            CachedDecision::Allow(idx) => assert_eq!(idx, 5),
            CachedDecision::Block => panic!("Expected Allow"),
        }
    }

    #[test]
    fn test_routing_cache_block_decision() {
        let cache = RoutingCache::new(100);
        let location = NetLocation::new(Address::Hostname("blocked.com".to_string()), 443);

        cache.insert(&location, CachedDecision::Block);

        let cached = cache.get(&location);
        assert!(matches!(cached, Some(CachedDecision::Block)));
    }

    #[test]
    fn test_routing_cache_different_ports() {
        let cache = RoutingCache::new(100);
        let loc_80 = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);
        let loc_443 = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 443);

        cache.insert(&loc_80, CachedDecision::Allow(1));
        cache.insert(&loc_443, CachedDecision::Allow(2));

        // Same IP, different ports should be different cache entries
        match cache.get(&loc_80).unwrap() {
            CachedDecision::Allow(idx) => assert_eq!(idx, 1),
            _ => panic!("Expected Allow(1)"),
        }
        match cache.get(&loc_443).unwrap() {
            CachedDecision::Allow(idx) => assert_eq!(idx, 2),
            _ => panic!("Expected Allow(2)"),
        }
    }

    #[test]
    fn test_routing_cache_hostname_case_insensitive() {
        let cache = RoutingCache::new(100);

        // Insert with uppercase
        let loc_upper = NetLocation::new(Address::Hostname("EXAMPLE.COM".to_string()), 443);
        cache.insert(&loc_upper, CachedDecision::Allow(1));

        // Retrieve with lowercase - should find it
        let loc_lower = NetLocation::new(Address::Hostname("example.com".to_string()), 443);
        assert!(cache.get(&loc_lower).is_some());

        // Retrieve with mixed case - should find it
        let loc_mixed = NetLocation::new(Address::Hostname("Example.Com".to_string()), 443);
        assert!(cache.get(&loc_mixed).is_some());
    }

    #[test]
    fn test_routing_cache_clear() {
        let cache = RoutingCache::new(100);

        // Add some entries
        for i in 0..10 {
            let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, i)), 80);
            cache.insert(&location, CachedDecision::Allow(i as usize));
        }
        assert_eq!(cache.len(), 10);

        // Clear
        cache.clear();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);

        // Verify entries are gone
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 0)), 80);
        assert!(cache.get(&location).is_none());
    }

    #[test]
    fn test_routing_cache_lru_eviction() {
        // Small cache to test eviction
        let cache = RoutingCache::new(3);

        // Insert 3 entries
        let loc1 = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 0, 0, 1)), 80);
        let loc2 = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 0, 0, 2)), 80);
        let loc3 = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 0, 0, 3)), 80);

        cache.insert(&loc1, CachedDecision::Allow(1));
        cache.insert(&loc2, CachedDecision::Allow(2));
        cache.insert(&loc3, CachedDecision::Allow(3));
        assert_eq!(cache.len(), 3);

        // Insert 4th entry - should evict the oldest (loc1)
        let loc4 = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 0, 0, 4)), 80);
        cache.insert(&loc4, CachedDecision::Allow(4));
        assert_eq!(cache.len(), 3);

        // loc1 should be evicted
        assert!(cache.get(&loc1).is_none());
        // Others should still be present
        assert!(cache.get(&loc2).is_some());
        assert!(cache.get(&loc3).is_some());
        assert!(cache.get(&loc4).is_some());
    }

    #[test]
    fn test_routing_cache_overwrite() {
        let cache = RoutingCache::new(100);
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);

        // Insert Allow
        cache.insert(&location, CachedDecision::Allow(1));
        match cache.get(&location).unwrap() {
            CachedDecision::Allow(idx) => assert_eq!(idx, 1),
            _ => panic!("Expected Allow(1)"),
        }

        // Overwrite with Block
        cache.insert(&location, CachedDecision::Block);
        assert!(matches!(cache.get(&location), Some(CachedDecision::Block)));

        // Overwrite with different Allow
        cache.insert(&location, CachedDecision::Allow(5));
        match cache.get(&location).unwrap() {
            CachedDecision::Allow(idx) => assert_eq!(idx, 5),
            _ => panic!("Expected Allow(5)"),
        }
    }

    /// Helper to create a selector with caching enabled (via resolve_rule_hostnames=true)
    fn selector_with_cache(rules: Vec<ConnectRule>) -> ClientProxySelector {
        ClientProxySelector::with_options(rules, true)
    }

    #[tokio::test]
    async fn test_selector_cache_disabled_for_few_rules() {
        // With few rules and resolve_rule_hostnames=false, cache should be disabled
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "lan"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::new(rules);
        assert!(!selector.is_cache_enabled());

        // Routing should still work correctly
        let resolver = mock_resolver();
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 100)), 80);
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }
    }

    #[tokio::test]
    async fn test_selector_cache_enabled_with_dns_resolution() {
        // With resolve_rule_hostnames=true, cache should be enabled even with few rules
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "lan"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = ClientProxySelector::with_options(rules, true);
        assert!(selector.is_cache_enabled());
    }

    #[tokio::test]
    async fn test_selector_cache_enabled_with_many_rules() {
        // With many rules (>16), cache should be enabled even without DNS resolution
        let mut rules: Vec<ConnectRule> = (0..20)
            .map(|i| allow_rule(vec![&format!("10.0.{}.0/24", i)], &format!("rule{}", i)))
            .collect();
        rules.push(allow_rule(vec!["0.0.0.0/0"], "default"));

        let selector = ClientProxySelector::new(rules);
        assert!(selector.is_cache_enabled());
    }

    #[tokio::test]
    async fn test_selector_cache_hit() {
        // Use selector_with_cache to ensure caching is enabled for this test
        let rules = vec![
            allow_rule(vec!["192.168.1.0/24"], "lan"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 100)), 80);

        // First call - cache miss
        assert_eq!(selector.cache_size(), 0);
        let decision = selector
            .judge(location.clone().into(), &resolver)
            .await
            .unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Should be cached now
        assert_eq!(selector.cache_size(), 1);

        // Second call - cache hit (same result)
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Still only 1 entry (was a hit, not a new insert)
        assert_eq!(selector.cache_size(), 1);
    }

    #[tokio::test]
    async fn test_selector_cache_block_decision() {
        let rules = vec![
            block_rule(vec!["192.168.1.0/24"]),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 100)), 80);

        // First call - cache miss, should block
        let decision = selector
            .judge(location.clone().into(), &resolver)
            .await
            .unwrap();
        assert!(matches!(decision, ConnectDecision::Block));
        assert_eq!(selector.cache_size(), 1);

        // Second call - cache hit, still blocks
        let decision = selector.judge(location.into(), &resolver).await.unwrap();
        assert!(matches!(decision, ConnectDecision::Block));
    }

    #[tokio::test]
    async fn test_selector_clear_cache() {
        let rules = vec![allow_rule(vec!["0.0.0.0/0"], "default")];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        // Make some cached entries
        for i in 0..5 {
            let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 0, 0, i)), 80);
            let _ = selector.judge(location.into(), &resolver).await.unwrap();
        }
        assert_eq!(selector.cache_size(), 5);

        // Clear cache
        selector.clear_cache();
        assert_eq!(selector.cache_size(), 0);
    }

    #[tokio::test]
    async fn test_selector_judge_uncached() {
        let rules = vec![allow_rule(vec!["0.0.0.0/0"], "default")];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(1, 2, 3, 4)), 80);

        // Use judge_uncached - should NOT populate cache
        let decision = selector
            .judge_uncached(location.into(), None, &resolver)
            .await
            .unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            ConnectDecision::Block => panic!("Expected Allow"),
        }

        // Cache should still be empty
        assert_eq!(selector.cache_size(), 0);
    }

    #[tokio::test]
    async fn test_selector_cache_different_destinations() {
        let rules = vec![
            allow_rule(vec!["192.168.0.0/16"], "lan"),
            allow_rule(vec!["10.0.0.0/8"], "private"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        // Hit different rules
        let loc_lan = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 1)), 80);
        let loc_private = NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 0, 0, 1)), 80);
        let loc_public = NetLocation::new(Address::Ipv4(Ipv4Addr::new(8, 8, 8, 8)), 80);

        let d1 = selector
            .judge(loc_lan.clone().into(), &resolver)
            .await
            .unwrap();
        let d2 = selector
            .judge(loc_private.clone().into(), &resolver)
            .await
            .unwrap();
        let d3 = selector
            .judge(loc_public.clone().into(), &resolver)
            .await
            .unwrap();

        // Verify correct routing (all should be Allow decisions)
        assert!(
            matches!(d1, ConnectDecision::Allow { .. }),
            "Expected lan to allow"
        );
        assert!(
            matches!(d2, ConnectDecision::Allow { .. }),
            "Expected private to allow"
        );
        assert!(
            matches!(d3, ConnectDecision::Allow { .. }),
            "Expected default to allow"
        );

        // All 3 should be cached
        assert_eq!(selector.cache_size(), 3);

        // Verify cache hits return same results
        let d1_cached = selector.judge(loc_lan.into(), &resolver).await.unwrap();
        assert!(
            matches!(d1_cached, ConnectDecision::Allow { .. }),
            "Expected lan from cache"
        );
    }

    #[tokio::test]
    async fn test_selector_cache_hostname_destinations() {
        let rules = vec![
            allow_rule(vec!["google.com"], "google"),
            allow_rule(vec!["0.0.0.0/0"], "default"),
        ];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        // Hostname match
        let loc_google = NetLocation::new(Address::Hostname("www.google.com".to_string()), 443);
        let decision = selector
            .judge(loc_google.clone().into(), &resolver)
            .await
            .unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            _ => panic!("Expected google"),
        }

        // Should be cached
        assert_eq!(selector.cache_size(), 1);

        // Case-insensitive cache hit
        let loc_google_upper =
            NetLocation::new(Address::Hostname("WWW.GOOGLE.COM".to_string()), 443);
        let decision = selector
            .judge(loc_google_upper.into(), &resolver)
            .await
            .unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            _ => panic!("Expected google from cache"),
        }

        // Should still be 1 entry (case-insensitive hit)
        assert_eq!(selector.cache_size(), 1);
    }

    #[tokio::test]
    async fn test_selector_cache_with_custom_size() {
        // Use resolve_rule_hostnames=true to enable caching with custom size
        let rules = vec![allow_rule(vec!["0.0.0.0/0"], "default")];
        let selector = ClientProxySelector::with_options_and_cache_size(rules, true, 5);
        let resolver = mock_resolver();

        // Fill cache to capacity
        for i in 0..5 {
            let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 0, 0, i)), 80);
            let _ = selector.judge(location.into(), &resolver).await.unwrap();
        }
        assert_eq!(selector.cache_size(), 5);

        // Add one more - should evict oldest
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 0, 0, 100)), 80);
        let _ = selector.judge(location.into(), &resolver).await.unwrap();
        assert_eq!(selector.cache_size(), 5); // Still 5, one was evicted

        // First entry should be evicted - verify by checking the cache is full
        // but we can't directly access the internal cache to verify eviction
        // So we verify indirectly: if we add another entry, size stays at 5
        let location = NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 0, 0, 200)), 80);
        let _ = selector.judge(location.into(), &resolver).await.unwrap();
        assert_eq!(selector.cache_size(), 5);
    }

    #[tokio::test]
    async fn test_selector_concurrent_cache_access() {
        use std::sync::Arc as StdArc;

        let rules = vec![allow_rule(vec!["0.0.0.0/0"], "default")];
        let selector = StdArc::new(selector_with_cache(rules));
        let resolver = mock_resolver();

        // Spawn multiple tasks accessing the cache concurrently
        let mut handles = vec![];
        for i in 0..10 {
            let selector = selector.clone();
            let resolver = resolver.clone();
            handles.push(tokio::spawn(async move {
                for j in 0..100 {
                    let location =
                        NetLocation::new(Address::Ipv4(Ipv4Addr::new(10, 0, i as u8, j as u8)), 80);
                    let decision = selector.judge(location.into(), &resolver).await.unwrap();
                    match decision {
                        ConnectDecision::Allow { .. } => {}
                        ConnectDecision::Block => panic!("Expected Allow"),
                    }
                }
            }));
        }

        // Wait for all tasks
        for handle in handles {
            handle.await.unwrap();
        }

        // Should have cached entries (exact number depends on timing)
        assert!(selector.cache_size() > 0);
    }

    #[tokio::test]
    async fn test_selector_cache_preserves_rule_priority() {
        // Ensure caching doesn't break rule priority
        let rules = vec![
            allow_rule(vec!["192.168.1.100/32"], "specific"), // Rule 0
            allow_rule(vec!["192.168.1.0/24"], "subnet"),     // Rule 1
            allow_rule(vec!["192.168.0.0/16"], "network"),    // Rule 2
            allow_rule(vec!["0.0.0.0/0"], "default"),         // Rule 3
        ];
        let selector = selector_with_cache(rules);
        let resolver = mock_resolver();

        // Specific IP should match rule 0 (most specific)
        let loc_specific = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 100)), 80);
        let decision = selector
            .judge(loc_specific.clone().into(), &resolver)
            .await
            .unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            _ => panic!("Expected specific"),
        }

        // Verify from cache - should still be "specific"
        let decision_cached = selector
            .judge(loc_specific.into(), &resolver)
            .await
            .unwrap();
        match decision_cached {
            ConnectDecision::Allow { .. } => {}
            _ => panic!("Expected specific from cache"),
        }

        // Different IP in same subnet should match rule 1
        let loc_subnet = NetLocation::new(Address::Ipv4(Ipv4Addr::new(192, 168, 1, 50)), 80);
        let decision = selector.judge(loc_subnet.into(), &resolver).await.unwrap();
        match decision {
            ConnectDecision::Allow { .. } => {}
            _ => panic!("Expected subnet"),
        }
    }

    #[test]
    fn test_netmask_value_for_cidr_0() {
        // Verify that 0.0.0.0/0 actually produces netmask == 0
        let mask = NetLocationMask::from("0.0.0.0/0").unwrap();
        assert_eq!(
            mask.address_mask.netmask, 0,
            "0.0.0.0/0 should have netmask == 0, got {}",
            mask.address_mask.netmask
        );
    }

    #[test]
    fn test_netmask_value_for_cidr_24() {
        // Verify that /24 does NOT produce netmask == 0
        let mask = NetLocationMask::from("172.17.0.0/24").unwrap();
        assert_ne!(
            mask.address_mask.netmask, 0,
            "172.17.0.0/24 should have netmask != 0"
        );
    }
}