snap-control 0.8.3

Control plane implementation of the SNAP transport underlay for SCION
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
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
// Copyright 2026 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! IP based grants.
//!
//! A grant is a promise that a client IP may use a target, and a set of private segments
//! towards it, until a point in time:
//!
//! - **Additive**: [`GrantManager::authorize`] adds targets and segments to whatever the IP already
//!   has, and never shortens an existing grant.
//! - **Bounded**: an IP holds at most [`GrantManagerConfig::max_targets_per_ip`] target grants, and
//!   a target holds at most [`GrantManagerConfig::max_segments_per_target`] segment grants. Grants
//!   over a limit evict unguarded grants, or fail.
//! - **Not revocable**: apart from that eviction, state leaves the manager only via
//!   [`GrantManager::clean`], and only once it has expired.
//! - **Observable**: every grant carries a [`CancellationToken`] that is cancelled when the grant
//!   is removed, so consumers can tear down or re-path. Cancellation is latched, so a waiter that
//!   has not been polled yet still observes it.
//!
//! A segment grant never outlives the segment it was granted on: `granted_until` is capped at
//! the segment's own expiry. Without that cap an expired segment would have to be pulled out
//! from under a live grant, which is indistinguishable from a revocation.
//!
//! The invariants we maintain are:
//! - A segment grant never outlives the segment it was granted on.
//! - A segment is removed from the authoritative store once its last grant is gone.
//! - If a segment was granted for an IP and an SNI, it cannot be used for another IP or SNI.
//! - As soon as a grant is removed, it's connected cancellation token is cancelled.
//! - An IP never holds more than `max_targets_per_ip` target grants.
//! - A target never holds more than `max_segments_per_target` segment grants.
//! - A grant with a live [`SegmentGrantGuard`] or [`TargetGrantGuard`] is never evicted.

use std::{
    collections::{BTreeMap, HashMap, hash_map::Entry},
    net::IpAddr,
    sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
    time::{Duration, SystemTime},
};

use sciparse::segment::{SegmentFp, SignedPathSegment};
use serde::{Deserialize, Serialize};
use serde_with::{DurationSeconds, serde_as};
use tokio_util::sync::CancellationToken;

use crate::pg_wap::{
    crpc::model::AuthSegments,
    sni::{CustomerDomain, CustomerDomainRef},
};

/// Configuration for a [`GrantManager`].
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct GrantManagerConfig {
    /// How long a grant is handed out for, after which the client has to re-authorize.
    #[serde_as(as = "DurationSeconds<u64>")]
    #[serde(default = "GrantManagerConfig::default_grant_duration")]
    pub grant_duration: Duration,
    /// Shortest sleep between two [`GrantManager::clean`] runs.
    #[serde_as(as = "DurationSeconds<u64>")]
    #[serde(default = "GrantManagerConfig::default_min_clean_interval")]
    pub min_clean_interval: Duration,
    /// Longest sleep between two [`GrantManager::clean`] runs.
    #[serde_as(as = "DurationSeconds<u64>")]
    #[serde(default = "GrantManagerConfig::default_max_clean_interval")]
    pub max_clean_interval: Duration,
    /// Maximum total number of segments a client may grant in one authorization request.
    #[serde(default = "GrantManagerConfig::default_max_segments_per_request")]
    pub max_segments_per_request: usize,
    /// Maximum number of segment grants one target holds per authorized IP.
    ///
    /// Grants over the limit are evicted by [`GrantManager::authorize`].
    #[serde(default = "GrantManagerConfig::default_max_segments_per_target")]
    pub max_segments_per_target: usize,
    /// Maximum number of targets a client may grant in one authorization request.
    #[serde(default = "GrantManagerConfig::default_max_targets_per_request")]
    pub max_targets_per_request: usize,
    /// Maximum number of target grants one IP holds.
    ///
    /// Grants over the limit are evicted by [`GrantManager::authorize`].
    #[serde(default = "GrantManagerConfig::default_max_targets_per_ip")]
    pub max_targets_per_ip: usize,
}

impl GrantManagerConfig {
    fn default_grant_duration() -> Duration {
        Duration::from_secs(2 * 60)
    }

    fn default_min_clean_interval() -> Duration {
        Duration::from_secs(10)
    }

    fn default_max_clean_interval() -> Duration {
        Duration::from_secs(30)
    }

    fn default_max_segments_per_request() -> usize {
        100
    }

    fn default_max_segments_per_target() -> usize {
        10
    }

    fn default_max_targets_per_request() -> usize {
        10
    }

    fn default_max_targets_per_ip() -> usize {
        50
    }

    /// Validates the configuration, returning an error if it is invalid.
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.min_clean_interval > self.max_clean_interval {
            anyhow::bail!(
                "min_clean_interval ({:?}) is greater than max_clean_interval ({:?})",
                self.min_clean_interval,
                self.max_clean_interval
            );
        }

        if self.max_segments_per_request == 0 {
            anyhow::bail!("max_segments_per_request must be greater than 0");
        }

        if self.max_segments_per_target == 0 {
            anyhow::bail!("max_segments_per_target must be greater than 0");
        }

        if self.max_targets_per_request == 0 {
            anyhow::bail!("max_targets_per_request must be greater than 0");
        }

        if self.max_targets_per_ip == 0 {
            anyhow::bail!("max_targets_per_ip must be greater than 0");
        }

        if self.grant_duration == Duration::ZERO {
            anyhow::bail!("grant_duration must be greater than 0");
        }

        if self.min_clean_interval == Duration::ZERO {
            anyhow::bail!("min_clean_interval must be greater than 0");
        }

        if self.max_clean_interval == Duration::ZERO {
            anyhow::bail!("max_clean_interval must be greater than 0");
        }

        Ok(())
    }
}

impl Default for GrantManagerConfig {
    fn default() -> Self {
        Self {
            grant_duration: Self::default_grant_duration(),
            min_clean_interval: Self::default_min_clean_interval(),
            max_clean_interval: Self::default_max_clean_interval(),
            max_segments_per_request: Self::default_max_segments_per_request(),
            max_segments_per_target: Self::default_max_segments_per_target(),
            max_targets_per_request: Self::default_max_targets_per_request(),
            max_targets_per_ip: Self::default_max_targets_per_ip(),
        }
    }
}

/// Tracks which client IPs are authorized for which targets and segments.
#[derive(Clone)]
pub struct GrantManager(Arc<GrantManagerShared>);

struct GrantManagerShared {
    /// The mutable authorization state.
    inner: RwLock<GrantManagerInner>,
    config: GrantManagerConfig,
}

/// The mutable state of a [`GrantManager`].
pub struct GrantManagerInner {
    /// Map of all authenticated IPs.
    auth_ips: HashMap<IpAddr, IpAuthInfo>,

    /// Authoritative, deduplicated list of all granted non-core segments for all IPs and dst
    /// domains.
    ///
    /// Segments are removed once their last grant is gone.
    private_non_core_segments: HashMap<SegmentFp, AuthSegmentEntry>,
    /// Same as `private_non_core_segments`, but for core segments.
    private_core_segments: HashMap<SegmentFp, AuthSegmentEntry>,
}

impl GrantManager {
    /// Creates an empty service handing out grants as `config` describes.
    ///
    /// Returns an error if `config` does not [`GrantManagerConfig::validate`].
    pub fn new(config: GrantManagerConfig) -> anyhow::Result<Self> {
        config.validate()?;

        Ok(Self(Arc::new(GrantManagerShared {
            inner: RwLock::new(GrantManagerInner {
                auth_ips: HashMap::new(),
                private_non_core_segments: HashMap::new(),
                private_core_segments: HashMap::new(),
            }),
            config,
        })))
    }

