seshcookie 0.1.0

Stateless, encrypted, type-safe session cookies for Rust web applications.
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
2479
2480
//! Tower [`Layer`] and [`Service`] wiring. Framework-agnostic at this layer — the
//! Axum-specific extractor lives in [`crate::extract`] (`src/extract.rs`).
//!
//! pattern: Imperative Shell
//!
//! [`SessionLayer<T>`] wraps the per-layer policy (derived keys, config, RNG) and
//! produces a [`SessionService<S, T>`] for any inner service `S`. The service's
//! request path parses the configured `Cookie` header, decrypts and deserializes the
//! payload, inserts `Arc<tokio::sync::Mutex<SessionState<T>>>` into the request
//! extensions, and delegates to the inner service. The response path runs
//! [`crate::state::should_rewrite`] and emits at most one `Set-Cookie` header.
//!
//! All decisions about *whether* to rewrite are delegated to the pure
//! [`state::should_rewrite`] decision function; this module is responsible for
//! the side-effecting steps (clock reads, RNG fill, header parsing/emission)
//! that surround it.
//!
//! [`Layer`]: tower::Layer
//! [`Service`]: tower::Service

use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::SystemTime;

use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
use http::{HeaderValue, Request, Response};
use ring::rand::{SecureRandom, SystemRandom};
use tokio::sync::Mutex;
use tower::{Layer, Service};

use crate::aead::{self, DerivedKey};
use crate::codec;
use crate::config::SessionConfig;
use crate::envelope;
use crate::error::BuildError;
use crate::keys::SessionKeys;
use crate::state::{self, DecodedCookie, RewriteAction, SessionState};

/// A Tower [`Layer`] producing a [`SessionService`] wrapping an inner service.
///
/// Each `SessionLayer<T>` is parameterized by a typed session payload `T`.
/// Multiple layers with distinct `T`s and distinct cookie names may be
/// composed on the same service stack.
///
/// See [the crate root](crate) for a quickstart example.
pub struct SessionLayer<T> {
    inner: Arc<Inner>,
    _phantom: PhantomData<fn() -> T>,
}

struct Inner {
    keys: Arc<[DerivedKey]>,
    config: Arc<SessionConfig>,
    rng: Arc<SystemRandom>,
    /// Injectable clock. Defaults to [`SystemTime::now`]; swappable in tests
    /// via [`SessionLayer::with_clock`]. The indirection costs one pointer
    /// chase per request — negligible alongside the AEAD work — and keeps
    /// the production and test code paths identical.
    now: Arc<dyn Fn() -> SystemTime + Send + Sync>,
}

impl<T> Clone for SessionLayer<T> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            _phantom: PhantomData,
        }
    }
}

/// Debug prints the cookie name, path, and domain from the config. The RNG
/// and key material are deliberately omitted — they are sensitive and not
/// useful for diagnostics.
impl<T> std::fmt::Debug for SessionLayer<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cfg = &self.inner.config;
        let mut s = f.debug_struct("SessionLayer");
        s.field("cookie_name", &cfg.cookie_name);
        s.field("path", &cfg.path);
        if let Some(d) = &cfg.domain {
            s.field("domain", d);
        }
        s.finish_non_exhaustive()
    }
}

impl<T> SessionLayer<T> {
    /// Build a new layer from a validated key list and a config.
    ///
    /// Returns [`BuildError`] if any additional policy-level validation fails.
    /// Today this function is infallible beyond the per-key validation that
    /// already happened inside [`SessionKeys::new`]; the `Result` is retained
    /// for forward compatibility.
    ///
    /// At construction time this function:
    ///
    /// 1. Derives each IKM in `keys` via HKDF-SHA256 and stores the resulting
    ///    AEAD keys in an `Arc<[_]>`.
    /// 2. Constructs a single [`SystemRandom`] and primes it with a one-byte
    ///    `fill` so the first request-path seal does not pay the cost of OS
    ///    RNG initialization.
    ///
    /// # Errors
    ///
    /// Currently infallible beyond the per-key validation already performed in
    /// [`SessionKeys::new`]. The `Result` return type is retained for forward
    /// compatibility.
    ///
    /// # Examples
    ///
    /// ```
    /// use seshcookie::{SessionConfig, SessionKeys, SessionLayer};
    ///
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct MySession { user_id: u64 }
    /// let keys = SessionKeys::new(b"0123456789abcdef0123456789abcdef")?;
    /// let layer = SessionLayer::<MySession>::new(keys, SessionConfig::default())?;
    /// # Ok::<(), seshcookie::BuildError>(())
    /// ```
    pub fn new(keys: SessionKeys, config: SessionConfig) -> Result<Self, BuildError> {
        let derived: Vec<DerivedKey> = keys.ikm_in_order().map(DerivedKey::derive).collect();
        let derived: Arc<[DerivedKey]> = derived.into();

        let rng = SystemRandom::new();
        // Force OS RNG initialization at startup. Otherwise the first call to
        // `fill` on the request path can block while the kernel collects
        // entropy.
        let mut prime = [0u8; 1];
        rng.fill(&mut prime)
            .expect("OS RNG initialization is required for any subsequent seal; failure is fatal");

        Ok(Self {
            inner: Arc::new(Inner {
                keys: derived,
                config: Arc::new(config),
                rng: Arc::new(rng),
                now: Arc::new(SystemTime::now),
            }),
            _phantom: PhantomData,
        })
    }

    /// Encode a payload as a cookie value under this layer's primary key.
    ///
    /// This helper exists so external integration tests can construct
    /// cookie values without re-implementing the seal pipeline. It is
    /// `#[doc(hidden)]` and is reached through the `__testing` module — it
    /// is **not** part of the public API contract and may change at any
    /// point without a SemVer bump. Application code must never call this.
    ///
    /// `issued_at` is the wall-clock time embedded inside the AEAD
    /// plaintext. Production callers obtain it from the layer's clock; in
    /// tests, `SystemTime::now()` is the natural choice and keeps the
    /// resulting cookies non-expired against the default 24h `max_age`.
    #[doc(hidden)]
    pub fn __testing_encode_cookie(&self, payload: &T, issued_at: SystemTime) -> String
    where
        T: serde::Serialize,
    {
        let payload_json =
            serde_json::to_vec(payload).expect("test payload must be JSON-serializable");
        crate::codec::encode_cookie(
            &self.inner.keys[0],
            &*self.inner.rng,
            issued_at,
            &payload_json,
        )
    }
}

#[cfg(test)]
impl<T> SessionLayer<T> {
    /// Test-only: replace the wall clock used by the request path.
    ///
    /// Production code constructs the layer via [`SessionLayer::new`], which
    /// installs `SystemTime::now` as the clock. Tests that need to assert
    /// behavior at a specific instant (cookie expiry, sliding refresh
    /// thresholds) call this helper to swap in a deterministic closure.
    pub(crate) fn with_clock(
        mut self,
        now: impl Fn() -> SystemTime + Send + Sync + 'static,
    ) -> Self {
        let old = &*self.inner;
        self.inner = Arc::new(Inner {
            keys: Arc::clone(&old.keys),
            config: Arc::clone(&old.config),
            rng: Arc::clone(&old.rng),
            now: Arc::new(now),
        });
        self
    }
}

impl<S, T> Layer<S> for SessionLayer<T> {
    type Service = SessionService<S, T>;

    fn layer(&self, inner: S) -> Self::Service {
        SessionService {
            inner,
            layer: Arc::clone(&self.inner),
            _phantom: PhantomData,
        }
    }
}

/// The wrapped service produced by [`SessionLayer::layer`].
///
/// Users typically interact with [`SessionLayer`]; `SessionService` is exposed
/// so downstream code can name the middleware type (for example, when boxing
/// services for fallback routing).
pub struct SessionService<S, T> {
    inner: S,
    layer: Arc<Inner>,
    _phantom: PhantomData<fn() -> T>,
}

impl<S: Clone, T> Clone for SessionService<S, T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            layer: Arc::clone(&self.layer),
            _phantom: PhantomData,
        }
    }
}

/// Debug prints the same config fields as [`SessionLayer`]. The inner service
/// is excluded because it rarely implements `Debug` in practice and is not
/// useful for session-layer diagnostics.
impl<S, T> std::fmt::Debug for SessionService<S, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cfg = &self.layer.config;
        let mut s = f.debug_struct("SessionService");
        s.field("cookie_name", &cfg.cookie_name);
        s.field("path", &cfg.path);
        if let Some(d) = &cfg.domain {
            s.field("domain", d);
        }
        s.finish_non_exhaustive()
    }
}

/// Maximum accepted cookie value length in bytes. Cookie values longer than
/// this are rejected before base64 decoding, preventing a malicious client
/// from forcing large allocations multiplied by the number of rotation keys.
/// The 4 KB design ceiling plus 2x headroom gives 8 KB. Payloads exceeding
/// this cap should use a different crate with server-side session storage.
const MAX_COOKIE_VALUE_BYTES: usize = 8192;

/// Outcome of scanning `Cookie` headers for a session cookie.
#[derive(Debug, PartialEq)]
enum CookieLookup {
    /// The configured cookie name was not found in any `Cookie` header.
    NotFound,
    /// The cookie was found and its value is within the size limit.
    Found(String),
    /// The cookie was found but its value exceeded [`MAX_COOKIE_VALUE_BYTES`].
    /// Treated as a malformed cookie: the caller emits a delete to clean up
    /// the oversized cookie from the browser, and the handler sees `None`.
    Oversized,
}

