koan-server 0.57.0

GraphQL, Subsonic REST, and MCP server for koan music player.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
use std::sync::Arc;

use axum::body::Body;
use axum::http::{HeaderMap, Request, StatusCode, header};
use koan_core::auth::{self, Role};
use koan_core::db::connection::Database;
use koan_core::db::queries::{self, TrackMeta};
use tower::ServiceExt;

use crate::auth::routes::{AuthRouteState, RateLimiter};

const HOST: &str = "koan.test";
const ORIGIN: &str = "https://koan.test";

fn meta(path: &std::path::Path, title: &str, n: i32) -> TrackMeta {
    TrackMeta {
        title: title.into(),
        artist: "Rrose".into(),
        album: "Hymn <to> Moisture".into(),
        album_artist: Some("Rrose".into()),
        track_number: Some(n),
        disc: Some(1),
        duration_ms: Some(125_000),
        codec: Some("FLAC".into()),
        sample_rate: Some(44100),
        bit_depth: Some(16),
        channels: Some(2),
        bitrate: Some(1000),
        genre: None,
        path: Some(path.to_string_lossy().into_owned()),
        date: Some("2019".into()),
        label: None,
        size_bytes: None,
        mtime: None,
        source: "local".into(),
        remote_id: None,
        remote_url: None,
        album_remote_id: None,
        artist_remote_id: None,
        mbid: None,
        album_mbid: None,
        album_added_at: None,
    }
}

struct Fixture {
    dir: tempfile::TempDir,
    app: axum::Router,
    state: AuthRouteState,
    album_id: i64,
    track_id: i64,
}

/// A library of one album, a user `alice` with password `hunter2`, and the UI
/// with auth on or off.
fn setup(auth_enabled: bool) -> Fixture {
    setup_at(auth_enabled, None)
}

/// `setup`, with `sharing.public_url` set when OAuth needs one.
fn setup_at(auth_enabled: bool, public_url: Option<&str>) -> Fixture {
    setup_full(auth_enabled, public_url, None)
}

fn setup_full(
    auth_enabled: bool,
    public_url: Option<&str>,
    proxy_auth: Option<super::ProxyAuth>,
) -> Fixture {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("koan.db");
    let db = Database::open(&db_path).unwrap();
    let file = dir.path().join("a.flac");
    std::fs::write(&file, b"0123456789").unwrap();
    let track_id = queries::upsert_track(&db.conn, &meta(&file, "Wet <Moss> & Stone", 1)).unwrap();
    let album_id = queries::tracks_by_ids(&db.conn, &[track_id]).unwrap()[0]
        .album_id
        .unwrap();
    queries::auth::create_user(&db.conn, "alice", "hunter2", Role::User).unwrap();
    let (private_pem, public_pem) = auth::generate_keypair_pem().unwrap();
    let pool = Arc::new(koan_core::db::pool::Pool::new(db_path));
    let state = AuthRouteState {
        pool: pool.clone(),
        private_pem: Arc::new(private_pem.into_bytes()),
        public_pem: Arc::new(public_pem.into_bytes()),
        access_ttl_secs: 900,
        refresh_ttl_secs: 3600,
        cookie_secure: true,
        login_limiter: Arc::new(RateLimiter::default()),
        users: Arc::new(crate::auth::password::PasswordVerifier::new(pool.clone())),
    };
    Fixture {
        app: super::router(
            pool,
            state.clone(),
            auth_enabled,
            Arc::new(crate::covers::Covers::new(dir.path().join("covers"))),
            public_url.map(str::to_owned),
            Vec::new(),
            proxy_auth,
        ),
        dir,
        state,
        album_id,
        track_id,
    }
}

struct Reply {
    status: StatusCode,
    headers: HeaderMap,
    body: String,
}

impl Reply {
    fn location(&self) -> &str {
        self.headers[header::LOCATION].to_str().unwrap()
    }

    fn cookies(&self) -> Vec<&str> {
        self.headers
            .get_all(header::SET_COOKIE)
            .iter()
            .map(|v| v.to_str().unwrap())
            .collect()
    }

    /// The value of a cookie this reply set.
    fn cookie(&self, name: &str) -> String {
        self.cookies()
            .iter()
            .find_map(|c| c.strip_prefix(&format!("{name}=")))
            .and_then(|c| c.split(';').next())
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| panic!("no {name} cookie in {:?}", self.cookies()))
            .to_owned()
    }
}

async fn send(app: &axum::Router, req: Request<Body>) -> Reply {
    let resp = app.clone().oneshot(req).await.unwrap();
    let (parts, body) = resp.into_parts();
    let body = axum::body::to_bytes(body, usize::MAX).await.unwrap();
    Reply {
        status: parts.status,
        headers: parts.headers,
        body: String::from_utf8_lossy(&body).into_owned(),
    }
}

fn get(uri: &str) -> axum::http::request::Builder {
    Request::get(uri).header(header::HOST, HOST)
}

fn form(uri: &str, body: &str) -> Request<Body> {
    Request::post(uri)
        .header(header::HOST, HOST)
        .header(header::ORIGIN, ORIGIN)
        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
        .body(Body::from(body.to_owned()))
        .unwrap()
}

fn access_token(state: &AuthRouteState) -> String {
    auth::mint_access_token(&state.private_pem, 1, "alice", Role::User, 900).unwrap()
}

fn authed(state: &AuthRouteState, uri: &str) -> axum::http::request::Builder {
    get(uri).header(
        header::COOKIE,
        format!("koan_access={}", access_token(state)),
    )
}