    fn read(&self) -> RwLockReadGuard<'_, GrantManagerInner> {
        self.0.inner.read().unwrap()
    }

    fn write(&self) -> RwLockWriteGuard<'_, GrantManagerInner> {
        self.0.inner.write().unwrap()
    }

    /// Checks if the ip has any kind of grant.
    pub fn ip_is_authorized(&self, ip: IpAddr, now: SystemTime) -> bool {
        let this = self.read();

        this.auth_ips
            .get(&ip)
            .is_some_and(|ip_auth| ip_auth.auth_dsts.values().any(|dst| dst.is_valid(now)))
    }

    /// Authorizes the given IP address for the given destinations and segments.
    ///
    /// Grants are additive: after applying the operation, the set of authorized destinations and
    /// segments is a superset of the previous set. The expiration of an authorized segment is
    /// the maximum of an already existing authorization and the provided. Already expired
    /// segments are not inserted.
    ///
    /// A segment grant is capped at the expiry of the segment it is granted on, so refreshing
    /// only extends it as far as the freshest copy of that segment allows.
    ///
    /// An IP holds at most [`GrantManagerConfig::max_targets_per_ip`] destination grants, and a
    /// destination holds at most [`GrantManagerConfig::max_segments_per_target`] segment grants.
    /// A request that does not fit evicts destination grants without a [`TargetGrantGuard`], and
    /// segment grants without a [`SegmentGrantGuard`]. Grants with the least time left are evicted
    /// first. Evicting a destination grant removes its segment grants as well.
    ///
    /// The request is rejected if eviction can not free enough room, or if it supplies too many
    /// destinations or segments at once. A rejection does not modify the state of the manager.
    ///
    /// Returns the time the destination grants hold until, which is when the client has to
    /// authorize again. A segment grant capped at its segment's expiry ends before that.
    ///
    /// Note: Segments are currently not being validated in this function.
    pub fn authorize(
        &self,
        ip: IpAddr,
        destinations: BTreeMap<CustomerDomain, AuthSegments>,
        now: SystemTime,
    ) -> Result<SystemTime, AuthorizeError> {
        if destinations.len() > self.0.config.max_targets_per_request {
            return Err(AuthorizeError::TooManyTargetsInRequest {
                requested: destinations.len(),
                max: self.0.config.max_targets_per_request,
            });
        }

        if destinations.len() > self.0.config.max_targets_per_ip {
            return Err(AuthorizeError::TooManyTargetsForIp {
                requested: destinations.len(),
                max: self.0.config.max_targets_per_ip,
            });
        }

        let requested = destinations
            .values()
            .map(AuthSegments::count)
            .sum::<usize>();

        if requested > self.0.config.max_segments_per_request {
            return Err(AuthorizeError::TooManySegmentsInRequest {
                requested,
                max: self.0.config.max_segments_per_request,
            });
        }

        // TODO: Auth segments are client input and should be validated.

        let dst_granted_until = now + self.0.config.grant_duration;

        let mut this = self.write();

        // Plan against the current state, before changing any of it.
        let evicted_targets =
            plan_targets(&this, self.0.config.max_targets_per_ip, ip, &destinations)?;

        let plans = destinations
            .into_iter()
            .map(|(dst, auth_segments)| {
                plan_destination(
                    &this,
                    self.0.config.max_segments_per_target,
                    ip,
                    dst,
                    auth_segments,
                    dst_granted_until,
                    now,
                )
            })
            .collect::<Result<Vec<_>, _>>()?;

        let GrantManagerInner {
            auth_ips,
            private_non_core_segments,
            private_core_segments,
        } = &mut *this;

        let auth_entry = auth_ips.entry(ip).or_default();

        for dst in evicted_targets {
            evict_target_grant(
                &mut auth_entry.auth_dsts,
                private_core_segments,
                private_non_core_segments,
                &dst,
            );
            tracing::debug!(%ip, %dst, "Evicted an unused target grant");
        }

        for DstPlan {
            dst,
            grants,
            evictions,
        } in plans
        {
            // Get the grant entry for this (ip, dst) pair, or create a new one if it doesn't
            // exist. An existing grant is only ever extended.
            let dst_entry = auth_entry
                .auth_dsts
                .entry(dst.clone())
                .and_modify(|dst_auth| {
                    dst_auth.granted_until = dst_auth.granted_until.max(dst_granted_until);
                })
                .or_insert_with(|| DstAuthInfo::new(dst_granted_until));

            // Evict grants
            for id in evictions {
                evict_segment_grant(
                    &mut dst_entry.segment_grants,
                    segment_store(id, private_core_segments, private_non_core_segments),
                    id,
                );
                tracing::debug!(%ip, %dst, fp = %id.fp(), "Evicted an unused segment grant");
            }

            for PlannedGrant {
                id,
                segment,
                segment_expiry,
                granted_until,
            } in grants
            {
                grant_segment(
                    &mut dst_entry.segment_grants,
                    segment_store(id, private_core_segments, private_non_core_segments),
                    id,
                    segment,
                    segment_expiry,
                    granted_until,
                );
            }
        }

        Ok(dst_granted_until)
    }

    /// Checks if the IP has a grant for the given SNI.
    ///
    /// Returns `None` if no valid grant exists.
    /// Returns `DstGrant` with the segments currently granted for the given SNI if a valid
    /// grant exists.
    pub fn dst_grant(
        &self,
        ip: IpAddr,
        dst: CustomerDomainRef<'_>,
        now: SystemTime,
    ) -> Option<DstGrant> {
        let this = self.read();

        let dst_auth = this.auth_ips.get(&ip)?.auth_dsts.get(dst.as_str())?;

        // Grant has already expired, return None to indicate that the client needs to
        // reauthenticate.
        if !dst_auth.is_valid(now) {
            return None;
        }

        let mut granted_segments = DstGrant::default();

        for (id, grant) in dst_auth.segment_grants.iter() {
            // Skip expired grants, they will be cleaned up later.
            if !grant.is_valid(now) {
                continue;
            }

            let (store, out) = match id {
                GrantedSegmentId::Core(_) => {
                    (
                        &this.private_core_segments,
                        &mut granted_segments.core_segments,
                    )
                }
                GrantedSegmentId::NonCore(_) => {
                    (
                        &this.private_non_core_segments,
                        &mut granted_segments.non_core_segments,
                    )
                }
            };

            let Some(segment_entry) = store.get(&id.fp()) else {
                continue;
            };

            out.insert(id.fp(), segment_entry.segment.clone());
        }

        Some(granted_segments)
    }

    /// Returns the time when the grant for the given IP and destination expires
    /// Returns `None` if there is no valid grant for the given IP and destination.
    pub fn grant_expiry(
        &self,
        ip: IpAddr,
        dst: CustomerDomainRef<'_>,
        now: SystemTime,
    ) -> Option<SystemTime> {
        let this = self.read();

        this.auth_ips
            .get(&ip)?
            .auth_dsts
            .get(dst.as_str())
            .filter(|dst_auth| dst_auth.is_valid(now))
            .map(|dst_auth| dst_auth.granted_until)
    }

    /// Returns when the given IP's grant on the given segment for the given destination expires,
    /// if that grant is valid.
    pub fn segment_grant_expiry(
        &self,
        ip: IpAddr,
        dst: CustomerDomainRef<'_>,
        id: &GrantedSegmentId,
        now: SystemTime,
    ) -> Option<SystemTime> {
        let this = self.read();

        this.auth_ips
            .get(&ip)?
            .auth_dsts
            .get(dst.as_str())?
            .segment_grants
            .get(id)
            .filter(|grant| grant.is_valid(now))
            .map(|grant| grant.granted_until)
    }

    /// Guards the grant for the given IP and destination against eviction.
    ///
    /// Returns `None` if there is no valid grant to watch.
    pub fn watch_grant(
        &self,
        ip: IpAddr,
        customer_domain: CustomerDomainRef<'_>,
        now: SystemTime,
    ) -> Option<TargetGrantGuard> {
        let this = self.read();

        let grant = this
            .auth_ips
            .get(&ip)
            .and_then(|auth_entry| auth_entry.auth_dsts.get(customer_domain.as_str()));

        let Some(grant) = grant else {
            tracing::debug!(%ip, %customer_domain, "No grant found");
            return None;
        };

        if !grant.is_valid(now) {
            tracing::debug!(%ip, %customer_domain, "Grant has already expired");
            return None;
        }

        Some(grant.guard())
    }

    /// Guards the given IP's grant on the given segment for the given destination.
    ///
    /// Returns `None` if there is no valid grant.
    pub fn watch_segment_grant(
        &self,
        ip: IpAddr,
        customer_domain: CustomerDomainRef<'_>,
        id: &GrantedSegmentId,
        now: SystemTime,
    ) -> Option<SegmentGrantGuard> {
        let this = self.read();

        let segment_grant = this
            .auth_ips
            .get(&ip)?
            .auth_dsts
            .get(customer_domain.as_str())?
            .segment_grants
            .get(id)?;

        if !segment_grant.is_valid(now) {
            tracing::debug!(%ip, %customer_domain, ?id, "Segment grant has already expired");
            return None;
        }

        Some(segment_grant.guard())
    }

    /// Returns the segment `id` refers to, as long as any grant on it is still valid.
    ///
    /// Returns `None` if the segment is not in the authoritative store, or if it has no valid
    /// grants.
    pub fn segment(&self, id: &GrantedSegmentId, now: SystemTime) -> Option<SignedPathSegment> {
        let this: RwLockReadGuard<'_, GrantManagerInner> = self.read();

        let store = match id {
            GrantedSegmentId::Core(_) => &this.private_core_segments,
            GrantedSegmentId::NonCore(_) => &this.private_non_core_segments,
        };

        store
            .get(&id.fp())
            .filter(|segment_entry| segment_entry.expiration > now)
            .filter(|segment_entry| {
                debug_assert!(
                    segment_entry.grant_count > 0,
                    "segment {id:?} is in the store but has no grants referencing it, it should have been removed by clean()"
                );
                segment_entry.grant_count > 0
            })
            .map(|segment_entry| segment_entry.segment.clone())
    }

    /// Drops all expired authentication state and notifies everything that waited on it.
    ///
    /// Removal cascades from the outside in:
    /// - A destination grant is removed once its `granted_until` has passed. Removing it removes
    ///   all of its segment grants, regardless of their own expiry.
    /// - A segment grant is removed once its own `granted_until` has passed.
    /// - An IP is removed once it has no destination grants left, i.e. it is fully de-authed.
    /// - A segment is removed from the authoritative store once its last grant is gone. It cannot
    ///   outlive its grants, because a grant is capped at the segment's expiry.
    ///
    /// Every removed grant has its cancellation token cancelled before it is dropped, so the
    /// streams watching it via [`Self::watch_grant`] or [`Self::watch_segment_grant`] can tear
    /// down.
    ///
    /// Returns the time the next grant expires, i.e. when calling this again has an effect.
    /// The functions should be called regularely, to ensure newly added grants are cleaned up
    /// in time.
    pub fn clean(&self, now: SystemTime) -> SystemTime {
        let mut next_expiry = now + self.0.config.grant_duration;

        let mut this = self.write();
        let GrantManagerInner {
            auth_ips,
            private_non_core_segments,
            private_core_segments,
        } = &mut *this;

        auth_ips.retain(|ip, ip_auth| {
            ip_auth.auth_dsts.retain(|dst, dst_auth| {
                let dst_expired = !dst_auth.is_valid(now);

                dst_auth.segment_grants.retain(|id, segment_grant| {
                    // Retain if the dst is not expired and the segment grant is not expired.
                    // Otherwise, remove it.
                    if !dst_expired && segment_grant.is_valid(now) {
                        next_expiry = next_expiry.min(segment_grant.granted_until);
                        return true;
                    }

                    // Otherwise, clean up the grant.
                    let store = match id {
                        GrantedSegmentId::Core(_) => &mut *private_core_segments,
                        GrantedSegmentId::NonCore(_) => &mut *private_non_core_segments,
                    };

                    release_segment_grant(store, id.fp());
                    segment_grant.expired.cancel();

                    tracing::trace!(%ip, %dst, fp = %id.fp(), "Removed expired segment grant");
                    false
                });

                if dst_expired {
                    dst_auth.expired.cancel();
                    tracing::debug!(%ip, %dst, "Removed expired destination grant");
                } else {
                    next_expiry = next_expiry.min(dst_auth.granted_until);
                }

                !dst_expired
            });

            let ip_authorized = !ip_auth.auth_dsts.is_empty();
            if !ip_authorized {
                tracing::debug!(%ip, "IP has no grants left, de-authorizing");
            }

            ip_authorized
        });

        // Drop segments that lost their last grant above.
        for store in [private_core_segments, private_non_core_segments] {
            store.retain(|fp, segment_entry| {
                if segment_entry.grant_count > 0 {
                    debug_assert!(
                        segment_entry.expiration > now,
                        "segment {fp} outlived by a grant, grants must be capped at the \
                         segment expiry"
                    );
                    return true;
                }

                tracing::debug!(%fp, "Removed unreferenced segment from the authoritative store");
                false
            });
        }

        next_expiry
    }

    /// Periodically runs [`Self::clean`] so grant expiry is observed close to when it happens.
    ///
    /// Reads the wall clock itself, unlike every other entry point. Never returns.
    pub async fn run(&self) {
        loop {
            let now = SystemTime::now();
            let next = self.clean(now);
            let sleep = next
                .duration_since(now)
                .unwrap_or(Duration::ZERO)
                .max(self.0.config.min_clean_interval)
                .min(self.0.config.max_clean_interval);

            tracing::trace!("Next grant manager cleanup in {:?}", sleep);
            tokio::time::sleep(sleep).await;
        }
    }
}