/// Scan all `Cookie` headers for the configured session cookie.
///
/// Handles two RFC 6265 edge cases simultaneously:
///
/// - Multiple cookies in a single header (`a=1; session=xyz; b=2`) — the
///   semicolon-separated list is parsed and each name/value pair inspected.
/// - Multiple `Cookie` headers on the same request — `HeaderMap::get_all`
///   yields every entry; each is scanned in order.
///
/// Returns the first match across all headers. Cookie values exceeding
/// [`MAX_COOKIE_VALUE_BYTES`] return [`CookieLookup::Oversized`] so the
/// caller can emit a delete. Malformed individual sibling cookies are
/// silently skipped.
fn extract_session_cookie_value(headers: &http::HeaderMap, cookie_name: &str) -> CookieLookup {
    for hval in headers.get_all(http::header::COOKIE) {
        let Ok(s) = hval.to_str() else { continue };
        for parsed in cookie::Cookie::split_parse(s) {
            let Ok(c) = parsed else { continue };
            if c.name() == cookie_name {
                let value = c.value();
                if value.len() > MAX_COOKIE_VALUE_BYTES {
                    return CookieLookup::Oversized;
                }
                return CookieLookup::Found(value.to_string());
            }
        }
    }
    CookieLookup::NotFound
}

/// Build the `Set-Cookie` for a normal session set.
///
/// Omits `Max-Age` and `Expires` so the result is a browser session cookie
/// (seshcookie-rs.AC7.6). `Secure`, `HttpOnly`, `SameSite`, `Path`, and the
/// optional `Domain` reflect the supplied config.
fn build_set_cookie<'a>(config: &'a SessionConfig, value: String) -> cookie::Cookie<'a> {
    let mut builder = cookie::Cookie::build((config.cookie_name.clone(), value))
        .path(config.path.clone())
        .secure(config.secure)
        .http_only(config.http_only)
        .same_site(config.same_site);
    if let Some(d) = &config.domain {
        builder = builder.domain(d.clone());
    }
    builder.build()
}

/// Build the cookie-delete `Set-Cookie`: empty value, `Max-Age=0`, `Expires`
/// in the past, with the same `Path` / `Domain` as a regular set
/// (seshcookie-rs.AC3.5).
fn build_delete_cookie(config: &SessionConfig) -> cookie::Cookie<'_> {
    let mut builder = cookie::Cookie::build((config.cookie_name.clone(), String::new()))
        .path(config.path.clone())
        .secure(config.secure)
        .http_only(config.http_only)
        .same_site(config.same_site)
        .removal();
    if let Some(d) = &config.domain {
        builder = builder.domain(d.clone());
    }
    builder.build()
}

impl<S, T, ReqBody, ResBody> Service<Request<ReqBody>> for SessionService<S, T>
where
    S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send,
    T: serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
    ReqBody: Send + 'static,
    ResBody: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        // Canonical "move the proven-ready service into the future" pattern.
        // `self.inner` was just polled-ready by the caller; we must drive that
        // exact instance through `call`, not the freshly cloned one.
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);
        let layer = Arc::clone(&self.layer);

        Box::pin(async move {
            let now = (layer.now)();
            let (mut parts, body) = req.into_parts();

            // --- request path -------------------------------------------------
            let lookup = extract_session_cookie_value(&parts.headers, &layer.config.cookie_name);

            // A cookie was present (even if oversized or malformed) when the
            // name appeared in the headers. The oversized case is flagged here
            // to avoid any decoding work while still ensuring a cleanup delete
            // is emitted on the response.
            let had_incoming_cookie = !matches!(lookup, CookieLookup::NotFound);

            let cookie_value_str: Option<String> = match lookup {
                CookieLookup::Found(v) => Some(v),
                _ => None,
            };

            let decoded: Option<DecodedCookie<T>> = cookie_value_str.as_deref().and_then(|v| {
                let (issued_at, payload_json, key_idx) = codec::decode_cookie(&layer.keys, v)?;
                let payload: T = serde_json::from_slice(&payload_json).ok()?;
                // Reconstruct the layer-1 plaintext from the decoded `issued_at`
                // and serialized payload bytes, then SHA-256 it for the
                // response-path no-op-rewrite suppression compare.
                let layer1 = envelope::encode_envelope(issued_at, &payload_json);
                let plaintext_hash = state::sha256(&layer1);
                Some(DecodedCookie {
                    payload,
                    issued_at,
                    plaintext_hash,
                    decrypt_key_index: key_idx,
                })
            });

            let malformed_cookie_present = had_incoming_cookie && decoded.is_none();

            let state = SessionState::from_decrypt(decoded, layer.config.max_age, now);

            // For malformed-but-present cookies (unknown key, base64 bad,
            // schema-mismatched JSON, ...) `from_decrypt` returns the
            // empty-state shape because its input was `None`. That shape
            // would suppress the response-path delete since
            // `original_plaintext_hash` is `None`. Override here: a marker
            // hash plus `needs_rewrite = true` together force the Delete
            // branch of `should_rewrite`. The marker bytes never reach the
            // wire — only `RewriteAction::Delete` is observable downstream.
            let state = if malformed_cookie_present {
                SessionState {
                    payload: None,
                    issued_at: now,
                    original_plaintext_hash: Some([0u8; 32]),
                    decrypt_key_index: None,
                    mutated: false,
                    needs_rewrite: true,
                }
            } else {
                state
            };

            let state_arc = Arc::new(Mutex::new(state));
            parts.extensions.insert(Arc::clone(&state_arc));
            let req = Request::from_parts(parts, body);

            // --- handler ------------------------------------------------------
            let mut response = inner.call(req).await?;

            // --- response path ------------------------------------------------
            let action = {
                let guard = state_arc.lock().await;
                state::should_rewrite(
                    &guard,
                    layer.config.max_age,
                    layer.config.refresh_after,
                    now,
                )
            };

            match action {
                RewriteAction::None => {}
                RewriteAction::Emit {
                    plaintext,
                    issued_at,
                } => {
                    // The decision function already chose `effective_issued_at`
                    // and built the layer-1 plaintext. Sealing under the
                    // primary key guarantees AC4.2's "auto-migrate to primary"
                    // even when the cookie originally arrived under a fallback.
                    let sealed = aead::seal(&layer.keys[0], &*layer.rng, &plaintext);
                    let b64 = BASE64_URL_SAFE_NO_PAD.encode(&sealed);
                    let cookie = build_set_cookie(&layer.config, b64);
                    let hval = HeaderValue::try_from(cookie.to_string())
                        .expect("cookie::Cookie::to_string produces valid header bytes");
                    response
                        .headers_mut()
                        .append(http::header::SET_COOKIE, hval);
                    // `issued_at` is already authenticated inside `plaintext`;
                    // we keep it bound here so a tracing build can log it
                    // without re-decoding the envelope.
                    #[cfg(feature = "tracing")]
                    tracing::trace!(
                        cookie_name = %layer.config.cookie_name,
                        ?issued_at,
                        "seshcookie: emitted Set-Cookie"
                    );
                    #[cfg(not(feature = "tracing"))]
                    let _ = issued_at;
                }
                RewriteAction::Delete => {
                    let cookie = build_delete_cookie(&layer.config);
                    let hval = HeaderValue::try_from(cookie.to_string())
                        .expect("cookie::Cookie::to_string produces valid header bytes");
                    response
                        .headers_mut()
                        .append(http::header::SET_COOKIE, hval);
                    #[cfg(feature = "tracing")]
                    tracing::trace!(
                        cookie_name = %layer.config.cookie_name,
                        "seshcookie: emitted Set-Cookie delete"
                    );
                }
            }

            Ok(response)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use http::HeaderMap;

    /// Build a `HeaderMap` with the given `Cookie` header values, in order.
    fn headers_with_cookies(values: &[&str]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for v in values {
            headers.append(
                http::header::COOKIE,
                HeaderValue::from_str(v).expect("test cookie value must be valid header bytes"),
            );
        }
        headers
    }

    // --- extract_session_cookie_value -----------------------------------------

    /// seshcookie-rs.AC6.6: a single `Cookie` header carrying multiple cookies
    /// (`a=1; session=FIRST; b=2`) yields the configured one. The middleware
    /// never confuses sibling cookies for the session cookie.
    #[test]
    fn extract_finds_session_in_multi_cookie_header_seshcookie_rs_ac6_6() {
        let headers = headers_with_cookies(&["a=1; session=FIRST; b=2"]);
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::Found("FIRST".into()));
    }

    /// seshcookie-rs.AC6.7: RFC 6265 permits multiple `Cookie` headers on a
    /// single request. `extract_session_cookie_value` scans every header,
    /// returning the first match found (here, the cookie in the second
    /// header).
    #[test]
    fn extract_scans_multiple_cookie_headers_seshcookie_rs_ac6_7() {
        let headers = headers_with_cookies(&["a=1", "session=SECOND; b=2"]);
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::Found("SECOND".into()));
    }

    /// When the configured cookie name is not present, the helper returns
    /// `NotFound`. Sibling cookies that exist but do not match the configured
    /// name must not leak through as a false positive.
    #[test]
    fn extract_returns_not_found_when_session_cookie_absent() {
        let headers = headers_with_cookies(&["a=1; b=2"]);
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::NotFound, "no session cookie present");
    }

    /// A request with no `Cookie` header at all yields `NotFound`.
    #[test]
    fn extract_returns_not_found_when_no_cookie_header() {
        let headers = HeaderMap::new();
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::NotFound);
    }

    /// Multiple session-named cookies spread across two `Cookie` headers:
    /// the first match in header-iteration order wins. This test pins the
    /// "first match" behavior so future refactors that change iteration order
    /// surface the regression.
    #[test]
    fn extract_returns_first_match_across_headers() {
        let headers = headers_with_cookies(&["session=ONE", "session=TWO"]);
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::Found("ONE".into()));
    }

    /// A header containing a non-ASCII byte fails `HeaderValue::to_str`; the
    /// helper skips that header and continues with the rest. Subsequent
    /// headers must still be scanned.
    #[test]
    fn extract_skips_non_ascii_header_and_continues() {
        let mut headers = HeaderMap::new();
        // 0xFF is outside ASCII; HeaderValue accepts it but `to_str` fails.
        headers.append(
            http::header::COOKIE,
            HeaderValue::from_bytes(b"\xff").expect("HeaderValue accepts opaque bytes"),
        );
        headers.append(
            http::header::COOKIE,
            HeaderValue::from_static("session=GOOD"),
        );
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::Found("GOOD".into()));
    }

    /// A cookie value exceeding MAX_COOKIE_VALUE_BYTES returns `Oversized`
    /// so the caller can emit a delete without any base64-decode work.
    #[test]
    fn extract_returns_oversized_for_large_cookie_value() {
        let value = "A".repeat(MAX_COOKIE_VALUE_BYTES + 1);
        let headers = headers_with_cookies(&[&format!("session={value}")]);
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::Oversized);
    }

    /// A cookie value at exactly MAX_COOKIE_VALUE_BYTES is accepted.
    #[test]
    fn extract_accepts_cookie_value_at_exact_cap() {
        let value = "A".repeat(MAX_COOKIE_VALUE_BYTES);
        let headers = headers_with_cookies(&[&format!("session={value}")]);
        let got = extract_session_cookie_value(&headers, "session");
        assert_eq!(got, CookieLookup::Found(value));
    }

    // --- build_set_cookie -----------------------------------------------------

    /// seshcookie-rs.AC7.6: a normal `Set-Cookie` for a session set has no
    /// `Max-Age` and no `Expires` attribute, making it a browser session
    /// cookie (cleared when the browser closes). The other configured
    /// attributes (`Path`, `HttpOnly`, `Secure`, `SameSite`) are reflected
    /// in the rendered header value.
    #[test]
    fn build_set_cookie_omits_max_age_and_expires_seshcookie_rs_ac7_6() {
        let config = SessionConfig::default();
        let cookie = build_set_cookie(&config, "VAL".to_string());
        let rendered = cookie.to_string();

        assert!(
            !rendered.contains("Max-Age"),
            "normal set must not include Max-Age; got: {rendered}"
        );
        assert!(
            !rendered.contains("Expires"),
            "normal set must not include Expires; got: {rendered}"
        );
        assert!(
            rendered.contains("Path=/"),
            "configured Path must be reflected; got: {rendered}"
        );
        assert!(
            rendered.contains("HttpOnly"),
            "configured HttpOnly must be reflected; got: {rendered}"
        );
        assert!(
            rendered.contains("Secure"),
            "configured Secure must be reflected; got: {rendered}"
        );
        assert!(
            rendered.contains("SameSite=Lax"),
            "configured SameSite must be reflected; got: {rendered}"
        );
        assert!(
            rendered.starts_with("session=VAL"),
            "name=value prefix must come first; got: {rendered}"
        );
    }

    /// Custom config values are reflected in the rendered cookie. This is the
    /// per-attribute portion of seshcookie-rs.AC7.2; full end-to-end coverage
    /// (through the Tower service) lives in Phase 4.
    #[test]
    fn build_set_cookie_reflects_custom_config_seshcookie_rs_ac7_2() {
        use crate::config::SameSite;
        use std::time::Duration;

        let config = SessionConfig::default()
            .cookie_name("CUSTOM")
            .path("/api")
            .domain("x.test")
            .secure(false)
            .http_only(false)
            .same_site(SameSite::Strict)
            .max_age(Duration::from_secs(60));
        let cookie = build_set_cookie(&config, "VAL".to_string());
        let rendered = cookie.to_string();

        assert!(rendered.starts_with("CUSTOM=VAL"));
        assert!(rendered.contains("Path=/api"));
        assert!(rendered.contains("Domain=x.test"));
        assert!(rendered.contains("SameSite=Strict"));
        assert!(
            !rendered.contains("HttpOnly"),
            "http_only=false must omit HttpOnly: {rendered}"
        );
        assert!(
            !rendered.contains("Secure"),
            "secure=false must omit Secure: {rendered}"
        );
        // max_age on the config is the *server-side* expiry; it is intentionally
        // NOT reflected on the wire (AC7.6).
        assert!(
            !rendered.contains("Max-Age"),
            "server-side max_age must not appear in normal set: {rendered}"
        );
    }

    // --- build_delete_cookie --------------------------------------------------

    /// seshcookie-rs.AC3.5: a cookie-delete `Set-Cookie` carries an empty
    /// value, `Max-Age=0`, and an `Expires` attribute in the past. The
    /// `Path`, `Domain`, `Secure`, `HttpOnly`, and `SameSite` attributes
    /// match what a regular set would emit, so the browser unambiguously
    /// recognizes the delete as targeting the same cookie.
    #[test]
    fn build_delete_cookie_has_max_age_zero_and_past_expires_seshcookie_rs_ac3_5() {
        let config = SessionConfig::default();
        let cookie = build_delete_cookie(&config);
        let rendered = cookie.to_string();

        assert!(
            rendered.starts_with("session=;"),
            "delete must have empty value; got: {rendered}"
        );
        assert!(
            rendered.contains("Max-Age=0"),
            "delete must have Max-Age=0; got: {rendered}"
        );
        assert!(
            rendered.contains("Expires="),
            "delete must include an Expires attribute (in the past); got: {rendered}"
        );
        assert!(
            rendered.contains("Path=/"),
            "delete must reflect the configured Path; got: {rendered}"
        );
    }

    /// A delete cookie reflects the configured Domain so the browser-side
    /// cookie store matches the original set (without the matching Domain
    /// attribute the browser would not recognize the delete as targeting the
    /// same cookie).
    #[test]
    fn build_delete_cookie_reflects_configured_domain() {
        let config = SessionConfig::default().domain("x.test");
        let cookie = build_delete_cookie(&config);
        let rendered = cookie.to_string();
        assert!(
            rendered.contains("Domain=x.test"),
            "delete must reflect configured Domain; got: {rendered}"
        );
    }

    // --- Debug impls for SessionLayer and SessionService ----------------------

    /// `SessionLayer` implements `Debug`. The output must include the cookie
    /// name and path from the config, and must omit key material and RNG.
    #[test]
    fn session_layer_debug_includes_config_fields() {
        use crate::keys::SessionKeys;
        let keys = SessionKeys::new(b"debug-test-ikm-with-32-bytes!!!!").expect("valid key");
        let config = SessionConfig::default()
            .cookie_name("my_session")
            .path("/app");
        let layer: SessionLayer<u32> = SessionLayer::new(keys, config).expect("layer builds");
        let debug = format!("{layer:?}");
        assert!(
            debug.contains("my_session"),
            "Debug must show cookie_name; got: {debug}"
        );
        assert!(debug.contains("/app"), "Debug must show path; got: {debug}");
        assert!(
            !debug.contains("keys"),
            "Debug must not expose key material; got: {debug}"
        );
        assert!(
            !debug.contains("rng"),
            "Debug must not expose RNG; got: {debug}"
        );
    }

    /// `SessionLayer` Debug output includes the domain when one is configured.
    #[test]
    fn session_layer_debug_includes_domain_when_set() {
        use crate::keys::SessionKeys;
        let keys = SessionKeys::new(b"debug-test-ikm-with-32-bytes!!!!").expect("valid key");
        let config = SessionConfig::default().domain("example.com");
        let layer: SessionLayer<u32> = SessionLayer::new(keys, config).expect("layer builds");
        let debug = format!("{layer:?}");
        assert!(
            debug.contains("example.com"),
            "Debug must show domain; got: {debug}"
        );
    }

    /// `SessionService` implements `Debug` and its output reflects the same
    /// config fields as `SessionLayer`.
    #[test]
    fn session_service_debug_includes_config_fields() {
        use crate::keys::SessionKeys;
        let keys = SessionKeys::new(b"debug-test-ikm-with-32-bytes!!!!").expect("valid key");
        let config = SessionConfig::default()
            .cookie_name("svc_session")
            .path("/svc")
            .domain("svc.test");
        let layer: SessionLayer<u32> = SessionLayer::new(keys, config).expect("layer builds");
        let inner = tower::service_fn(|_req: Request<()>| async {
            Ok::<_, std::convert::Infallible>(Response::builder().body(()).unwrap())
        });
        let svc = layer.layer(inner);
        let debug = format!("{svc:?}");
        assert!(
            debug.contains("svc_session"),
            "Debug must show cookie_name; got: {debug}"
        );
        assert!(debug.contains("/svc"), "Debug must show path; got: {debug}");
        assert!(
            debug.contains("svc.test"),
            "Debug must show domain; got: {debug}"
        );
    }
}