#[tokio::test]
async fn page_loads_without_a_session_resume_it_and_script_requests_are_refused() {
    let f = setup(true);
    let r = send(&f.app, get("/album/1?x=y").body(Body::empty()).unwrap()).await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/auth/resume?next=%2Falbum%2F1%3Fx%3Dy");

    for req in [
        get("/albums").header("x-koan-partial", "1"),
        get("/search/results").header("datastar-request", "true"),
        get(&format!("/ui/stream/{}", f.track_id)),
        get("/albums").header(header::COOKIE, "koan_access=forged"),
    ] {
        let r = send(&f.app, req.body(Body::empty()).unwrap()).await;
        assert!(
            matches!(r.status, StatusCode::UNAUTHORIZED | StatusCode::SEE_OTHER),
            "{}",
            r.status
        );
        assert_ne!(r.status, StatusCode::OK);
    }
    let r = send(
        &f.app,
        get("/albums")
            .header("x-koan-partial", "1")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn signing_in_sets_http_only_cookies_and_goes_only_to_local_paths() {
    let f = setup(true);
    let r = send(
        &f.app,
        form("/login", "username=alice&password=hunter2&next=%2Fartists"),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/artists");
    assert!(!r.body.contains(&r.cookie("koan_access")));
    let cookies = r.cookies();
    assert_eq!(cookies.len(), 3);
    for c in &cookies {
        assert!(c.contains("HttpOnly") && c.contains("SameSite=Lax") && c.contains("Secure"));
    }
    assert!(
        cookies
            .iter()
            .any(|c| c.starts_with("koan_access=") && c.contains("Path=/;"))
    );
    assert!(
        cookies
            .iter()
            .any(|c| c.starts_with("koan_refresh=") && c.contains("Path=/auth;"))
    );

    for next in [
        "%2F%2Fevil.example",
        "https%3A%2F%2Fevil.example",
        "%2F%5Cevil.example",
        "%2Fauth%2Fresume",
    ] {
        let r = send(
            &f.app,
            form(
                "/login",
                &format!("username=alice&password=hunter2&next={next}"),
            ),
        )
        .await;
        assert_eq!(
            (r.status, r.location()),
            (StatusCode::SEE_OTHER, "/"),
            "{next}"
        );
    }
}

#[tokio::test]
async fn wrong_passwords_and_cross_site_forms_do_not_sign_in() {
    let f = setup(true);
    let r = send(
        &f.app,
        form("/login", "username=alice&password=nope&next=%2F"),
    )
    .await;
    assert_eq!(r.status, StatusCode::UNAUTHORIZED);
    assert!(r.body.contains("Wrong username or password."));
    assert!(r.cookies().is_empty());

    let req = Request::post("/login")
        .header(header::HOST, HOST)
        .header(header::ORIGIN, "https://evil.example")
        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
        .body(Body::from("username=alice&password=hunter2"))
        .unwrap();
    let r = send(&f.app, req).await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);
    assert!(r.cookies().is_empty());
}

#[tokio::test]
async fn resume_spends_the_refresh_cookie_once() {
    let f = setup(true);
    let signed_in = send(&f.app, form("/login", "username=alice&password=hunter2")).await;
    let refresh = signed_in.cookie("koan_refresh");
    let resume = || {
        get("/auth/resume?next=%2Fqueue")
            .header(header::COOKIE, format!("koan_refresh={refresh}"))
            .body(Body::empty())
            .unwrap()
    };

    let r = send(&f.app, resume()).await;
    assert_eq!((r.status, r.location()), (StatusCode::SEE_OTHER, "/queue"));
    let access = r.cookie("koan_access");
    assert_ne!(r.cookie("koan_refresh"), refresh, "rotated");
    let page = send(
        &f.app,
        get("/queue")
            .header(header::COOKIE, format!("koan_access={access}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(page.status, StatusCode::OK);

    // Spent: the same cookie again goes to the sign-in form.
    let r = send(&f.app, resume()).await;
    assert_eq!(
        (r.status, r.location()),
        (StatusCode::SEE_OTHER, "/login?next=%2Fqueue")
    );
    let r = send(&f.app, get("/auth/resume").body(Body::empty()).unwrap()).await;
    assert_eq!(r.location(), "/login?next=%2F");
}

#[tokio::test]
async fn renew_answers_with_cookies_and_no_tokens() {
    let f = setup(true);
    let signed_in = send(&f.app, form("/login", "username=alice&password=hunter2")).await;
    let refresh = signed_in.cookie("koan_refresh");
    let renew = |origin: &str| {
        Request::post("/auth/renew")
            .header(header::HOST, HOST)
            .header(header::ORIGIN, origin)
            .header(header::COOKIE, format!("koan_refresh={refresh}"))
            .body(Body::empty())
            .unwrap()
    };
    assert_eq!(
        send(&f.app, renew("https://evil.example")).await.status,
        StatusCode::FORBIDDEN
    );
    let r = send(&f.app, renew(ORIGIN)).await;
    assert_eq!(r.status, StatusCode::NO_CONTENT);
    assert!(r.body.is_empty());
    assert!(!r.cookie("koan_access").is_empty());
}

#[tokio::test]
async fn signing_out_revokes_the_refresh_token() {
    let f = setup(true);
    let signed_in = send(&f.app, form("/login", "username=alice&password=hunter2")).await;
    let refresh = signed_in.cookie("koan_refresh");
    let mut req = form("/auth/signout", "");
    req.headers_mut().insert(
        header::COOKIE,
        format!("koan_refresh={refresh}").parse().unwrap(),
    );
    let r = send(&f.app, req).await;
    assert_eq!((r.status, r.location()), (StatusCode::SEE_OTHER, "/login"));
    assert!(r.cookies().iter().all(|c| c.contains("Max-Age=0")));

    let r = send(
        &f.app,
        get("/auth/resume")
            .header(header::COOKIE, format!("koan_refresh={refresh}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(r.location().starts_with("/login"));
}

#[tokio::test]
async fn streams_serve_ranges_to_a_signed_in_user() {
    let f = setup(true);
    let uri = format!("/ui/stream/{}", f.track_id);
    let r = send(
        &f.app,
        authed(&f.state, &uri)
            .header(header::RANGE, "bytes=2-4")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(
        (r.status, r.body.as_str()),
        (StatusCode::PARTIAL_CONTENT, "234")
    );
    let r = send(&f.app, get(&uri).body(Body::empty()).unwrap()).await;
    assert_eq!(r.status, StatusCode::UNAUTHORIZED);
    let r = send(
        &f.app,
        authed(&f.state, "/ui/stream/999")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn every_class_on_every_page_has_a_rule() {
    let f = setup(true);
    let db = Database::open(f.state.pool.path()).unwrap();
    let boss = queries::auth::create_user(&db.conn, "boss", "sesame", Role::Admin).unwrap();
    let artist = queries::tracks_by_ids(&db.conn, &[f.track_id]).unwrap()[0]
        .artist_id
        .unwrap();
    let access =
        auth::mint_access_token(&f.state.private_pem, boss, "boss", Role::Admin, 900).unwrap();
    let page = |uri: &str| {
        get(uri)
            .header(header::COOKIE, format!("koan_access={access}"))
            .body(Body::empty())
            .unwrap()
    };
    let post = |uri: &str, body: &str| {
        Request::post(uri)
            .header(header::HOST, HOST)
            .header(header::COOKIE, format!("koan_access={access}"))
            .header(header::CONTENT_TYPE, "application/json")
            .header("datastar-request", "true")
            .body(Body::from(body.to_owned()))
            .unwrap()
    };
    let mut rendered = Vec::new();
    for uri in [
        "/albums".to_owned(),
        "/albums?lossless=1&codec=MP3".to_owned(),
        format!("/album/{}", f.album_id),
        "/artists".to_owned(),
        format!("/artist/{artist}"),
        "/playlists".to_owned(),
        "/search?q=Wet".to_owned(),
        "/search?q=nothing-here".to_owned(),
        "/queue".to_owned(),
        "/library".to_owned(),
        "/favourites".to_owned(),
        "/history".to_owned(),
        "/recent".to_owned(),
        "/tracks".to_owned(),
        "/tracks?fav=1&recent=1&sort=played".to_owned(),
        "/albums?recent=1".to_owned(),
        "/account".to_owned(),
        "/scrobbling".to_owned(),
        "/users".to_owned(),
        "/connect".to_owned(),
    ] {
        let r = send(&f.app, page(&uri)).await;
        assert_eq!(r.status, StatusCode::OK, "{uri}");
        rendered.push((uri, r.body));
    }
    for (uri, body) in [
        ("/account/keys", r#"{"keyname":"phone"}"#),
        ("/account/app-passwords", r#"{"appname":"Arpeggi"}"#),
        ("/users/1/password/form", "{}"),
    ] {
        let r = send(&f.app, post(uri, body)).await;
        assert_eq!(r.status, StatusCode::OK, "{uri}");
        rendered.push((uri.to_owned(), r.body));
    }
    let r = send(&f.app, get("/login").body(Body::empty()).unwrap()).await;
    rendered.push(("/login".into(), r.body));
    for (uri, html) in rendered {
        let missing = crate::share::unstyled_classes(
            &html,
            super::UI_CSS,
            &["page", "browse", "toolbar", "search", "group"],
        );
        assert!(
            missing.is_empty(),
            "{uri}: no rule in ui.css for {missing:?}"
        );
    }
}

#[tokio::test]
async fn pages_render_whole_or_as_content_escaped_and_without_inline_script() {
    let f = setup(true);
    let uri = format!("/album/{}", f.album_id);
    let full = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
    assert_eq!(full.status, StatusCode::OK);
    assert!(full.body.starts_with("<!doctype html>"));
    assert!(full.body.contains("rel=icon"), "pages carry the favicon");
    assert!(full.body.contains("aria-label=Library>"));
    assert!(full.body.contains("Wet &lt;Moss&gt; &amp; Stone"));
    assert!(full.body.contains("Hymn &lt;to&gt; Moisture"));
    assert!(!full.body.contains("<Moss>") && !full.body.contains("<to>"));
    assert!(!full.body.contains("<script>") && !full.body.contains(" style="));
    let csp = full.headers[header::CONTENT_SECURITY_POLICY]
        .to_str()
        .unwrap();
    assert!(csp.contains("script-src 'self' 'unsafe-eval';") && !csp.contains("unsafe-inline"));
    // The stylesheet's URL changes with its contents, so an upgrade never pairs
    // new markup with a cached stylesheet.
    let css = &super::ASSETS.css;
    assert!(css.starts_with("/ui/assets/ui.css?v=") && full.body.contains(css.as_str()));
    let served = send(&f.app, get(css).body(Body::empty()).unwrap()).await;
    assert_eq!(served.status, StatusCode::OK);
    assert!(
        served.headers[header::CACHE_CONTROL]
            .to_str()
            .unwrap()
            .contains("immutable")
    );
    // Every page and patch names it too, so an open tab can catch up.
    assert_eq!(full.headers["x-koan-css"], super::ASSETS.css_hash.as_str());

    let partial = send(
        &f.app,
        authed(&f.state, &uri)
            .header("x-koan-partial", "1")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(partial.body.starts_with("<section class=\"page\" "));
    assert!(
        partial
            .body
            .contains("data-title=\"Hymn &lt;to&gt; Moisture\"")
    );
    assert!(!partial.body.contains("<nav"));

    for page in [
        "/",
        "/albums",
        "/artists",
        "/search?q=moss",
        "/queue",
        "/artist/1",
    ] {
        let r = send(&f.app, authed(&f.state, page).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::OK, "{page}");
    }
    let r = send(
        &f.app,
        authed(&f.state, "/search?q=moss")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(r.body.contains("Wet &lt;Moss&gt; &amp; Stone"));
}

#[tokio::test]
async fn live_fragments_are_datastar_events_and_posts_need_datastar() {
    let f = setup(true);
    let r = send(
        &f.app,
        authed(
            &f.state,
            "/search/results?datastar=%7B%22q%22%3A%22moss%22%7D",
        )
        .header("datastar-request", "true")
        .body(Body::empty())
        .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.starts_with("event: datastar-patch-elements\n"));
    assert!(r.body.contains("data: elements <div id=results>"));

    let share = format!("/album/{}/share", f.album_id);
    let bare = Request::post(&share)
        .header(header::HOST, HOST)
        .header(
            header::COOKIE,
            format!("koan_access={}", access_token(&f.state)),
        )
        .body(Body::empty())
        .unwrap();
    assert_eq!(send(&f.app, bare).await.status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn pages_link_versioned_covers_and_a_missing_cover_is_remembered_and_drawn() {
    let f = setup(true);
    let page = send(
        &f.app,
        authed(&f.state, "/albums").body(Body::empty()).unwrap(),
    )
    .await;
    let src = format!("src=\"/ui/cover/{}?size=400&amp;v=", f.album_id);
    let src_raw = format!("src=\"/ui/cover/{}?size=400&v=", f.album_id);
    assert!(
        page.body.contains(&src) || page.body.contains(&src_raw),
        "{}",
        page.body
    );
    assert!(
        page.body
            .contains("loading=lazy decoding=async width=400 height=400")
    );

    let uri = format!("/ui/cover/{}?size=300&v=1", f.album_id);
    for _ in 0..2 {
        let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::OK, "the fake file has no art");
        assert_eq!(r.headers[header::CONTENT_TYPE], "image/svg+xml");
        assert!(r.body.contains("<svg"), "the apps' placeholder, drawn");
        assert!(
            !r.headers[header::CACHE_CONTROL]
                .to_str()
                .unwrap()
                .contains("immutable"),
            "art added later must replace it"
        );
    }
    let r = send(
        &f.app,
        authed(&f.state, "/ui/cover/999999?size=300")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::NOT_FOUND, "no such album");
    let kept: Vec<_> = std::fs::read_dir(f.dir.path().join("covers"))
        .unwrap()
        .map(|e| e.unwrap())
        .collect();
    assert_eq!(kept.len(), 1, "one remembered miss");
    assert_eq!(kept[0].metadata().unwrap().len(), 0);
    assert!(kept[0].file_name().to_string_lossy().ends_with("-400.jpg"));
}

#[tokio::test]
async fn sorting_and_filtering_live_in_the_query_string() {
    let f = setup(true);
    let page = |uri: &str| {
        let req = authed(&f.state, uri).body(Body::empty()).unwrap();
        let app = f.app.clone();
        async move { send(&app, req).await }
    };
    let r = page("/albums?sort=title&lossless=1&genre=").await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(
        r.body.contains("Hymn &lt;to&gt; Moisture"),
        "FLAC is lossless"
    );
    assert!(r.body.contains("<option value=\"title\" selected>"));
    assert!(r.body.contains("name=lossless value=1 checked"));
    assert!(r.body.contains(">1</span></summary>"));

    let r = page("/albums?codec=MP3").await;
    assert!(r.body.contains("No albums match."));
    let r = page("/albums?from=2020").await;
    assert!(r.body.contains("No albums match."), "released 2019");
    let r = page("/albums?from=2015&to=2019").await;
    assert!(r.body.contains("Hymn &lt;to&gt; Moisture"));

    // A value from a link, not among those offered, is still shown and kept.
    let r = page("/albums?genre=%22%3E%3Cscript%3E").await;
    assert!(
        r.body
            .contains("<option value=\"&quot;&gt;&lt;script&gt;\" selected>")
    );
    assert!(!r.body.contains("\"><script>"));

    for uri in [
        "/artists?sort=albums&fav=1",
        "/artists?sort=recent&lossless=1",
        "/albums?sort=random",
    ] {
        assert_eq!(page(uri).await.status, StatusCode::OK, "{uri}");
    }
    let r = page("/albums?sort=random").await;
    assert!(
        r.body.contains("<input type=hidden name=seed value="),
        "the shuffle is pinned"
    );
}

/// The `data-id`s of the track rows on a page, in order.
fn row_ids(body: &str) -> Vec<String> {
    body.split("<li tabindex=0 data-id=")
        .skip(1)
        .map(|r| r.split(' ').next().unwrap().to_owned())
        .collect()
}

#[tokio::test]
async fn a_shelf_heading_opens_the_browser_its_preview_is_the_head_of() {
    let f = setup(true);
    {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        queries::add_favourite(&db.conn, 1, f.track_id).unwrap();
        for n in 2..=12 {
            let path = f.dir.path().join(format!("{n}.flac"));
            std::fs::write(&path, b"x").unwrap();
            let id =
                queries::upsert_track(&db.conn, &meta(&path, &format!("Track {n:02}"), n)).unwrap();
            queries::add_favourite(&db.conn, 1, id).unwrap();
        }
    }
    let get = |uri: &str| authed(&f.state, uri).body(Body::empty()).unwrap();
    let shelf = send(&f.app, get("/favourites")).await.body;
    let preview = row_ids(&shelf);
    assert_eq!(preview.len(), 10, "ten in the preview");
    // The Tracks heading: a link, with the shelf's whole count in it.
    let heading = shelf
        .split("<h2>")
        .skip(1)
        .find(|h| h.contains(">Tracks<"))
        .expect("a Tracks heading");
    assert!(heading.contains(">12</span>"), "{heading}");
    let link = heading
        .split("href=\"")
        .nth(1)
        .unwrap()
        .split('"')
        .next()
        .unwrap()
        .replace("&amp;", "&");
    assert!(link.starts_with("/tracks?"), "{link}");

    let browser = send(&f.app, get(&link)).await.body;
    assert!(browser.contains("12 tracks"), "the count the heading gave");
    assert_eq!(
        row_ids(&browser)[..10],
        preview[..],
        "the same tracks, in the same order"
    );
    assert!(
        browser.contains("name=fav value=1 checked"),
        "the filter shows, to be cleared"
    );
}

#[tokio::test]
async fn favourites_are_the_callers_own_as_a_shelf() {
    let f = setup(true);
    let artist = {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        let bob = queries::auth::create_user(&db.conn, "bob", "hunter3", Role::User).unwrap();
        queries::add_favourite(&db.conn, bob, f.track_id).unwrap();
        queries::set_favourite_album(&db.conn, bob, f.album_id, true).unwrap();
        queries::tracks_by_ids(&db.conn, &[f.track_id]).unwrap()[0]
            .artist_id
            .unwrap()
    };
    let page = || authed(&f.state, "/favourites").body(Body::empty()).unwrap();

    let r = send(&f.app, page()).await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(
        r.body.contains("Nothing favourited yet") && !r.body.contains("data-id="),
        "another account's favourites are not alice's"
    );

    {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        queries::add_favourite(&db.conn, 1, f.track_id).unwrap();
        queries::set_favourite_album(&db.conn, 1, f.album_id, true).unwrap();
        queries::set_favourite_artist(&db.conn, 1, artist, true).unwrap();
    }
    let r = send(&f.app, page()).await;
    assert!(
        r.body.contains(&format!("href=\"/artist/{artist}\"")),
        "the artist, as a pill"
    );
    assert!(
        r.body.contains(&format!("href=\"/album/{}\"", f.album_id)),
        "the record, as a tile"
    );
    assert!(
        r.body.contains(&format!("data-id={}", f.track_id))
            && r.body.contains("data-context=album")
            && r.body.contains("Wet &lt;Moss&gt; &amp; Stone"),
        "the track, in a list that plays on"
    );

    let r = send(
        &f.app,
        authed(&f.state, "/library").body(Body::empty()).unwrap(),
    )
    .await;
    assert!(r.body.contains("href=\"/favourites\"") && r.body.contains("href=\"/playlists\""));
}

#[tokio::test]
async fn history_lists_the_callers_own_plays_by_day_and_forgets_only_those() {
    let f = setup(true);
    let now = chrono::Utc::now().timestamp();
    let (mine, theirs) = {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        let bob = queries::auth::create_user(&db.conn, "bob", "hunter3", Role::User).unwrap();
        let mine = queries::record_play_at(&db.conn, 1, f.track_id, now, None, "local").unwrap();
        queries::record_play_at(&db.conn, 1, f.track_id, now - 3 * 86_400, None, "local").unwrap();
        let theirs =
            queries::record_play_at(&db.conn, bob, f.track_id, now, None, "local").unwrap();
        (mine, theirs)
    };
    let page = || {
        authed(&f.state, "/history")
            .header(header::COOKIE, "koan_tz=0")
            .body(Body::empty())
            .unwrap()
    };
    let r = send(&f.app, page()).await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.contains(">Today</li>"), "grouped by day");
    assert_eq!(
        r.body.matches("type=checkbox").count(),
        2,
        "alice's two plays, not bob's"
    );
    assert!(
        r.body.contains(&format!("value={mine}")) && !r.body.contains(&format!("value={theirs}"))
    );

    let forget = |ids: &str| {
        Request::post("/history/forget")
            .header(header::HOST, HOST)
            .header(
                header::COOKIE,
                format!("koan_access={}", access_token(&f.state)),
            )
            .header(header::CONTENT_TYPE, "application/json")
            .header("datastar-request", "true")
            .body(Body::from(format!("{{\"forget\":{ids}}}")))
            .unwrap()
    };
    // Another account's play, named by id, is left alone.
    let r = send(&f.app, forget(&format!("[\"{theirs}\"]"))).await;
    assert_eq!(r.status, StatusCode::OK);
    let r = send(&f.app, forget(&format!("[\"{mine}\"]"))).await;
    assert!(r.body.contains("datastar-patch-elements") && r.body.contains("\"forget\":[]"));
    let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
    let left: Vec<i64> = db
        .conn
        .prepare("SELECT id FROM play_history ORDER BY id")
        .unwrap()
        .query_map([], |r| r.get(0))
        .unwrap()
        .flatten()
        .collect();
    assert!(!left.contains(&mine), "alice's play is forgotten");
    assert!(left.contains(&theirs), "bob's is not");
    assert_eq!(left.len(), 2);
    // Recorded, so the account's devices forget it too; bob's is not.
    let forgotten: i64 = db
        .conn
        .query_row("SELECT COUNT(*) FROM play_history_forgotten", [], |r| {
            r.get(0)
        })
        .unwrap();
    assert_eq!(forgotten, 1);
}

#[tokio::test]
async fn recently_played_is_the_callers_own_each_once() {
    let f = setup(true);
    let now = chrono::Utc::now().timestamp();
    {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        let bob = queries::auth::create_user(&db.conn, "bob", "hunter3", Role::User).unwrap();
        queries::record_play_at(&db.conn, bob, f.track_id, now, None, "local").unwrap();
    }
    let page = || authed(&f.state, "/recent").body(Body::empty()).unwrap();
    let r = send(&f.app, page()).await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(
        r.body.contains("Nothing played in the last 30 days"),
        "bob's play is not alice's"
    );

    {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        for ago in [0, 60, 120] {
            queries::record_play_at(&db.conn, 1, f.track_id, now - ago, None, "local").unwrap();
        }
        // Older than the month, and not counted.
        queries::record_play_at(&db.conn, 1, f.track_id, now - 40 * 86_400, None, "local").unwrap();
    }
    let r = send(&f.app, page()).await;
    assert_eq!(
        r.body.matches(&format!("data-id={}", f.track_id)).count(),
        1,
        "three plays, one track"
    );
    assert!(r.body.contains(&format!("href=\"/album/{}\"", f.album_id)));
}

#[tokio::test]
async fn playlists_list_the_callers_own_and_play_like_albums() {
    let f = setup(true);
    let (mine, theirs) = {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        let bob = queries::auth::create_user(&db.conn, "bob", "hunter3", Role::User).unwrap();
        let mine = queries::create_playlist(&db.conn, 1, "Damp <Mix>", None).unwrap();
        queries::add_tracks(&db.conn, mine, &[f.track_id]).unwrap();
        let theirs = queries::create_playlist(&db.conn, bob, "Bob's Secret", None).unwrap();
        (mine, theirs)
    };
    let r = send(
        &f.app,
        authed(&f.state, "/playlists").body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.contains("Damp &lt;Mix&gt;") && r.body.contains("1 track"));
    assert!(
        !r.body.contains("Bob"),
        "another account's private playlist is not listed"
    );

    let uri = format!("/playlist/{mine}");
    let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.contains("data-act=queue") && r.body.contains("data-context=album"));
    assert!(r.body.contains(&format!("data-id={}", f.track_id)));

    let uri = format!("/playlist/{theirs}");
    let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
    assert_eq!(r.status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn with_auth_off_everything_is_open() {
    let f = setup(false);
    let r = send(&f.app, get("/albums").body(Body::empty()).unwrap()).await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(!r.body.contains("Sign out"));
    assert!(
        r.body
            .contains(concat!("kōan ", env!("CARGO_PKG_VERSION"), "</a>")),
        "the version shows without an account too"
    );
    let r = send(
        &f.app,
        get("/login?next=%2Fqueue").body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.location(), "/queue");
}

#[tokio::test]
async fn api_keys_are_shown_once_listed_and_revoked() {
    let f = setup(true);
    let post = |uri: &str, body: &str, datastar: bool| {
        let mut req = Request::post(uri)
            .header(header::HOST, HOST)
            .header(
                header::COOKIE,
                format!("koan_access={}", access_token(&f.state)),
            )
            .header(header::CONTENT_TYPE, "application/json");
        if datastar {
            req = req.header("datastar-request", "true");
        }
        req.body(Body::from(body.to_owned())).unwrap()
    };

    let r = send(
        &f.app,
        authed(&f.state, "/account").body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.contains("No keys yet."), "{}", r.body);

    let r = send(
        &f.app,
        post("/account/keys", r#"{"keyname":"phone"}"#, false),
    )
    .await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);

    let r = send(
        &f.app,
        post("/account/keys", r#"{"keyname":"phone"}"#, true),
    )
    .await;
    let key = r
        .body
        .split("id=key-result-value readonly value=\"")
        .nth(1)
        .and_then(|rest| rest.split('"').next())
        .unwrap_or_else(|| panic!("no key in {}", r.body))
        .to_owned();
    let db = Database::open(f.state.pool.path()).unwrap();
    let user = queries::api_keys::authenticate_api_key(&db.conn, &key)
        .unwrap()
        .unwrap();
    assert_eq!(user.username, "alice");

    let r = send(
        &f.app,
        authed(&f.state, "/account").body(Body::empty()).unwrap(),
    )
    .await;
    assert!(
        r.body.contains("phone") && r.body.contains("last used"),
        "{}",
        r.body
    );
    assert!(!r.body.contains(&key));

    let id = queries::api_keys::list_api_keys(&db.conn, Some(user.id)).unwrap()[0].id;
    let r = send(
        &f.app,
        post(&format!("/account/keys/{id}/revoke"), "{}", true),
    )
    .await;
    assert!(r.body.contains("No keys yet."), "{}", r.body);
    assert!(
        queries::api_keys::authenticate_api_key(&db.conn, &key)
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
async fn app_passwords_are_shown_once_sealed_and_revoked() {
    let f = setup(true);
    let post = |uri: &str, body: &str| {
        Request::post(uri)
            .header(header::HOST, HOST)
            .header(
                header::COOKIE,
                format!("koan_access={}", access_token(&f.state)),
            )
            .header(header::CONTENT_TYPE, "application/json")
            .header("datastar-request", "true")
            .body(Body::from(body.to_owned()))
            .unwrap()
    };
    let r = send(
        &f.app,
        authed(&f.state, "/account").body(Body::empty()).unwrap(),
    )
    .await;
    assert!(r.body.contains("No app passwords yet."), "{}", r.body);

    let r = send(
        &f.app,
        post("/account/app-passwords", r#"{"appname":"Arpeggi"}"#),
    )
    .await;
    let password = r
        .body
        .split("id=app-password-result-value readonly value=\"")
        .nth(1)
        .and_then(|rest| rest.split('"').next())
        .unwrap_or_else(|| panic!("no app password in {}", r.body))
        .to_owned();

    // Sealed in the database, never kept or listed as itself.
    let db = Database::open(f.state.pool.path()).unwrap();
    let stored: Vec<u8> = db
        .conn
        .query_row("SELECT sealed FROM app_passwords", [], |row| row.get(0))
        .unwrap();
    assert!(
        !stored
            .windows(password.len())
            .any(|w| w == password.as_bytes())
    );
    let r = send(
        &f.app,
        authed(&f.state, "/account").body(Body::empty()).unwrap(),
    )
    .await;
    assert!(r.body.contains("Arpeggi") && !r.body.contains(&password));

    let key = koan_core::auth::app_password_key(&f.state.private_pem);
    let signed_in = |db: &Database| {
        matches!(
            queries::app_passwords::authenticate_app_password(&db.conn, &key, "alice", |p| {
                p == password
            })
            .unwrap(),
            queries::app_passwords::AppPasswordAuth::Matched(_)
        )
    };
    assert!(signed_in(&db));

    let user = queries::auth::get_user_by_username(&db.conn, "alice")
        .unwrap()
        .unwrap();
    let id = queries::app_passwords::list_app_passwords(&db.conn, user.id).unwrap()[0].id;
    let r = send(
        &f.app,
        post(&format!("/account/app-passwords/{id}/revoke"), "{}"),
    )
    .await;
    assert!(r.body.contains("No app passwords yet."), "{}", r.body);
    assert!(!signed_in(&db));
}

#[tokio::test]
async fn an_app_password_does_not_sign_in_to_the_web_ui() {
    let f = setup(true);
    let password = {
        let db = Database::open(f.state.pool.path()).unwrap();
        let user = queries::auth::get_user_by_username(&db.conn, "alice")
            .unwrap()
            .unwrap();
        let key = koan_core::auth::app_password_key(&f.state.private_pem);
        queries::app_passwords::create_app_password(&db.conn, &key, user.id, "arpeggi")
            .unwrap()
            .1
    };
    // Apps only: the web sign-in, and with it GraphQL, MCP and OAuth, takes
    // the account's own password.
    let r = send(
        &f.app,
        form(
            "/login",
            &format!("username=alice&password={password}&next=%2F"),
        ),
    )
    .await;
    assert_eq!(r.status, StatusCode::UNAUTHORIZED);
    assert!(r.cookies().is_empty());
}

#[tokio::test]
async fn admins_create_invite_and_remove_accounts() {
    static CONFIG: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
    koan_core::config::set_config_dir(CONFIG.get_or_init(|| tempfile::tempdir().unwrap()).path());
    let f = setup(true);
    let db = Database::open(f.state.pool.path()).unwrap();
    let boss = queries::auth::create_user(&db.conn, "boss", "sesame", Role::Admin).unwrap();
    let token = |id: i64, name: &str, role: Role| {
        auth::mint_access_token(&f.state.private_pem, id, name, role, 900).unwrap()
    };
    let admin = token(boss, "boss", Role::Admin);
    let post = |uri: &str, body: &str, access: &str| {
        Request::post(uri)
            .header(header::HOST, HOST)
            .header(header::COOKIE, format!("koan_access={access}"))
            .header(header::CONTENT_TYPE, "application/json")
            .header("datastar-request", "true")
            .body(Body::from(body.to_owned()))
            .unwrap()
    };
    let page = |access: &str| {
        get("/users")
            .header(header::COOKIE, format!("koan_access={access}"))
            .body(Body::empty())
            .unwrap()
    };

    let r = send(&f.app, page(&access_token(&f.state))).await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);
    let r = send(
        &f.app,
        post("/users", r#"{"newuser":"x"}"#, &access_token(&f.state)),
    )
    .await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);
    // A token minted while alice was an admin: the account's role now governs.
    let r = send(&f.app, page(&token(1, "alice", Role::Admin))).await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);

    let r = send(&f.app, page(&admin)).await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(
        r.body.contains("alice") && r.body.contains("boss"),
        "{}",
        r.body
    );

    let r = send(
        &f.app,
        post(
            "/users",
            r#"{"newuser":"sarita","newrole":"readonly"}"#,
            &admin,
        ),
    )
    .await;
    let link = r
        .body
        .split("id=invite-link readonly value=\"")
        .nth(1)
        .and_then(|rest| rest.split('"').next())
        .unwrap_or_else(|| panic!("no link in {}", r.body))
        .replace("&amp;", "&");
    let invite = koan_core::invite::Invite::parse(&link).unwrap();
    assert_eq!(invite.server, format!("http://{HOST}"));
    assert_eq!(invite.username, "sarita");
    assert_eq!(invite.password, None);
    let password = r
        .body
        .split("<dt>Password</dt><dd><code>")
        .nth(1)
        .and_then(|rest| rest.split('<').next())
        .unwrap_or_else(|| panic!("no password in {}", r.body))
        .to_owned();
    let row = queries::auth::get_user_by_username(&db.conn, "sarita")
        .unwrap()
        .unwrap();
    assert_eq!(row.role, Role::Readonly);
    auth::verify_password(&password, &row.password_hash).unwrap();

    // The link's token is signed with this server's key and redeems for a key.
    let joined = koan_core::invite::redeem(
        &db.conn,
        &crate::auth::signing_keys().unwrap().1,
        invite.token.as_deref().unwrap(),
        "phone",
    )
    .unwrap();
    assert_eq!(joined.username, "sarita");

    // Inviting again shows no password: the server cannot read one back.
    let r = send(
        &f.app,
        post(&format!("/users/{}/invite", row.id), "{}", &admin),
    )
    .await;
    assert!(r.body.contains("id=invite-link"), "{}", r.body);
    assert!(!r.body.contains("<dt>Password</dt>"), "{}", r.body);

    // A reset does show one, and signs the account's devices out.
    let alice_link = open_link("alice");
    let r = send(&f.app, post("/users/1/invite?reset=true", "{}", &admin)).await;
    assert!(r.body.contains("<dt>Password</dt>"), "{}", r.body);
    assert_closed(alice_link);

    // So does a password the admin chooses. The row's button asks for the
    // form, and a value typed into another account's form and never
    // submitted, which Datastar posts along with it, changes nothing.
    let before = queries::auth::get_user_by_id(&db.conn, 1)
        .unwrap()
        .unwrap()
        .password_hash;
    let r = send(
        &f.app,
        post(
            "/users/1/password/form",
            r#"{"setpassword":"typed for someone else"}"#,
            &admin,
        ),
    )
    .await;
    assert!(r.body.contains("data-bind:setpassword"), "{}", r.body);
    assert!(r.body.contains(r#"{"setpassword":""}"#), "{}", r.body);
    let after = queries::auth::get_user_by_id(&db.conn, 1)
        .unwrap()
        .unwrap()
        .password_hash;
    assert_eq!(before, after);
    let r = send(
        &f.app,
        post("/users/1/password", r#"{"setpassword":"short"}"#, &admin),
    )
    .await;
    assert!(r.body.contains("at least 8"), "{}", r.body);
    let r = send(
        &f.app,
        post(
            "/users/1/password",
            r#"{"setpassword":"correct horse"}"#,
            &admin,
        ),
    )
    .await;
    assert!(r.body.contains("password is changed"), "{}", r.body);
    let alice = queries::auth::get_user_by_id(&db.conn, 1).unwrap().unwrap();
    auth::verify_password("correct horse", &alice.password_hash).unwrap();
    assert!(
        queries::api_keys::authenticate_api_key(&db.conn, &joined.api_key)
            .unwrap()
            .is_some()
    );

    let r = send(
        &f.app,
        post(&format!("/users/{}/role?role=user", row.id), "{}", &admin),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    let r = send(
        &f.app,
        post(&format!("/users/{boss}/role?role=user",), "{}", &admin),
    )
    .await;
    assert!(r.body.contains("last admin"), "{}", r.body);
    assert_eq!(
        queries::auth::get_user_by_username(&db.conn, "sarita")
            .unwrap()
            .unwrap()
            .role,
        Role::User
    );

    let r = send(&f.app, post(&format!("/users/{boss}/delete"), "{}", &admin)).await;
    assert!(r.body.contains("own account"), "{}", r.body);
    let sarita_link = open_link("sarita");
    send(
        &f.app,
        post(&format!("/users/{}/delete", row.id), "{}", &admin),
    )
    .await;
    assert!(
        queries::auth::get_user_by_username(&db.conn, "sarita")
            .unwrap()
            .is_none()
    );
    assert_closed(sarita_link);
}

/// An open koanLink for `username`, as the link route registers one.
fn open_link(
    username: &str,
) -> tokio::sync::mpsc::UnboundedReceiver<koan_core::remote::link::LinkCommand> {
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
    crate::clients::registry().register(username, "phone", "ios", "ui-tests", tx, false);
    rx
}

/// The link's session would see its channel close, which is what ends it.
fn assert_closed(
    mut rx: tokio::sync::mpsc::UnboundedReceiver<koan_core::remote::link::LinkCommand>,
) {
    while rx.try_recv().is_ok() {}
    assert!(matches!(
        rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Disconnected)
    ));
}

#[tokio::test]
async fn a_waiting_device_is_approved_from_the_pair_page() {
    let f = setup(true);
    let r = send(&f.app, get("/pair/ABCD-EFGH").body(Body::empty()).unwrap()).await;
    assert_eq!(r.location(), "/auth/resume?next=%2Fpair%2FABCD-EFGH");

    let opened = crate::pair::pairings()
        .open("Living <room> TV", "10.0.0.8".parse().unwrap())
        .unwrap();
    let typed = opened.code.to_lowercase();
    let r = send(
        &f.app,
        authed(&f.state, &format!("/pair?code={typed}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.location(), format!("/pair/{typed}"));
    let r = send(
        &f.app,
        authed(&f.state, r.location()).body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(
        r.body.contains("Sign in Living &lt;room&gt; TV?"),
        "{}",
        r.body
    );
    assert!(r.body.contains("<strong>alice</strong>"));
    assert!(r.body.contains("Requested from 10.0.0.8, on your network."));
    let far = crate::pair::pairings()
        .open("Far TV", "2001:db8::7".parse().unwrap())
        .unwrap();
    let r = send(
        &f.app,
        authed(&f.state, &format!("/pair/{}", far.code))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(
        r.body
            .contains("Requested from 2001:db8::7, from the internet."),
        "{}",
        r.body
    );
    drop(far);

    let post = |origin: &str| {
        Request::post(format!("/pair/{typed}/approve"))
            .header(header::HOST, HOST)
            .header(header::ORIGIN, origin)
            .header(
                header::COOKIE,
                format!("koan_access={}", access_token(&f.state)),
            )
            .body(Body::empty())
            .unwrap()
    };
    let r = send(&f.app, post("https://evil.test")).await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);
    let r = send(&f.app, post(ORIGIN)).await;
    assert!(r.body.contains("Signed in"), "{}", r.body);
    let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
    let keys = queries::api_keys::list_api_keys(&db.conn, Some(1)).unwrap();
    assert_eq!(keys[0].name, "Living <room> TV");

    // Settled: the code no longer names anything.
    let r = send(&f.app, post(ORIGIN)).await;
    assert!(r.body.contains("Nothing to sign in"));
    drop(opened);
}

mod oauth {
    use super::*;
    use base64::Engine as _;
    use sha2::{Digest, Sha256};

    const CALLBACK: &str = "https://claude.ai/api/mcp/auth_callback";
    const VERIFIER: &str = "a-verifier-of-at-least-forty-three-characters-long";

    fn challenge() -> String {
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(VERIFIER))
    }

    fn query(pairs: &[(&str, &str)]) -> String {
        form_urlencoded::Serializer::new(String::new())
            .extend_pairs(pairs)
            .finish()
    }

    fn json(r: &Reply) -> serde_json::Value {
        serde_json::from_str(&r.body).unwrap_or_else(|_| panic!("not JSON: {}", r.body))
    }

    async fn register(f: &Fixture, redirect: &str) -> Reply {
        send(
            &f.app,
            Request::post("/oauth/register")
                .header(header::HOST, HOST)
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(
                    serde_json::json!({ "redirect_uris": [redirect], "client_name": "Claude" })
                        .to_string(),
                ))
                .unwrap(),
        )
        .await
    }

    fn authorize_params<'a>(client_id: &'a str, challenge: &'a str) -> Vec<(&'a str, &'a str)> {
        vec![
            ("response_type", "code"),
            ("client_id", client_id),
            ("redirect_uri", CALLBACK),
            ("code_challenge", challenge),
            ("code_challenge_method", "S256"),
            ("state", "xyz"),
            ("resource", "https://koan.test/mcp"),
        ]
    }

    /// Approve as alice; the reply is the redirect to the client.
    async fn approve(f: &Fixture, params: &[(&str, &str)], origin: &str) -> Reply {
        let mut params = params.to_vec();
        params.push(("decision", "allow"));
        send(
            &f.app,
            Request::post("/oauth/authorize")
                .header(header::HOST, HOST)
                .header(header::ORIGIN, origin)
                .header(
                    header::COOKIE,
                    format!("koan_access={}", access_token(&f.state)),
                )
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from(query(&params)))
                .unwrap(),
        )
        .await
    }

    fn code_of(location: &str) -> String {
        let url = reqwest::Url::parse(location).unwrap();
        let get = |k: &str| {
            url.query_pairs()
                .find(|(n, _)| n == k)
                .map(|(_, v)| v.into_owned())
        };
        assert_eq!(get("state").as_deref(), Some("xyz"));
        assert_eq!(get("iss").as_deref(), Some(ORIGIN));
        get("code").expect("a code")
    }

    async fn token(f: &Fixture, pairs: &[(&str, &str)]) -> Reply {
        let mut req = form("/oauth/token", &query(pairs));
        req.headers_mut().remove(header::ORIGIN);
        send(&f.app, req).await
    }

    #[tokio::test]
    async fn an_mcp_client_signs_in_and_refreshes() {
        let f = setup_at(true, Some("https://koan.test/"));
        let meta = send(
            &f.app,
            get("/.well-known/oauth-authorization-server")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        assert_eq!(json(&meta)["issuer"], ORIGIN);
        let resource = send(
            &f.app,
            get(crate::ui::RESOURCE_METADATA)
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        assert_eq!(json(&resource)["resource"], "https://koan.test/mcp");

        let reg = register(&f, CALLBACK).await;
        assert_eq!(reg.status, StatusCode::CREATED);
        let client_id = json(&reg)["client_id"].as_str().unwrap().to_owned();
        let challenge = challenge();
        let params = authorize_params(&client_id, &challenge);
        let uri = format!("/oauth/authorize?{}", query(&params));

        // Signed out: through sign-in and back.
        let r = send(&f.app, get(&uri).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::SEE_OTHER);
        assert!(
            r.location()
                .starts_with("/auth/resume?next=%2Foauth%2Fauthorize")
        );

        let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::OK);
        assert!(r.body.contains("Connect kōan to claude.ai?"), "{}", r.body);
        let csp = r.headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap();
        assert!(csp.contains("form-action 'self' https://claude.ai"));
        assert!(csp.contains("frame-ancestors 'none'"));

        let r = approve(&f, &params, ORIGIN).await;
        assert_eq!(r.status, StatusCode::SEE_OTHER);
        assert!(r.location().starts_with(CALLBACK));
        let code = code_of(r.location());

        let exchange = [
            ("grant_type", "authorization_code"),
            ("code", code.as_str()),
            ("redirect_uri", CALLBACK),
            ("client_id", client_id.as_str()),
            ("code_verifier", VERIFIER),
            ("resource", "https://koan.test/mcp"),
        ];
        let r = token(&f, &exchange).await;
        assert_eq!(r.status, StatusCode::OK, "{}", r.body);
        let t = json(&r);
        // Good at /mcp and nowhere else.
        let access = t["access_token"].as_str().unwrap();
        let claims =
            auth::validate_scoped_token(&f.state.public_pem, access, Some(auth::MCP_SCOPE))
                .unwrap();
        assert_eq!(claims.username, "alice");
        assert!(auth::validate_access_token(&f.state.public_pem, access).is_err());
        let r = send(
            &f.app,
            get("/albums")
                .header(header::COOKIE, format!("koan_access={access}"))
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        assert_ne!(r.status, StatusCode::OK);
        let refresh = t["refresh_token"].as_str().unwrap().to_owned();

        let r = token(
            &f,
            &[
                ("grant_type", "refresh_token"),
                ("refresh_token", refresh.as_str()),
                ("client_id", client_id.as_str()),
            ],
        )
        .await;
        assert_eq!(r.status, StatusCode::OK, "{}", r.body);
        let refreshed = json(&r)["access_token"].as_str().unwrap().to_owned();
        assert!(auth::validate_access_token(&f.state.public_pem, &refreshed).is_err());
        let rotated = json(&r)["refresh_token"].as_str().unwrap().to_owned();

        // The code again: refused, and the grant it made is revoked.
        let r = token(&f, &exchange).await;
        assert_eq!(r.status, StatusCode::BAD_REQUEST);
        let r = token(
            &f,
            &[
                ("grant_type", "refresh_token"),
                ("refresh_token", rotated.as_str()),
            ],
        )
        .await;
        assert_eq!(r.status, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn a_redirect_uri_is_matched_as_registered_and_may_be_left_out() {
        let f = setup_at(true, Some(ORIGIN));
        // Re-serialised, this gains a trailing slash.
        let registered = "http://localhost:33418";
        let reg = register(&f, registered).await;
        let client_id = json(&reg)["client_id"].as_str().unwrap().to_owned();
        let challenge = challenge();
        for given in ["", registered] {
            let mut params = authorize_params(&client_id, &challenge);
            params[2] = ("redirect_uri", given);
            let uri = format!("/oauth/authorize?{}", query(&params));
            let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
            assert_eq!(r.status, StatusCode::OK, "{}", r.body);
            let r = approve(&f, &params, ORIGIN).await;
            assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
            let code = code_of(r.location());
            let r = token(
                &f,
                &[
                    ("grant_type", "authorization_code"),
                    ("code", code.as_str()),
                    ("redirect_uri", given),
                    ("client_id", client_id.as_str()),
                    ("code_verifier", VERIFIER),
                ],
            )
            .await;
            assert_eq!(r.status, StatusCode::OK, "{given:?}: {}", r.body);
        }
    }

    #[tokio::test]
    async fn requests_that_do_not_hold_are_refused() {
        let f = setup_at(true, Some(ORIGIN));
        assert_eq!(
            register(&f, "http://evil.example/cb").await.status,
            StatusCode::BAD_REQUEST
        );
        let client_id = json(&register(&f, CALLBACK).await)["client_id"]
            .as_str()
            .unwrap()
            .to_owned();
        let challenge = challenge();

        // Not this client's redirect, or not a client: a page, never a redirect.
        let mut params = authorize_params(&client_id, &challenge);
        params[2] = ("redirect_uri", "https://evil.example/cb");
        let uri = format!("/oauth/authorize?{}", query(&params));
        let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::BAD_REQUEST);
        assert!(!r.headers.contains_key(header::LOCATION));
        let uri = format!(
            "/oauth/authorize?{}",
            query(&authorize_params("forged", &challenge))
        );
        let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::BAD_REQUEST);

        // No PKCE: back to the client with an error.
        let mut params = authorize_params(&client_id, &challenge);
        params[4] = ("code_challenge_method", "plain");
        let uri = format!("/oauth/authorize?{}", query(&params));
        let r = send(&f.app, authed(&f.state, &uri).body(Body::empty()).unwrap()).await;
        assert!(r.location().contains("error=invalid_request"));

        // Another site's form.
        let params = authorize_params(&client_id, &challenge);
        let r = approve(&f, &params, "https://evil.example").await;
        assert_eq!(r.status, StatusCode::FORBIDDEN);

        // A wrong verifier.
        let code = code_of(approve(&f, &params, ORIGIN).await.location());
        let r = token(
            &f,
            &[
                ("grant_type", "authorization_code"),
                ("code", code.as_str()),
                ("redirect_uri", CALLBACK),
                ("client_id", client_id.as_str()),
                ("code_verifier", "not-the-verifier"),
            ],
        )
        .await;
        assert_eq!(json(&r)["error"], "invalid_grant");

        // An unknown client is told to register again.
        let r = token(
            &f,
            &[
                ("grant_type", "authorization_code"),
                ("code", code.as_str()),
                ("client_id", "forged"),
            ],
        )
        .await;
        assert_eq!(r.status, StatusCode::UNAUTHORIZED);
        assert_eq!(json(&r)["error"], "invalid_client");
    }

    #[tokio::test]
    async fn the_assistants_page_gives_the_address_once_there_is_one() {
        let f = setup_at(true, Some(ORIGIN));
        let r = send(
            &f.app,
            authed(&f.state, "/connect").body(Body::empty()).unwrap(),
        )
        .await;
        assert_eq!(r.status, StatusCode::OK);
        assert!(
            r.body.contains("value=\"https://koan.test/mcp\""),
            "{}",
            r.body
        );
        let f = setup(true);
        let r = send(
            &f.app,
            authed(&f.state, "/connect").body(Body::empty()).unwrap(),
        )
        .await;
        assert!(
            r.body.contains("needs to know its own address"),
            "{}",
            r.body
        );
    }

    #[tokio::test]
    async fn without_a_public_url_there_is_no_oauth() {
        let f = setup(true);
        for uri in [
            "/.well-known/oauth-authorization-server",
            crate::ui::RESOURCE_METADATA,
        ] {
            let r = send(&f.app, get(uri).body(Body::empty()).unwrap()).await;
            assert_eq!(r.status, StatusCode::NOT_FOUND);
        }
        assert_eq!(register(&f, CALLBACK).await.status, StatusCode::NOT_FOUND);
    }
}

#[tokio::test]
async fn the_icon_is_where_favicon_fetchers_look() {
    let f = setup(true);
    for uri in ["/favicon.ico", "/apple-touch-icon.png"] {
        let r = send(&f.app, get(uri).body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::OK, "{uri}");
        assert_eq!(r.headers[header::CONTENT_TYPE], "image/png");
    }
}

/// Behind an authenticating proxy at 10.0.0.1 that names the account in
/// `Remote-User`.
fn setup_behind_proxy() -> Fixture {
    let proxy = super::ProxyAuth::from_config("Remote-User", &["10.0.0.1".into()]).unwrap();
    setup_full(true, None, proxy)
}

fn from_peer(builder: axum::http::request::Builder, peer: &str) -> axum::http::request::Builder {
    let addr: std::net::SocketAddr = format!("{peer}:50000").parse().unwrap();
    builder.extension(axum::extract::ConnectInfo(addr))
}

#[tokio::test]
async fn the_proxy_signs_in_the_account_it_names() {
    let f = setup_behind_proxy();
    let r = send(
        &f.app,
        from_peer(get("/login?next=/artists"), "10.0.0.1")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/ui/resume?next=%2Fartists");

    let r = send(
        &f.app,
        from_peer(get("/ui/resume?next=/artists"), "10.0.0.1")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/artists");
    let access = r.cookie("koan_access");
    let claims = auth::validate_access_token(&f.state.public_pem, &access).unwrap();
    assert_eq!(claims.username, "alice");
}

#[tokio::test]
async fn page_loads_behind_the_proxy_resume_through_it() {
    let f = setup_behind_proxy();
    let r = send(
        &f.app,
        get("/oauth/authorize?x=y").body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/ui/resume?next=%2Foauth%2Fauthorize%3Fx%3Dy");

    // Without the header it falls back to the refresh cookie.
    let r = send(
        &f.app,
        get("/ui/resume?next=/queue").body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/auth/resume?next=%2Fqueue");
    assert!(r.cookies().is_empty());
}

#[tokio::test]
async fn the_header_counts_only_from_the_proxy_with_one_value() {
    let f = setup_behind_proxy();
    let stranger = from_peer(get("/ui/resume"), "203.0.113.9")
        .header("remote-user", "alice")
        .body(Body::empty())
        .unwrap();
    let unknown_peer = get("/ui/resume")
        .header("remote-user", "alice")
        .body(Body::empty())
        .unwrap();
    for req in [stranger, unknown_peer] {
        let r = send(&f.app, req).await;
        assert_eq!(r.status, StatusCode::SEE_OTHER);
        assert_eq!(r.location(), "/auth/resume?next=%2F");
        assert!(r.cookies().is_empty());
    }
    // From the proxy, a header naming no one account signs in no one, and
    // ends the browser's own session rather than falling back to it.
    for req in unusable_headers() {
        let r = send(&f.app, req.uri("/ui/resume").body(Body::empty()).unwrap()).await;
        assert_eq!(r.status, StatusCode::FORBIDDEN);
        assert_signed_out(&r);
    }
    let r = send(
        &f.app,
        from_peer(get("/login"), "203.0.113.9")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
}

/// The paths the docs tell operators to exempt from the proxy, where a
/// client's own header arrives from the proxy's address unchecked, sign in
/// no one.
///
/// Only the web UI and the auth routes are mounted here. `/rest`, `/graphql`,
/// `/mcp`, `/share` and `/push` are other routers, none of which reads the
/// header at all.
#[tokio::test]
async fn paths_exempt_from_the_proxy_ignore_the_header() {
    let f = setup_behind_proxy();
    let app = f
        .app
        .clone()
        .merge(crate::auth::routes::auth_router(f.state.clone()));
    let json = |uri: &str, body: &str| {
        from_peer(Request::post(uri), "10.0.0.1")
            .header(header::HOST, HOST)
            .header(header::ORIGIN, ORIGIN)
            .header(header::CONTENT_TYPE, "application/json")
            .header("remote-user", "alice")
            .body(Body::from(body.to_owned()))
            .unwrap()
    };
    let form = |uri: &str, body: &str| {
        from_peer(Request::post(uri), "10.0.0.1")
            .header(header::HOST, HOST)
            .header(header::ORIGIN, ORIGIN)
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .header("remote-user", "alice")
            .body(Body::from(body.to_owned()))
            .unwrap()
    };
    let page = |uri: &str| {
        from_peer(get(uri), "10.0.0.1")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap()
    };
    for req in [
        json("/auth/login", r#"{"username":"alice","password":"wrong"}"#),
        json("/auth/refresh", r#"{"refresh_token":"nope"}"#),
        json("/auth/logout", r#"{"refresh_token":"nope"}"#),
        form(
            "/oauth/token",
            "grant_type=refresh_token&refresh_token=nope",
        ),
        json(
            "/oauth/register",
            r#"{"redirect_uris":["https://claude.ai/api/mcp/auth_callback"]}"#,
        ),
        page("/auth/resume"),
        form("/auth/renew", ""),
        page("/.well-known/oauth-authorization-server"),
    ] {
        let uri = req.uri().to_string();
        let r = send(&app, req).await;
        let minted = r
            .cookies()
            .iter()
            .any(|c| c.starts_with("koan_access=") && !c.starts_with("koan_access=;"));
        assert!(!minted, "{uri} signed in: {:?}", r.cookies());
        assert!(!r.body.contains("\"access_token\":\""), "{uri}: {}", r.body);
    }
}

/// Requests from the proxy whose `Remote-User` names no one account: sent
/// twice, merged, or not text.
fn unusable_headers() -> Vec<axum::http::request::Builder> {
    let from_proxy = || from_peer(get("/"), "10.0.0.1");
    vec![
        from_proxy()
            .header("remote-user", "mallory")
            .header("remote-user", "alice"),
        from_proxy().header("remote-user", "alice, mallory"),
        from_proxy().header(
            "remote-user",
            axum::http::HeaderValue::from_bytes(b"al\xffice").unwrap(),
        ),
    ]
}

/// The reply cleared both session cookies and set no new ones.
fn assert_signed_out(r: &Reply) {
    for name in ["koan_access", "koan_refresh"] {
        assert!(
            r.cookies()
                .iter()
                .any(|c| c.starts_with(&format!("{name}=;")) && c.contains("Max-Age=0")),
            "{name} not cleared: {:?}",
            r.cookies()
        );
        assert!(
            !r.cookies()
                .iter()
                .any(|c| c.starts_with(&format!("{name}=")) && !c.starts_with(&format!("{name}=;"))),
            "{name} set: {:?}",
            r.cookies()
        );
    }
}

#[tokio::test]
async fn an_account_the_server_lacks_is_refused() {
    let f = setup_behind_proxy();
    let r = send(
        &f.app,
        from_peer(get("/ui/resume"), "10.0.0.1")
            .header("remote-user", "bob")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);
    assert_signed_out(&r);
}

#[tokio::test]
async fn an_account_named_in_utf8_signs_in() {
    let f = setup_behind_proxy();
    {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        queries::auth::create_user(&db.conn, "josé", "pw", Role::User).unwrap();
    }
    let r = send(
        &f.app,
        from_peer(get("/ui/resume"), "10.0.0.1")
            .header(
                "remote-user",
                axum::http::HeaderValue::from_bytes("josé".as_bytes()).unwrap(),
            )
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    let claims =
        auth::validate_access_token(&f.state.public_pem, &r.cookie("koan_access")).unwrap();
    assert_eq!(claims.username, "josé");
}

#[tokio::test]
async fn a_header_from_the_proxy_naming_no_one_lets_no_session_through() {
    let f = setup_behind_proxy();
    for req in unusable_headers() {
        let r = send(
            &f.app,
            req.uri("/albums")
                .header(
                    header::COOKIE,
                    format!("koan_access={}", access_token(&f.state)),
                )
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        assert_eq!(r.status, StatusCode::FORBIDDEN);
        assert_signed_out(&r);
    }
    for req in unusable_headers() {
        let r = send(
            &f.app,
            req.method("POST")
                .uri("/ui/renew")
                .header(header::ORIGIN, ORIGIN)
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        assert_eq!(r.status, StatusCode::FORBIDDEN);
        assert_signed_out(&r);
    }
}

/// The comparison with the proxy's account holds for script requests too, not
/// only page loads.
#[tokio::test]
async fn a_script_request_for_another_account_than_the_proxy_names_is_refused() {
    let f = setup_behind_proxy();
    let post = |user: &str| {
        from_peer(Request::post("/history/forget"), "10.0.0.1")
            .header(header::HOST, HOST)
            .header(header::ORIGIN, ORIGIN)
            .header("datastar-request", "true")
            .header(
                header::COOKIE,
                format!("koan_access={}", access_token(&f.state)),
            )
            .header("remote-user", user)
            .body(Body::empty())
            .unwrap()
    };
    assert_eq!(
        send(&f.app, post("bob")).await.status,
        StatusCode::UNAUTHORIZED
    );
    assert_ne!(
        send(&f.app, post("alice")).await.status,
        StatusCode::UNAUTHORIZED
    );
}

#[tokio::test]
async fn a_session_for_another_account_than_the_proxy_names_is_resumed() {
    let f = setup_behind_proxy();
    let r = send(
        &f.app,
        from_peer(authed(&f.state, "/albums"), "10.0.0.1")
            .header("remote-user", "bob")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::SEE_OTHER);
    assert_eq!(r.location(), "/ui/resume?next=%2Falbums");

    let r = send(
        &f.app,
        from_peer(authed(&f.state, "/albums"), "10.0.0.1")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
}

/// Every way a browser through the proxy gets a session.
fn proxied_requests(user: &str) -> Vec<Request<Body>> {
    let from_proxy = |req: axum::http::request::Builder| {
        from_peer(req, "10.0.0.1")
            .header(header::HOST, HOST)
            .header(header::ORIGIN, ORIGIN)
            .header("remote-user", user)
    };
    vec![
        from_proxy(Request::get("/ui/resume?next=%2Falbums"))
            .body(Body::empty())
            .unwrap(),
        from_proxy(Request::get("/login"))
            .body(Body::empty())
            .unwrap(),
        from_proxy(Request::post("/login"))
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(Body::from("username=alice&password=hunter2"))
            .unwrap(),
        from_proxy(Request::post("/ui/renew"))
            .body(Body::empty())
            .unwrap(),
    ]
}

fn refresh_tokens(f: &Fixture) -> i64 {
    let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
    db.conn
        .query_row("SELECT COUNT(*) FROM refresh_tokens", [], |r| r.get(0))
        .unwrap()
}

/// A session through the proxy is an access token alone, derived again from
/// the header on each page load: nothing outlives what the proxy says.
#[tokio::test]
async fn no_refresh_cookie_is_issued_through_the_proxy() {
    let f = setup_behind_proxy();
    for req in proxied_requests("alice") {
        let uri = req.uri().clone();
        let r = send(&f.app, req).await;
        assert!(
            !r.cookies()
                .iter()
                .any(|c| c.starts_with("koan_refresh=") && !c.starts_with("koan_refresh=;")),
            "{uri} set a refresh cookie: {:?}",
            r.cookies()
        );
    }
    assert_eq!(refresh_tokens(&f), 0, "no refresh token stored");
}

/// The proxy switching the browser from alice to bob ends alice's access
/// within one access token's lifetime: her session is the access token the
/// proxy's say-so minted, and nothing renews it once the proxy names bob.
#[tokio::test]
async fn a_switch_at_the_proxy_ends_the_previous_account_within_one_access_ttl() {
    let f = setup_behind_proxy();
    {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        queries::auth::create_user(&db.conn, "bob", "pw", Role::User).unwrap();
    }
    let resume = |user: &str| {
        from_peer(get("/ui/resume?next=%2Falbums"), "10.0.0.1")
            .header("remote-user", user)
            .body(Body::empty())
            .unwrap()
    };
    let alice = send(&f.app, resume("alice")).await.cookie("koan_access");
    let claims = auth::validate_access_token(&f.state.public_pem, &alice).unwrap();
    assert!(claims.exp - claims.iat <= f.state.access_ttl_secs);

    // Alice's cookie, the proxy now naming bob: a page load hands over, and
    // neither it nor a renewal gives alice anything more.
    let page = send(
        &f.app,
        from_peer(get("/albums"), "10.0.0.1")
            .header(header::COOKIE, format!("koan_access={alice}"))
            .header("remote-user", "bob")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(page.location(), "/ui/resume?next=%2Falbums");
    for req in [resume("bob")]
        .into_iter()
        .chain(proxied_requests("bob").into_iter().skip(3))
    {
        let r = send(&f.app, req).await;
        let access = r.cookie("koan_access");
        let claims = auth::validate_access_token(&f.state.public_pem, &access).unwrap();
        assert_eq!(claims.username, "bob");
    }
    assert_eq!(refresh_tokens(&f), 0, "nothing to renew alice with");
}

#[tokio::test]
async fn a_cross_site_renewal_through_the_proxy_is_refused() {
    let f = setup_behind_proxy();
    let r = send(
        &f.app,
        from_peer(Request::post("/ui/renew"), "10.0.0.1")
            .header(header::HOST, HOST)
            .header(header::ORIGIN, "https://evil.example")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::FORBIDDEN);
    assert!(r.cookies().is_empty());
}

/// Pages behind the proxy tell the script to renew from the proxy first, so a
/// refresh cookie from before proxy mode cannot keep a session going.
#[tokio::test]
async fn pages_say_when_the_proxy_renews_them() {
    let f = setup_behind_proxy();
    let r = send(
        &f.app,
        from_peer(authed(&f.state, "/albums"), "10.0.0.1")
            .header("remote-user", "alice")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.contains("<body data-proxied>"));

    let f = setup(true);
    let r = send(
        &f.app,
        authed(&f.state, "/albums").body(Body::empty()).unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(!r.body.contains("data-proxied"));
}

/// Off the proxy, a password sign-in keeps its refresh cookie.
#[tokio::test]
async fn a_password_sign_in_off_the_proxy_still_refreshes() {
    let f = setup_behind_proxy();
    let r = send(&f.app, form("/login", "username=alice&password=hunter2")).await;
    assert!(!r.cookie("koan_refresh").is_empty());
}

#[test]
fn proxy_auth_is_off_unless_configured() {
    assert!(super::ProxyAuth::from_config("", &[]).unwrap().is_none());
    assert!(super::ProxyAuth::from_config("  ", &[]).unwrap().is_none());
}

#[test]
fn a_proxy_header_without_a_proxy_is_refused() {
    let err = super::ProxyAuth::from_config("Remote-User", &[])
        .err()
        .unwrap();
    assert!(err.contains("proxy_auth_from is empty"), "{err}");
}

#[test]
fn a_proxy_without_a_header_is_refused() {
    let err = super::ProxyAuth::from_config("", &["10.0.0.1".into()])
        .err()
        .unwrap();
    assert!(err.contains("proxy_auth_header is empty"), "{err}");
}

#[test]
fn a_proxy_range_covering_every_address_is_refused() {
    for everyone in ["0.0.0.0/0", "::/0"] {
        let err =
            super::ProxyAuth::from_config("Remote-User", &["10.0.0.1".into(), everyone.into()])
                .err()
                .unwrap();
        assert!(err.contains("covers every address"), "{everyone}: {err}");
    }
}

#[test]
fn a_bad_proxy_setting_is_refused_not_dropped() {
    use super::ProxyAuth;
    assert!(ProxyAuth::from_config("Remote User", &["10.0.0.1".into()]).is_err());
    assert!(ProxyAuth::from_config("Remote-User", &["not an address".into()]).is_err());
    assert!(
        ProxyAuth::from_config("Remote-User", &["junk".into(), "172.18.0.0/16".into()]).is_err()
    );
}

/// An entry written as an IPv4-mapped IPv6 address matches the IPv4 peer it
/// maps, as the peer is compared in that form.
#[test]
fn a_mapped_proxy_entry_is_its_ipv4_address() {
    let proxy = super::ProxyAuth::from_config("Remote-User", &["::ffff:172.18.0.5".into()])
        .unwrap()
        .unwrap();
    let mut headers = HeaderMap::new();
    headers.insert("remote-user", "alice".parse().unwrap());
    let mut ext = axum::http::Extensions::new();
    ext.insert(axum::extract::ConnectInfo(
        "172.18.0.5:1".parse::<std::net::SocketAddr>().unwrap(),
    ));
    assert_eq!(
        proxy.user(&headers, &ext),
        super::session::Vouch::Named("alice")
    );
}

#[test]
fn proxy_auth_believes_one_header_from_the_proxy() {
    use super::ProxyAuth;
    let proxy = ProxyAuth::from_config("Remote-User", &["172.18.0.0/16".into()])
        .unwrap()
        .unwrap();
    let mut headers = HeaderMap::new();
    headers.insert("remote-user", "alice".parse().unwrap());
    let at = |peer: &str| {
        let mut ext = axum::http::Extensions::new();
        ext.insert(axum::extract::ConnectInfo(
            peer.parse::<std::net::SocketAddr>().unwrap(),
        ));
        ext
    };
    use super::session::Vouch;
    assert_eq!(
        proxy.user(&headers, &at("172.18.0.5:1")),
        Vouch::Named("alice")
    );
    assert_eq!(
        proxy.user(&headers, &at("[::ffff:172.18.0.5]:1")),
        Vouch::Named("alice")
    );
    assert_eq!(proxy.user(&headers, &at("172.19.0.5:1")), Vouch::Absent);
    headers.insert("remote-user", "alice,admin".parse().unwrap());
    assert_eq!(proxy.user(&headers, &at("172.18.0.5:1")), Vouch::Unusable);
    assert_eq!(proxy.user(&headers, &at("172.19.0.5:1")), Vouch::Absent);
}

#[tokio::test]
async fn hearts_favourite_for_the_caller_and_redraw_every_copy() {
    let f = setup(true);
    let (bob, viewer) = {
        let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
        let bob = queries::auth::create_user(&db.conn, "bob", "hunter3", Role::User).unwrap();
        let viewer =
            queries::auth::create_user(&db.conn, "viewer", "hunter4", Role::Readonly).unwrap();
        (bob, viewer)
    };
    let as_user = |id: i64, name: &str, role: Role| {
        format!(
            "koan_access={}",
            auth::mint_access_token(&f.state.private_pem, id, name, role, 900).unwrap()
        )
    };
    let toggle = |cookie: String, uri: String| {
        Request::post(uri)
            .header(header::HOST, HOST)
            .header(header::COOKIE, cookie)
            .header("datastar-request", "true")
            .body(Body::empty())
            .unwrap()
    };
    let song = format!("data-fav=\"song-{}\"", f.track_id);
    let album_page = format!("/album/{}", f.album_id);

    let r = send(
        &f.app,
        authed(&f.state, &album_page).body(Body::empty()).unwrap(),
    )
    .await;
    assert!(r.body.contains(&format!("{song} aria-pressed=\"false\"")));

    let r = send(
        &f.app,
        toggle(
            as_user(1, "alice", Role::User),
            format!("/favourite/song/{}?on=1", f.track_id),
        ),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    assert!(r.body.contains("datastar-patch-elements"));
    assert!(r.body.contains(&format!("{song} aria-pressed=\"true\"")));
    let r = send(
        &f.app,
        toggle(
            as_user(1, "alice", Role::User),
            format!("/favourite/album/{}?on=1", f.album_id),
        ),
    )
    .await;
    assert!(r.body.contains(&format!(
        "data-fav=\"album-{}\" aria-pressed=\"true\"",
        f.album_id
    )));

    let db = Database::open(&f.dir.path().join("koan.db")).unwrap();
    assert!(
        queries::load_favourites(&db.conn, 1)
            .unwrap()
            .contains(&f.track_id)
    );
    assert!(
        queries::favourite_album_id_set(&db.conn, 1)
            .unwrap()
            .contains(&f.album_id)
    );
    assert!(
        queries::load_favourites(&db.conn, bob).unwrap().is_empty(),
        "alice's only"
    );

    let r = send(
        &f.app,
        authed(&f.state, &album_page).body(Body::empty()).unwrap(),
    )
    .await;
    assert!(
        r.body.contains(&format!("{song} aria-pressed=\"true\"")),
        "drawn on reload"
    );
    let r = send(
        &f.app,
        get(&album_page)
            .header(header::COOKIE, as_user(bob, "bob", Role::User))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(
        r.body.contains(&format!("{song} aria-pressed=\"false\"")),
        "bob's are his own"
    );

    // A read-only account is drawn no hearts, and its toggles change nothing.
    let r = send(
        &f.app,
        get(&album_page)
            .header(header::COOKIE, as_user(viewer, "viewer", Role::Readonly))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(!r.body.contains("data-fav="));
    send(
        &f.app,
        toggle(
            as_user(viewer, "viewer", Role::Readonly),
            format!("/favourite/song/{}?on=1", f.track_id),
        ),
    )
    .await;
    assert!(
        queries::load_favourites(&db.conn, viewer)
            .unwrap()
            .is_empty()
    );

    let r = send(
        &f.app,
        toggle(
            as_user(1, "alice", Role::User),
            format!("/favourite/song/{}?on=0", f.track_id),
        ),
    )
    .await;
    assert!(r.body.contains(&format!("{song} aria-pressed=\"false\"")));
    assert!(queries::load_favourites(&db.conn, 1).unwrap().is_empty());
}

#[tokio::test]
async fn track_rows_carry_what_the_track_menu_needs() {
    let f = setup(true);
    let r = send(
        &f.app,
        authed(&f.state, &format!("/album/{}", f.album_id))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert!(
        r.body.contains("<div id=track-menu popover"),
        "the shell's one menu"
    );
    let row = r
        .body
        .split("<li tabindex=0 data-id=")
        .nth(1)
        .expect("a track row");
    let row = &row[..row.find("</li>").unwrap()];
    assert!(row.contains(&format!("data-album-id={}", f.album_id)));
    assert!(row.contains("data-artist-id="), "for Go to Artist");
    assert!(row.contains("data-act=menu"), "the phone's way in");
    assert!(row.contains("data-fav="), "the heart the menu presses");
    assert!(row.contains("data-act-share"), "the share the menu presses");
}

#[tokio::test]
async fn a_spent_username_budget_refuses_strangers_but_not_the_accounts_network() {
    let f = setup(true);
    let from = |ip: [u8; 4]| {
        let mut req = form("/login", "username=alice&password=hunter2");
        req.extensions_mut()
            .insert(axum::extract::ConnectInfo(std::net::SocketAddr::from((
                ip, 1234,
            ))));
        req
    };
    let home = [198, 51, 100, 4];
    assert_eq!(send(&f.app, from(home)).await.status, StatusCode::SEE_OTHER);
    // Spent by guesses from elsewhere.
    for _ in 0..crate::auth::password::FAILURES_PER_USERNAME_PER_MINUTE {
        f.state.users.failed("alice");
    }
    let r = send(&f.app, from([203, 0, 113, 9])).await;
    assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
    assert!(
        r.body
            .contains("Too many failed sign-ins for this account.")
    );
    assert!(r.cookies().is_empty());
    // The network alice signed in from still signs in.
    assert_eq!(send(&f.app, from(home)).await.status, StatusCode::SEE_OTHER);
}

#[tokio::test]
async fn a_username_reaches_the_delete_confirmation_as_data() {
    let f = setup(true);
    let db = Database::open(f.state.pool.path()).unwrap();
    let boss = queries::auth::create_user(&db.conn, "boss", "sesame", Role::Admin).unwrap();
    queries::auth::create_user(&db.conn, "x');alert(1)//", "sesame", Role::User).unwrap();
    let admin =
        auth::mint_access_token(&f.state.private_pem, boss, "boss", Role::Admin, 900).unwrap();
    let r = send(
        &f.app,
        get("/users")
            .header(header::COOKIE, format!("koan_access={admin}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(r.status, StatusCode::OK);
    let button = r
        .body
        .split("<button")
        .find(|b| b.contains("data-username=\"x&#39;);alert(1)//\""))
        .unwrap_or_else(|| panic!("{}", r.body));
    let expression = button
        .split("data-on:click=\"")
        .nth(1)
        .and_then(|rest| rest.split('"').next())
        .unwrap();
    assert!(expression.contains("/delete')"), "{expression}");
    assert!(!expression.contains("alert"), "{expression}");
}