/// Picks the target grants a [`GrantManager::authorize`] call has to evict to fit `max_targets`.
///
/// Changes nothing, so a caller can plan every destination before applying any of them.
///
/// The IP holds the requested targets plus the ones the request does not name. Targets over
/// `max_targets` are evicted, by these rules:
/// - A requested target is never evicted. It is refreshed instead.
/// - A target with a live [`TargetGrantGuard`], or with a segment grant that a consumer holds, is
///   never evicted.
/// - Of the rest, the ones that expire first are evicted, until the IP fits.
///
/// Fails, and plans nothing, if evicting every evictable target still does not fit. Returns
/// [`AuthorizeError::IpTargetLimitReached`].
fn plan_targets(
    inner: &GrantManagerInner,
    max_targets: usize,
    ip: IpAddr,
    requested: &BTreeMap<CustomerDomain, AuthSegments>,
) -> Result<Vec<CustomerDomain>, AuthorizeError> {
    let Some(ip_auth) = inner.auth_ips.get(&ip) else {
        return Ok(Vec::new());
    };

    // The targets the request refreshes are already counted in `requested`.
    let untouched = ip_auth
        .auth_dsts
        .keys()
        .filter(|dst| !requested.contains_key(*dst))
        .count();
    let over = (untouched + requested.len()).saturating_sub(max_targets);

    if over == 0 {
        return Ok(Vec::new());
    }

    // The evictable targets, ordered by the rules above.
    let mut candidates = ip_auth
        .auth_dsts
        .iter()
        .filter(|(dst, dst_auth)| !requested.contains_key(*dst) && !dst_auth.is_in_use())
        .map(|(dst, dst_auth)| (dst_auth.granted_until, dst))
        .collect::<Vec<_>>();

    if candidates.len() < over {
        return Err(AuthorizeError::IpTargetLimitReached {
            in_use: untouched - candidates.len(),
            needed: over,
            max: max_targets,
        });
    }

    candidates.sort_unstable_by(|(left_expiry, left_dst), (right_expiry, right_dst)| {
        left_expiry
            .cmp(right_expiry)
            .then_with(|| left_dst.as_str().cmp(right_dst.as_str()))
    });

    Ok(candidates
        .into_iter()
        .take(over)
        .map(|(_, dst)| dst.clone())
        .collect())
}

/// Plans the changes one destination of a [`GrantManager::authorize`] call turns into.
///
/// Changes nothing, so a caller can plan every destination before applying any of them.
///
/// The requested segments become the wanted grants:
/// - Up and down segments become non-core grants, core segments become core grants.
/// - The same [`GrantedSegmentId`] wanted more than once is one grant, on the longest lived copy.
/// - A segment that is already expired is dropped.
///
/// The destination then holds the wanted grants plus the ones the request does not name.
/// Grants over `max_grants` are evicted, by these rules:
/// - A wanted grant is never evicted. It is refreshed instead.
/// - A grant with a live [`SegmentGrantGuard`] is never evicted.
/// - Of the rest, the ones that expire first are evicted, until the destination fits.
///
/// Fails, and plans nothing, if:
/// - The request wants more than `max_grants` grants. Returns
///   [`AuthorizeError::TooManySegmentsForTarget`].
/// - Evicting every evictable grant still does not fit. Returns
///   [`AuthorizeError::TargetGrantLimitReached`].
fn plan_destination(
    inner: &GrantManagerInner,
    max_grants: usize,
    ip: IpAddr,
    dst: CustomerDomain,
    auth_segments: AuthSegments,
    dst_granted_until: SystemTime,
    now: SystemTime,
) -> Result<DstPlan, AuthorizeError> {
    let AuthSegments {
        up_segments,
        down_segments,
        core_segments,
    } = auth_segments;

    // Up and down segments both become non-core grants, see `GrantedSegmentId`.
    let tagged = core_segments
        .into_iter()
        .map(|segment| (segment, true))
        .chain(
            up_segments
                .into_iter()
                .chain(down_segments)
                .map(|segment| (segment, false)),
        );

    // Deduplicate segments.
    let mut wanted: HashMap<GrantedSegmentId, PlannedGrant> = HashMap::new();

    for (segment, is_core) in tagged {
        let fp = segment.fingerprint();
        let segment_expiry = segment.expires_earliest();

        // A grant can never outlive the segment it is granted on, see the module docs.
        let granted_until = dst_granted_until.min(segment_expiry);
        if granted_until <= now {
            tracing::debug!(
                %ip, %dst, %fp,
                "Ignoring grant for a segment that has already expired"
            );
            continue;
        }

        let id = if is_core {
            GrantedSegmentId::Core(fp)
        } else {
            GrantedSegmentId::NonCore(fp)
        };

        let planned = PlannedGrant {
            id,
            segment,
            segment_expiry,
            granted_until,
        };

        match wanted.entry(id) {
            // Keep the copy that lives longest.
            Entry::Occupied(mut existing) => {
                if existing.get().segment_expiry < segment_expiry {
                    existing.insert(planned);
                }
            }
            Entry::Vacant(vacant) => {
                vacant.insert(planned);
            }
        }
    }

    if wanted.len() > max_grants {
        return Err(AuthorizeError::TooManySegmentsForTarget {
            dst,
            requested: wanted.len(),
            max: max_grants,
        });
    }

    let held = inner
        .auth_ips
        .get(&ip)
        .and_then(|ip_auth| ip_auth.auth_dsts.get(&dst));

    let mut evictions = Vec::new();

    if let Some(dst_auth) = held {
        // The grants the request refreshes are already counted in `wanted`.
        let untouched = dst_auth
            .segment_grants
            .keys()
            .filter(|id| !wanted.contains_key(id))
            .count();
        let over = (untouched + wanted.len()).saturating_sub(max_grants);

        if over > 0 {
            // The evictable grants, ordered by the rules above.
            let mut candidates = dst_auth
                .segment_grants
                .iter()
                .filter(|(id, grant)| !wanted.contains_key(id) && !grant.is_in_use())
                .map(|(id, grant)| (grant.granted_until, *id))
                .collect::<Vec<_>>();

            if candidates.len() < over {
                return Err(AuthorizeError::TargetGrantLimitReached {
                    dst,
                    in_use: untouched - candidates.len(),
                    needed: over,
                    max: max_grants,
                });
            }

            candidates.sort_unstable();
            evictions.extend(candidates.into_iter().take(over).map(|(_, id)| id));
        }
    }

    Ok(DstPlan {
        dst,
        grants: wanted.into_values().collect(),
        evictions,
    })
}