#[cfg(test)]
mod integration_tests {
    //! End-to-end integration tests through the Tower service. Each test
    //! constructs a [`SessionLayer<T>`] (with an injected clock where time
    //! sensitivity is in scope), wraps a [`tower::service_fn`] inner handler
    //! that locks the per-request `Arc<Mutex<SessionState<T>>>` from the
    //! extensions, and drives an [`http::Request`] through the resulting
    //! `Service::call`. Assertions cover both observed handler state and the
    //! `Set-Cookie` headers (or their absence) on the response.
    //!
    //! These tests share the parent module's private items — `Inner`'s fields
    //! and the test-only [`SessionLayer::with_clock`] — without any visibility
    //! widening, because the module sits in the same file as production code.
    //! Phase 4's extractor tests will exercise the higher-level `Session<T>`
    //! handle separately.
    //!
    //! Each test is named with its acceptance-criterion identifier embedded so
    //! the AC -> test mapping can be recovered with `grep seshcookie-rs.AC`.
    use super::*;
    use std::convert::Infallible;
    use std::time::Duration;
    use std::time::SystemTime;
    use std::time::UNIX_EPOCH;
    use std::{future::Future, pin::Pin};
    use tower::ServiceExt;
    use tower::service_fn;

    use serde::{Deserialize, Serialize};

    use crate::config::SameSite;
    use crate::keys::SessionKeys;

    /// `cookie::Cookie::max_age()` returns the `cookie` crate's own
    /// `time::Duration`, distinct from `std::time::Duration`. Convert here so
    /// assertions can use the standard-library type (which is what the rest
    /// of the suite passes around).
    fn cookie_max_age_secs(c: &cookie::Cookie<'_>) -> Option<i64> {
        c.max_age().map(|d| d.whole_seconds())
    }

    // --- fixtures ------------------------------------------------------------

    const IKM_PRIMARY: &[u8; 32] = b"primary-ikm-fixed-bytes-32-len!!";
    const IKM_FALLBACK_1: &[u8; 32] = b"o1-fallback-ikm-fixed-bytes-32!!";
    const IKM_FALLBACK_2: &[u8; 32] = b"o2-fallback-ikm-fixed-bytes-32!!";
    const IKM_UNKNOWN: &[u8; 32] = b"x-unknown-ikm-not-in-keylist-32!";

    /// A concrete payload type used by the bulk of the round-trip tests. The
    /// fields together exercise primitive integers and an owned `String`,
    /// which is enough to catch JSON shape regressions without the full
    /// nested-struct/enum/Option matrix that AC1.2 explicitly demands.
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct User {
        id: u64,
        name: String,
    }

    /// Sub-shape used by [`Complex`] to exercise nested struct serialization.
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct Address {
        city: String,
        zip: u32,
    }

    /// Enum payload field to exercise variant round-trip (AC1.2).
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    enum Role {
        Admin,
        Member(u32),
        Guest,
    }

    /// Production-shaped payload combining nested struct, `Vec<_>`, `Option<_>`,
    /// and enum-with-variants. Used by the AC1.2 round-trip test.
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct Complex {
        user_id: u64,
        email: Option<String>,
        roles: Vec<Role>,
        address: Option<Address>,
    }

    /// A canonical fixed `SystemTime` used as the test clock anchor. The exact
    /// instant is unimportant; what matters is that it is well above
    /// `UNIX_EPOCH` so any signed-arithmetic edge cases stay clear of zero
    /// and that subtractions used inside tests never underflow into the
    /// pre-epoch range.
    fn t0() -> SystemTime {
        UNIX_EPOCH + Duration::from_secs(1_700_000_000)
    }

    fn sample_user() -> User {
        User {
            id: 42,
            name: "alice".into(),
        }
    }

    /// Build a fresh layer wrapping the supplied keys and config, then pin the
    /// clock to `clock_at`. Tests that need different clocks per request swap
    /// the closure for an `Arc<RwLock<SystemTime>>` lookup; the simple
    /// "frozen at one instant" form covers the bulk of the suite.
    fn make_layer<T>(
        keys: SessionKeys,
        config: SessionConfig,
        clock_at: SystemTime,
    ) -> SessionLayer<T> {
        SessionLayer::new(keys, config)
            .expect("test fixtures must build a valid layer")
            .with_clock(move || clock_at)
    }

    /// Build a `SessionLayer<User>` with default config rooted at the supplied
    /// instant. The default config is `secure = true`, `http_only = true`,
    /// `same_site = Lax`, `max_age = 24h`, `refresh_after = None`.
    fn default_user_layer(clock_at: SystemTime) -> SessionLayer<User> {
        let keys = SessionKeys::new(IKM_PRIMARY).expect("primary key is valid");
        make_layer::<User>(keys, SessionConfig::default(), clock_at)
    }

    /// Encode a payload as a sealed cookie value under the layer's keylist
    /// position `key_idx`. Uses the layer's own RNG so the test exercises the
    /// production AEAD path. `key_idx = 0` is the primary; `1..` are
    /// fallbacks in insertion order.
    fn encode_cookie_value<T: Serialize>(
        layer: &SessionLayer<T>,
        key_idx: usize,
        payload: &T,
        issued_at: SystemTime,
    ) -> String {
        let payload_json = serde_json::to_vec(payload).expect("payload serializes");
        let layer1 = envelope::encode_envelope(issued_at, &payload_json);
        let sealed = aead::seal(&layer.inner.keys[key_idx], &*layer.inner.rng, &layer1);
        BASE64_URL_SAFE_NO_PAD.encode(&sealed)
    }

    /// Encode a payload as a sealed cookie under an arbitrary IKM that is not
    /// part of any layer's keylist. Used by the AC4.5 unknown-key test.
    fn encode_cookie_with_unknown_key<T: Serialize>(
        ikm: &[u8],
        payload: &T,
        issued_at: SystemTime,
    ) -> String {
        let payload_json = serde_json::to_vec(payload).expect("payload serializes");
        let layer1 = envelope::encode_envelope(issued_at, &payload_json);
        let key = aead::DerivedKey::derive(ikm);
        let rng = SystemRandom::new();
        let sealed = aead::seal(&key, &rng, &layer1);
        BASE64_URL_SAFE_NO_PAD.encode(&sealed)
    }

    /// Encode a payload under a layer key but with a JSON shape that does not
    /// deserialize to `T`. Used by the AC6.5 schema-mismatch test.
    fn encode_cookie_with_wrong_schema<T>(
        layer: &SessionLayer<T>,
        key_idx: usize,
        issued_at: SystemTime,
    ) -> String {
        let bad_json = serde_json::to_vec(&"just a string").expect("string serializes to JSON");
        let layer1 = envelope::encode_envelope(issued_at, &bad_json);
        let sealed = aead::seal(&layer.inner.keys[key_idx], &*layer.inner.rng, &layer1);
        BASE64_URL_SAFE_NO_PAD.encode(&sealed)
    }

    /// Build a `Request<()>` carrying a `Cookie: <name>=<value>` header.
    fn request_with_cookie(cookie_name: &str, cookie_value: &str) -> Request<()> {
        Request::builder()
            .header(
                http::header::COOKIE,
                format!("{cookie_name}={cookie_value}"),
            )
            .body(())
            .expect("request builds")
    }

    /// Build a `Request<()>` with no `Cookie` header at all.
    fn request_no_cookie() -> Request<()> {
        Request::builder().body(()).expect("request builds")
    }

    /// Synchronous result returned by handlers in this suite. Boxed so each
    /// test can choose its own future type without re-typing the whole
    /// closure signature.
    type HandlerFuture = Pin<Box<dyn Future<Output = Result<Response<()>, Infallible>> + Send>>;

    /// Run a request through the layer with a handler closure that has access
    /// to the per-request session state. The handler's mutations are visible
    /// on the response side because the same `Arc` is held by the layer.
    async fn drive_request<F>(
        layer: SessionLayer<User>,
        req: Request<()>,
        handler: F,
    ) -> Response<()>
    where
        F: Fn(Arc<Mutex<SessionState<User>>>) -> HandlerFuture + Clone + Send + Sync + 'static,
    {
        let inner = service_fn(move |req: Request<()>| {
            let handler = handler.clone();
            async move {
                let state = req
                    .extensions()
                    .get::<Arc<Mutex<SessionState<User>>>>()
                    .cloned()
                    .expect("layer must insert SessionState into extensions");
                handler(state).await
            }
        });
        let svc = layer.layer(inner);
        svc.oneshot(req).await.expect("inner service is infallible")
    }

    /// Like [`drive_request`] but parameterized over the payload type. Used by
    /// the AC1.2 complex-payload test; the rest of the suite locks `T = User`.
    async fn drive_request_t<T, F>(
        layer: SessionLayer<T>,
        req: Request<()>,
        handler: F,
    ) -> Response<()>
    where
        T: Serialize + serde::de::DeserializeOwned + Send + Sync + 'static,
        F: Fn(
                Arc<Mutex<SessionState<T>>>,
            )
                -> Pin<Box<dyn Future<Output = Result<Response<()>, Infallible>> + Send>>
            + Clone
            + Send
            + Sync
            + 'static,
    {
        let inner = service_fn(move |req: Request<()>| {
            let handler = handler.clone();
            async move {
                let state = req
                    .extensions()
                    .get::<Arc<Mutex<SessionState<T>>>>()
                    .cloned()
                    .expect("layer must insert SessionState into extensions");
                handler(state).await
            }
        });
        let svc = layer.layer(inner);
        svc.oneshot(req).await.expect("inner service is infallible")
    }