/// Picks the authoritative store `id` belongs to.
fn segment_store<'store>(
    id: GrantedSegmentId,
    core: &'store mut HashMap<SegmentFp, AuthSegmentEntry>,
    non_core: &'store mut HashMap<SegmentFp, AuthSegmentEntry>,
) -> &'store mut HashMap<SegmentFp, AuthSegmentEntry> {
    if id.is_core() { core } else { non_core }
}

/// Records a grant for `id` and inserts or refreshes the granted segment.
///
/// - The grant for `id` is only ever extended, never shortened.
/// - The stored copy of the segment is replaced only by a longer lived one.
/// - The grant count grows by one only if this call adds a grant that did not exist before.
fn grant_segment(
    grants: &mut HashMap<GrantedSegmentId, SegmentGrant>,
    store: &mut HashMap<SegmentFp, AuthSegmentEntry>,
    id: GrantedSegmentId,
    segment: SignedPathSegment,
    segment_expiry: SystemTime,
    granted_until: SystemTime,
) {
    let is_new_grant = match grants.entry(id) {
        // Extend the existing grant.
        Entry::Occupied(mut existing) => {
            let grant = existing.get_mut();
            grant.granted_until = grant.granted_until.max(granted_until);
            false
        }
        // Insert a new grant.
        Entry::Vacant(vacant) => {
            vacant.insert(SegmentGrant::new(granted_until));
            true
        }
    };

    match store.entry(id.fp()) {
        // Segment already exists, extend its expiry, and increase the grant count if a new
        // grant was added above.
        Entry::Occupied(mut existing) => {
            let existing = existing.get_mut();

            // Keep the copy that lives longest, a refresh may carry a fresher one.
            if existing.expiration < segment_expiry {
                existing.segment = segment;
                existing.expiration = segment_expiry;
            }

            if is_new_grant {
                existing.grant_count += 1;
            }
        }
        // Segment does not exist yet, insert it with a grant count of 1. For the new grant
        // added above
        Entry::Vacant(vacant) => {
            debug_assert!(
                is_new_grant,
                "segment store was missing a segment that was already referenced by a grant"
            );
            vacant.insert(AuthSegmentEntry::new(segment, segment_expiry, 1));
        }
    }
}

/// Drops the grant on `id` before it expired.
///
/// - Cancels the grant's token.
/// - Releases the grant's hold on the segment.
/// - Drops the segment from the store if it lost its last grant.
fn evict_segment_grant(
    grants: &mut HashMap<GrantedSegmentId, SegmentGrant>,
    store: &mut HashMap<SegmentFp, AuthSegmentEntry>,
    id: GrantedSegmentId,
) {
    let Some(grant) = grants.remove(&id) else {
        debug_assert!(
            false,
            "grant {id:?} was planned for eviction but is not there"
        );
        return;
    };

    drop_segment_grant(store, id.fp(), grant);
}

/// Drops the target grant on `dst`, and all of its segment grants, before they expired.
///
/// Cancels the token of the target grant and of every segment grant it held.
fn evict_target_grant(
    auth_dsts: &mut HashMap<CustomerDomain, DstAuthInfo>,
    core: &mut HashMap<SegmentFp, AuthSegmentEntry>,
    non_core: &mut HashMap<SegmentFp, AuthSegmentEntry>,
    dst: &CustomerDomain,
) {
    let Some(dst_auth) = auth_dsts.remove(dst) else {
        debug_assert!(
            false,
            "target {dst} was planned for eviction but is not there"
        );
        return;
    };

    for (id, grant) in dst_auth.segment_grants {
        drop_segment_grant(segment_store(id, core, non_core), id.fp(), grant);
    }

    dst_auth.expired.cancel();
}

/// Releases `grant`'s hold on the segment `fp` refers to and cancels the grant.
///
/// Drops the segment from the store if it lost its last grant. The caller has already taken the
/// grant out of the map that held it.
fn drop_segment_grant(
    store: &mut HashMap<SegmentFp, AuthSegmentEntry>,
    fp: SegmentFp,
    grant: SegmentGrant,
) {
    release_segment_grant(store, fp);

    // Drop the segment right away; there is no sweep after this, unlike in `clean`.
    if store
        .get(&fp)
        .is_some_and(|segment_entry| segment_entry.grant_count == 0)
    {
        store.remove(&fp);
        tracing::debug!(%fp, "Removed unreferenced segment from the authoritative store");
    }

    grant.expired.cancel();
}

/// Decrements the grant count of the segment `fp` refers to.
///
/// The entry itself is left in place; it is dropped by the store sweep in
/// [`GrantManager::clean`] once its count has reached zero.
fn release_segment_grant(store: &mut HashMap<SegmentFp, AuthSegmentEntry>, fp: SegmentFp) {
    let Some(segment_entry) = store.get_mut(&fp) else {
        debug_assert!(false, "segment {fp} has a grant but is not in the store");
        return;
    };

    debug_assert!(
        segment_entry.grant_count > 0,
        "segment {fp} is in the store but has no grants referencing it"
    );
    segment_entry.grant_count = segment_entry.grant_count.saturating_sub(1);
}

/// Failures of [`GrantManager::authorize`].
#[derive(Debug, thiserror::Error)]
pub enum AuthorizeError {
    /// The request is over [`GrantManagerConfig::max_segments_per_request`].
    #[error("request grants {requested} segments, at most {max} are allowed per request")]
    TooManySegmentsInRequest {
        /// The number of segments the request wants to grant, over all its targets.
        requested: usize,
        /// The maximum number of segments allowed per request.
        max: usize,
    },
    /// The request is over [`GrantManagerConfig::max_targets_per_request`].
    #[error("request has {requested} targets, at most {max} are allowed per request")]
    TooManyTargetsInRequest {
        /// The number of targets in the request.
        requested: usize,
        /// The maximum number of targets allowed per request.
        max: usize,
    },
    /// One destination of the request is over [`GrantManagerConfig::max_segments_per_target`].
    #[error("request grants {requested} segments for {dst}, at most {max} are allowed per target")]
    TooManySegmentsForTarget {
        /// The destination that is over the limit.
        dst: CustomerDomain,
        /// The number of segments the request wants to grant for that destination.
        requested: usize,
        /// The maximum number of segments allowed per destination.
        max: usize,
    },
    /// One destination is at its limit, and too many of its grants are guarded to evict.
    #[error(
        "target {dst} needs {needed} of its {max} segment grants freed, but {in_use} of the \
         candidates are in use"
    )]
    TargetGrantLimitReached {
        /// The destination that is over the limit.
        dst: CustomerDomain,
        /// The number of grants that are currently in use and cannot be evicted.
        in_use: usize,
        /// The number of grants that need to be freed to fit the request.
        needed: usize,
        /// The maximum number of grants allowed per destination.
        max: usize,
    },
    /// The request alone is over [`GrantManagerConfig::max_targets_per_ip`].
    #[error("request has {requested} targets, an IP may hold at most {max}")]
    TooManyTargetsForIp {
        /// The number of targets the request wants to grant for the IP.
        requested: usize,
        /// The maximum number of targets allowed per IP.
        max: usize,
    },
    /// The IP is at its limit, and too many of its target grants are in use to evict.
    #[error(
        "the IP needs {needed} of its {max} target grants freed, but {in_use} of the candidates \
         are in use"
    )]
    IpTargetLimitReached {
        /// The number of target grants that are in use and cannot be evicted.
        in_use: usize,
        /// The number of target grants that have to be freed to fit the request.
        needed: usize,
        /// The maximum number of target grants allowed per IP.
        max: usize,
    },
}

/// The changes [`GrantManager::authorize`] applies to one destination.
struct DstPlan {
    dst: CustomerDomain,
    /// The grants to add or extend, deduplicated by id.
    grants: Vec<PlannedGrant>,
    /// The grants to evict first.
    evictions: Vec<GrantedSegmentId>,
}

/// One grant of a [`DstPlan`].
struct PlannedGrant {
    id: GrantedSegmentId,
    segment: SignedPathSegment,
    segment_expiry: SystemTime,
    granted_until: SystemTime,
}

/// Identification of a segment of the authoritative store.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GrantedSegmentId {
    /// A core segment with the given fingerprint.
    Core(SegmentFp),
    /// An up or down segment with the given fingerprint.
    NonCore(SegmentFp),
}