    /// Convenience: wrap a `FnOnce` handler body so the closure can `await`.
    /// All handlers in this suite are pure async work over the session state.
    fn handler<F, Fut>(
        f: F,
    ) -> impl Fn(Arc<Mutex<SessionState<User>>>) -> HandlerFuture + Clone + Send + Sync + 'static
    where
        F: Fn(Arc<Mutex<SessionState<User>>>) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        move |state| {
            let f = f.clone();
            Box::pin(async move {
                f(state).await;
                Ok(Response::builder().body(()).unwrap())
            })
        }
    }

    /// Collect all `Set-Cookie` headers from a response into owned strings,
    /// preserving order. The header values are guaranteed to be ASCII because
    /// the layer constructs them from `cookie::Cookie::to_string`.
    fn set_cookie_headers(resp: &Response<()>) -> Vec<String> {
        resp.headers()
            .get_all(http::header::SET_COOKIE)
            .iter()
            .map(|hv| hv.to_str().expect("set-cookie is ASCII").to_string())
            .collect()
    }

    /// Parse the first `Set-Cookie` header on the response into a
    /// `cookie::Cookie`. Panics if there is not exactly one — the suite never
    /// assertion-bundles "expected exactly one Set-Cookie" away from the
    /// header check that proves the count.
    fn parse_only_set_cookie<'a>(resp: &'a Response<()>) -> cookie::Cookie<'a> {
        let headers = set_cookie_headers(resp);
        assert_eq!(
            headers.len(),
            1,
            "expected exactly one Set-Cookie, got {}: {:?}",
            headers.len(),
            headers
        );
        // Cookie::parse takes a String/&str and returns owned-on-error;
        // we leak the heap string into a Box to extend its lifetime to 'static
        // so the returned Cookie can be inspected by the caller.
        let s = headers.into_iter().next().unwrap();
        let leaked: &'static str = Box::leak(s.into_boxed_str());
        cookie::Cookie::parse(leaked).expect("layer-emitted Set-Cookie must parse")
    }

    /// Decode an emitted `Set-Cookie`'s value as a sealed cookie under the
    /// supplied keylist, returning the deserialized payload and `issued_at`.
    fn decode_emitted_cookie<T: serde::de::DeserializeOwned>(
        keys: &[aead::DerivedKey],
        cookie_value: &str,
    ) -> (SystemTime, T) {
        let (issued_at, payload_json, _idx) =
            crate::codec::decode_cookie(keys, cookie_value).expect("emitted cookie must decode");
        let payload: T =
            serde_json::from_slice(&payload_json).expect("emitted JSON must deserialize");
        (issued_at, payload)
    }

    /// Snapshot of the relevant fields of a [`SessionState`] taken inside a
    /// handler. Used to assert state observations without holding the mutex
    /// across an await boundary outside the handler scope.
    #[derive(Debug, Clone, PartialEq)]
    struct StateSnapshot {
        payload: Option<User>,
        decrypt_key_index: Option<usize>,
    }

    /// Lock the state, snapshot the salient fields, then drop the lock. The
    /// returned snapshot can be smuggled out of the handler via an
    /// `Arc<Mutex<Option<StateSnapshot>>>` shared with the test scope.
    async fn snapshot_state(state: &Arc<Mutex<SessionState<User>>>) -> StateSnapshot {
        let g = state.lock().await;
        StateSnapshot {
            payload: g.payload.clone(),
            decrypt_key_index: g.decrypt_key_index,
        }
    }

    // ---------------------------------------------------------------------
    // round-trip (AC1.1, AC1.2, AC1.3)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC1.1: a payload inserted on round 1 is observed on
    /// round 2 when the emitted cookie is replayed. Round 2 is read-only, so
    /// the response carries zero `Set-Cookie` headers (also pinning AC3.1
    /// at HTTP level).
    #[tokio::test]
    async fn http_level_encrypt_decrypt_roundtrip_seshcookie_rs_ac1_1() {
        let layer = default_user_layer(t0());
        let target_user = sample_user();

        // Round 1: handler inserts a brand-new session.
        let to_insert = target_user.clone();
        let resp1 = drive_request(
            layer.clone(),
            request_no_cookie(),
            handler(move |state| {
                let to_insert = to_insert.clone();
                async move {
                    let mut g = state.lock().await;
                    g.payload = Some(to_insert);
                    g.mutated = true;
                }
            }),
        )
        .await;
        let cookie1 = parse_only_set_cookie(&resp1);
        assert_eq!(cookie1.name(), "session");
        let cookie_value = cookie1.value().to_string();

        // Round 2: replay the emitted cookie; handler reads only.
        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp2 = drive_request(
            layer,
            request_with_cookie("session", &cookie_value),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    let snap = snapshot_state(&state).await;
                    *observed_clone.lock().await = Some(snap);
                }
            }),
        )
        .await;

        assert_eq!(
            observed.lock().await.as_ref().unwrap().payload,
            Some(target_user),
            "round 2 must surface the round-1 payload"
        );
        assert!(
            set_cookie_headers(&resp2).is_empty(),
            "read-only round 2 must emit zero Set-Cookie headers"
        );
    }

    /// seshcookie-rs.AC1.2: round-trip preserves complex shapes — nested
    /// struct, `Vec<_>`, `Option<_>`, and enum variants. Mirrors AC1.1 but
    /// with the [`Complex`] payload type.
    #[tokio::test]
    async fn http_level_complex_payload_roundtrip_seshcookie_rs_ac1_2() {
        let keys = SessionKeys::new(IKM_PRIMARY).expect("primary key is valid");
        let layer: SessionLayer<Complex> = make_layer(keys, SessionConfig::default(), t0());

        let target = Complex {
            user_id: 99,
            email: Some("alice@example.test".into()),
            roles: vec![Role::Admin, Role::Member(7), Role::Guest],
            address: Some(Address {
                city: "Springfield".into(),
                zip: 12345,
            }),
        };

        // Round 1: insert.
        let to_insert = target.clone();
        let resp1 =
            drive_request_t::<Complex, _>(layer.clone(), request_no_cookie(), move |state| {
                let to_insert = to_insert.clone();
                Box::pin(async move {
                    {
                        let mut g = state.lock().await;
                        g.payload = Some(to_insert);
                        g.mutated = true;
                    }
                    Ok(Response::builder().body(()).unwrap())
                })
            })
            .await;
        let cookie1 = parse_only_set_cookie(&resp1);
        let cookie_value = cookie1.value().to_string();

        // Round 2: read it back.
        let observed: Arc<Mutex<Option<Complex>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        drive_request_t::<Complex, _>(
            layer,
            request_with_cookie("session", &cookie_value),
            move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                Box::pin(async move {
                    {
                        let g = state.lock().await;
                        *observed_clone.lock().await = g.payload.clone();
                    }
                    Ok(Response::builder().body(()).unwrap())
                })
            },
        )
        .await;
        assert_eq!(observed.lock().await.as_ref(), Some(&target));
    }

    /// seshcookie-rs.AC1.3: a payload serializing to roughly 3 KB JSON
    /// round-trips correctly and produces a cookie value strictly under the
    /// 4 KB browser cap (the practical realistic ceiling — see Phase 1's
    /// codec-level analysis).
    #[tokio::test]
    async fn http_level_large_payload_cookie_under_4kb_seshcookie_rs_ac1_3() {
        let layer = default_user_layer(t0());

        // Build a User whose JSON serialization lands near 3 KB. The JSON
        // shape is `{"id":N,"name":"..."}` so padding the name field by
        // ~3000 bytes drives the total close to the target.
        let target = User {
            id: 7,
            name: "x".repeat(3000),
        };

        let payload_json = serde_json::to_vec(&target).expect("serializes");
        assert!(
            (2900..=3100).contains(&payload_json.len()),
            "fixture must produce ~3 KB JSON, got {}",
            payload_json.len()
        );

        // Round 1: insert.
        let to_insert = target.clone();
        let resp1 = drive_request(
            layer.clone(),
            request_no_cookie(),
            handler(move |state| {
                let to_insert = to_insert.clone();
                async move {
                    let mut g = state.lock().await;
                    g.payload = Some(to_insert);
                    g.mutated = true;
                }
            }),
        )
        .await;
        let cookie1 = parse_only_set_cookie(&resp1);
        let cookie_value = cookie1.value().to_string();
        assert!(
            cookie_value.len() < 4096,
            "cookie value {} bytes exceeds 4 KB browser cap",
            cookie_value.len()
        );

        // Round 2: read it back; payload must round-trip byte-for-byte.
        let observed: Arc<Mutex<Option<User>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        drive_request(
            layer,
            request_with_cookie("session", &cookie_value),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    let g = state.lock().await;
                    *observed_clone.lock().await = g.payload.clone();
                }
            }),
        )
        .await;
        assert_eq!(observed.lock().await.as_ref(), Some(&target));
    }

    // ---------------------------------------------------------------------
    // tampered cookie (AC1.4)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC1.4: a single bit-flip in the base64-decoded sealed
    /// blob causes AEAD authentication to fail. The handler observes
    /// `payload = None` and the response emits exactly one cookie-delete to
    /// clean up the browser-side state.
    #[tokio::test]
    async fn http_level_tampered_cookie_handler_sees_none_seshcookie_rs_ac1_4() {
        let layer = default_user_layer(t0());
        let valid = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        // Flip one bit in the middle of the ciphertext region.
        let mut sealed = BASE64_URL_SAFE_NO_PAD
            .decode(&valid)
            .expect("our cookie is well-formed base64");
        let mid = sealed.len() / 2;
        sealed[mid] ^= 0x01;
        let tampered = BASE64_URL_SAFE_NO_PAD.encode(&sealed);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &tampered),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none(), "tampered cookie must not surface");
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    // ---------------------------------------------------------------------
    // silent fallback (AC6.1, AC6.3, AC6.5)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC6.1: a base64-invalid cookie value is treated as a
    /// malformed session — handler sees `None`, response emits one cookie-
    /// delete, request still proceeds (no HTTP-level error).
    #[tokio::test]
    async fn http_level_non_base64_cookie_handler_sees_none_and_delete_emitted_seshcookie_rs_ac6_1()
    {
        let layer = default_user_layer(t0());
        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);

        let resp = drive_request(
            layer,
            request_with_cookie("session", "@@@not-valid-base64@@@"),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none());
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
        assert!(emitted.expires().is_some(), "delete must include Expires");
    }

    /// seshcookie-rs.AC6.3: AEAD authentication failure (ciphertext byte
    /// flipped after a clean base64 decode) surfaces as `payload = None`
    /// plus a cookie-delete. Distinct from AC6.1 because here the base64
    /// pipeline succeeds and the AEAD layer is the one that rejects.
    #[tokio::test]
    async fn http_level_aead_authentication_failure_handler_sees_none_and_delete_emitted_seshcookie_rs_ac6_3()
     {
        let layer = default_user_layer(t0());
        let valid = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        // Flip one byte inside the ciphertext region. The first 12 bytes are
        // the nonce; the last 16 are the tag. The middle byte is in the
        // ciphertext region for any plaintext > 1 byte (our payload is far
        // larger), so this exercises the "base64 ok, AEAD rejects" path
        // unambiguously.
        let mut sealed = BASE64_URL_SAFE_NO_PAD
            .decode(&valid)
            .expect("our cookie is well-formed base64");
        let ct_byte = 12 + (sealed.len() - 12 - 16) / 2; // mid-ciphertext
        sealed[ct_byte] ^= 0x80;
        let tampered = BASE64_URL_SAFE_NO_PAD.encode(&sealed);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &tampered),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none());
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    /// seshcookie-rs.AC6.5: a cookie whose plaintext is valid JSON but does
    /// not match `T`'s schema yields `None` to the handler and a cookie-
    /// delete on the response. The codec layer succeeds (cookie is
    /// authentic and well-formed); the typed deserialize one layer up is
    /// what rejects.
    #[tokio::test]
    async fn http_level_bad_json_schema_handler_sees_none_and_delete_emitted_seshcookie_rs_ac6_5() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_with_wrong_schema(&layer, 0, t0() - Duration::from_secs(60));

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none(), "schema-mismatch must not surface");
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    // ---------------------------------------------------------------------
    // server-side expiry (AC2.1, AC2.2, AC2.4)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC2.1: a session issued at `T` is still valid at
    /// `T + max_age - 1s`. The handler observes the payload; no rewrite
    /// fires (no rotation, no refresh, read-only).
    #[tokio::test]
    async fn http_level_session_valid_up_to_max_age_minus_1s_seshcookie_rs_ac2_1() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(24 * 3_600 - 1);
        let layer = default_user_layer(now);
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        assert_eq!(
            observed.lock().await.as_ref().unwrap().payload,
            Some(sample_user()),
            "session at T+max_age-1s must still be valid"
        );
        assert!(
            set_cookie_headers(&resp).is_empty(),
            "valid read-only request must not emit Set-Cookie"
        );
    }

    /// seshcookie-rs.AC2.2: at `T + max_age + 1s`, the same session is
    /// rejected. Handler observes `None`; response emits a cookie-delete to
    /// clean up the stale browser cookie.
    #[tokio::test]
    async fn http_level_session_expires_at_max_age_plus_1s_seshcookie_rs_ac2_2() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(24 * 3_600 + 1);
        let layer = default_user_layer(now);
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none(), "expired session must not surface");
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    /// seshcookie-rs.AC2.4: a browser that appends `; Max-Age=99999` to its
    /// `Cookie` request header cannot extend the server-side session lifetime.
    /// The middleware ignores that token entirely — it appears as a sibling
    /// cookie named "Max-Age" with value "99999", not as the session-level
    /// `Max-Age` directive. Session validity is governed solely by the
    /// authenticated `issued_at` inside the encrypted cookie value.
    ///
    /// This test builds an expired cookie, attaches a browser-injected
    /// `; Max-Age=99999` suffix, sends it through the middleware, and confirms
    /// the session is still rejected and a cookie-delete is emitted.
    #[tokio::test]
    async fn http_level_browser_long_max_age_does_not_extend_seshcookie_rs_ac2_4() {
        // Cookie issued at t0, but we advance the clock past max_age so the
        // session is expired from the server's perspective.
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(24 * 3_600 + 1);
        let layer = default_user_layer(now);
        let cookie_value = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        // A browser might send the cookie value followed by `; Max-Age=99999`
        // believing this overrides the server's expiry. From RFC 6265 §4.2.1
        // the server-side parsing of `Cookie:` treats this as a second
        // name/value pair (`Max-Age` = `99999`), not a directive.
        let req = Request::builder()
            .header(
                http::header::COOKIE,
                format!("session={cookie_value}; Max-Age=99999"),
            )
            .body(())
            .expect("request builds");

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            req,
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(
            snap.payload.is_none(),
            "expired session must be rejected regardless of browser-injected Max-Age"
        );
        // The middleware should emit a cookie-delete to clean up the stale
        // browser cookie, not refresh it.
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(
            cookie_max_age_secs(&emitted),
            Some(0),
            "must emit cookie-delete, not a refresh"
        );
    }

    // ---------------------------------------------------------------------
    // decision-table (AC3.1 - AC3.6)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC3.1: a read-only handler against a valid cookie emits
    /// zero `Set-Cookie` headers.
    #[tokio::test]
    async fn http_level_read_only_handler_emits_zero_set_cookie_seshcookie_rs_ac3_1() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let _g = state.lock().await; // read-only; do not mutate
            }),
        )
        .await;

        assert!(
            set_cookie_headers(&resp).is_empty(),
            "read-only must emit zero Set-Cookie: {:?}",
            set_cookie_headers(&resp)
        );
    }

    /// seshcookie-rs.AC3.2: `insert(same_value)` is suppressed by hash-compare.
    /// `mutated = true` plus an unchanged payload yields zero `Set-Cookie`.
    #[tokio::test]
    async fn http_level_insert_same_value_suppressed_seshcookie_rs_ac3_2() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let mut g = state.lock().await;
                // Re-insert the same payload bytes-for-bytes.
                g.payload = Some(sample_user());
                g.mutated = true;
            }),
        )
        .await;

        assert!(
            set_cookie_headers(&resp).is_empty(),
            "insert(same_value) must be suppressed by hash-compare: {:?}",
            set_cookie_headers(&resp)
        );
    }

    /// seshcookie-rs.AC3.3: `insert(different_value)` emits exactly one
    /// `Set-Cookie` whose plaintext encodes the new payload at the
    /// preserved `issued_at`.
    #[tokio::test]
    async fn http_level_insert_different_value_emits_one_set_cookie_seshcookie_rs_ac3_3() {
        let issued_at = t0() - Duration::from_secs(3_600);
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let new_user = User {
            id: 100,
            name: "bob".into(),
        };
        let to_insert = new_user.clone();
        let resp = drive_request(
            layer.clone(),
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let to_insert = to_insert.clone();
                async move {
                    let mut g = state.lock().await;
                    g.payload = Some(to_insert);
                    g.mutated = true;
                }
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        let derived = [aead::DerivedKey::derive(IKM_PRIMARY)];
        let (emitted_issued_at, emitted_payload): (_, User) =
            decode_emitted_cookie(&derived, emitted.value());
        assert_eq!(emitted_payload, new_user);
        assert_eq!(
            emitted_issued_at, issued_at,
            "insert must preserve original issued_at"
        );
    }

    /// seshcookie-rs.AC3.4: `mutated = true` without a payload change emits
    /// zero `Set-Cookie` (modify no-op closure path).
    #[tokio::test]
    async fn http_level_modify_noop_emits_zero_seshcookie_rs_ac3_4() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let mut g = state.lock().await;
                g.mutated = true; // payload untouched
            }),
        )
        .await;

        assert!(
            set_cookie_headers(&resp).is_empty(),
            "modify(no-op) must be suppressed: {:?}",
            set_cookie_headers(&resp)
        );
    }

    /// seshcookie-rs.AC3.5: `clear()` against a valid cookie emits exactly
    /// one cookie-delete with empty value, `Max-Age=0`, a past `Expires`,
    /// and matching `Path` / `Domain` (verified via the parsed attributes).
    #[tokio::test]
    async fn http_level_clear_on_valid_cookie_emits_delete_seshcookie_rs_ac3_5() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let mut g = state.lock().await;
                g.payload = None;
                g.mutated = true;
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "", "clear must emit empty value");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
        assert!(emitted.expires().is_some(), "clear must include Expires");
        assert_eq!(emitted.path(), Some("/"));
    }

    /// seshcookie-rs.AC3.6: `clear()` on a request without a cookie emits
    /// zero `Set-Cookie` headers (no browser state to clean up).
    #[tokio::test]
    async fn http_level_clear_on_no_cookie_emits_zero_seshcookie_rs_ac3_6() {
        let layer = default_user_layer(t0());

        let resp = drive_request(
            layer,
            request_no_cookie(),
            handler(|state| async move {
                let mut g = state.lock().await;
                g.payload = None;
                g.mutated = true;
            }),
        )
        .await;

        assert!(
            set_cookie_headers(&resp).is_empty(),
            "clear() with no incoming cookie must emit nothing: {:?}",
            set_cookie_headers(&resp)
        );
    }

    // ---------------------------------------------------------------------
    // rotation (AC4.1 - AC4.6)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC4.1: a cookie sealed under the primary key on a
    /// single-key layer emits zero `Set-Cookie` headers (read-only handler;
    /// no migration). Handler-side `decrypt_key_index` is `Some(0)`.
    #[tokio::test]
    async fn http_level_primary_decrypt_no_emission_seshcookie_rs_ac4_1() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert_eq!(snap.decrypt_key_index, Some(0));
        assert!(set_cookie_headers(&resp).is_empty());
    }

    /// seshcookie-rs.AC4.2 + seshcookie-rs.AC4.3: a cookie sealed under the
    /// fallback key (`O`) decrypts via `[P, O]` with index 1 and triggers
    /// auto-migration to the primary on the response. Verifying the emitted
    /// cookie decrypts under `[P]` alone (and *not* under `[O]` alone)
    /// proves the rewrite re-encrypted under the primary.
    #[tokio::test]
    async fn http_level_fallback_decrypt_emits_primary_encryption_seshcookie_rs_ac4_2_ac4_3() {
        let issued_at = t0() - Duration::from_secs(3_600);
        let keys = SessionKeys::new(IKM_PRIMARY)
            .expect("valid")
            .with_fallback(IKM_FALLBACK_1)
            .expect("valid");
        let layer: SessionLayer<User> = make_layer(keys, SessionConfig::default(), t0());
        let cookie = encode_cookie_value(&layer, 1, &sample_user(), issued_at);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;
        let snap = observed.lock().await.clone().unwrap();
        assert_eq!(snap.decrypt_key_index, Some(1));
        assert_eq!(snap.payload, Some(sample_user()));

        let emitted = parse_only_set_cookie(&resp);
        let primary_only = [aead::DerivedKey::derive(IKM_PRIMARY)];
        let fallback_only = [aead::DerivedKey::derive(IKM_FALLBACK_1)];
        assert!(
            crate::codec::decode_cookie(&primary_only, emitted.value()).is_some(),
            "emitted cookie must decrypt under primary alone"
        );
        assert!(
            crate::codec::decode_cookie(&fallback_only, emitted.value()).is_none(),
            "emitted cookie must NOT decrypt under fallback (must be re-encrypted under primary)"
        );
    }

    /// seshcookie-rs.AC4.4: a rotation-only rewrite preserves the original
    /// `issued_at`. Verified by decoding the emitted cookie's plaintext and
    /// asserting its timestamp equals the cookie-side input, *not* `now`.
    #[tokio::test]
    async fn http_level_rotation_emit_preserves_issued_at_seshcookie_rs_ac4_4() {
        let issued_at = t0() - Duration::from_secs(3_600);
        let keys = SessionKeys::new(IKM_PRIMARY)
            .expect("valid")
            .with_fallback(IKM_FALLBACK_1)
            .expect("valid");
        let layer: SessionLayer<User> = make_layer(keys, SessionConfig::default(), t0());
        let cookie = encode_cookie_value(&layer, 1, &sample_user(), issued_at);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let _g = state.lock().await; // read-only
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        let primary_only = [aead::DerivedKey::derive(IKM_PRIMARY)];
        let (emitted_issued_at, emitted_payload): (_, User) =
            decode_emitted_cookie(&primary_only, emitted.value());
        assert_eq!(
            emitted_issued_at, issued_at,
            "rotation-only rewrite must preserve issued_at"
        );
        assert_eq!(emitted_payload, sample_user());
    }

    /// seshcookie-rs.AC4.5: a cookie sealed under an IKM the layer does not
    /// know about authentication-fails on every layer key. The handler
    /// observes `None`; response emits a cookie-delete to invalidate the
    /// browser's copy.
    #[tokio::test]
    async fn http_level_unknown_key_returns_none_and_emits_delete_seshcookie_rs_ac4_5() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_with_unknown_key(
            IKM_UNKNOWN,
            &sample_user(),
            t0() - Duration::from_secs(60),
        );

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;
        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none());
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    /// seshcookie-rs.AC4.6: a cookie sealed under the second fallback `O2`
    /// decrypts via `[P, O1, O2]` with index 2, and the migration emit is
    /// re-encrypted under the primary.
    #[tokio::test]
    async fn http_level_ordered_fallbacks_seshcookie_rs_ac4_6() {
        let issued_at = t0() - Duration::from_secs(3_600);
        let keys = SessionKeys::new(IKM_PRIMARY)
            .expect("valid")
            .with_fallbacks([&IKM_FALLBACK_1[..], &IKM_FALLBACK_2[..]])
            .expect("valid");
        let layer: SessionLayer<User> = make_layer(keys, SessionConfig::default(), t0());
        let cookie = encode_cookie_value(&layer, 2, &sample_user(), issued_at);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;
        let snap = observed.lock().await.clone().unwrap();
        assert_eq!(snap.decrypt_key_index, Some(2));
        assert_eq!(snap.payload, Some(sample_user()));

        let emitted = parse_only_set_cookie(&resp);
        let primary_only = [aead::DerivedKey::derive(IKM_PRIMARY)];
        assert!(
            crate::codec::decode_cookie(&primary_only, emitted.value()).is_some(),
            "ordered-fallback migration must re-encrypt under primary"
        );
    }

    // ---------------------------------------------------------------------
    // multi-cookie HTTP edges (AC6.6, AC6.7)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC6.6: `Cookie: a=1; session=<valid>; b=2` parses the
    /// session cookie correctly. Sibling cookies are ignored, and the
    /// handler observes the payload as expected.
    #[tokio::test]
    async fn http_level_multiple_cookies_in_single_header_extracts_configured_seshcookie_rs_ac6_6()
    {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let req = Request::builder()
            .header(http::header::COOKIE, format!("a=1; session={cookie}; b=2"))
            .body(())
            .expect("request builds");

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        drive_request(
            layer,
            req,
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        assert_eq!(
            observed.lock().await.as_ref().unwrap().payload,
            Some(sample_user())
        );
    }

    /// seshcookie-rs.AC6.7: a request with two `Cookie` headers (one carrying
    /// `a=1`, the other carrying the session cookie alongside `b=2`) is
    /// scanned in full. Both headers contribute candidates; the matching one
    /// wins.
    #[tokio::test]
    async fn http_level_multiple_cookie_headers_scanned_seshcookie_rs_ac6_7() {
        let layer = default_user_layer(t0());
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), t0() - Duration::from_secs(60));

        let req = Request::builder()
            .header(http::header::COOKIE, "a=1")
            .header(http::header::COOKIE, format!("session={cookie}; b=2"))
            .body(())
            .expect("request builds");

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        drive_request(
            layer,
            req,
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        assert_eq!(
            observed.lock().await.as_ref().unwrap().payload,
            Some(sample_user())
        );
    }

    // ---------------------------------------------------------------------
    // config reflection (AC7.2 end-to-end, AC7.6)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC7.2 (end-to-end): every customizable config attribute
    /// is reflected in the emitted `Set-Cookie` on a fresh-session response.
    #[tokio::test]
    async fn http_level_set_cookie_reflects_all_config_attributes_seshcookie_rs_ac7_2() {
        let keys = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let config = SessionConfig::default()
            .cookie_name("CUSTOM")
            .path("/api")
            .domain("x.test")
            .secure(false)
            .http_only(false)
            .same_site(SameSite::Strict);
        let layer: SessionLayer<User> = make_layer(keys, config, t0());

        let resp = drive_request(
            layer,
            request_no_cookie(),
            handler(|state| async move {
                let mut g = state.lock().await;
                g.payload = Some(sample_user());
                g.mutated = true;
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.name(), "CUSTOM");
        assert_eq!(emitted.path(), Some("/api"));
        assert_eq!(emitted.domain(), Some("x.test"));
        // The `cookie` crate's `Display` impl emits `Secure` and `HttpOnly`
        // only when the builder set them to `Some(true)`. With
        // `secure(false)` / `http_only(false)`, no attribute is rendered, so
        // a round-tripped parse sees `None`. Absence of the attribute IS the
        // negative value on the wire.
        assert_eq!(emitted.secure(), None, "secure(false) renders no attribute");
        assert_eq!(
            emitted.http_only(),
            None,
            "http_only(false) renders no attribute"
        );
        assert_eq!(emitted.same_site(), Some(SameSite::Strict));
    }

    /// seshcookie-rs.AC7.6: a normal session-set `Set-Cookie` carries no
    /// `Max-Age` and no `Expires` — browser session-cookie semantics. The
    /// emitted value parses with `max_age() == None` and
    /// `expires() == None`.
    #[tokio::test]
    async fn http_level_normal_set_has_no_max_age_no_expires_seshcookie_rs_ac7_6() {
        let layer = default_user_layer(t0());

        let resp = drive_request(
            layer,
            request_no_cookie(),
            handler(|state| async move {
                let mut g = state.lock().await;
                g.payload = Some(sample_user());
                g.mutated = true;
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        assert!(
            emitted.max_age().is_none(),
            "normal set must omit Max-Age, got {:?}",
            emitted.max_age()
        );
        assert!(
            emitted.expires().is_none(),
            "normal set must omit Expires, got {:?}",
            emitted.expires()
        );
    }

    // ---------------------------------------------------------------------
    // sliding refresh (AC8.1 - AC8.5)
    // ---------------------------------------------------------------------

    /// seshcookie-rs.AC8.1: `refresh_after = None` (default) plus a 23h-old
    /// session under a 24h `max_age` emits zero `Set-Cookie` (read-only
    /// handler).
    #[tokio::test]
    async fn http_level_refresh_none_no_emission_at_23h_seshcookie_rs_ac8_1() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(23 * 3_600);
        let keys = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let layer: SessionLayer<User> = make_layer(keys, SessionConfig::default(), now);
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let _g = state.lock().await;
            }),
        )
        .await;

        assert!(
            set_cookie_headers(&resp).is_empty(),
            "refresh_after=None must never refresh: {:?}",
            set_cookie_headers(&resp)
        );
    }

    /// seshcookie-rs.AC8.2: `refresh_after = Some(1h)` with a 30-minute-old
    /// session emits zero `Set-Cookie` — the threshold has not been crossed.
    #[tokio::test]
    async fn http_level_refresh_1h_within_window_no_emission_seshcookie_rs_ac8_2() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(30 * 60);
        let keys = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let config = SessionConfig::default().refresh_after(Some(Duration::from_secs(3_600)));
        let layer: SessionLayer<User> = make_layer(keys, config, now);
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let _g = state.lock().await;
            }),
        )
        .await;

        assert!(
            set_cookie_headers(&resp).is_empty(),
            "age below threshold must not refresh: {:?}",
            set_cookie_headers(&resp)
        );
    }

    /// seshcookie-rs.AC8.3: `refresh_after = Some(1h)`, `max_age = 24h`, age
    /// = 2h emits exactly one `Set-Cookie` whose plaintext encodes the
    /// **bumped** `issued_at = now` and the unchanged payload.
    #[tokio::test]
    async fn http_level_refresh_1h_exceeded_emits_bumped_issued_at_seshcookie_rs_ac8_3() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(2 * 3_600);
        let keys = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let config = SessionConfig::default().refresh_after(Some(Duration::from_secs(3_600)));
        let layer: SessionLayer<User> = make_layer(keys, config, now);
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let _g = state.lock().await;
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        let primary_only = [aead::DerivedKey::derive(IKM_PRIMARY)];
        let (emitted_issued_at, emitted_payload): (_, User) =
            decode_emitted_cookie(&primary_only, emitted.value());
        assert_eq!(emitted_issued_at, now, "refresh must bump issued_at to now");
        assert_eq!(emitted_payload, sample_user());
    }

    /// seshcookie-rs.AC8.4: simultaneous refresh + rotation. Cookie sealed
    /// under fallback `O` at age 2h; threshold is 1h. The single emitted
    /// `Set-Cookie` carries the bumped `issued_at = now` AND decrypts under
    /// the primary alone (rotated).
    #[tokio::test]
    async fn http_level_refresh_plus_rotation_one_emission_seshcookie_rs_ac8_4() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(2 * 3_600);
        let keys = SessionKeys::new(IKM_PRIMARY)
            .expect("valid")
            .with_fallback(IKM_FALLBACK_1)
            .expect("valid");
        let config = SessionConfig::default().refresh_after(Some(Duration::from_secs(3_600)));
        let layer: SessionLayer<User> = make_layer(keys, config, now);
        let cookie = encode_cookie_value(&layer, 1, &sample_user(), issued_at);

        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(|state| async move {
                let _g = state.lock().await;
            }),
        )
        .await;

        let emitted = parse_only_set_cookie(&resp);
        let primary_only = [aead::DerivedKey::derive(IKM_PRIMARY)];
        let (emitted_issued_at, emitted_payload): (_, User) =
            decode_emitted_cookie(&primary_only, emitted.value());
        assert_eq!(emitted_issued_at, now, "refresh+rotation bumps issued_at");
        assert_eq!(emitted_payload, sample_user());

        let fallback_only = [aead::DerivedKey::derive(IKM_FALLBACK_1)];
        assert!(
            crate::codec::decode_cookie(&fallback_only, emitted.value()).is_none(),
            "emitted cookie must be re-encrypted under the primary"
        );
    }

    /// seshcookie-rs.AC8.5: a 25h-old session with `refresh_after = Some(1h)`
    /// is rejected as expired (24h `max_age`). Refresh never gets a chance
    /// to fire; the response emits a cookie-delete instead.
    #[tokio::test]
    async fn http_level_25h_old_rejected_not_refreshed_seshcookie_rs_ac8_5() {
        let issued_at = t0();
        let now = issued_at + Duration::from_secs(25 * 3_600);
        let keys = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let config = SessionConfig::default().refresh_after(Some(Duration::from_secs(3_600)));
        let layer: SessionLayer<User> = make_layer(keys, config, now);
        let cookie = encode_cookie_value(&layer, 0, &sample_user(), issued_at);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &cookie),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(snap.payload.is_none(), "expired session must not surface");
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(
            emitted.value(),
            "",
            "must be a cookie-delete, not a refresh"
        );
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    // ---------------------------------------------------------------------
    // oversized cookie DoS guard (Important #3)
    // ---------------------------------------------------------------------

    /// A cookie value that exceeds MAX_COOKIE_VALUE_BYTES is treated as absent.
    /// Handler sees None; a delete is emitted to clean up the browser state.
    /// This prevents a malicious client from triggering large allocations
    /// (base64-decoded buffer multiplied by keys.len()) before AEAD rejection.
    #[tokio::test]
    async fn http_level_oversized_cookie_treated_as_absent_emits_delete() {
        let layer = default_user_layer(t0());

        // Build a cookie value that exceeds the cap. We use 64 KB of 'A'
        // characters — valid base64 characters, so the rejection must happen
        // before any base64 decode, not because of a decode error.
        let oversized: String = "A".repeat(65536);

        let observed: Arc<Mutex<Option<StateSnapshot>>> = Arc::new(Mutex::new(None));
        let observed_clone = Arc::clone(&observed);
        let resp = drive_request(
            layer,
            request_with_cookie("session", &oversized),
            handler(move |state| {
                let observed_clone = Arc::clone(&observed_clone);
                async move {
                    *observed_clone.lock().await = Some(snapshot_state(&state).await);
                }
            }),
        )
        .await;

        let snap = observed.lock().await.clone().unwrap();
        assert!(
            snap.payload.is_none(),
            "oversized cookie must surface as None to the handler"
        );
        // A delete must be emitted (same shape as the malformed-cookie tests).
        let emitted = parse_only_set_cookie(&resp);
        assert_eq!(emitted.value(), "");
        assert_eq!(cookie_max_age_secs(&emitted), Some(0));
    }

    // ---------------------------------------------------------------------
    // SessionService::clone (Minor #3)
    // ---------------------------------------------------------------------

    /// `SessionService` implements `Clone`. Two independently-cloned services
    /// must both be independently usable via `oneshot`.
    #[tokio::test]
    async fn session_service_clone_is_independently_usable() {
        let layer = default_user_layer(t0());
        let inner = tower::service_fn(|req: Request<()>| async move {
            // Read-only; just confirm the extension is present.
            let _ = req
                .extensions()
                .get::<Arc<Mutex<SessionState<User>>>>()
                .expect("extensions must contain SessionState");
            Ok::<_, Infallible>(Response::builder().body(()).unwrap())
        });
        let svc = layer.layer(inner);
        let svc2 = svc.clone();

        // Drive both clones; neither should error.
        svc.oneshot(request_no_cookie())
            .await
            .expect("first clone must handle request");
        svc2.oneshot(request_no_cookie())
            .await
            .expect("second clone must handle request");
    }

    // ---------------------------------------------------------------------
    // Two-layer coexistence (Important #1, Phase 3 completion checklist)
    // ---------------------------------------------------------------------

    /// Second payload type used by the two-layer coexistence test. Deliberately
    /// different from `User` so the `Extensions` TypeId key is distinct.
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct Account {
        account_id: u64,
        email: String,
    }

    fn sample_account() -> Account {
        Account {
            account_id: 7,
            email: "test@example.com".into(),
        }
    }

    /// Two `SessionLayer`s with distinct payload types and distinct cookie names
    /// must coexist on the same service stack without interference. This test
    /// stacks `SessionLayer<Account>` (cookie "a") above `SessionLayer<User>`
    /// (cookie "b"), mutates the "a" session, and asserts that:
    ///
    /// - Round 1 (write "a"): the emitted `Set-Cookie` is for cookie "a"; the
    ///   "b" layer emits nothing.
    /// - Round 2 (read both): replaying the "a" cookie surfaces the Account
    ///   payload; "b" is still absent (no "b" cookie was ever sent).
    /// - Mutation of the "a" session did not leak into or corrupt the "b" state.
    ///
    /// This confirms the design property: `Extensions` keys by
    /// `TypeId<Arc<Mutex<SessionState<T>>>>`, so two layers with distinct `T`s
    /// insert and read from distinct slots even when running on the same request.
    #[tokio::test]
    async fn http_level_two_session_layers_coexist_without_interference() {
        // Layers share the same IKM for simplicity; cookie names differ.
        let keys_a = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let config_a = SessionConfig::default().cookie_name("a").secure(false);
        let layer_a: SessionLayer<Account> = make_layer(keys_a, config_a, t0());

        let keys_b = SessionKeys::new(IKM_FALLBACK_1).expect("valid");
        let config_b = SessionConfig::default().cookie_name("b").secure(false);
        let layer_b: SessionLayer<User> = make_layer(keys_b, config_b, t0());

        // ---- Round 1: write an Account session via the "a" layer ----------------
        // The inner handler mutates the Account state; User state is untouched.
        let inner = tower::service_fn(|req: Request<()>| async move {
            // Write Account.
            if let Some(state_a) = req
                .extensions()
                .get::<Arc<Mutex<SessionState<Account>>>>()
                .cloned()
            {
                let mut g = state_a.lock().await;
                g.payload = Some(sample_account());
                g.mutated = true;
            }
            // User state should be None (no "b" cookie sent).
            if let Some(state_b) = req
                .extensions()
                .get::<Arc<Mutex<SessionState<User>>>>()
                .cloned()
            {
                let g = state_b.lock().await;
                assert!(
                    g.payload.is_none(),
                    "User state must be None when no 'b' cookie is present"
                );
            }
            Ok::<_, Infallible>(Response::builder().body(()).unwrap())
        });

        // Stack: request comes in → layer_a → layer_b → inner.
        // `layer_a.layer(layer_b.layer(inner))` means layer_a runs outermost.
        let inner_svc = layer_b.layer(inner);
        let svc = layer_a.clone().layer(inner_svc);

        let resp1 = svc
            .oneshot(request_no_cookie())
            .await
            .expect("round 1 infallible");

        // Collect Set-Cookie headers; the "a" layer should have emitted exactly one.
        let set_cookies = set_cookie_headers(&resp1);
        assert_eq!(
            set_cookies.len(),
            1,
            "only the 'a' layer should emit a Set-Cookie on round 1; got: {set_cookies:?}"
        );
        let emitted_cookie: cookie::Cookie<'static> = {
            let s = set_cookies.into_iter().next().unwrap();
            let leaked: &'static str = Box::leak(s.into_boxed_str());
            cookie::Cookie::parse(leaked).expect("round-1 Set-Cookie must parse")
        };
        assert_eq!(
            emitted_cookie.name(),
            "a",
            "emitted cookie must be for the 'a' layer"
        );
        let a_cookie_value = emitted_cookie.value().to_string();

        // ---- Round 2: replay the "a" cookie; assert "b" state is unaffected -----
        // Send only the "a" cookie; "b" layer should still see None.
        let observed_account: Arc<Mutex<Option<Account>>> = Arc::new(Mutex::new(None));
        let observed_user: Arc<Mutex<Option<Option<User>>>> = Arc::new(Mutex::new(None));
        let obs_acc = Arc::clone(&observed_account);
        let obs_usr = Arc::clone(&observed_user);

        let inner2 = tower::service_fn(move |req: Request<()>| {
            let obs_acc = Arc::clone(&obs_acc);
            let obs_usr = Arc::clone(&obs_usr);
            async move {
                if let Some(state_a) = req
                    .extensions()
                    .get::<Arc<Mutex<SessionState<Account>>>>()
                    .cloned()
                {
                    let g = state_a.lock().await;
                    *obs_acc.lock().await = g.payload.clone();
                }
                if let Some(state_b) = req
                    .extensions()
                    .get::<Arc<Mutex<SessionState<User>>>>()
                    .cloned()
                {
                    let g = state_b.lock().await;
                    *obs_usr.lock().await = Some(g.payload.clone());
                }
                Ok::<_, Infallible>(Response::builder().body(()).unwrap())
            }
        });

        let keys_a2 = SessionKeys::new(IKM_PRIMARY).expect("valid");
        let config_a2 = SessionConfig::default().cookie_name("a").secure(false);
        let layer_a2: SessionLayer<Account> = make_layer(keys_a2, config_a2, t0());

        let keys_b2 = SessionKeys::new(IKM_FALLBACK_1).expect("valid");
        let config_b2 = SessionConfig::default().cookie_name("b").secure(false);
        let layer_b2: SessionLayer<User> = make_layer(keys_b2, config_b2, t0());

        let inner_svc2 = layer_b2.layer(inner2);
        let svc2 = layer_a2.layer(inner_svc2);

        let req2 = Request::builder()
            .header(http::header::COOKIE, format!("a={a_cookie_value}"))
            .body(())
            .expect("round-2 request builds");

        let resp2 = svc2.oneshot(req2).await.expect("round 2 infallible");

        // The "a" layer decrypted the Account payload successfully.
        assert_eq!(
            *observed_account.lock().await,
            Some(sample_account()),
            "round 2 must surface the Account written in round 1"
        );
        // The "b" layer saw no "b" cookie, so User is still None.
        assert_eq!(
            *observed_user.lock().await,
            Some(None),
            "User state must remain None — 'b' cookie was never sent"
        );

        // Round 2 is read-only for "a" (payload unchanged) and no "b" cookie
        // was ever sent, so no Set-Cookie should be emitted.
        let set_cookies2 = set_cookie_headers(&resp2);
        assert!(
            set_cookies2.is_empty(),
            "read-only round 2 must emit zero Set-Cookie headers; got: {set_cookies2:?}"
        );
    }
}