impl GrantedSegmentId {
    /// The fingerprint of the segment.
    pub fn fp(&self) -> SegmentFp {
        match self {
            Self::Core(fp) | Self::NonCore(fp) => *fp,
        }
    }

    /// Returns true if this identifies a core segment.
    pub fn is_core(&self) -> bool {
        matches!(self, Self::Core(_))
    }
}

/// A segment in the authoritative store, with the number of grants referencing it.
struct AuthSegmentEntry {
    segment: SignedPathSegment,
    expiration: SystemTime,
    grant_count: usize,
}

impl AuthSegmentEntry {
    fn new(segment: SignedPathSegment, expiration: SystemTime, initial_grant_count: usize) -> Self {
        Self {
            segment,
            expiration,
            grant_count: initial_grant_count,
        }
    }
}

/// Everything one IP is authorized for.
#[derive(Default)]
struct IpAuthInfo {
    auth_dsts: HashMap<CustomerDomain, DstAuthInfo>,
}

/// A grant for one (IP, destination) pair.
struct DstAuthInfo {
    segment_grants: HashMap<GrantedSegmentId, SegmentGrant>,
    granted_until: SystemTime,
    /// Cancelled when this grant is removed, either by [`GrantManager::clean`] or by eviction.
    expired: CancellationToken,
    /// Holds one strong reference per live [`TargetGrantGuard`], plus the one kept here.
    in_use: Arc<()>,
}

impl DstAuthInfo {
    fn new(granted_until: SystemTime) -> Self {
        Self {
            segment_grants: HashMap::new(),
            granted_until,
            expired: CancellationToken::new(),
            in_use: Arc::new(()),
        }
    }

    fn is_valid(&self, now: SystemTime) -> bool {
        now < self.granted_until
    }

    /// Whether a consumer holds this grant, or one of the segment grants it would take with it.
    ///
    /// May stay true for a moment after the last guard is dropped.
    fn is_in_use(&self) -> bool {
        Arc::strong_count(&self.in_use) > 1
            || self.segment_grants.values().any(SegmentGrant::is_in_use)
    }

    /// Guards this grant from eviction.
    fn guard(&self) -> TargetGrantGuard {
        TargetGrantGuard {
            expired: self.expired.clone(),
            _in_use: Arc::clone(&self.in_use),
        }
    }
}

/// A grant for one segment within a [`DstAuthInfo`].
struct SegmentGrant {
    granted_until: SystemTime,
    /// Cancelled when this grant is removed, either by [`GrantManager::clean`] or by eviction.
    expired: CancellationToken,
    /// Holds one strong reference per live [`SegmentGrantGuard`], plus the one kept here.
    in_use: Arc<()>,
}

impl SegmentGrant {
    fn new(granted_until: SystemTime) -> Self {
        Self {
            granted_until,
            expired: CancellationToken::new(),
            in_use: Arc::new(()),
        }
    }

    fn is_valid(&self, now: SystemTime) -> bool {
        now < self.granted_until
    }

    /// Whether a [`SegmentGrantGuard`] on this grant is alive.
    ///
    /// May stay true for a moment after the last guard is dropped.
    fn is_in_use(&self) -> bool {
        Arc::strong_count(&self.in_use) > 1
    }

    /// Guards this grant from eviction.
    fn guard(&self) -> SegmentGrantGuard {
        SegmentGrantGuard {
            expired: self.expired.clone(),
            _in_use: Arc::clone(&self.in_use),
        }
    }
}

/// Guards a target grant from eviction, and allows a client to observe expiry.
///
/// Handed out by [`GrantManager::watch_grant`].
/// Use [`Self::expired`] to await expiry.
pub struct TargetGrantGuard {
    expired: CancellationToken,
    /// Counted by [`DstAuthInfo::is_in_use`] for as long as this guard lives.
    _in_use: Arc<()>,
}

impl TargetGrantGuard {
    /// The token that is cancelled once the grant is gone.
    ///
    /// Cancellation is latched.
    pub fn expired(&self) -> &CancellationToken {
        &self.expired
    }
}

/// Guards a segment grant from eviction, and allows a client to observe expiry.
///
/// Handed out by [`GrantManager::watch_segment_grant`].
/// Use [`Self::expired`] to await expiry.
pub struct SegmentGrantGuard {
    expired: CancellationToken,
    /// Counted by [`SegmentGrant::is_in_use`] for as long as this guard lives.
    _in_use: Arc<()>,
}

impl SegmentGrantGuard {
    /// The token that is cancelled once the grant is gone.
    ///
    /// Cancellation is latched.
    pub fn expired(&self) -> &CancellationToken {
        &self.expired
    }
}

// XXX: this should not copy the segments, just an iterator over the granted segments, but that
// would require locking magic.
/// A grany for one destination in [`GrantManager::dst_grant`].
#[derive(Default)]
pub struct DstGrant {
    core_segments: HashMap<SegmentFp, SignedPathSegment>,
    non_core_segments: HashMap<SegmentFp, SignedPathSegment>,
}

impl DstGrant {
    /// Iterates over the granted core segments.
    pub fn iter_core_segments(&self) -> impl Iterator<Item = &SignedPathSegment> {
        self.core_segments.values()
    }

    /// Iterates over the granted up and down segments.
    pub fn iter_non_core_segments(&self) -> impl Iterator<Item = &SignedPathSegment> {
        self.non_core_segments.values()
    }

    /// Returns whether a core segment with the given fingerprint is granted.
    pub fn has_core_segment(&self, fp: SegmentFp) -> bool {
        self.core_segments.contains_key(&fp)
    }

    /// Returns whether an up or down segment with the given fingerprint is granted.
    pub fn has_non_core_segment(&self, fp: SegmentFp) -> bool {
        self.non_core_segments.contains_key(&fp)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;
    use crate::pg_wap::test_util::{
        Fixture, MockFetcher, at, client_ip, granted_id, nth_sni, nth_up_segment, other_client_ip,
        other_sni, other_up_segment, secs_since_epoch, sni, up_segment,
    };

    #[test]
    fn refreshing_a_grant_adds_to_it_without_shortening_it() {
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(100));

        let first = up_segment(0);
        let second = other_up_segment(0);

        fixture.grant_non_core(vec![first.clone()], at(0));
        let first_expiry = fixture
            .grant
            .segment_grant_expiry(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&first),
                at(0),
            )
            .expect("the first segment is granted");

        // A refresh 10s later that only mentions the second segment must not take the first away.
        fixture.grant_non_core(vec![second.clone()], at(10));

        assert_eq!(
            fixture.grant.segment_grant_expiry(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&first),
                at(10)
            ),
            Some(first_expiry),
            "the first grant must be kept, with its original expiry"
        );
        assert_eq!(
            fixture.grant.segment_grant_expiry(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&second),
                at(10)
            ),
            Some(at(110)),
            "the second grant runs for the full grant duration from the refresh"
        );
        assert_eq!(
            fixture
                .grant
                .grant_expiry(client_ip(), sni().customer_domain(), at(10)),
            Some(at(110)),
            "the target grant is extended by the refresh"
        );
    }

    #[test]
    fn a_segment_grant_never_outlives_its_segment() {
        // The grant duration is far longer than the segment lives.
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(10 * 24 * 3600));

        let segment = up_segment(0);
        fixture.grant_non_core(vec![segment.clone()], at(0));

        assert_eq!(
            fixture.grant.segment_grant_expiry(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&segment),
                at(0)
            ),
            Some(segment.expires_earliest()),
            "the grant must be capped at the expiry of the segment it is granted on"
        );
    }

    #[test]
    fn a_grant_on_an_expired_segment_is_ignored() {
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(100));

        let segment = up_segment(0);
        let expired = at(secs_since_epoch(segment.expires_earliest()) + 1);
        fixture.grant_non_core(vec![segment.clone()], expired);

        assert_eq!(
            fixture.grant.segment_grant_expiry(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&segment),
                expired
            ),
            None
        );
    }

    #[tokio::test]
    async fn expired_grants_are_cleaned_up_and_observable() {
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(100));

        let segment = up_segment(0);
        fixture.grant_non_core(vec![segment.clone()], at(0));

        let target_expired = fixture
            .grant
            .watch_grant(client_ip(), sni().customer_domain(), at(0))
            .expect("the target grant is live");
        let segment_expired = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&segment),
                at(0),
            )
            .expect("the segment grant is live");

        assert!(fixture.grant.ip_is_authorized(client_ip(), at(0)));

        // Nothing has expired yet, so cleaning changes nothing.
        assert_eq!(
            fixture.grant.clean(at(0)),
            at(100),
            "clean reports when the next grant expires"
        );
        assert!(
            fixture
                .grant
                .dst_grant(client_ip(), sni().customer_domain(), at(0))
                .is_some()
        );

        fixture.grant.clean(at(101));

        // Both notifiers were handed out before the expiry and still resolve.
        target_expired.expired().cancelled().await;
        segment_expired.expired().cancelled().await;

        assert!(
            !fixture.grant.ip_is_authorized(client_ip(), at(101)),
            "an IP without grants is de-authorized"
        );
        assert!(
            fixture
                .grant
                .dst_grant(client_ip(), sni().customer_domain(), at(101))
                .is_none()
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&segment), at(101))
                .is_none()
        );
        assert!(
            fixture
                .grant
                .watch_grant(client_ip(), sni().customer_domain(), at(101))
                .is_none(),
            "there is no live grant left to wait on"
        );
    }

    /// One IP with two destination grants: [`sni`] runs until t=100 with a shared and a private
    /// segment, [`other_sni`] is refreshed at t=50 and runs until t=150 with only the shared one.
    ///
    /// Returns the fixture, the shared segment and the segment only [`sni`] is granted.
    fn two_destination_fixture() -> (Fixture, SignedPathSegment, SignedPathSegment) {
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(100));

        let shared = up_segment(0);
        let only_sni = other_up_segment(0);

        fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([
                    (
                        sni().customer_domain().into(),
                        AuthSegments {
                            up_segments: vec![shared.clone(), only_sni.clone()],
                            ..AuthSegments::default()
                        },
                    ),
                    (
                        other_sni().customer_domain().into(),
                        AuthSegments {
                            up_segments: vec![shared.clone()],
                            ..AuthSegments::default()
                        },
                    ),
                ]),
                at(0),
            )
            .expect("both destinations fit");

        // Only the second destination re-authenticates, so the first one lapses at t=100.
        fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([(
                    other_sni().customer_domain().into(),
                    AuthSegments {
                        up_segments: vec![shared.clone()],
                        ..AuthSegments::default()
                    },
                )]),
                at(50),
            )
            .expect("the refresh fits");

        (fixture, shared, only_sni)
    }

    #[test]
    fn an_expired_destination_takes_only_its_own_grants_with_it() {
        let (fixture, shared, only_sni) = two_destination_fixture();

        let sni_expired = fixture
            .grant
            .watch_grant(client_ip(), sni().customer_domain(), at(50))
            .expect("the lapsing destination is granted");
        let other_expired = fixture
            .grant
            .watch_grant(client_ip(), other_sni().customer_domain(), at(50))
            .expect("the refreshed destination is granted");
        let shared_for_sni_expired = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&shared),
                at(50),
            )
            .expect("the shared segment is granted for the lapsing destination");
        let shared_for_other_expired = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                other_sni().customer_domain(),
                &granted_id(&shared),
                at(50),
            )
            .expect("the shared segment is granted for the refreshed destination");

        assert_eq!(
            fixture.grant.clean(at(101)),
            at(150),
            "the remaining destination is the next thing to expire"
        );

        assert!(
            fixture
                .grant
                .dst_grant(client_ip(), sni().customer_domain(), at(101))
                .is_none(),
            "the lapsed destination is gone"
        );
        assert!(sni_expired.expired().is_cancelled());
        assert!(
            shared_for_sni_expired.expired().is_cancelled(),
            "an expiring destination takes its segment grants with it, however long they had left"
        );

        let other_grant = fixture
            .grant
            .dst_grant(client_ip(), other_sni().customer_domain(), at(101))
            .expect("the refreshed destination is untouched");
        assert_eq!(
            other_grant
                .iter_non_core_segments()
                .map(SignedPathSegment::fingerprint)
                .collect::<Vec<_>>(),
            vec![shared.fingerprint()]
        );
        assert!(!other_expired.expired().is_cancelled());
        assert!(!shared_for_other_expired.expired().is_cancelled());

        assert!(
            fixture.grant.ip_is_authorized(client_ip(), at(101)),
            "an IP with one destination left stays authorized"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&shared), at(101))
                .is_some(),
            "the shared segment is still held by the destination that refreshed"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&only_sni), at(101))
                .is_none(),
            "the segment only the lapsed destination held lost its last grant"
        );
    }

    #[test]
    fn an_ip_is_dropped_with_its_last_destination() {
        let (fixture, shared, _only_sni) = two_destination_fixture();

        // The first destination goes at t=100, the second one at t=150.
        fixture.grant.clean(at(101));
        assert!(fixture.grant.ip_is_authorized(client_ip(), at(101)));

        fixture.grant.clean(at(151));

        assert!(
            !fixture.grant.ip_is_authorized(client_ip(), at(151)),
            "the IP is de-authorized once its last destination is gone"
        );
        assert!(
            fixture
                .grant
                .dst_grant(client_ip(), other_sni().customer_domain(), at(151))
                .is_none(),
            "and so is that last destination"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&shared), at(151))
                .is_none(),
            "a segment cannot outlive the last grant referencing it"
        );
    }

    #[test]
    fn a_refresh_that_omits_a_segment_keeps_it_until_its_own_grant_expires() {
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(100));

        let kept = up_segment(0);
        let omitted = other_up_segment(0);
        fixture.grant_non_core(vec![kept.clone(), omitted.clone()], at(0));

        let omitted_expired = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&omitted),
                at(0),
            )
            .expect("both segments are granted");

        // The re-grant carries only one of the two segments; the other keeps running out.
        fixture.grant_non_core(vec![kept.clone()], at(50));

        assert!(
            fixture
                .grant
                .segment(&granted_id(&omitted), at(50))
                .is_some(),
            "an omitted segment stays usable while its own grant is valid"
        );
        assert!(!omitted_expired.expired().is_cancelled());

        fixture.grant.clean(at(101));

        assert!(
            omitted_expired.expired().is_cancelled(),
            "the omitted segment's grant expires on its own schedule"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&omitted), at(101))
                .is_none(),
            "and the segment goes with its last grant"
        );

        let grant = fixture
            .grant
            .dst_grant(client_ip(), sni().customer_domain(), at(101))
            .expect("the destination was extended by the refresh");
        assert_eq!(
            grant
                .iter_non_core_segments()
                .map(SignedPathSegment::fingerprint)
                .collect::<Vec<_>>(),
            vec![kept.fingerprint()],
            "only the refreshed segment is left"
        );
        assert!(fixture.grant.segment(&granted_id(&kept), at(101)).is_some());
    }

    #[test]
    fn granted_segments_are_returned_per_target() {
        let fixture = Fixture::new(MockFetcher::empty(), Duration::from_secs(100));

        let granted = up_segment(0);
        let other = other_up_segment(0);
        fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([
                    (
                        sni().customer_domain().into(),
                        AuthSegments {
                            up_segments: vec![granted.clone()],
                            ..AuthSegments::default()
                        },
                    ),
                    (
                        other_sni().customer_domain().into(),
                        AuthSegments {
                            core_segments: vec![other.clone()],
                            ..AuthSegments::default()
                        },
                    ),
                ]),
                at(0),
            )
            .expect("both destinations fit");

        let segments = fixture
            .grant
            .dst_grant(client_ip(), sni().customer_domain(), at(0))
            .expect("the target is granted");
        assert_eq!(
            segments
                .iter_non_core_segments()
                .map(SignedPathSegment::fingerprint)
                .collect::<Vec<_>>(),
            vec![granted.fingerprint()]
        );
        assert_eq!(segments.iter_core_segments().count(), 0);

        let other_segments = fixture
            .grant
            .dst_grant(client_ip(), other_sni().customer_domain(), at(0))
            .expect("the other target is granted");
        assert_eq!(
            other_segments
                .iter_core_segments()
                .map(SignedPathSegment::fingerprint)
                .collect::<Vec<_>>(),
            vec![other.fingerprint()],
            "a segment granted for another target is only visible there"
        );

        let ungranted =
            CustomerDomain::new("ungranted.example.com".to_owned()).expect("a valid domain");
        assert!(
            fixture
                .grant
                .dst_grant(client_ip(), ungranted.as_domain(), at(0))
                .is_none()
        );
    }

    /// A fixture whose targets hold at most `max_grants` segment grants, with a 100s duration.
    fn capped_fixture(max_grants: usize) -> Fixture {
        Fixture::with_grant_config(
            MockFetcher::empty(),
            GrantManagerConfig {
                grant_duration: Duration::from_secs(100),
                max_segments_per_target: max_grants,
                ..Fixture::grant_config_defaults()
            },
        )
    }

    /// When the test client's grant on `segment` for [`sni`] expires, if it holds one.
    fn expiry_of(
        fixture: &Fixture,
        segment: &SignedPathSegment,
        now: SystemTime,
    ) -> Option<SystemTime> {
        fixture.grant.segment_grant_expiry(
            client_ip(),
            sni().customer_domain(),
            &granted_id(segment),
            now,
        )
    }

    #[test]
    fn a_target_at_its_limit_evicts_its_oldest_unused_grant() {
        let fixture = capped_fixture(2);

        let oldest = nth_up_segment(0);
        let newer = nth_up_segment(1);
        let extra = nth_up_segment(2);

        fixture.grant_non_core(vec![oldest.clone()], at(0));
        fixture.grant_non_core(vec![newer.clone()], at(10));

        // Watching a grant holds it, so keep only the token: this one is meant to be evictable.
        let watch = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&oldest),
                at(10),
            )
            .expect("the first segment is granted");
        let oldest_expired = watch.expired().clone();
        drop(watch);

        fixture.grant_non_core(vec![extra.clone()], at(20));

        assert_eq!(
            expiry_of(&fixture, &oldest, at(20)),
            None,
            "the grant with the least left to lose made room for the new one"
        );
        assert!(
            oldest_expired.is_cancelled(),
            "an evicted grant is cancelled, just like an expired one"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&oldest), at(20))
                .is_none(),
            "and the segment goes with its last grant"
        );

        assert_eq!(expiry_of(&fixture, &newer, at(20)), Some(at(110)));
        assert_eq!(expiry_of(&fixture, &extra, at(20)), Some(at(120)));
    }

    #[test]
    fn a_grant_a_consumer_holds_is_not_evicted() {
        let fixture = capped_fixture(2);

        let held = nth_up_segment(0);
        let unheld = nth_up_segment(1);
        let extra = nth_up_segment(2);

        // The held grant is the older of the two, so it would go first if nobody had it.
        fixture.grant_non_core(vec![held.clone()], at(0));
        fixture.grant_non_core(vec![unheld.clone()], at(10));

        let hold = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&held),
                at(10),
            )
            .expect("the first segment is granted");

        fixture.grant_non_core(vec![extra.clone()], at(20));

        assert_eq!(
            expiry_of(&fixture, &held, at(20)),
            Some(at(100)),
            "a grant a consumer still holds is spared, however little it has left"
        );
        assert!(!hold.expired().is_cancelled());
        assert_eq!(
            expiry_of(&fixture, &unheld, at(20)),
            None,
            "the next candidate goes instead"
        );
        assert_eq!(expiry_of(&fixture, &extra, at(20)), Some(at(120)));
    }

    #[test]
    fn dropping_a_hold_frees_the_grant_for_eviction_again() {
        let fixture = capped_fixture(1);

        let held = nth_up_segment(0);
        let extra = nth_up_segment(1);

        fixture.grant_non_core(vec![held.clone()], at(0));

        let hold = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                sni().customer_domain(),
                &granted_id(&held),
                at(0),
            )
            .expect("the segment is granted");

        fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([(
                    sni().customer_domain().into(),
                    AuthSegments {
                        up_segments: vec![extra.clone()],
                        ..AuthSegments::default()
                    },
                )]),
                at(10),
            )
            .expect_err("the only grant of the target is in use");

        drop(hold);

        fixture.grant_non_core(vec![extra.clone()], at(20));

        assert_eq!(expiry_of(&fixture, &held, at(20)), None);
        assert_eq!(expiry_of(&fixture, &extra, at(20)), Some(at(120)));
    }

    #[test]
    fn a_request_that_cannot_free_room_is_rejected_whole() {
        let fixture = capped_fixture(2);

        let first = nth_up_segment(0);
        let second = nth_up_segment(1);
        let extra = nth_up_segment(2);

        fixture.grant_non_core(vec![first.clone(), second.clone()], at(0));

        let holds = [&first, &second].map(|segment| {
            fixture
                .grant
                .watch_segment_grant(
                    client_ip(),
                    sni().customer_domain(),
                    &granted_id(segment),
                    at(0),
                )
                .expect("both segments are granted")
        });

        // The same request carries a second destination, which would have fit on its own.
        let error = fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([
                    (
                        sni().customer_domain().into(),
                        AuthSegments {
                            up_segments: vec![extra.clone()],
                            ..AuthSegments::default()
                        },
                    ),
                    (
                        other_sni().customer_domain().into(),
                        AuthSegments::default(),
                    ),
                ]),
                at(10),
            )
            .expect_err("a full target whose grants are all in use takes nothing more");

        assert!(
            matches!(
                error,
                AuthorizeError::TargetGrantLimitReached {
                    needed: 1,
                    in_use: 2,
                    max: 2,
                    ..
                }
            ),
            "{error:?}"
        );

        assert!(holds.iter().all(|hold| !hold.expired().is_cancelled()));
        assert_eq!(expiry_of(&fixture, &first, at(10)), Some(at(100)));
        assert_eq!(expiry_of(&fixture, &second, at(10)), Some(at(100)));
        assert_eq!(
            expiry_of(&fixture, &extra, at(10)),
            None,
            "the segment that did not fit was not granted"
        );
        assert_eq!(
            fixture
                .grant
                .grant_expiry(client_ip(), sni().customer_domain(), at(10)),
            Some(at(100)),
            "and the target grant it came with was not extended either"
        );
        assert!(
            fixture
                .grant
                .grant_expiry(client_ip(), other_sni().customer_domain(), at(10))
                .is_none(),
            "the destination that would have fit is rejected with the request it came in"
        );
    }

    #[test]
    fn a_request_granting_more_than_a_target_can_hold_is_rejected() {
        let fixture = capped_fixture(2);

        let error = fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([(
                    sni().customer_domain().into(),
                    AuthSegments {
                        up_segments: vec![nth_up_segment(0), nth_up_segment(1)],
                        core_segments: vec![nth_up_segment(2)],
                        ..AuthSegments::default()
                    },
                )]),
                at(0),
            )
            .expect_err("three segments never fit into two grants");

        assert!(
            matches!(
                error,
                AuthorizeError::TooManySegmentsForTarget {
                    requested: 3,
                    max: 2,
                    ..
                }
            ),
            "{error:?}"
        );
        assert!(
            !fixture.grant.ip_is_authorized(client_ip(), at(0)),
            "a rejected request leaves the IP as unauthorized as it was"
        );
    }

    #[test]
    fn a_request_over_the_request_limit_is_rejected() {
        let fixture = Fixture::with_grant_config(
            MockFetcher::empty(),
            GrantManagerConfig {
                grant_duration: Duration::from_secs(100),
                max_segments_per_request: 1,
                ..Fixture::grant_config_defaults()
            },
        );

        let error = fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([
                    (
                        sni().customer_domain().into(),
                        AuthSegments {
                            up_segments: vec![up_segment(0)],
                            ..AuthSegments::default()
                        },
                    ),
                    (
                        other_sni().customer_domain().into(),
                        AuthSegments {
                            up_segments: vec![other_up_segment(0)],
                            ..AuthSegments::default()
                        },
                    ),
                ]),
                at(0),
            )
            .expect_err("one segment per destination is two over the whole request");

        assert!(
            matches!(
                error,
                AuthorizeError::TooManySegmentsInRequest {
                    requested: 2,
                    max: 1
                }
            ),
            "{error:?}"
        );
        assert!(!fixture.grant.ip_is_authorized(client_ip(), at(0)));
    }

    #[test]
    fn the_same_segment_granted_twice_costs_one_grant() {
        let fixture = capped_fixture(1);

        // Up and down segments both become the same non-core grant, see `GrantedSegmentId`.
        let segment = nth_up_segment(0);
        fixture.grant_for(
            client_ip(),
            sni().customer_domain(),
            AuthSegments {
                up_segments: vec![segment.clone()],
                down_segments: vec![segment.clone()],
                ..AuthSegments::default()
            },
            at(0),
        );

        assert_eq!(expiry_of(&fixture, &segment, at(0)), Some(at(100)));
    }

    #[test]
    fn a_core_and_a_non_core_grant_on_one_segment_are_two_grants() {
        let fixture = capped_fixture(1);

        let segment = nth_up_segment(0);
        let error = fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([(
                    sni().customer_domain().into(),
                    AuthSegments {
                        up_segments: vec![segment.clone()],
                        core_segments: vec![segment.clone()],
                        ..AuthSegments::default()
                    },
                )]),
                at(0),
            )
            .expect_err("the two grants are told apart by more than the fingerprint");

        assert!(
            matches!(
                error,
                AuthorizeError::TooManySegmentsForTarget {
                    requested: 2,
                    max: 1,
                    ..
                }
            ),
            "{error:?}"
        );
    }

    #[test]
    fn refreshing_a_target_at_its_limit_evicts_nothing() {
        let fixture = capped_fixture(2);

        let first = nth_up_segment(0);
        let second = nth_up_segment(1);

        fixture.grant_non_core(vec![first.clone(), second.clone()], at(0));
        fixture.grant_non_core(vec![first.clone(), second.clone()], at(10));

        assert_eq!(expiry_of(&fixture, &first, at(10)), Some(at(110)));
        assert_eq!(expiry_of(&fixture, &second, at(10)), Some(at(110)));
    }

    #[test]
    fn the_limit_is_per_target_not_per_ip() {
        let fixture = capped_fixture(1);

        let for_sni = nth_up_segment(0);
        let for_other = nth_up_segment(1);

        fixture.grant_for(
            client_ip(),
            sni().customer_domain(),
            AuthSegments {
                up_segments: vec![for_sni.clone()],
                ..AuthSegments::default()
            },
            at(0),
        );
        fixture.grant_for(
            client_ip(),
            other_sni().customer_domain(),
            AuthSegments {
                up_segments: vec![for_other.clone()],
                ..AuthSegments::default()
            },
            at(0),
        );

        assert_eq!(expiry_of(&fixture, &for_sni, at(0)), Some(at(100)));
        assert_eq!(
            fixture.grant.segment_grant_expiry(
                client_ip(),
                other_sni().customer_domain(),
                &granted_id(&for_other),
                at(0)
            ),
            Some(at(100))
        );
    }
    /// A fixture whose IPs hold at most `max_targets` target grants, with a 100s duration.
    fn target_capped_fixture(max_targets: usize) -> Fixture {
        Fixture::with_grant_config(
            MockFetcher::empty(),
            GrantManagerConfig {
                grant_duration: Duration::from_secs(100),
                max_targets_per_ip: max_targets,
                ..Fixture::grant_config_defaults()
            },
        )
    }

    /// Grants `ip` the `n`th target over the `n`th up segment.
    fn grant_nth_target(fixture: &Fixture, ip: IpAddr, n: usize, now: SystemTime) {
        fixture.grant_for(
            ip,
            nth_sni(n).customer_domain(),
            AuthSegments {
                up_segments: vec![nth_up_segment(n as u16)],
                ..AuthSegments::default()
            },
            now,
        );
    }

    /// When the test client's grant on the `n`th target expires, if it holds one.
    fn target_expiry_of(fixture: &Fixture, n: usize, now: SystemTime) -> Option<SystemTime> {
        fixture
            .grant
            .grant_expiry(client_ip(), nth_sni(n).customer_domain(), now)
    }

    #[test]
    fn an_ip_at_its_target_limit_evicts_its_oldest_unused_target() {
        let fixture = target_capped_fixture(2);

        grant_nth_target(&fixture, client_ip(), 0, at(0));
        grant_nth_target(&fixture, client_ip(), 1, at(10));

        // Watching a target holds it, so keep only the token: this one is meant to be evictable.
        let watch = fixture
            .grant
            .watch_grant(client_ip(), nth_sni(0).customer_domain(), at(10))
            .expect("the first target is granted");
        let oldest_expired = watch.expired().clone();
        drop(watch);

        grant_nth_target(&fixture, client_ip(), 2, at(20));

        assert_eq!(
            target_expiry_of(&fixture, 0, at(20)),
            None,
            "the target with the least left to lose made room for the new one"
        );
        assert!(
            oldest_expired.is_cancelled(),
            "an evicted target is cancelled, just like an expired one"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&nth_up_segment(0)), at(20))
                .is_none(),
            "an evicted target takes its segment grants with it"
        );

        assert_eq!(target_expiry_of(&fixture, 1, at(20)), Some(at(110)));
        assert_eq!(target_expiry_of(&fixture, 2, at(20)), Some(at(120)));
    }

    #[test]
    fn a_target_a_consumer_holds_is_not_evicted() {
        let fixture = target_capped_fixture(2);

        // The held target is the older of the two, so it would go first if nobody had it.
        grant_nth_target(&fixture, client_ip(), 0, at(0));
        grant_nth_target(&fixture, client_ip(), 1, at(10));

        let hold = fixture
            .grant
            .watch_grant(client_ip(), nth_sni(0).customer_domain(), at(10))
            .expect("the first target is granted");

        grant_nth_target(&fixture, client_ip(), 2, at(20));

        assert_eq!(
            target_expiry_of(&fixture, 0, at(20)),
            Some(at(100)),
            "a target a consumer still holds is spared, however little it has left"
        );
        assert!(!hold.expired().is_cancelled());
        assert_eq!(
            target_expiry_of(&fixture, 1, at(20)),
            None,
            "the next candidate goes instead"
        );
        assert_eq!(target_expiry_of(&fixture, 2, at(20)), Some(at(120)));
    }

    #[test]
    fn a_target_whose_segment_grant_is_in_use_is_not_evicted() {
        let fixture = target_capped_fixture(2);

        grant_nth_target(&fixture, client_ip(), 0, at(0));
        grant_nth_target(&fixture, client_ip(), 1, at(10));

        // Only the segment grant is held, the target grant itself is not.
        let hold = fixture
            .grant
            .watch_segment_grant(
                client_ip(),
                nth_sni(0).customer_domain(),
                &granted_id(&nth_up_segment(0)),
                at(10),
            )
            .expect("the segment of the first target is granted");

        grant_nth_target(&fixture, client_ip(), 2, at(20));

        assert_eq!(
            target_expiry_of(&fixture, 0, at(20)),
            Some(at(100)),
            "evicting the target would evict a segment grant a consumer holds"
        );
        assert!(!hold.expired().is_cancelled());
        assert_eq!(target_expiry_of(&fixture, 1, at(20)), None);
        assert_eq!(target_expiry_of(&fixture, 2, at(20)), Some(at(120)));
    }

    #[test]
    fn dropping_a_target_hold_frees_it_for_eviction_again() {
        let fixture = target_capped_fixture(1);

        grant_nth_target(&fixture, client_ip(), 0, at(0));

        let hold = fixture
            .grant
            .watch_grant(client_ip(), nth_sni(0).customer_domain(), at(0))
            .expect("the target is granted");

        fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([(nth_sni(1).customer_domain().into(), AuthSegments::default())]),
                at(10),
            )
            .expect_err("the only target of the IP is in use");

        drop(hold);

        grant_nth_target(&fixture, client_ip(), 1, at(20));

        assert_eq!(target_expiry_of(&fixture, 0, at(20)), None);
        assert_eq!(target_expiry_of(&fixture, 1, at(20)), Some(at(120)));
    }

    #[test]
    fn a_request_that_cannot_free_a_target_is_rejected_whole() {
        let fixture = target_capped_fixture(2);

        grant_nth_target(&fixture, client_ip(), 0, at(0));
        grant_nth_target(&fixture, client_ip(), 1, at(0));

        let holds = [0, 1].map(|n| {
            fixture
                .grant
                .watch_grant(client_ip(), nth_sni(n).customer_domain(), at(0))
                .expect("both targets are granted")
        });

        let error = fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([(
                    nth_sni(2).customer_domain().into(),
                    AuthSegments {
                        up_segments: vec![nth_up_segment(2)],
                        ..AuthSegments::default()
                    },
                )]),
                at(10),
            )
            .expect_err("a full IP whose targets are all in use takes nothing more");

        assert!(
            matches!(
                error,
                AuthorizeError::IpTargetLimitReached {
                    needed: 1,
                    in_use: 2,
                    max: 2,
                }
            ),
            "{error:?}"
        );

        assert!(holds.iter().all(|hold| !hold.expired().is_cancelled()));
        assert_eq!(target_expiry_of(&fixture, 0, at(10)), Some(at(100)));
        assert_eq!(target_expiry_of(&fixture, 1, at(10)), Some(at(100)));
        assert_eq!(
            target_expiry_of(&fixture, 2, at(10)),
            None,
            "the target that did not fit was not granted"
        );
        assert!(
            fixture
                .grant
                .segment(&granted_id(&nth_up_segment(2)), at(10))
                .is_none(),
            "and neither were the segments it came with"
        );
    }

    #[test]
    fn a_request_naming_more_targets_than_an_ip_can_hold_is_rejected() {
        let fixture = target_capped_fixture(2);

        let error = fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([
                    (nth_sni(0).customer_domain().into(), AuthSegments::default()),
                    (nth_sni(1).customer_domain().into(), AuthSegments::default()),
                    (nth_sni(2).customer_domain().into(), AuthSegments::default()),
                ]),
                at(0),
            )
            .expect_err("three targets never fit into two grants");

        assert!(
            matches!(
                error,
                AuthorizeError::TooManyTargetsForIp {
                    requested: 3,
                    max: 2
                }
            ),
            "{error:?}"
        );
        assert!(
            !fixture.grant.ip_is_authorized(client_ip(), at(0)),
            "a rejected request leaves the IP as unauthorized as it was"
        );
    }

    #[test]
    fn refreshing_the_targets_of_a_full_ip_evicts_nothing() {
        let fixture = target_capped_fixture(2);

        grant_nth_target(&fixture, client_ip(), 0, at(0));
        grant_nth_target(&fixture, client_ip(), 1, at(0));

        fixture
            .grant
            .authorize(
                client_ip(),
                BTreeMap::from([
                    (nth_sni(0).customer_domain().into(), AuthSegments::default()),
                    (nth_sni(1).customer_domain().into(), AuthSegments::default()),
                ]),
                at(10),
            )
            .expect("a refresh of every target fits");

        assert_eq!(target_expiry_of(&fixture, 0, at(10)), Some(at(110)));
        assert_eq!(target_expiry_of(&fixture, 1, at(10)), Some(at(110)));
        assert!(
            fixture
                .grant
                .segment(&granted_id(&nth_up_segment(0)), at(10))
                .is_some(),
            "a refreshed target keeps the segment grants the refresh omits"
        );
    }

    #[test]
    fn the_target_limit_is_per_ip_not_global() {
        let fixture = target_capped_fixture(1);

        grant_nth_target(&fixture, client_ip(), 0, at(0));
        grant_nth_target(&fixture, other_client_ip(), 1, at(0));

        assert_eq!(target_expiry_of(&fixture, 0, at(0)), Some(at(100)));
        assert_eq!(
            fixture
                .grant
                .grant_expiry(other_client_ip(), nth_sni(1).customer_domain(), at(0)),
            Some(at(100)),
            "another IP at its own limit is untouched"
        );
    }
}