defter 0.5.3

Self-hosted Zotero sync and file storage server, with metadata in SQLite and attachments in S3.
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
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
//! End-to-end tests of the HTTP API: the router over a temporary database and
//! in-memory object storage.

use std::collections::HashMap;
use std::io::Write;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use axum::{
    Router,
    body::Body,
    http::{Request, StatusCode, header},
    response::Response,
};
use serde_json::{Value, json};
use tower::ServiceExt;

use crate::app::{self, App, Config};
use crate::auth::{Access, Keys};
use crate::control::Control;
use crate::db::Db;
use crate::registry::{self, Libraries};
use crate::storage::{Backend, Storage};

const RW: &str = "rw-key";
const RO: &str = "ro-key";
const PUBLIC: &str = "http://defter.test";

const ORCID: &str = "0000-0003-1419-2405";

struct Server {
    router: Router,
    app: app::AppState,
    _dir: tempfile::TempDir,
    _owner: std::sync::Arc<Db>,
}

async fn server() -> Server {
    server_with_orcid(None).await
}

async fn server_with_orcid(orcid: Option<&str>) -> Server {
    server_with(orcid, None).await
}

async fn server_with(orcid: Option<&str>, oidc: Option<crate::oidc::OidcConfig>) -> Server {
    server_configured(orcid, oidc, true).await
}

async fn server_configured(
    orcid: Option<&str>,
    oidc: Option<crate::oidc::OidcConfig>,
    key_login: bool,
) -> Server {
    server_admins(orcid, oidc, key_login, &[]).await
}

/// The default storage quota of the test servers.
const QUOTA: u64 = 1024 * 1024;

async fn server_admins(
    orcid: Option<&str>,
    oidc: Option<crate::oidc::OidcConfig>,
    key_login: bool,
    admins: &[&str],
) -> Server {
    let dir = tempfile::tempdir().unwrap();
    let control = Arc::new(Control::open(&dir.path().join("control.sqlite3")).unwrap());
    control
        .ensure_owner(registry::owner(1, "tester", false))
        .await
        .unwrap();
    let libraries = Libraries::new(dir.path().join("libraries"), control.clone(), 150);
    let storage = Storage::new(&Backend::Memory, Duration::from_secs(60), false).unwrap();
    let keys = Keys::new(HashMap::from([
        (RW.to_string(), Access { write: true }),
        (RO.to_string(), Access { write: false }),
    ]))
    .unwrap();
    let cfg = Config {
        user_id: 1,
        username: "tester".into(),
        public_url: PUBLIC.into(),
        login_authorized_user: None,
        max_upload: 1024 * 1024,
        schema_url: "http://127.0.0.1:9/unreachable".into(),
        orcid: orcid.map(String::from),
        oidc,
        key_login,
        admin_orcids: admins.iter().map(|a| a.to_string()).collect(),
        default_quota: QUOTA,
    };
    let app = App::new(cfg, control, libraries, storage, keys)
        .await
        .unwrap();
    // The owner's library, held so it stays the one the server has open.
    let db = app.owner_library().await.unwrap().db.clone();
    Server {
        router: app::router(app.clone()),
        app,
        _dir: dir,
        _owner: db,
    }
}

impl Server {
    async fn send(&self, req: Request<Body>) -> Response {
        self.router.clone().oneshot(req).await.unwrap()
    }

    async fn call(
        &self,
        method: &str,
        uri: &str,
        key: Option<&str>,
        headers: &[(&str, &str)],
        body: Body,
    ) -> Response {
        let mut req = Request::builder().method(method).uri(uri);
        if let Some(key) = key {
            req = req.header("zotero-api-key", key);
        }
        for (name, value) in headers {
            req = req.header(*name, *value);
        }
        self.send(req.body(body).unwrap()).await
    }

    async fn get(&self, uri: &str) -> Response {
        self.call("GET", uri, Some(RW), &[], Body::empty()).await
    }

    async fn json(
        &self,
        method: &str,
        uri: &str,
        headers: &[(&str, &str)],
        body: Value,
    ) -> Response {
        let mut all = vec![("content-type", "application/json")];
        all.extend_from_slice(headers);
        self.call(method, uri, Some(RW), &all, Body::from(body.to_string()))
            .await
    }

    async fn form(&self, uri: &str, headers: &[(&str, &str)], form: &[(&str, &str)]) -> Response {
        let mut all = vec![("content-type", "application/x-www-form-urlencoded")];
        all.extend_from_slice(headers);
        let body = serde_urlencoded::to_string(form).unwrap();
        self.call("POST", uri, Some(RW), &all, Body::from(body))
            .await
    }
}

async fn body_json(resp: Response) -> Value {
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    serde_json::from_slice(&bytes)
        .unwrap_or_else(|_| panic!("not JSON: {}", String::from_utf8_lossy(&bytes)))
}

async fn body_text(resp: Response) -> String {
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    String::from_utf8_lossy(&bytes).into_owned()
}

fn header_str<'a>(resp: &'a Response, name: &str) -> &'a str {
    resp.headers()
        .get(name)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
}

fn gzip(value: &Value) -> Vec<u8> {
    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
    encoder.write_all(value.to_string().as_bytes()).unwrap();
    encoder.finish().unwrap()
}

#[tokio::test]
async fn the_api_root_identifies_the_server() {
    let s = server().await;
    for uri in ["/api", "/api/"] {
        let resp = s.call("GET", uri, None, &[], Body::empty()).await;
        assert_eq!(resp.status(), StatusCode::OK, "{uri}");
        assert_eq!(header_str(&resp, "zotero-server-id").len(), 32, "{uri}");
    }
    // The dashboard needs signing in, but still names the server.
    let resp = s.call("GET", "/", None, &[], Body::empty()).await;
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(header_str(&resp, "zotero-server-id").len(), 32);
}

/// Sign in to the web UI with `key`; returns the response.
async fn sign_in(s: &Server, key: &str, origin: &str) -> Response {
    let form = serde_urlencoded::to_string([("key", key)]).unwrap();
    s.call(
        "POST",
        "/ui/session",
        None,
        &[
            ("content-type", "application/x-www-form-urlencoded"),
            ("origin", origin),
        ],
        Body::from(form),
    )
    .await
}

/// The `name=value` of the session cookie a sign-in set.
fn session_cookie(resp: &Response) -> String {
    header_str(resp, "set-cookie")
        .split(';')
        .next()
        .unwrap()
        .to_string()
}

/// A signed-in session's cookie header.
async fn signed_in(s: &Server) -> String {
    let resp = sign_in(s, RO, PUBLIC).await;
    assert_eq!(resp.status(), StatusCode::SEE_OTHER);
    session_cookie(&resp)
}

#[tokio::test]
async fn pages_say_what_they_are_built_with() {
    let s = profile_server().await;
    for (uri, accept, built_with, tagline) in [
        ("/".to_string(), "en", "Built with", "Self-hosted"),
        (format!("/{ORCID}"), "en", "Built with", "Self-hosted"),
        (
            format!("/{ORCID}"),
            "de",
            "Erstellt mit",
            "Selbst gehostete",
        ),
    ] {
        let page = s
            .call(
                "GET",
                &uri,
                None,
                &[("accept-language", accept)],
                Body::empty(),
            )
            .await;
        let html = body_text(page).await;
        // The tagline is in the header, not the footer.
        let (header, footer) = html.split_once("<footer").unwrap();
        assert!(header.contains(tagline), "{uri}");
        assert!(!footer.contains(tagline), "{uri}");
        for shown in [
            built_with,
            "https://crates.io/crates/defter",
            "https://front-matter.de",
            "https://opensource.org/license/mit",
            "mailto:info@front-matter.de",
            "https://hachyderm.io/@mfenner",
        ] {
            assert!(html.contains(shown), "{shown} missing from {uri}");
        }
    }
}

#[tokio::test]
async fn the_dashboard_needs_an_api_key() {
    let s = server().await;
    // Without a session: the sign-in page, nothing about the instance.
    let page = s.call("GET", "/", None, &[], Body::empty()).await;
    assert_eq!(page.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(header_str(&page, "cache-control"), "no-store");
    let html = body_text(page).await;
    assert!(html.contains(r#"<form method="post" action="/ui/session""#));
    for secret in ["memory://", "Connect Zotero", "Library version", "Sign out"] {
        assert!(!html.contains(secret), "{secret} shown without signing in");
    }
    let status = s.call("GET", "/ui/status", None, &[], Body::empty()).await;
    assert_eq!(status.status(), StatusCode::UNAUTHORIZED);
    // htmx's poll after the session ended reloads the page.
    let poll = s
        .call("GET", "/", None, &[("hx-request", "true")], Body::empty())
        .await;
    assert_eq!(poll.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(header_str(&poll, "hx-refresh"), "true");

    // Wrong keys and foreign sites are turned away, without a cookie.
    let wrong = sign_in(&s, "guess", PUBLIC).await;
    assert_eq!(wrong.status(), StatusCode::FORBIDDEN);
    assert!(header_str(&wrong, "set-cookie").is_empty());
    assert!(body_text(wrong).await.contains("not an API key"));
    let foreign = sign_in(&s, RW, "https://evil.example").await;
    assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
    assert!(header_str(&foreign, "set-cookie").is_empty());

    // Any key signs in, read-only included; the cookie is HttpOnly.
    let ok = sign_in(&s, RO, PUBLIC).await;
    assert_eq!(ok.status(), StatusCode::SEE_OTHER);
    assert_eq!(header_str(&ok, "location"), "/");
    let set_cookie = header_str(&ok, "set-cookie").to_string();
    assert!(set_cookie.starts_with("defter_session="), "{set_cookie}");
    for attribute in ["HttpOnly", "SameSite=Lax", "Path=/"] {
        assert!(set_cookie.contains(attribute), "{set_cookie}");
    }
    let cookie = session_cookie(&ok);
    let page = s
        .call("GET", "/", None, &[("cookie", &cookie)], Body::empty())
        .await;
    assert_eq!(page.status(), StatusCode::OK);
    let html = body_text(page).await;
    assert!(html.contains("Connect Zotero"));
    assert!(html.contains(r#"<form method="post" action="/ui/logout">"#));

    // /ui/status takes the session or an API key.
    for headers in [
        vec![("cookie", cookie.as_str())],
        vec![("zotero-api-key", RO)],
    ] {
        let status = s
            .call("GET", "/ui/status", None, &headers, Body::empty())
            .await;
        assert_eq!(status.status(), StatusCode::OK);
        assert_eq!(body_json(status).await["name"], "defter");
    }

    // Signing out ends the session and clears the cookie.
    let out = s
        .call(
            "POST",
            "/ui/logout",
            None,
            &[("cookie", &cookie), ("origin", PUBLIC)],
            Body::empty(),
        )
        .await;
    assert_eq!(out.status(), StatusCode::SEE_OTHER);
    assert!(header_str(&out, "set-cookie").contains("Max-Age=0"));
    let after = s
        .call("GET", "/", None, &[("cookie", &cookie)], Body::empty())
        .await;
    assert_eq!(after.status(), StatusCode::UNAUTHORIZED);
}

/// A server with an owner's ORCID record already fetched, and a library of two
/// works in My Publications and two works that are not public.
async fn profile_server() -> Server {
    let s = server_with_orcid(Some(ORCID)).await;
    s.app.person.set(
        ORCID,
        serde_json::from_value(json!({
            "given_name": "Ada",
            "family_name": "Example",
            "description": "<b>First</b> paragraph.",
            "country": "DE",
            "affiliations": [{"name": "Front Matter", "role": "Founder"}],
        }))
        .unwrap(),
    );
    let resp = s
        .json(
            "POST",
            "/users/1/items",
            &[("if-unmodified-since-version", "0")],
            json!([
                {"key": "ARTICLEA", "itemType": "journalArticle", "title": "Article work",
                 "date": "2020", "DOI": "10.1234/article", "inPublications": true,
                 "abstractNote": "The abstract.", "language": "en", "rights": "CC BY 4.0",
                 "creators": [{"firstName": "Ada", "lastName": "Author", "creatorType": "author"}],
                 "tags": [{"tag": "secret tag"}]},
                {"key": "BLGPSTAA", "itemType": "blogPost", "title": "Blog work",
                 "date": "2021-05-01", "inPublications": true, "tags": [{"tag": "Featured"}]},
                {"key": "LIBRARYA", "itemType": "book", "title": "Library work", "date": "1999"},
                {"key": "PDFWEBAA", "itemType": "attachment", "parentItem": "ARTICLEA",
                 "linkMode": "imported_url", "contentType": "application/pdf",
                 "url": "https://publisher.example/article.pdf", "filename": "article.pdf"},
                {"key": "PDFSTRGE", "itemType": "attachment", "parentItem": "BLGPSTAA",
                 "linkMode": "imported_url", "contentType": "application/pdf",
                 "url": "https://zotero.fsn1.your-objectstorage.com/blog.pdf"},
                {"key": "PDFDISKA", "itemType": "attachment", "parentItem": "BLGPSTAA",
                 "linkMode": "imported_file", "contentType": "application/pdf",
                 "filename": "blog.pdf"},
                {"key": "PDFPRIVA", "itemType": "attachment", "parentItem": "LIBRARYA",
                 "linkMode": "imported_url", "contentType": "application/pdf",
                 "url": "https://private.example/library.pdf"},
                {"key": "TRASHEDA", "itemType": "book", "title": "Trashed work", "date": "1998",
                 "inPublications": true, "deleted": 1},
            ]),
        )
        .await;
    assert_eq!(resp.status(), StatusCode::OK);
    // An item with an invalid key is only refused here, and a test of it would
    // pass for nothing.
    let body = body_json(resp).await;
    assert_eq!(body["failed"], json!({}), "{body}");
    s
}

async fn visit(s: &Server, uri: &str) -> Response {
    s.call("GET", uri, None, &[], Body::empty()).await
}

#[tokio::test]
async fn the_public_profile_shows_my_publications() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}");
    let page = visit(&s, &format!("{uri}?featured=0")).await;
    assert_eq!(page.status(), StatusCode::OK);
    assert!(!header_str(&page, "content-security-policy").is_empty());
    let html = body_text(page).await;
    for shown in [
        r#"<html lang="en">"#,
        "Ada Example",
        "Germany",
        "Founder",
        "Article work",
        "Blog work",
        "The abstract.",
        "May 1, 2021",
        "English",
        "CC BY 4.0",
        "https://doi.org/10.1234/article",
        "https://publisher.example/article.pdf",
        // What a copy button asks for.
        r#"data-copy-work="ARTICLEA""#,
        // The biography is text, not markup.
        "&#60;b&#62;First",
    ] {
        assert!(html.contains(shown), "{shown} missing from {html}");
    }
    for hidden in [
        "Library work",
        "Trashed work",
        // Their years are not offered either.
        ">1999<",
        ">1998<",
        "secret tag",
        "noindex",
        "Sign out",
        "commonmeta.org",
        // Stored copies and what is not public are not linked.
        "your-objectstorage.com",
        "blog.pdf",
        "private.example",
        "/file",
        // Titles are not links.
        r#"noreferrer" class="hover:underline">Article work"#,
    ] {
        assert!(!html.contains(hidden), "{hidden} shown");
    }

    // Nothing else lives at the root or at the old address, and the data API
    // still needs a key.
    for other in [
        "/0000-0002-1825-0097".to_string(),
        "/nonsense".to_string(),
        format!("/users/{ORCID}"),
    ] {
        let resp = visit(&s, &other).await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{other}");
    }
    let items = visit(&s, "/users/1/items").await;
    assert_eq!(items.status(), StatusCode::FORBIDDEN);
    assert_eq!(visit(&s, "/api").await.status(), StatusCode::OK);
    // No profile without an iD configured.
    let none = server().await;
    assert_eq!(visit(&none, &uri).await.status(), StatusCode::NOT_FOUND);
}

/// Whether the profile offers a link with this in its query.
async fn html_has_facet(s: &Server, uri: &str, query: &str, path: &str) -> bool {
    let html = body_text(visit(s, uri).await).await;
    html.contains(&format!("{path}?{query}"))
}

#[tokio::test]
async fn the_public_profile_narrows_works_by_facets_and_search() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}");
    let html = body_text(visit(&s, &format!("{uri}?featured=0")).await).await;
    // Each value is a link that picks it.
    assert!(html.contains(&format!("{uri}?year=2020")), "{html}");
    assert!(html.contains(&format!("{uri}?type=blogPost")));

    let html = body_text(visit(&s, &format!("{uri}?type=blogPost")).await).await;
    assert!(html.contains("Blog work"));
    assert!(!html.contains("Article work"));
    // The picked value clears itself, to all works, another one adds to it.
    assert!(
        html.contains(&format!(r#"href="{uri}?featured=0" aria-current="true""#)),
        "{html}"
    );
    assert!(html.contains(&format!("{uri}?year=2020&#38;type=blogPost")));

    // Values of a facet are ORed, the facets ANDed.
    let html = body_text(visit(&s, &format!("{uri}?year=2020&year=2021")).await).await;
    assert!(html.contains("Article work") && html.contains("Blog work"));
    let html = body_text(visit(&s, &format!("{uri}?year=2020&type=blogPost")).await).await;
    assert!(html.contains("0 works"));
    assert!(html.contains("No results found"));

    // Search keeps the facets, and shows what it looked for.
    let html = body_text(visit(&s, &format!("{uri}?q=BLOG")).await).await;
    assert!(html.contains("Blog work"));
    assert!(!html.contains("Article work"));
    assert!(html.contains(r#"value="BLOG""#), "{html}");
    assert!(html.contains(&format!("{uri}?q=BLOG&#38;year=2021")));

    // Works with a PDF link: not one that only has a stored copy.
    assert!(html_has_facet(&s, &format!("{uri}?featured=0"), "content=pdf", &uri).await);
    let html = body_text(visit(&s, &format!("{uri}?content=pdf")).await).await;
    assert!(html.contains("Article work"));
    assert!(!html.contains("Blog work"));
    assert!(html.contains(r#"<input type="hidden" name="content" value="pdf">"#));
    let ris = body_text(visit(&s, &format!("/{ORCID}/export?format=ris&content=pdf")).await).await;
    assert!(
        ris.contains("Article work") && !ris.contains("Blog work"),
        "{ris}"
    );

    // Featured only.
    let html = body_text(visit(&s, &format!("{uri}?featured=1")).await).await;
    assert!(html.contains("Blog work"));
    assert!(!html.contains("Article work"));
    assert!(html.contains("Featured only"));
    assert!(html.contains(&format!(r#"href="{uri}?featured=0" aria-current="true""#)));
    // It does not reach what stays private.
    for q in ["secret", "Library", "abstract"] {
        let html = body_text(visit(&s, &format!("{uri}?q={q}")).await).await;
        assert!(html.contains("0 works"), "{q}");
    }

    // Works outside My Publications cannot be reached by a filter.
    let html = body_text(visit(&s, &format!("{uri}?year=1999")).await).await;
    assert!(!html.contains("Library work"));
    // Nonsense pages are the first one; pages past the end are empty.
    let html = body_text(visit(&s, &format!("{uri}?page=nope")).await).await;
    assert!(html.contains("Article work"));
    let page = visit(&s, &format!("{uri}?page=4294967295")).await;
    assert_eq!(page.status(), StatusCode::OK);
    assert!(!body_text(page).await.contains("Article work"));
}

#[tokio::test]
async fn htmx_gets_only_the_list_of_works() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}?type=blogPost");
    let page = s
        .call("GET", &uri, None, &[("hx-request", "true")], Body::empty())
        .await;
    assert_eq!(page.status(), StatusCode::OK);
    assert_eq!(header_str(&page, "vary"), "HX-Request, Accept-Language");
    let html = body_text(page).await;
    assert!(
        html.trim_start().starts_with(r#"<section id="works""#),
        "{html}"
    );
    assert!(html.contains("Blog work"));
    for frame in ["<html", "Ada Example", "Founder"] {
        assert!(!html.contains(frame), "{frame} in {html}");
    }
    // The search box is part of it, with the filters it holds.
    assert!(html.contains(r#"id="work-search""#), "{html}");
    assert!(html.contains(r#"<input type="hidden" name="type" value="blogPost">"#));
    // Going back to a page htmx has not kept asks for all of it.
    let page = s
        .call(
            "GET",
            &uri,
            None,
            &[
                ("hx-request", "true"),
                ("hx-history-restore-request", "true"),
            ],
            Body::empty(),
        )
        .await;
    assert!(body_text(page).await.contains("<html"));
}

#[tokio::test]
async fn the_public_profile_speaks_the_visitors_language() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}");
    let german = |lang: &'static str| {
        let (s, uri) = (&s, format!("{uri}?featured=0"));
        async move {
            let page = s
                .call(
                    "GET",
                    &uri,
                    None,
                    &[("accept-language", lang)],
                    Body::empty(),
                )
                .await;
            body_text(page).await
        }
    };
    let html = german("de-DE,de;q=0.9").await;
    for shown in [
        r#"<html lang="de">"#,
        "Vorname",
        "Deutschland",
        "Zugehörigkeiten",
        "2 Werke",
        "Blogbeitrag veröffentlicht 1. Mai 2021",
        "Englisch",
        "Veröffentlicht unter den Bedingungen der",
        "Selbst gehostete",
        "Exportieren",
    ] {
        assert!(html.contains(shown), "{shown} missing from {html}");
    }
    // Austrian German is German.
    let html = german("de-AT").await;
    assert!(html.contains(r#"<html lang="de">"#));
    assert!(!html.contains("de-AT"));

    // The URL wins over the browser, and links keep it.
    let page = s
        .call(
            "GET",
            &format!("{uri}?featured=0&lang=en"),
            None,
            &[("accept-language", "de")],
            Body::empty(),
        )
        .await;
    let html = body_text(page).await;
    assert!(html.contains("Given name"));
    assert!(
        html.contains(&format!("{uri}?year=2020&#38;lang=en")),
        "{html}"
    );
    // An unknown language is no language.
    let html = body_text(visit(&s, &format!("{uri}?lang=xx")).await).await;
    assert!(html.contains("Given name"));
    assert!(!html.contains("lang=xx"));
}

#[tokio::test]
async fn the_public_profile_pages_its_works() {
    let s = profile_server().await;
    let items: Vec<Value> = (0..30u8)
        .map(|i| {
            json!({"key": format!("PAGEDA{}{}", (b'A' + i / 10) as char, (b'A' + i % 10) as char),
                   "itemType": "book", "title": format!("Paged {i}"),
                   "date": "2000", "inPublications": true})
        })
        .collect();
    let resp = s
        .json(
            "POST",
            "/users/1/items",
            &[("if-unmodified-since-version", "1")],
            json!(items),
        )
        .await;
    assert_eq!(resp.status(), StatusCode::OK, "{}", body_text(resp).await);
    let uri = format!("/{ORCID}");
    let first = body_text(visit(&s, &format!("{uri}?featured=0")).await).await;
    assert!(first.contains(&format!("{uri}?page=2")));
    assert!(first.contains("page 1 of 4"));
    assert!(!first.contains("Previous page"));
    assert!(first.contains("Next page"));
    let last = body_text(visit(&s, &format!("{uri}?page=4")).await).await;
    assert!(last.contains("Previous page"));
    assert!(!last.contains("Next page"));
    assert!(last.contains(r#"aria-current="page""#));
    assert!(last.contains("31."));
}

#[tokio::test]
async fn the_public_profile_opens_on_up_to_five_featured_works() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}");
    // A work with the manual tag already, and six more, one of them newest.
    let items: Vec<Value> = (0..6u8)
        .map(|i| {
            json!({"key": format!("FEATRDA{}", (b'A' + i) as char),
                   "itemType": "book", "title": format!("Featured {i}"),
                   "date": format!("203{i}"), "inPublications": true,
                   "tags": [{"tag": "featured"}]})
        })
        .collect();
    let resp = s
        .json(
            "POST",
            "/users/1/items",
            &[("if-unmodified-since-version", "1")],
            json!(items),
        )
        .await;
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(body_json(resp).await["failed"], json!({}));

    let rendered = |html: &str| {
        html.matches(r#"text-base font-semibold leading-snug"#)
            .count()
    };
    for view in [
        uri.clone(),
        format!("{uri}?lang=en"),
        format!("{uri}?featured=1"),
    ] {
        let html = body_text(visit(&s, &view).await).await;
        assert_eq!(rendered(&html), 5, "{view}");
        assert!(html.contains("5 works"), "{view}");
        // Ticked, newest first, nothing to page through, and not the others.
        assert!(
            html.contains("Featured 5") && !html.contains("Featured 0"),
            "{view}"
        );
        assert!(!html.contains("Article work"), "{view}");
        assert!(!html.contains("Next page"), "{view}");
        assert!(html.contains("?featured=0"), "{view}: {html}");
        assert!(html.contains(r#"aria-current="true""#), "{view}");
    }
    // Picking a facet value from it unticks it, for all works of that value.
    let html = body_text(visit(&s, &uri).await).await;
    for picked in ["year=2021", "type=blogPost", "content=pdf"] {
        assert!(
            html.contains(&format!(r#"href="{uri}?{picked}""#)),
            "{picked}: {html}"
        );
    }
    // Taking one away leaves it ticked.
    let html = body_text(visit(&s, &format!("{uri}?featured=1&type=book")).await).await;
    assert!(html.contains(r#"aria-current="true""#));
    assert!(
        html.contains(&format!(r#"href="{uri}?featured=1" aria-current="true""#)),
        "{html}"
    );
    assert!(
        html.contains(&format!(r#"href="{uri}?year=2035&#38;type=book""#)),
        "{html}"
    );

    // A page of it is no different.
    let html = body_text(visit(&s, &format!("{uri}?featured=1&page=2")).await).await;
    assert_eq!(rendered(&html), 5);

    // Unticked it lists all of them, and paging stays there.
    let html = body_text(visit(&s, &format!("{uri}?featured=0")).await).await;
    assert!(html.contains("8 works"), "{html}");
    assert!(html.contains("Article work"));

    // What asks for something else shows all works, as such addresses always did.
    let html = body_text(visit(&s, &format!("{uri}?year=2020")).await).await;
    assert!(html.contains("Article work"), "{html}");
    let html = body_text(visit(&s, &format!("{uri}?q=")).await).await;
    assert!(html.contains("8 works"), "{html}");

    // An export goes with what is ticked: a bare export is everything.
    let count = |ris: &str| ris.matches("TY  -").count();
    let all = body_text(visit(&s, &format!("{uri}/export?format=ris")).await).await;
    assert_eq!(count(&all), 8, "{all}");
    let featured = body_text(visit(&s, &format!("{uri}/export?format=ris&featured=1")).await).await;
    assert_eq!(count(&featured), 5, "{featured}");

    // Without featured works, the bare address has nothing to narrow to.
    let plain = server_with_orcid(Some(ORCID)).await;
    plain.app.person.set(
        ORCID,
        serde_json::from_value(json!({"family_name": "Example"})).unwrap(),
    );
    let resp = plain
        .json(
            "POST",
            "/users/1/items",
            &[("if-unmodified-since-version", "0")],
            json!([{"key": "ARTICLEA", "itemType": "book", "title": "Plain work",
                    "inPublications": true}]),
        )
        .await;
    assert_eq!(resp.status(), StatusCode::OK);
    let html = body_text(visit(&plain, &uri).await).await;
    assert!(html.contains("Plain work"), "{html}");
    assert!(!html.contains("Featured only"), "{html}");
}

#[tokio::test]
async fn the_public_profile_exports_what_the_list_shows() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}/export");

    let resp = visit(&s, &format!("{uri}?format=ris")).await;
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(
        header_str(&resp, "content-type"),
        "text/plain; charset=utf-8"
    );
    assert_eq!(
        header_str(&resp, "content-disposition"),
        format!("attachment; filename=\"{ORCID}.ris\"")
    );
    let ris = body_text(resp).await;
    assert!(
        ris.contains("Article work") && ris.contains("Blog work"),
        "{ris}"
    );
    assert!(!ris.contains("Library work") && !ris.contains("Trashed work"));
    assert!(!ris.contains("secret tag"), "{ris}");

    // Under the filters of the list, and commonmeta's own format by default.
    let bare = body_text(visit(&s, &format!("{uri}?featured=1")).await).await;
    assert!(
        bare.contains("Blog work") && !bare.contains("Article work"),
        "{bare}"
    );
    let csl = body_text(visit(&s, &format!("{uri}?format=csl&year=2020")).await).await;
    assert!(
        csl.contains("Article work") && !csl.contains("Blog work"),
        "{csl}"
    );

    // A formatted citation in a style on offer, in plain text.
    let citation = visit(&s, &format!("{uri}?format=citation&style=ieee")).await;
    assert_eq!(citation.status(), StatusCode::OK);
    let citation = body_text(citation).await;
    assert!(citation.contains("Article work"), "{citation}");
    assert!(!citation.contains('<'), "{citation}");

    // One work, for its copy button, in the format picked.
    let one = body_text(visit(&s, &format!("{uri}?format=ris&key=ARTICLEA")).await).await;
    assert!(
        one.contains("Article work") && !one.contains("Blog work"),
        "{one}"
    );
    assert_eq!(one.matches("TY  -").count(), 1, "{one}");
    let one = body_text(
        visit(
            &s,
            &format!("{uri}?format=citation&style=ieee&key=BLGPSTAA"),
        )
        .await,
    )
    .await;
    assert!(one.contains("Blog work"), "{one}");
    // Not one that is private, in the trash, unknown, or an attachment.
    for private in ["LIBRARYA", "TRASHEDA", "UNKNOWNA", "PDFWEBAA"] {
        let resp = visit(&s, &format!("{uri}?format=ris&key={private}")).await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{private}");
    }

    // Nothing else, and nothing while hidden or for another iD.
    for bad in ["?format=nonsense", "?format=citation&style=../../etc"] {
        let resp = visit(&s, &format!("{uri}{bad}")).await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{bad}");
    }
    let other = visit(&s, "/0000-0002-1825-0097/export").await;
    assert_eq!(other.status(), StatusCode::NOT_FOUND);
    s.app.control.set_profile_hidden(1, true).await.unwrap();
    assert_eq!(visit(&s, &uri).await.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn the_owner_can_hide_the_public_profile() {
    let s = profile_server().await;
    let uri = format!("/{ORCID}");
    let set_hidden = |cookie: String, origin: &'static str, hidden: &'static str| {
        let s = &s;
        async move {
            s.call(
                "POST",
                "/ui/profile",
                None,
                &[
                    ("content-type", "application/x-www-form-urlencoded"),
                    ("cookie", &cookie),
                    ("origin", origin),
                ],
                Body::from(format!("hidden={hidden}")),
            )
            .await
            .status()
        }
    };

    // Nobody without a session, a key that may write, and this site's origin.
    assert_eq!(
        set_hidden(String::new(), PUBLIC, "true").await,
        StatusCode::UNAUTHORIZED
    );
    let read_only = signed_in(&s).await;
    assert_eq!(
        set_hidden(read_only.clone(), PUBLIC, "true").await,
        StatusCode::FORBIDDEN
    );
    let owner = session_cookie(&sign_in(&s, RW, PUBLIC).await);
    assert_eq!(
        set_hidden(owner.clone(), "https://evil.example", "true").await,
        StatusCode::FORBIDDEN
    );
    assert_eq!(visit(&s, &uri).await.status(), StatusCode::OK);

    // A read-only session sees the section, but no button.
    let dashboard = |cookie: String| {
        let s = &s;
        async move {
            let page = s
                .call("GET", "/", None, &[("cookie", &cookie)], Body::empty())
                .await;
            body_text(page).await
        }
    };
    let html = dashboard(read_only).await;
    assert!(html.contains("Public profile"));
    assert!(!html.contains("Hide profile"));
    let html = dashboard(owner.clone()).await;
    assert!(html.contains("Hide profile"));
    assert!(html.contains("It lists 2 works"));
    assert!(html.contains(&format!("{PUBLIC}/{ORCID}")));

    assert_eq!(
        set_hidden(owner.clone(), PUBLIC, "true").await,
        StatusCode::SEE_OTHER
    );
    assert_eq!(visit(&s, &uri).await.status(), StatusCode::NOT_FOUND);
    assert!(dashboard(owner.clone()).await.contains("Show profile"));

    assert_eq!(
        set_hidden(owner, PUBLIC, "false").await,
        StatusCode::SEE_OTHER
    );
    assert_eq!(visit(&s, &uri).await.status(), StatusCode::OK);
}

// ── OpenID Connect ───────────────────────────────────────────────────────────

/// What the mock provider puts in its tokens, and what it has been told.
#[derive(Default)]
struct MockIdp {
    nonce: String,
    challenge: String,
    id_claims: Value,
    userinfo: Value,
}

/// An OpenID Connect provider on a local port, which checks PKCE and the code
/// as a real one would. Returns its issuer URL and state.
async fn mock_idp() -> (String, Arc<Mutex<MockIdp>>) {
    use axum::{Form, Json, extract::State, routing};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let issuer = format!("http://{}", listener.local_addr().unwrap());
    let idp = Arc::new(Mutex::new(MockIdp::default()));
    let (i1, i2) = (issuer.clone(), issuer.clone());
    let app = Router::new()
        .route(
            "/.well-known/openid-configuration",
            routing::get(move || {
                let issuer = i1.clone();
                async move {
                    Json(json!({
                        "issuer": issuer,
                        "authorization_endpoint": format!("{issuer}/auth"),
                        "token_endpoint": format!("{issuer}/token"),
                        "userinfo_endpoint": format!("{issuer}/userinfo"),
                        "end_session_endpoint": format!("{issuer}/logout"),
                    }))
                }
            }),
        )
        .route(
            "/token",
            routing::post(
                move |State(idp): State<Arc<Mutex<MockIdp>>>,
                      Form(form): Form<HashMap<String, String>>| {
                    let issuer = i2.clone();
                    async move {
                        let idp = idp.lock().unwrap();
                        let verifier = form.get("code_verifier").cloned().unwrap_or_default();
                        if form.get("code").map(String::as_str) != Some("good-code")
                            || crate::oidc::challenge(&verifier) != idp.challenge
                            || form.get("client_secret").map(String::as_str) != Some("s3cret")
                        {
                            return (
                                StatusCode::BAD_REQUEST,
                                Json(json!({"error": "invalid_grant"})),
                            );
                        }
                        let mut claims = json!({
                            "iss": issuer, "aud": "defter", "exp": 4_000_000_000u64,
                            "nonce": idp.nonce, "sub": "abc",
                        });
                        for (k, v) in idp.id_claims.as_object().into_iter().flatten() {
                            claims[k] = v.clone();
                        }
                        let part = |v: &Value| {
                            base64::Engine::encode(
                                &base64::engine::general_purpose::URL_SAFE_NO_PAD,
                                v.to_string(),
                            )
                        };
                        let id_token =
                            format!("{}.{}.sig", part(&json!({"alg": "RS256"})), part(&claims));
                        (
                            StatusCode::OK,
                            Json(json!({"id_token": id_token, "access_token": "at"})),
                        )
                    }
                },
            ),
        )
        .route(
            "/userinfo",
            routing::get(|State(idp): State<Arc<Mutex<MockIdp>>>| async move {
                Json(idp.lock().unwrap().userinfo.clone())
            }),
        )
        .with_state(idp.clone());
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    (issuer, idp)
}

const OTHER_ORCID: &str = "0000-0002-1825-0097";

async fn oidc_server(orcid: Option<&str>) -> (Server, Arc<Mutex<MockIdp>>) {
    let (issuer, idp) = mock_idp().await;
    let cfg = crate::oidc::OidcConfig::new(
        &issuer,
        "defter",
        Some("s3cret".to_string()),
        "orcid",
        "Keycloak",
    )
    .unwrap();
    (server_admins(orcid, Some(cfg), true, &[ORCID]).await, idp)
}

/// Start a sign-in; returns the state, its cookie, and the provider's URL.
async fn oidc_start(s: &Server, idp: &Mutex<MockIdp>, query: &str) -> (String, String) {
    let resp = visit(s, &format!("/ui/oidc/login{query}")).await;
    assert_eq!(resp.status(), StatusCode::SEE_OTHER);
    let cookie = session_cookie(&resp);
    let location = header_str(&resp, "location").to_string();
    let (_, q) = location.split_once('?').unwrap();
    let params: HashMap<String, String> = serde_urlencoded::from_str(q).unwrap();
    assert_eq!(params["response_type"], "code");
    assert_eq!(params["code_challenge_method"], "S256");
    assert_eq!(params["redirect_uri"], format!("{PUBLIC}/ui/oidc/callback"));
    {
        let mut idp = idp.lock().unwrap();
        idp.nonce = params["nonce"].clone();
        idp.challenge = params["code_challenge"].clone();
    }
    (params["state"].clone(), cookie)
}

async fn oidc_finish(s: &Server, state: &str, cookie: &str) -> Response {
    s.call(
        "GET",
        &format!("/ui/oidc/callback?state={state}&code=good-code"),
        None,
        &[("cookie", cookie)],
        Body::empty(),
    )
    .await
}

fn set_cookies(resp: &Response) -> Vec<String> {
    resp.headers()
        .get_all("set-cookie")
        .iter()
        .map(|v| v.to_str().unwrap().to_string())
        .collect()
}

/// The `defter_session` cookie a response set, if any.
fn signed_in_cookie(resp: &Response) -> Option<String> {
    set_cookies(resp)
        .into_iter()
        .find(|c| c.starts_with("defter_session=") && !c.contains("Max-Age=0"))
        .map(|c| c.split(';').next().unwrap().to_string())
}

#[tokio::test]
async fn an_allowed_account_signs_in_through_the_provider() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().id_claims = json!({"orcid": format!("https://orcid.org/{ORCID}")});

    // No profile yet, and the sign-in page offers the provider.
    assert_eq!(
        visit(&s, &format!("/{ORCID}")).await.status(),
        StatusCode::NOT_FOUND
    );
    let html = body_text(visit(&s, "/").await).await;
    assert!(html.contains("Sign in with Keycloak"), "{html}");

    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let resp = oidc_finish(&s, &state, &cookie).await;
    assert_eq!(resp.status(), StatusCode::SEE_OTHER);
    assert_eq!(header_str(&resp, "location"), "/");
    let session = signed_in_cookie(&resp).expect("a session");
    assert!(
        set_cookies(&resp)
            .iter()
            .any(|c| c.starts_with("defter_oidc=;"))
    );

    // The dashboard opens, with what a read/write key may do, and the account
    // owns the profile now.
    s.app.person.set(
        ORCID,
        serde_json::from_value(json!({"family_name": "Example"})).unwrap(),
    );
    let page = s
        .call("GET", "/", None, &[("cookie", &session)], Body::empty())
        .await;
    assert_eq!(page.status(), StatusCode::OK);
    assert!(body_text(page).await.contains("Hide profile"));
    assert_eq!(
        visit(&s, &format!("/{ORCID}")).await.status(),
        StatusCode::OK
    );

    // The state works once.
    let again = oidc_finish(&s, &state, &cookie).await;
    assert_eq!(again.status(), StatusCode::FORBIDDEN);
    assert!(signed_in_cookie(&again).is_none());
}

#[tokio::test]
async fn the_orcid_claim_may_come_from_userinfo() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().userinfo = json!({"sub": "abc", "orcid": ORCID});
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let resp = oidc_finish(&s, &state, &cookie).await;
    assert!(signed_in_cookie(&resp).is_some());

    // Not when userinfo is about somebody else.
    idp.lock().unwrap().userinfo = json!({"sub": "other", "orcid": ORCID});
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let resp = oidc_finish(&s, &state, &cookie).await;
    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    assert!(signed_in_cookie(&resp).is_none());
}

#[tokio::test]
async fn others_get_no_session_from_the_provider() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().userinfo = json!({"sub": "abc"});
    for (claims, message) in [
        (
            json!({"orcid": OTHER_ORCID}),
            "not allowed into this library",
        ),
        (json!({"orcid": "not an orcid"}), "no ORCID iD"),
        (json!({}), "no ORCID iD"),
        (json!({"orcid": ORCID, "aud": "other"}), "did not work"),
        (
            json!({"orcid": ORCID, "iss": "https://evil.example"}),
            "did not work",
        ),
        (json!({"orcid": ORCID, "nonce": "other"}), "did not work"),
        (json!({"orcid": ORCID, "exp": 1}), "did not work"),
    ] {
        idp.lock().unwrap().id_claims = claims.clone();
        let (state, cookie) = oidc_start(&s, &idp, "").await;
        let resp = oidc_finish(&s, &state, &cookie).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN, "{claims}");
        assert!(signed_in_cookie(&resp).is_none(), "{claims}");
        let html = body_text(resp).await;
        assert!(html.contains(message), "{claims}: {html}");
    }
    // None of them came to own the profile.
    assert_eq!(
        visit(&s, &format!("/{OTHER_ORCID}")).await.status(),
        StatusCode::NOT_FOUND
    );
    assert_eq!(
        visit(&s, &format!("/{ORCID}")).await.status(),
        StatusCode::NOT_FOUND
    );

    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});
    // Another browser's state, none, an unknown one, or a wrong code.
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    for (uri, sent) in [
        (
            format!("/ui/oidc/callback?state={state}&code=good-code"),
            "defter_oidc=other",
        ),
        (
            format!("/ui/oidc/callback?state={state}&code=good-code"),
            "",
        ),
        (
            "/ui/oidc/callback?code=good-code".to_string(),
            cookie.as_str(),
        ),
        (
            "/ui/oidc/callback?state=unknown&code=good-code".to_string(),
            "defter_oidc=unknown",
        ),
    ] {
        let headers: &[(&str, &str)] = if sent.is_empty() {
            &[]
        } else {
            &[("cookie", sent)]
        };
        let resp = s.call("GET", &uri, None, headers, Body::empty()).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN, "{uri} {sent}");
        assert!(signed_in_cookie(&resp).is_none(), "{uri} {sent}");
    }
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let wrong = s
        .call(
            "GET",
            &format!("/ui/oidc/callback?state={state}&code=wrong"),
            None,
            &[("cookie", &cookie)],
            Body::empty(),
        )
        .await;
    assert_eq!(wrong.status(), StatusCode::FORBIDDEN);
    // The provider saying no.
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let denied = s
        .call(
            "GET",
            &format!("/ui/oidc/callback?state={state}&error=access_denied"),
            None,
            &[("cookie", &cookie)],
            Body::empty(),
        )
        .await;
    assert_eq!(denied.status(), StatusCode::FORBIDDEN);
    assert!(signed_in_cookie(&denied).is_none());
}

#[tokio::test]
async fn orcid_setting_keeps_the_profile_and_oidc_is_optional() {
    // --orcid wins over who signs in.
    let (s, idp) = oidc_server(Some(OTHER_ORCID)).await;
    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    assert!(signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).is_some());
    s.app.person.set(
        ORCID,
        serde_json::from_value(json!({"family_name": "Example"})).unwrap(),
    );
    assert_eq!(
        visit(&s, &format!("/{OTHER_ORCID}")).await.status(),
        StatusCode::OK
    );
    assert_eq!(
        visit(&s, &format!("/{ORCID}")).await.status(),
        StatusCode::NOT_FOUND
    );

    // Without a provider there is nothing to sign in through.
    let s = server().await;
    assert!(
        !body_text(visit(&s, "/").await)
            .await
            .contains("Sign in with")
    );
    for uri in ["/ui/oidc/login", "/ui/oidc/callback?state=a&code=b"] {
        assert_eq!(
            visit(&s, uri).await.status(),
            StatusCode::NOT_FOUND,
            "{uri}"
        );
    }
}

#[tokio::test]
async fn an_invited_account_gets_a_library_of_its_own_not_the_owners() {
    // The owner has no ORCID iD recorded, and nobody is an admin.
    let (issuer, idp) = mock_idp().await;
    let cfg = crate::oidc::OidcConfig::new(&issuer, "defter", Some("s3cret".into()), "orcid", "K")
        .unwrap();
    let s = server_admins(None, Some(cfg), true, &[]).await;
    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});
    // Not invited, not let in.
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    assert!(signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).is_none());
    assert!(s.app.control.invite(ORCID.into(), 1, None).await.unwrap());
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    assert!(signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).is_some());
    // Invited, they became a user of their own, with their profile hidden.
    let user = s.app.control.user_by_orcid(ORCID).await.unwrap().unwrap();
    assert_ne!(user.id, 1);
    assert!(user.profile_hidden);
    assert_eq!(s.app.control.user(1).await.unwrap().unwrap().orcid, None);
    assert_eq!(
        visit(&s, &format!("/{ORCID}")).await.status(),
        StatusCode::NOT_FOUND
    );
    // The invitation is used up.
    let invites = s.app.control.invites().await.unwrap();
    assert_eq!(invites[0].used_by, Some(user.id));
}

#[tokio::test]
async fn a_provider_sign_in_approves_zotero_logins() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});
    let created = s
        .call("POST", "/keys/sessions", None, &[], Body::empty())
        .await;
    let created = body_json(created).await;
    let token = created["sessionToken"].as_str().unwrap().to_string();

    // The consent page offers the provider, and asks for a key until then.
    let uri = format!("/login?session={token}");
    let html = body_text(visit(&s, &uri).await).await;
    assert!(html.contains(r#"name="key""#));
    assert!(
        html.contains(&format!("/ui/oidc/login?session={token}")),
        "{html}"
    );

    // Without a session a POST without a key approves nothing.
    let form = |session: &str, cookie: Option<&str>| {
        let body = serde_urlencoded::to_string([("session", session)]).unwrap();
        let mut headers = vec![
            (
                "content-type".to_string(),
                "application/x-www-form-urlencoded".to_string(),
            ),
            ("origin".to_string(), PUBLIC.to_string()),
        ];
        if let Some(cookie) = cookie {
            headers.push(("cookie".to_string(), cookie.to_string()));
        }
        (body, headers)
    };
    let post = |body: String, headers: Vec<(String, String)>| {
        let s = &s;
        async move {
            let refs: Vec<(&str, &str)> = headers
                .iter()
                .map(|(a, b)| (a.as_str(), b.as_str()))
                .collect();
            s.call("POST", "/login", None, &refs, Body::from(body))
                .await
        }
    };
    let (body, headers) = form(&token, None);
    assert_eq!(post(body, headers).await.status(), StatusCode::FORBIDDEN);
    // Neither does a session from a key, even a read/write one.
    let by_key = session_cookie(&sign_in(&s, RW, PUBLIC).await);
    let (body, headers) = form(&token, Some(&by_key));
    assert_eq!(post(body, headers).await.status(), StatusCode::FORBIDDEN);
    let pending = body_json(
        s.call(
            "GET",
            &format!("/keys/sessions/{token}"),
            None,
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert_eq!(pending["status"], "pending");

    // Signing in comes back to the login, which a button then approves.
    let (state, cookie) = oidc_start(&s, &idp, &format!("?session={token}")).await;
    let resp = oidc_finish(&s, &state, &cookie).await;
    assert_eq!(header_str(&resp, "location"), uri);
    let session = signed_in_cookie(&resp).unwrap();
    let page = s
        .call("GET", &uri, None, &[("cookie", &session)], Body::empty())
        .await;
    let html = body_text(page).await;
    assert!(!html.contains(r#"name="key""#), "{html}");
    assert!(html.contains("Approve"));
    // But not from another site.
    let (body, mut headers) = form(&token, Some(&session));
    headers[1].1 = "https://evil.example".to_string();
    assert_eq!(post(body, headers).await.status(), StatusCode::FORBIDDEN);

    let (body, headers) = form(&token, Some(&session));
    assert_eq!(post(body, headers).await.status(), StatusCode::SEE_OTHER);
    let done = body_json(
        s.call(
            "GET",
            &format!("/keys/sessions/{token}"),
            None,
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert_eq!(done["status"], "completed");
    // A key of their own, not one configured on the server, for the owner the
    // admin's iD became.
    let key = done["apiKey"].as_str().unwrap().to_string();
    assert_ne!(key, RW);
    assert_eq!(done["userID"], 1);
    let items = s
        .call("GET", "/users/1/items", Some(&key), &[], Body::empty())
        .await;
    assert_eq!(items.status(), StatusCode::OK);
    let current = body_json(
        s.call("GET", "/keys/current", Some(&key), &[], Body::empty())
            .await,
    )
    .await;
    assert_eq!(current["userID"], 1);
    assert_eq!(current["access"]["user"]["write"], true);
    // Listed as a device on the dashboard; only its hash is stored.
    let dashboard = body_text(
        s.call("GET", "/", None, &[("cookie", &session)], Body::empty())
            .await,
    )
    .await;
    assert!(dashboard.contains(&key[..8]), "{dashboard}");
    assert!(!dashboard.contains(&key));
    // Unlinking the account in Zotero revokes it.
    let unlinked = s
        .call("DELETE", "/keys/current", Some(&key), &[], Body::empty())
        .await;
    assert_eq!(unlinked.status(), StatusCode::NO_CONTENT);
    let after = s
        .call("GET", "/users/1/items", Some(&key), &[], Body::empty())
        .await;
    assert_eq!(after.status(), StatusCode::FORBIDDEN);
    // A key configured on the server stays.
    let kept = s
        .call("DELETE", "/keys/current", Some(RW), &[], Body::empty())
        .await;
    assert_eq!(kept.status(), StatusCode::NO_CONTENT);
    assert_eq!(s.get("/users/1/items").await.status(), StatusCode::OK);
}

async fn log_out(s: &Server, cookie: &str, origin: &str) -> Response {
    s.call(
        "POST",
        "/ui/logout",
        None,
        &[("cookie", cookie), ("origin", origin)],
        Body::empty(),
    )
    .await
}

#[tokio::test]
async fn signing_out_ends_the_session_at_the_provider_too() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let session = signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).unwrap();

    // Not from another site, which leaves the session as it was.
    let foreign = log_out(&s, &session, "https://evil.example").await;
    assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
    let dashboard = s
        .call("GET", "/", None, &[("cookie", &session)], Body::empty())
        .await;
    assert_eq!(dashboard.status(), StatusCode::OK);

    let out = log_out(&s, &session, PUBLIC).await;
    assert_eq!(out.status(), StatusCode::OK);
    assert!(header_str(&out, "set-cookie").contains("Max-Age=0"));
    assert_eq!(header_str(&out, "cache-control"), "no-store");
    assert_eq!(header_str(&out, "referrer-policy"), "no-referrer");
    let html = body_text(out).await;
    assert!(html.contains(r#"http-equiv="refresh""#), "{html}");
    assert!(html.contains("/logout?client_id=defter"), "{html}");
    assert!(html.contains("id_token_hint="), "{html}");
    let back =
        serde_urlencoded::to_string([("post_logout_redirect_uri", format!("{PUBLIC}/"))]).unwrap();
    assert!(html.contains(&back), "{html}");

    // The session is over here whatever the provider does.
    let after = s
        .call("GET", "/", None, &[("cookie", &session)], Body::empty())
        .await;
    assert_eq!(after.status(), StatusCode::UNAUTHORIZED);
    // Going through it again has no session to send to the provider.
    assert_eq!(
        log_out(&s, &session, PUBLIC).await.status(),
        StatusCode::SEE_OTHER
    );
}

#[tokio::test]
async fn signing_out_of_a_key_session_stays_here() {
    let (s, _idp) = oidc_server(None).await;
    let session = session_cookie(&sign_in(&s, RW, PUBLIC).await);
    let out = log_out(&s, &session, PUBLIC).await;
    assert_eq!(out.status(), StatusCode::SEE_OTHER);
    assert_eq!(header_str(&out, "location"), "/");
}

#[tokio::test]
async fn without_key_login_only_the_provider_signs_in() {
    let (issuer, idp) = mock_idp().await;
    let cfg = crate::oidc::OidcConfig::new(
        &issuer,
        "defter",
        Some("s3cret".to_string()),
        "orcid",
        "Keycloak",
    )
    .unwrap();
    let s = server_admins(None, Some(cfg), false, &[ORCID]).await;
    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});

    // The sign-in page offers the provider and no key, and a posted key is refused,
    // even a right one.
    let html = body_text(visit(&s, "/").await).await;
    assert!(html.contains("Sign in with Keycloak"), "{html}");
    assert!(!html.contains(r#"name="key""#), "{html}");
    let refused = sign_in(&s, RW, PUBLIC).await;
    assert_eq!(refused.status(), StatusCode::FORBIDDEN);
    assert!(signed_in_cookie(&refused).is_none());

    // So does a Zotero login.
    let created = s
        .call("POST", "/keys/sessions", None, &[], Body::empty())
        .await;
    let token = body_json(created).await["sessionToken"]
        .as_str()
        .unwrap()
        .to_string();
    let html = body_text(visit(&s, &format!("/login?session={token}")).await).await;
    assert!(!html.contains(r#"name="key""#), "{html}");
    assert!(!html.contains(">Approve<"), "{html}");
    assert!(html.contains("Sign in with Keycloak to approve"), "{html}");
    let form = serde_urlencoded::to_string([("session", token.as_str()), ("key", RW)]).unwrap();
    let post = |cookie: Option<String>| {
        let (s, form) = (&s, form.clone());
        async move {
            let mut headers = vec![
                (
                    "content-type",
                    "application/x-www-form-urlencoded".to_string(),
                ),
                ("origin", PUBLIC.to_string()),
            ];
            if let Some(cookie) = cookie {
                headers.push(("cookie", cookie));
            }
            let refs: Vec<(&str, &str)> = headers.iter().map(|(a, b)| (*a, b.as_str())).collect();
            s.call("POST", "/login", None, &refs, Body::from(form))
                .await
        }
    };
    assert_eq!(post(None).await.status(), StatusCode::FORBIDDEN);
    let status_uri = format!("/keys/sessions/{token}");
    let pending = body_json(s.call("GET", &status_uri, None, &[], Body::empty()).await).await;
    assert_eq!(pending["status"], "pending");

    // Keys still work for the data API and for monitoring.
    assert_eq!(s.get("/users/1/items").await.status(), StatusCode::OK);
    let status = s
        .call(
            "GET",
            "/ui/status",
            None,
            &[("zotero-api-key", RO)],
            Body::empty(),
        )
        .await;
    assert_eq!(status.status(), StatusCode::OK);

    // The provider signs in, and approves.
    let (state, cookie) = oidc_start(&s, &idp, &format!("?session={token}")).await;
    let session = signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).unwrap();
    let page = s
        .call(
            "GET",
            &format!("/login?session={token}"),
            None,
            &[("cookie", &session)],
            Body::empty(),
        )
        .await;
    assert!(body_text(page).await.contains("Approve"));
    assert_eq!(post(Some(session)).await.status(), StatusCode::SEE_OTHER);
    let done = body_json(s.call("GET", &status_uri, None, &[], Body::empty()).await).await;
    assert_eq!(done["status"], "completed");
}

#[tokio::test]
async fn pages_use_the_browsers_language_until_one_is_picked() {
    let s = server().await;
    let page = |headers: Vec<(&'static str, &'static str)>, uri: &'static str| {
        let s = &s;
        async move { s.call("GET", uri, None, &headers, Body::empty()).await }
    };

    // The browser's language by default, and nothing is remembered from that.
    let de = page(vec![("accept-language", "de-DE,de;q=0.9")], "/").await;
    assert!(set_cookies(&de).is_empty());
    let vary: Vec<_> = de
        .headers()
        .get_all("vary")
        .iter()
        .map(|v| v.to_str().unwrap().to_string())
        .collect();
    assert!(vary.iter().any(|v| v == "Cookie"), "{vary:?}");
    assert!(vary.iter().any(|v| v == "Accept-Language"), "{vary:?}");
    let html = body_text(de).await;
    assert!(html.contains(r#"<html lang="de">"#));
    assert!(html.contains("API-Schlüssel"), "{html}");
    assert!(html.contains(r#"<option value="de" selected>"#), "{html}");
    let html = body_text(page(vec![("accept-language", "fr")], "/").await).await;
    assert!(html.contains("API key"), "{html}");
    assert!(html.contains(r#"<option value="en" selected>"#));

    // Picking one from the menu wins over the browser, and is remembered.
    let picked = page(vec![("accept-language", "de")], "/?lang=en").await;
    let cookie = set_cookies(&picked)
        .into_iter()
        .find(|c| c.starts_with("defter_lang="))
        .unwrap();
    assert!(cookie.starts_with("defter_lang=en;"), "{cookie}");
    assert!(
        cookie.contains("Max-Age=31536000") && cookie.contains("Path=/"),
        "{cookie}"
    );
    assert!(body_text(picked).await.contains("API key"));
    let html = body_text(
        page(
            vec![("accept-language", "de"), ("cookie", "defter_lang=en")],
            "/",
        )
        .await,
    )
    .await;
    assert!(html.contains("API key"), "{html}");
    // The URL wins over the cookie, and a cookie or URL with no such language is ignored.
    let html = body_text(page(vec![("cookie", "defter_lang=en")], "/?lang=de").await).await;
    assert!(html.contains("API-Schlüssel"));
    let html = body_text(
        page(
            vec![("accept-language", "de"), ("cookie", "defter_lang=xx")],
            "/",
        )
        .await,
    )
    .await;
    assert!(html.contains("API-Schlüssel"));
    let unknown = page(vec![], "/?lang=xx").await;
    assert!(set_cookies(&unknown).is_empty());

    // Assets don't depend on it.
    let html = body_text(page(vec![], "/").await).await;
    let css = html
        .split("href=\"")
        .find(|p| p.starts_with("/assets/"))
        .unwrap();
    let css = css.split('"').next().unwrap().to_string();
    let asset = s.call("GET", &css, None, &[], Body::empty()).await;
    assert_eq!(asset.status(), StatusCode::OK);
    assert!(
        asset
            .headers()
            .get_all("vary")
            .iter()
            .all(|v| v != "Cookie")
    );
}

#[tokio::test]
async fn the_dashboard_and_login_pages_speak_german() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().id_claims = json!({"orcid": OTHER_ORCID});
    const DE: (&str, &str) = ("accept-language", "de");

    // A session from a key, in the dashboard and its polled status.
    let session = session_cookie(&sign_in(&s, RW, PUBLIC).await);
    let headers = [("cookie", session.as_str()), DE];
    let html = body_text(s.call("GET", "/", None, &headers, Body::empty()).await).await;
    for shown in [
        "Bibliotheksversion",
        "Einträge",
        "Zotero verbinden",
        "Dateispeicher",
        "Abmelden",
    ] {
        assert!(html.contains(shown), "{shown} missing from {html}");
    }
    assert!(!html.contains("Connect Zotero"), "{html}");
    let poll = [("cookie", session.as_str()), ("hx-request", "true"), DE];
    let html = body_text(s.call("GET", "/", None, &poll, Body::empty()).await).await;
    assert!(html.contains("Bibliotheksversion"), "{html}");

    // What goes wrong is in German too.
    let form = serde_urlencoded::to_string([("key", "guess")]).unwrap();
    let wrong = s
        .call(
            "POST",
            "/ui/session",
            None,
            &[
                ("content-type", "application/x-www-form-urlencoded"),
                ("origin", PUBLIC),
                DE,
            ],
            Body::from(form),
        )
        .await;
    assert!(body_text(wrong).await.contains("kein API-Schlüssel"));
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let refused = s
        .call(
            "GET",
            &format!("/ui/oidc/callback?state={state}&code=good-code"),
            None,
            &[("cookie", &cookie), DE],
            Body::empty(),
        )
        .await;
    assert!(body_text(refused).await.contains("keinen Zugang"));

    // The consent page, whose menu has to come back to the same login.
    let created = s
        .call("POST", "/keys/sessions", None, &[], Body::empty())
        .await;
    let token = body_json(created).await["sessionToken"]
        .as_str()
        .unwrap()
        .to_string();
    let uri = format!("/login?session={token}");
    let html = body_text(s.call("GET", &uri, None, &[DE], Body::empty()).await).await;
    for shown in [
        "Zotero zulassen?",
        "Bestätigen",
        "Mit Keycloak anmelden und bestätigen",
    ] {
        assert!(html.contains(shown), "{shown} missing from {html}");
    }
    assert!(html.contains(&format!(
        r#"<input type="hidden" name="session" value="{token}">"#
    )));
    assert!(html.contains(r#"action="/login""#));
    let picked = format!("{uri}&lang=en");
    let html = body_text(visit(&s, &picked).await).await;
    assert!(html.contains("Authorize Zotero?"), "{html}");
}

#[tokio::test]
async fn a_returning_login_must_be_a_live_one() {
    let (s, idp) = oidc_server(None).await;
    idp.lock().unwrap().id_claims = json!({"orcid": ORCID});
    // An unknown session is dropped rather than redirected to.
    let (state, cookie) = oidc_start(&s, &idp, "?session=//evil.example").await;
    let resp = oidc_finish(&s, &state, &cookie).await;
    assert_eq!(header_str(&resp, "location"), "/");
}

/// Zotero sends `feeds` back unchanged after downloading it. That must not count as
/// a change, or two clients would keep sending it to each other.
#[tokio::test]
async fn clients_echoing_a_setting_do_not_make_new_versions() {
    let s = server().await;
    let feeds = json!({"https://a.example/rss": ["A", 3, 30, 60]});
    let post = |version: String, value: Value| {
        let s = &s;
        async move {
            let headers = [("if-unmodified-since-version", version.as_str())];
            s.json(
                "POST",
                "/users/1/settings",
                &headers,
                json!({"feeds": {"value": value}}),
            )
            .await
        }
    };
    let added = post("0".to_string(), feeds.clone()).await;
    assert_eq!(added.status(), StatusCode::NO_CONTENT);
    assert_eq!(header_str(&added, "last-modified-version"), "1");

    // Each client echoes what it downloaded, over and over.
    for _ in 0..3 {
        let echo = post("1".to_string(), feeds.clone()).await;
        assert_eq!(echo.status(), StatusCode::NO_CONTENT);
        assert_eq!(header_str(&echo, "last-modified-version"), "1");
    }
    // So another client has nothing new, and can still make its own change.
    let since = s
        .call(
            "GET",
            "/users/1/settings?since=1",
            Some(RW),
            &[("if-modified-since-version", "1")],
            Body::empty(),
        )
        .await;
    assert_eq!(since.status(), StatusCode::NOT_MODIFIED);
    let more = json!({"https://a.example/rss": ["A", 3, 30, 60], "https://b.example/rss": ["B", 3, 30, 60]});
    let change = post("1".to_string(), more).await;
    assert_eq!(change.status(), StatusCode::NO_CONTENT);
    assert_eq!(header_str(&change, "last-modified-version"), "2");
    // And a client that has not seen it is told, even with what it had.
    let stale = post("1".to_string(), feeds).await;
    assert_eq!(stale.status(), StatusCode::PRECONDITION_FAILED);
}

#[tokio::test]
async fn keys_guard_the_data_api() {
    let s = server().await;
    let none = s
        .call("GET", "/users/1/items", None, &[], Body::empty())
        .await;
    assert_eq!(none.status(), StatusCode::FORBIDDEN);
    let bad = s
        .call("GET", "/users/1/items", Some("nope"), &[], Body::empty())
        .await;
    assert_eq!(bad.status(), StatusCode::FORBIDDEN);
    let other_user = s.get("/users/2/items").await;
    assert_eq!(other_user.status(), StatusCode::FORBIDDEN);
    // users/0 is the local API's alias for the current user.
    assert_eq!(s.get("/api/users/0/items").await.status(), StatusCode::OK);
    // A read-only key reads but cannot write.
    let ro_read = s
        .call("GET", "/users/1/items", Some(RO), &[], Body::empty())
        .await;
    assert_eq!(ro_read.status(), StatusCode::OK);
    let ro_write = s
        .call(
            "POST",
            "/users/1/items",
            Some(RO),
            &[("if-unmodified-since-version", "0")],
            Body::from("[]"),
        )
        .await;
    assert_eq!(ro_write.status(), StatusCode::FORBIDDEN);
    // Bearer tokens work too.
    let bearer = s
        .call(
            "GET",
            "/keys/current",
            None,
            &[("authorization", "Bearer ro-key")],
            Body::empty(),
        )
        .await;
    let body = body_json(bearer).await;
    assert_eq!(body["userID"], 1);
    assert_eq!(body["access"]["user"]["write"], false);
}

#[tokio::test]
async fn a_zotero_client_syncs_items() {
    let s = server().await;
    // Gzipped write with the library version precondition.
    let batch = json!([
        {"key": "AAAAAAAA", "itemType": "book", "title": "Rust", "creators": [{"lastName": "Klabnik"}]},
        {"key": "BBBBBBBB", "itemType": "attachment", "parentItem": "AAAAAAAA",
         "filename": "rust.pdf", "linkMode": "imported_file", "contentType": "application/pdf"},
    ]);
    let resp = s
        .call(
            "POST",
            "/users/1/items",
            Some(RW),
            &[
                ("content-type", "application/json"),
                ("content-encoding", "gzip"),
                ("if-unmodified-since-version", "0"),
            ],
            Body::from(gzip(&batch)),
        )
        .await;
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(header_str(&resp, "last-modified-version"), "1");
    let result = body_json(resp).await;
    assert_eq!(result["success"]["0"], "AAAAAAAA");
    // Attachments come back linkMode first.
    let attachment = result["successful"]["1"]["data"].as_object().unwrap();
    assert_eq!(
        attachment.keys().next().map(String::as_str),
        Some("linkMode")
    );

    let versions = body_json(
        s.get("/users/1/items?format=versions&since=0&includeTrashed=1")
            .await,
    )
    .await;
    assert_eq!(versions, json!({"AAAAAAAA": 1, "BBBBBBBB": 1}));
    let top = body_json(s.get("/users/1/items/top?format=versions&since=0").await).await;
    assert_eq!(top, json!({"AAAAAAAA": 1}));
    let empty = s.get("/users/1/items?format=versions&since=1").await;
    assert_eq!(empty.status(), StatusCode::OK);
    assert_eq!(body_json(empty).await, json!({}));

    let fetched = body_json(
        s.get("/users/1/items?itemKey=AAAAAAAA,BBBBBBBB&format=json")
            .await,
    )
    .await;
    assert_eq!(fetched.as_array().unwrap().len(), 2);

    // A stale precondition is a 412; a missing one on delete a 428.
    let stale = s
        .json(
            "POST",
            "/users/1/items",
            &[("if-unmodified-since-version", "0")],
            json!([{"key": "AAAAAAAA", "title": "x"}]),
        )
        .await;
    assert_eq!(stale.status(), StatusCode::PRECONDITION_FAILED);
    assert_eq!(header_str(&stale, "last-modified-version"), "1");
    let no_precondition = s
        .call(
            "DELETE",
            "/users/1/items?itemKey=BBBBBBBB",
            Some(RW),
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(no_precondition.status(), StatusCode::PRECONDITION_REQUIRED);

    let deleted = s
        .call(
            "DELETE",
            "/users/1/items?itemKey=BBBBBBBB",
            Some(RW),
            &[("if-unmodified-since-version", "1")],
            Body::empty(),
        )
        .await;
    assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
    let log = body_json(s.get("/users/1/deleted?since=1").await).await;
    assert_eq!(log["items"], json!(["BBBBBBBB"]));

    // Settings answer 304 when the client is current.
    let settings = s
        .call(
            "GET",
            "/users/1/settings",
            Some(RW),
            &[("if-modified-since-version", "2")],
            Body::empty(),
        )
        .await;
    assert_eq!(settings.status(), StatusCode::NOT_MODIFIED);
    let groups = body_json(s.get("/users/1/groups?format=versions").await).await;
    assert_eq!(groups, json!({}));
    // Without format=versions it is a list, as zotero.org answers.
    let groups = body_json(s.get("/users/1/groups").await).await;
    assert_eq!(groups, json!([]));
    let groups = body_json(s.get("/users/1/groups?limit=25&start=0").await).await;
    assert_eq!(groups, json!([]));
}

#[tokio::test]
async fn commonmeta_sync_reads_and_writes_single_items() {
    let s = server().await;
    // commonmeta creates without If-Unmodified-Since-Version.
    let created = s
        .json(
            "POST",
            "/api/users/0/items",
            &[],
            json!([{"itemType": "journalArticle", "title": "Deep learning", "DOI": "10.1038/nature14539"}]),
        )
        .await;
    assert_eq!(created.status(), StatusCode::OK);
    let created = body_json(created).await;
    let key = created["successful"]["0"]["key"]
        .as_str()
        .unwrap()
        .to_string();
    let version = created["successful"]["0"]["version"].as_i64().unwrap();

    // Found by the DOI suffix with qmode=everything, as scoped_items searches.
    let found = body_json(
        s.get("/api/users/0/items?format=json&qmode=everything&q=nature14539")
            .await,
    )
    .await;
    assert_eq!(found[0]["key"], key.as_str());

    // PATCH with the item's own version merges.
    let item_url = format!("/api/users/0/items/{key}");
    let patched = s
        .json(
            "PATCH",
            &item_url,
            &[("if-unmodified-since-version", &version.to_string())],
            json!({"volume": "521"}),
        )
        .await;
    assert_eq!(patched.status(), StatusCode::NO_CONTENT);
    let item = s.get(&item_url).await;
    let item_version: i64 = header_str(&item, "last-modified-version").parse().unwrap();
    let item = body_json(item).await;
    assert_eq!(item["data"]["title"], "Deep learning");
    assert_eq!(item["data"]["volume"], "521");
    assert_eq!(item["version"], item_version);

    // Another write moves the library on; the item's version still works.
    s.json(
        "POST",
        "/api/users/0/items",
        &[],
        json!([{"itemType": "note", "note": "x", "parentItem": key}]),
    )
    .await;
    let stale = s
        .json(
            "PUT",
            &item_url,
            &[("if-unmodified-since-version", &version.to_string())],
            json!({"itemType": "book"}),
        )
        .await;
    assert_eq!(stale.status(), StatusCode::PRECONDITION_FAILED);
    let replaced = s
        .json(
            "PUT",
            &item_url,
            &[("if-unmodified-since-version", &item_version.to_string())],
            json!({"itemType": "journalArticle", "title": "Deep learning", "DOI": "10.1038/nature14539"}),
        )
        .await;
    assert_eq!(replaced.status(), StatusCode::NO_CONTENT);
    let item = body_json(s.get(&item_url).await).await;
    assert!(item["data"].get("volume").is_none());

    // Children, and numChildren on the parent.
    let children = body_json(s.get(&format!("{item_url}/children?format=json")).await).await;
    assert_eq!(children.as_array().unwrap().len(), 1);
    let top = body_json(s.get("/api/users/0/items/top?format=json").await).await;
    assert_eq!(top[0]["meta"]["numChildren"], 1);

    // Paging follows Link: rel="next" on the public URL.
    let page = s.get("/api/users/0/items?limit=1").await;
    assert_eq!(header_str(&page, "total-results"), "2");
    assert_eq!(
        header_str(&page, "link"),
        format!("<{PUBLIC}/api/users/0/items?limit=1&start=1>; rel=\"next\"")
    );
}

#[tokio::test]
async fn attachment_files_upload_and_download() {
    let s = server().await;
    s.json(
        "POST",
        "/users/1/items",
        &[("if-unmodified-since-version", "0")],
        json!([{"key": "FFFFFFFF", "itemType": "attachment", "linkMode": "imported_file", "filename": "a.pdf"}]),
    )
    .await;
    let bytes = b"%PDF-1.7 hello";
    let md5 = format!("{:x}", md5::compute(bytes));
    let size = bytes.len().to_string();
    let auth_form = [
        ("md5", md5.as_str()),
        ("filename", "a.pdf"),
        ("filesize", &size),
        ("mtime", "1700000000000"),
    ];

    let no_precondition = s
        .form("/users/1/items/FFFFFFFF/file", &[], &auth_form)
        .await;
    assert_eq!(no_precondition.status(), StatusCode::PRECONDITION_REQUIRED);
    let no_item = s
        .form(
            "/users/1/items/GGGGGGGG/file",
            &[("if-none-match", "*")],
            &auth_form,
        )
        .await;
    assert_eq!(no_item.status(), StatusCode::NOT_FOUND);

    // A file added through Zotero's local API comes with its hash marked as
    // synced: a 412 without a version makes Zotero retry with If-None-Match.
    let not_stored = s
        .form(
            "/users/1/items/FFFFFFFF/file",
            &[("if-match", md5.as_str())],
            &auth_form,
        )
        .await;
    assert_eq!(not_stored.status(), StatusCode::PRECONDITION_FAILED);
    assert!(not_stored.headers().get("last-modified-version").is_none());

    let auth = body_json(
        s.form(
            "/users/1/items/FFFFFFFF/file",
            &[("if-none-match", "*")],
            &auth_form,
        )
        .await,
    )
    .await;
    let url = auth["url"].as_str().unwrap();
    let upload_key = auth["uploadKey"].as_str().unwrap();
    assert!(url.starts_with(&format!("{PUBLIC}/uploads/")));
    assert_eq!(auth["prefix"], "");

    // Wrong bytes are refused; the right ones accepted.
    let path = url.strip_prefix(PUBLIC).unwrap();
    let wrong = s.call("POST", path, None, &[], Body::from("garbage")).await;
    assert_eq!(wrong.status(), StatusCode::BAD_REQUEST);
    let early = s
        .form(
            "/users/1/items/FFFFFFFF/file",
            &[("if-none-match", "*")],
            &[("upload", upload_key)],
        )
        .await;
    assert_eq!(early.status(), StatusCode::BAD_REQUEST);
    let sent = s
        .call(
            "POST",
            path,
            None,
            &[("content-type", "application/pdf")],
            Body::from(&bytes[..]),
        )
        .await;
    assert_eq!(sent.status(), StatusCode::CREATED);

    let registered = s
        .form(
            "/users/1/items/FFFFFFFF/file",
            &[("if-none-match", "*")],
            &[("upload", upload_key)],
        )
        .await;
    assert_eq!(registered.status(), StatusCode::NO_CONTENT);
    assert_eq!(header_str(&registered, "last-modified-version"), "2");
    let item = body_json(s.get("/users/1/items/FFFFFFFF").await).await;
    assert_eq!(item["data"]["md5"], md5.as_str());

    // Another write moves the library past the attachment's version, which is
    // the one file responses carry.
    s.json(
        "POST",
        "/users/1/items",
        &[("if-unmodified-since-version", "2")],
        json!([{"key": "HHHHHHHH", "itemType": "book", "title": "x"}]),
    )
    .await;

    // The same file again needs no upload, whichever precondition is sent.
    for precondition in [("if-none-match", "*"), ("if-match", md5.as_str())] {
        let again = s
            .form("/users/1/items/FFFFFFFF/file", &[precondition], &auth_form)
            .await;
        assert_eq!(header_str(&again, "last-modified-version"), "2");
        assert_eq!(body_json(again).await, json!({"exists": 1}));
    }
    let other_file = [
        ("md5", "0123456789abcdef0123456789abcdef"),
        ("filename", "a.pdf"),
        ("filesize", "3"),
        ("mtime", "1700000000001"),
    ];
    for precondition in [
        ("if-none-match", "*"),
        ("if-match", "fedcba9876543210fedcba9876543210"),
    ] {
        let stale = s
            .form("/users/1/items/FFFFFFFF/file", &[precondition], &other_file)
            .await;
        assert_eq!(stale.status(), StatusCode::PRECONDITION_FAILED);
        assert_eq!(header_str(&stale, "last-modified-version"), "2");
    }

    // Download: a 302 with metadata, then the bytes.
    let redirect = s.get("/users/1/items/FFFFFFFF/file").await;
    assert_eq!(redirect.status(), StatusCode::FOUND);
    assert_eq!(header_str(&redirect, "zotero-file-md5"), md5);
    assert_eq!(
        header_str(&redirect, "zotero-file-modification-time"),
        "1700000000000"
    );
    let location = header_str(&redirect, "location").to_string();
    let download = s
        .call(
            "GET",
            location.strip_prefix(PUBLIC).unwrap(),
            None,
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(download.status(), StatusCode::OK);
    assert_eq!(
        header_str(&download, header::CONTENT_DISPOSITION.as_str()),
        "attachment; filename=\"a.pdf\""
    );
    assert_eq!(body_text(download).await.as_bytes(), bytes);

    // Deleting the item removes the file.
    let deleted = s
        .call(
            "DELETE",
            "/users/1/items/FFFFFFFF",
            Some(RW),
            &[("if-unmodified-since-version", "2")],
            Body::empty(),
        )
        .await;
    assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
    assert_eq!(
        s.get("/users/1/items/FFFFFFFF/file").await.status(),
        StatusCode::NOT_FOUND
    );
}

#[tokio::test]
async fn snapshots_upload_as_zip_and_download_compressed() {
    let s = server().await;
    s.json(
        "POST",
        "/users/1/items",
        &[("if-unmodified-since-version", "0")],
        json!([{"key": "SSSSSSSS", "itemType": "attachment", "linkMode": "imported_url",
                "contentType": "text/html", "filename": "page.html"}]),
    )
    .await;
    // Zotero sends the ZIP of the attachment directory: md5 is the main file's,
    // zipMD5 and filesize the ZIP's.
    let html = b"<html>snapshot</html>";
    let zip = b"PK\x03\x04 not really a zip, but its own bytes";
    let md5 = format!("{:x}", md5::compute(html));
    let zip_md5 = format!("{:x}", md5::compute(zip));
    let size = zip.len().to_string();
    let auth = body_json(
        s.form(
            "/users/1/items/SSSSSSSS/file",
            &[("if-none-match", "*")],
            &[
                ("md5", md5.as_str()),
                ("filename", "page.html"),
                ("filesize", &size),
                ("mtime", "1700000000000"),
                ("zipMD5", &zip_md5),
                ("zipFilename", "SSSSSSSS.zip"),
            ],
        )
        .await,
    )
    .await;
    let path = auth["url"].as_str().unwrap().strip_prefix(PUBLIC).unwrap();
    let sent = s.call("POST", path, None, &[], Body::from(&zip[..])).await;
    assert_eq!(sent.status(), StatusCode::CREATED);
    let registered = s
        .form(
            "/users/1/items/SSSSSSSS/file",
            &[("if-none-match", "*")],
            &[("upload", auth["uploadKey"].as_str().unwrap())],
        )
        .await;
    assert_eq!(registered.status(), StatusCode::NO_CONTENT);
    let item = body_json(s.get("/users/1/items/SSSSSSSS").await).await;
    assert_eq!(item["data"]["md5"], md5.as_str());

    let redirect = s.get("/users/1/items/SSSSSSSS/file").await;
    assert_eq!(header_str(&redirect, "zotero-file-md5"), md5);
    assert_eq!(header_str(&redirect, "zotero-file-compressed"), "Yes");
    let location = header_str(&redirect, "location").to_string();
    let download = s
        .call(
            "GET",
            location.strip_prefix(PUBLIC).unwrap(),
            None,
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(
        header_str(&download, header::CONTENT_TYPE.as_str()),
        "application/zip"
    );
    assert_eq!(body_text(download).await.as_bytes(), zip);
}

#[tokio::test]
async fn a_login_session_hands_out_the_key_after_approval() {
    let s = server().await;
    let created = s
        .call("POST", "/keys/sessions", None, &[], Body::empty())
        .await;
    assert_eq!(created.status(), StatusCode::CREATED);
    let created = body_json(created).await;
    let token = created["sessionToken"].as_str().unwrap().to_string();
    assert_eq!(
        created["loginURL"],
        format!("{PUBLIC}/login?session={token}")
    );

    let session_uri = format!("/keys/sessions/{token}");
    async fn poll_session(s: &Server, uri: &str) -> Response {
        s.call("GET", uri, None, &[], Body::empty()).await
    }
    assert_eq!(
        body_json(poll_session(&s, &session_uri).await).await["status"],
        "pending"
    );
    // The consent page offers the Approve form, and is guarded against
    // framing and caching.
    let page = s
        .call(
            "GET",
            &format!("/login?session={token}"),
            None,
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(page.status(), StatusCode::OK);
    assert_eq!(header_str(&page, "x-frame-options"), "DENY");
    assert_eq!(header_str(&page, "cache-control"), "no-store");
    // Not no-referrer: browsers would then send `Origin: null` with the
    // Approve form, which the origin check rejects.
    assert_eq!(header_str(&page, "referrer-policy"), "same-origin");
    assert!(header_str(&page, "content-security-policy").contains("frame-ancestors 'none'"));
    let html = body_text(page).await;
    assert!(html.contains(r#"<form method="post" action="/login""#));
    assert!(html.contains(&format!(r#"name="session" value="{token}""#)));
    assert!(html.contains(r#"type="password" name="key""#));
    // Showing the page approves nothing.
    assert_eq!(
        body_json(poll_session(&s, &session_uri).await).await["status"],
        "pending"
    );

    let approve = |key: &str| {
        let form =
            serde_urlencoded::to_string([("session", token.as_str()), ("key", key)]).unwrap();
        s.call(
            "POST",
            "/login",
            None,
            &[
                ("content-type", "application/x-www-form-urlencoded"),
                ("origin", PUBLIC),
            ],
            Body::from(form),
        )
    };

    // Approving takes a key that may write: anyone can create a session, so
    // the page alone must not hand one out.
    for (key, why) in [
        ("", "not an API key"),
        ("guess", "not an API key"),
        (RO, "may only read"),
    ] {
        let refused = approve(key).await;
        assert_eq!(refused.status(), StatusCode::FORBIDDEN, "{key:?}");
        let html = body_text(refused).await;
        assert!(html.contains(why), "{key:?}: {html}");
        // The form is offered again, for the same session.
        assert!(html.contains(&format!(r#"name="session" value="{token}""#)));
        assert_eq!(
            body_json(poll_session(&s, &session_uri).await).await["status"],
            "pending"
        );
    }

    let form = serde_urlencoded::to_string([("session", token.as_str()), ("key", RW)]).unwrap();
    let foreign = s
        .call(
            "POST",
            "/login",
            None,
            &[
                ("content-type", "application/x-www-form-urlencoded"),
                ("origin", "https://evil.example"),
            ],
            Body::from(form.clone()),
        )
        .await;
    assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
    assert!(body_text(foreign).await.contains("another site"));
    assert_eq!(
        body_json(poll_session(&s, &session_uri).await).await["status"],
        "pending"
    );

    let approved = approve(RW).await;
    assert_eq!(approved.status(), StatusCode::SEE_OTHER);
    assert_eq!(header_str(&approved, "location"), "/login?approved=1");
    let page = s
        .call(
            "GET",
            &format!("/login?session={token}"),
            None,
            &[],
            Body::empty(),
        )
        .await;
    assert!(body_text(page).await.contains("Authorized"));

    let done = body_json(poll_session(&s, &session_uri).await).await;
    assert_eq!(done["status"], "completed");
    // The key that approved the session is the one the client gets.
    assert_eq!(done["apiKey"], RW);
    // A session hands out its key once.
    assert_eq!(
        body_json(poll_session(&s, &session_uri).await).await["status"],
        "pending"
    );
}

#[tokio::test]
async fn the_login_page_handles_bad_sessions() {
    let s = server().await;
    let missing = s.call("GET", "/login", None, &[], Body::empty()).await;
    assert_eq!(missing.status(), StatusCode::BAD_REQUEST);
    assert!(body_text(missing).await.contains("No login request"));

    let unknown = s
        .call(
            "GET",
            "/login?session=%3Cscript%3E",
            None,
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
    let html = body_text(unknown).await;
    assert!(html.contains("Login expired"));
    assert!(!html.contains("<script>"));

    let approve_unknown = s
        .call(
            "POST",
            "/login",
            None,
            &[("content-type", "application/x-www-form-urlencoded")],
            Body::from("session=nope"),
        )
        .await;
    assert_eq!(approve_unknown.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn the_login_page_uses_the_built_stylesheet() {
    let s = server().await;
    let html = body_text(s.call("GET", "/login", None, &[], Body::empty()).await).await;
    let href = html
        .split('"')
        .find(|part| part.starts_with("/assets/") && part.ends_with(".css"))
        .expect("the login page links the stylesheet")
        .to_string();
    let css = s.call("GET", &href, None, &[], Body::empty()).await;
    assert_eq!(css.status(), StatusCode::OK);
    // max-w-md appears only in templates/login.html: Tailwind scanned it.
    assert!(body_text(css).await.contains(".max-w-md"));
}

#[tokio::test]
async fn a_key_reaches_only_its_own_library_and_versions_served_are_kept() {
    let s = server().await;
    for uri in ["/users/2/items", "/api/users/2/items", "/users/2/settings"] {
        let resp = s.get(uri).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN, "{uri}");
    }
    let created = s
        .json(
            "POST",
            "/users/1/items",
            &[("if-unmodified-since-version", "0")],
            json!([{"key": "AAAAAAAA", "itemType": "book", "title": "x"}]),
        )
        .await;
    assert_eq!(created.status(), StatusCode::OK);
    // Through the local API's "current user" too.
    assert_eq!(s.get("/api/users/0/items").await.status(), StatusCode::OK);
    let library = crate::control::LibraryRef::User(1);
    assert_eq!(s.app.control.version_high(library).await.unwrap(), 1);
}

#[tokio::test]
async fn the_schema_is_served_from_the_database() {
    let s = server().await;
    // Nothing stored and zotero.org unreachable: a 502.
    let missing = s.call("GET", "/api/schema", None, &[], Body::empty()).await;
    assert_eq!(missing.status(), StatusCode::BAD_GATEWAY);
    s.app
        .control
        .set_meta(vec![
            ("schema", r#"{"version": 1, "itemTypes": []}"#.to_string()),
            ("schema_fetched", "0".to_string()),
        ])
        .await
        .unwrap();
    // Stale and unrefreshable: the stored copy.
    let stale = s.call("GET", "/api/schema", None, &[], Body::empty()).await;
    assert_eq!(stale.status(), StatusCode::OK);
    assert_eq!(body_json(stale).await["version"], 1);
}

#[tokio::test]
async fn the_web_ui_is_served() {
    let s = server().await;
    let cookie = signed_in(&s).await;
    let index = s
        .call("GET", "/", None, &[("cookie", &cookie)], Body::empty())
        .await;
    assert_eq!(index.status(), StatusCode::OK);
    assert_eq!(header_str(&index, "zotero-server-id").len(), 32);
    assert_eq!(header_str(&index, "vary"), "HX-Request");
    assert_eq!(header_str(&index, "x-frame-options"), "DENY");
    let csp = header_str(&index, "content-security-policy").to_string();
    let html = body_text(index).await;
    assert!(html.starts_with("<!DOCTYPE html>"));
    assert!(html.contains(r#"<div id="status" hx-get="/" hx-trigger="every 30s""#));
    assert!(html.contains("Connect Zotero"));
    assert!(html.contains(&format!("extensions.zotero.api.url = {PUBLIC}/api/")));
    // The theme switch runs under the page's nonce.
    let nonce = csp
        .split("'nonce-")
        .nth(1)
        .and_then(|rest| rest.split('\'').next())
        .expect("the CSP carries a nonce");
    assert!(html.contains(&format!(r#"<script nonce="{nonce}">"#)));
    let asset = html
        .split('"')
        .find(|part| part.starts_with("/assets/") && part.ends_with(".js"))
        .expect("the page names its script")
        .to_string();
    let js = s.call("GET", &asset, None, &[], Body::empty()).await;
    assert_eq!(js.status(), StatusCode::OK);
    assert!(header_str(&js, "cache-control").contains("immutable"));

    let status = body_json(
        s.call("GET", "/ui/status", Some(RW), &[], Body::empty())
            .await,
    )
    .await;
    assert_eq!(status["name"], "defter");
    assert_eq!(status["apiUrl"], format!("{PUBLIC}/api"));
    assert_eq!(status["library"]["version"], 0);
    assert_eq!(status["storage"]["location"], "memory://");
}

#[tokio::test]
async fn htmx_polls_get_only_the_status_block() {
    let s = server().await;
    s.json(
        "POST",
        "/users/1/items",
        &[("if-unmodified-since-version", "0")],
        json!([{"key": "AAAAAAAA", "itemType": "book", "title": "One"}]),
    )
    .await;
    let cookie = signed_in(&s).await;
    let poll = s
        .call(
            "GET",
            "/",
            None,
            &[("hx-request", "true"), ("cookie", &cookie)],
            Body::empty(),
        )
        .await;
    assert_eq!(poll.status(), StatusCode::OK);
    assert_eq!(header_str(&poll, "vary"), "HX-Request");
    let html = body_text(poll).await;
    assert!(
        html.trim_start().starts_with(r#"<div id="status""#),
        "{html}"
    );
    assert!(!html.contains("<html"));
    assert!(!html.contains("Connect Zotero"));
    assert!(html.contains("Library version 1"));

    // A history restore wants the whole page.
    let restore = s
        .call(
            "GET",
            "/",
            None,
            &[
                ("hx-request", "true"),
                ("hx-history-restore-request", "true"),
                ("cookie", &cookie),
            ],
            Body::empty(),
        )
        .await;
    assert!(body_text(restore).await.starts_with("<!DOCTYPE html>"));
}

// ── people ───────────────────────────────────────────────────────────────────

const ALICE: &str = "0000-0001-5109-3700";
const BOB: &str = "0000-0002-9079-593X";

/// Invite `orcid`, sign them in, and mint a key for their device. Returns their
/// user ID and key.
async fn person(s: &Server, orcid: &str) -> (u64, String) {
    assert!(
        s.app
            .control
            .invite(orcid.to_string(), 1, None)
            .await
            .unwrap()
    );
    let crate::control::SignIn::User(user) = s.app.control.sign_in(orcid, false, 1).await.unwrap()
    else {
        panic!("{orcid} was invited");
    };
    let key = s
        .app
        .control
        .mint_key(user.id, "Zotero".into(), true)
        .await
        .unwrap();
    (user.id, key)
}

/// A web UI session for `user_id`, as a sign-in would make it.
fn session_for(s: &Server, user_id: u64) -> String {
    let (token, _) = s.app.ui_sessions.insert(crate::auth::UiSession {
        user_id,
        access: Access { write: true },
        id_token: Some("id-token".into()),
    });
    format!("defter_session={token}")
}

/// Post an item titled `title` to `user_id`'s library with `key`.
async fn post_item(s: &Server, key: &str, user_id: u64, item: Value) -> StatusCode {
    let resp = s
        .call(
            "POST",
            &format!("/users/{user_id}/items"),
            Some(key),
            &[
                ("content-type", "application/json"),
                ("if-unmodified-since-version", "0"),
            ],
            Body::from(json!([item]).to_string()),
        )
        .await;
    let status = resp.status();
    if status == StatusCode::OK {
        let body = body_json(resp).await;
        assert_eq!(body["failed"], json!({}), "{body}");
    }
    status
}

/// Every route of a library, with every method, for every kind of caller and
/// library: what is not theirs is refused, before anything is read.
#[tokio::test]
async fn every_route_refuses_what_is_not_the_callers() {
    let s = server().await;
    let (alice, alice_key) = person(&s, ALICE).await;
    let (bob, bob_key) = person(&s, BOB).await;
    let revoked = s
        .app
        .control
        .mint_key(alice, "old".into(), true)
        .await
        .unwrap();
    let revoked_id = s.app.control.keys(alice).await.unwrap()[0].id;
    assert!(s.app.control.revoke_key(alice, revoked_id).await.unwrap());
    for (key, user, name) in [
        (RW, 1, "owner"),
        (alice_key.as_str(), alice, "alice"),
        (bob_key.as_str(), bob, "bob"),
    ] {
        let item =
            json!({"key": "MARKERAA", "itemType": "book", "title": format!("MARKER-{name}")});
        assert_eq!(
            post_item(&s, key, user, item).await,
            StatusCode::OK,
            "{name}"
        );
    }
    let markers = ["MARKER-owner", "MARKER-alice", "MARKER-bob"];

    // (key, whose, may write, what is theirs to see)
    let callers: [(Option<&str>, Option<u64>, bool, &str); 7] = [
        (None, None, false, ""),
        (Some("not-a-key"), None, false, ""),
        (Some(revoked.as_str()), None, false, ""),
        (Some(RW), Some(1), true, "MARKER-owner"),
        (Some(RO), Some(1), false, "MARKER-owner"),
        (Some(alice_key.as_str()), Some(alice), true, "MARKER-alice"),
        (Some(bob_key.as_str()), Some(bob), true, "MARKER-bob"),
    ];
    let mut checked = 0;
    for (key, whose, write, own) in callers {
        let other = match whose {
            Some(1) => alice,
            Some(_) => 1,
            None => bob,
        };
        let mut targets = vec![(other.to_string(), false)];
        if let Some(id) = whose {
            targets.push((id.to_string(), true));
            targets.push(("0".to_string(), true));
        } else {
            targets.push(("0".to_string(), false));
        }
        for (path, methods, _) in crate::zotero::library_routes() {
            let path = path.replace("{key}", "MARKERAA");
            for prefix in ["", "/api"] {
                for (target, theirs) in &targets {
                    for method in ["GET", "POST", "PUT", "PATCH", "DELETE"] {
                        let uri = format!("{prefix}/users/{target}{path}");
                        let resp = s
                            .call(
                                method,
                                &uri,
                                key,
                                &[("content-type", "application/json")],
                                Body::from("[]"),
                            )
                            .await;
                        let status = resp.status();
                        let body = body_text(resp).await;
                        let mutating = method != "GET";
                        let what = format!("{method} {uri} with {key:?}");
                        if whose.is_none() || !theirs || (mutating && !write) {
                            assert_eq!(status, StatusCode::FORBIDDEN, "{what}: {body}");
                        } else if !methods.contains(&method) {
                            assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{what}");
                        } else {
                            assert!(
                                status != StatusCode::FORBIDDEN && status.as_u16() < 500,
                                "{what}: {status} {body}"
                            );
                        }
                        for marker in markers {
                            assert!(
                                marker == own || !body.contains(marker),
                                "{what} shows {marker}"
                            );
                        }
                        checked += 1;
                    }
                }
            }
        }
    }
    assert!(checked > 3000, "{checked}");
    // users/0 is each caller's own library.
    let own = s
        .call(
            "GET",
            "/api/users/0/items",
            Some(&alice_key),
            &[],
            Body::empty(),
        )
        .await;
    assert!(body_text(own).await.contains("MARKER-alice"));
}

#[tokio::test]
async fn people_have_their_own_libraries_keys_and_profiles() {
    let s = server().await;
    let (alice, alice_key) = person(&s, ALICE).await;
    let (bob, bob_key) = person(&s, BOB).await;
    // Random IDs, which say nothing of how many there are or who came when.
    assert!(alice != bob && alice != 1 && bob != 1);
    assert!((1..=100_000).contains(&alice) && (1..=100_000).contains(&bob));
    let work = |title: &str| {
        json!({"key": "WRKAAAAA", "itemType": "journalArticle", "title": title,
               "date": "2024", "inPublications": true})
    };
    assert_eq!(
        post_item(&s, &alice_key, alice, work("Alice's work")).await,
        StatusCode::OK
    );
    assert_eq!(
        post_item(&s, &bob_key, bob, work("Bob's work")).await,
        StatusCode::OK
    );

    // keys/current tells each client whose library it syncs.
    let current = body_json(
        s.call("GET", "/keys/current", Some(&alice_key), &[], Body::empty())
            .await,
    )
    .await;
    assert_eq!(current["userID"], alice);
    assert_eq!(current["username"], ALICE);

    // Profiles start hidden; Alice shows hers.
    s.app.person.set(
        ALICE,
        serde_json::from_value(json!({"family_name": "Alice"})).unwrap(),
    );
    assert_eq!(
        visit(&s, &format!("/{ALICE}")).await.status(),
        StatusCode::NOT_FOUND
    );
    let alice_session = session_for(&s, alice);
    let shown = s
        .call(
            "POST",
            "/ui/profile",
            None,
            &[
                ("cookie", &alice_session),
                ("origin", PUBLIC),
                ("content-type", "application/x-www-form-urlencoded"),
            ],
            Body::from("hidden=false"),
        )
        .await;
    assert_eq!(shown.status(), StatusCode::SEE_OTHER);
    let page = body_text(visit(&s, &format!("/{ALICE}")).await).await;
    assert!(
        page.contains("Alice&#39;s work") || page.contains("Alice's work"),
        "{page}"
    );
    assert!(!page.contains("Bob"));
    assert_eq!(
        visit(&s, &format!("/{BOB}")).await.status(),
        StatusCode::NOT_FOUND
    );
    // Not even a lookalike of an iD gets to the database.
    let lookalike = format!("/{}", ALICE.replace('-', ""));
    assert_eq!(visit(&s, &lookalike).await.status(), StatusCode::NOT_FOUND);

    // Their dashboard is about them.
    let dashboard = body_text(
        s.call(
            "GET",
            "/",
            None,
            &[("cookie", &alice_session)],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert!(dashboard.contains(&format!("user {alice}")), "{dashboard}");
    assert!(dashboard.contains(&alice_key[..8]));
    assert!(!dashboard.contains("/ui/admin"), "not an admin");
    assert!(
        !dashboard.contains("memory://"),
        "nor where files are stored"
    );

    // Revoking her device from the dashboard signs it out.
    let key_id = s.app.control.keys(alice).await.unwrap()[0].id;
    let revoke = |cookie: String, id: i64| {
        let s = &s;
        async move {
            s.call(
                "POST",
                "/ui/keys/revoke",
                None,
                &[
                    ("cookie", &cookie),
                    ("origin", PUBLIC),
                    ("content-type", "application/x-www-form-urlencoded"),
                ],
                Body::from(format!("id={id}")),
            )
            .await
            .status()
        }
    };
    // Bob cannot revoke Alice's.
    assert_eq!(
        revoke(session_for(&s, bob), key_id).await,
        StatusCode::NOT_FOUND
    );
    assert_eq!(
        revoke(alice_session.clone(), key_id).await,
        StatusCode::SEE_OTHER
    );
    let after = s
        .call(
            "GET",
            &format!("/users/{alice}/items"),
            Some(&alice_key),
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(after.status(), StatusCode::FORBIDDEN);

    // Disabled, Bob's key, session and profile stop working.
    s.app.control.set_profile_hidden(bob, false).await.unwrap();
    s.app.person.set(
        BOB,
        serde_json::from_value(json!({"family_name": "Bob"})).unwrap(),
    );
    assert_eq!(visit(&s, &format!("/{BOB}")).await.status(), StatusCode::OK);
    let bob_session = session_for(&s, bob);
    s.app.control.set_disabled(bob, true).await.unwrap();
    assert_eq!(
        visit(&s, &format!("/{BOB}")).await.status(),
        StatusCode::NOT_FOUND
    );
    let refused = s
        .call(
            "GET",
            &format!("/users/{bob}/items"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(refused.status(), StatusCode::FORBIDDEN);
    let page = s
        .call("GET", "/", None, &[("cookie", &bob_session)], Body::empty())
        .await;
    assert_eq!(page.status(), StatusCode::UNAUTHORIZED);
    // And a disabled account cannot sign in again.
    assert_eq!(
        s.app.control.sign_in(BOB, false, 1).await.unwrap(),
        crate::control::SignIn::Disabled
    );
}

#[tokio::test]
async fn uploads_stop_at_the_quota_and_stay_in_their_library() {
    let s = server().await;
    let (alice, alice_key) = person(&s, ALICE).await;
    let (bob, bob_key) = person(&s, BOB).await;
    let attachment = json!({"key": "FILEAAAA", "itemType": "attachment",
                            "linkMode": "imported_file", "title": "a.pdf"});
    for (key, user) in [
        (RW, 1),
        (alice_key.as_str(), alice),
        (bob_key.as_str(), bob),
    ] {
        assert_eq!(
            post_item(&s, key, user, attachment.clone()).await,
            StatusCode::OK
        );
    }
    s.app.control.set_quota(alice, Some(1000)).await.unwrap();
    let authorize = |key: String, user: u64, size: usize| {
        let s = &s;
        async move {
            let form = serde_urlencoded::to_string([
                ("md5", "0123456789abcdef0123456789abcdef"),
                ("filename", "a.pdf"),
                ("filesize", &size.to_string()),
                ("mtime", "1"),
            ])
            .unwrap();
            s.call(
                "POST",
                &format!("/users/{user}/items/FILEAAAA/file"),
                Some(&key),
                &[
                    ("content-type", "application/x-www-form-urlencoded"),
                    ("if-none-match", "*"),
                ],
                Body::from(form),
            )
            .await
        }
    };
    // Over Alice's quota: refused as zotero.org refuses it.
    let over = authorize(alice_key.clone(), alice, 2000).await;
    assert_eq!(over.status(), StatusCode::PAYLOAD_TOO_LARGE);
    assert_eq!(header_str(&over, "zotero-storage-quota"), "0");
    assert_eq!(
        header_str(&over, "zotero-storage-userid"),
        alice.to_string()
    );
    // Within it, and the owner, who has no quota, at any size accepted.
    assert_eq!(
        authorize(alice_key.clone(), alice, 500).await.status(),
        StatusCode::OK
    );
    assert_eq!(
        authorize(RW.to_string(), 1, 2000).await.status(),
        StatusCode::OK
    );
    // Bob has the default quota.
    let too_big = authorize(bob_key.clone(), bob, QUOTA as usize + 1).await;
    assert!(matches!(too_big.status(), StatusCode::PAYLOAD_TOO_LARGE));

    // Alice's upload cannot be registered in Bob's library.
    let authorized = body_json(authorize(alice_key.clone(), alice, 500).await).await;
    let upload = authorized["uploadKey"].as_str().unwrap().to_string();
    let registered = s
        .call(
            "POST",
            &format!("/users/{bob}/items/FILEAAAA/file"),
            Some(&bob_key),
            &[("content-type", "application/x-www-form-urlencoded")],
            Body::from(format!("upload={upload}")),
        )
        .await;
    assert_eq!(registered.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn admins_invite_people_and_manage_users() {
    let s = server().await;
    // Without admin iDs configured, the owner is the admin.
    let owner = session_cookie(&sign_in(&s, RW, PUBLIC).await);
    let admin_get = |cookie: String| {
        let s = &s;
        async move {
            s.call(
                "GET",
                "/ui/admin",
                None,
                &[("cookie", &cookie)],
                Body::empty(),
            )
            .await
        }
    };
    let page = admin_get(owner.clone()).await;
    assert_eq!(page.status(), StatusCode::OK);
    assert!(body_text(page).await.contains("Invitations"));
    let post = |cookie: String, path: &'static str, form: String| {
        let s = &s;
        async move {
            s.call(
                "POST",
                path,
                None,
                &[
                    ("cookie", &cookie),
                    ("origin", PUBLIC),
                    ("content-type", "application/x-www-form-urlencoded"),
                ],
                Body::from(form),
            )
            .await
        }
    };
    let invited = post(
        owner.clone(),
        "/ui/admin/invite",
        format!("orcid=https://orcid.org/{ALICE}&note=colleague"),
    )
    .await;
    assert_eq!(header_str(&invited, "location"), "/ui/admin");
    let wrong = post(owner.clone(), "/ui/admin/invite", "orcid=nobody".into()).await;
    assert_eq!(header_str(&wrong, "location"), "/ui/admin?error=orcid");
    let invites = s.app.control.invites().await.unwrap();
    assert_eq!(invites.len(), 1);
    assert_eq!(
        (invites[0].orcid.as_str(), invites[0].note.as_deref()),
        (ALICE, Some("colleague"))
    );

    // Alice signs in, and is no admin.
    let crate::control::SignIn::User(alice) = s.app.control.sign_in(ALICE, false, 1).await.unwrap()
    else {
        panic!("invited");
    };
    let alice_session = session_for(&s, alice.id);
    assert_eq!(
        admin_get(alice_session.clone()).await.status(),
        StatusCode::NOT_FOUND
    );
    let refused = post(alice_session, "/ui/admin/invite", format!("orcid={BOB}")).await;
    assert_eq!(refused.status(), StatusCode::FORBIDDEN);
    // Nor from another site.
    let foreign = s
        .call(
            "POST",
            "/ui/admin/invite",
            None,
            &[
                ("cookie", &owner),
                ("origin", "https://evil.example"),
                ("content-type", "application/x-www-form-urlencoded"),
            ],
            Body::from(format!("orcid={BOB}")),
        )
        .await;
    assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
    // A read-only key's session may look but not change.
    let read_only = session_cookie(&sign_in(&s, RO, PUBLIC).await);
    assert_eq!(admin_get(read_only.clone()).await.status(), StatusCode::OK);
    let looked = post(read_only, "/ui/admin/invite", format!("orcid={BOB}")).await;
    assert_eq!(looked.status(), StatusCode::FORBIDDEN);

    // Quota and disabling.
    let set = post(
        owner.clone(),
        "/ui/admin/user",
        format!("id={}&quota_mb=5", alice.id),
    )
    .await;
    assert_eq!(set.status(), StatusCode::SEE_OTHER);
    let alice_now = s.app.control.user(alice.id).await.unwrap().unwrap();
    assert_eq!(alice_now.quota_bytes, Some(5 * 1024 * 1024));
    let bad = post(
        owner.clone(),
        "/ui/admin/user",
        format!("id={}&quota_mb=lots", alice.id),
    )
    .await;
    assert_eq!(header_str(&bad, "location"), "/ui/admin?error=quota");
    post(
        owner.clone(),
        "/ui/admin/user",
        format!("id={}&disabled=true", alice.id),
    )
    .await;
    assert!(
        s.app
            .control
            .user(alice.id)
            .await
            .unwrap()
            .unwrap()
            .disabled
    );
    // Admins cannot lock themselves out, nor anyone the owner.
    let me = post(owner.clone(), "/ui/admin/user", "id=1&disabled=true".into()).await;
    assert_eq!(me.status(), StatusCode::BAD_REQUEST);
    assert!(!s.app.control.user(1).await.unwrap().unwrap().disabled);

    // A used invitation stays, an unused one can be withdrawn.
    post(owner.clone(), "/ui/admin/invite", format!("orcid={BOB}")).await;
    post(
        owner.clone(),
        "/ui/admin/uninvite",
        format!("orcid={ALICE}"),
    )
    .await;
    post(owner, "/ui/admin/uninvite", format!("orcid={BOB}")).await;
    let left: Vec<String> = s
        .app
        .control
        .invites()
        .await
        .unwrap()
        .into_iter()
        .map(|i| i.orcid)
        .collect();
    assert_eq!(left, [ALICE]);
}

#[tokio::test]
async fn admin_orcids_sign_in_and_manage() {
    // With admin iDs configured, they decide, not ownership.
    let (issuer, idp) = mock_idp().await;
    let cfg = crate::oidc::OidcConfig::new(&issuer, "defter", Some("s3cret".into()), "orcid", "K")
        .unwrap();
    let s = server_admins(Some(ORCID), Some(cfg), true, &[BOB]).await;
    idp.lock().unwrap().id_claims = json!({"orcid": BOB});
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    let session =
        signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).expect("an admin signs in");
    let bob = s.app.control.user_by_orcid(BOB).await.unwrap().unwrap();
    assert_ne!(bob.id, 1, "a library of their own: the owner has an iD");
    let page = s
        .call(
            "GET",
            "/ui/admin",
            None,
            &[("cookie", &session)],
            Body::empty(),
        )
        .await;
    assert_eq!(page.status(), StatusCode::OK);
    // The owner signing in with a key is no admin now.
    let owner = session_cookie(&sign_in(&s, RW, PUBLIC).await);
    let page = s
        .call(
            "GET",
            "/ui/admin",
            None,
            &[("cookie", &owner)],
            Body::empty(),
        )
        .await;
    assert_eq!(page.status(), StatusCode::NOT_FOUND);
    // Somebody neither invited nor an admin is turned away.
    idp.lock().unwrap().id_claims = json!({"orcid": ALICE});
    let (state, cookie) = oidc_start(&s, &idp, "").await;
    assert!(signed_in_cookie(&oidc_finish(&s, &state, &cookie).await).is_none());
    assert!(s.app.control.user_by_orcid(ALICE).await.unwrap().is_none());
}

#[tokio::test]
async fn disabling_signs_out_and_stops_logins_and_the_owner_stays() {
    let (issuer, _) = mock_idp().await;
    let cfg = crate::oidc::OidcConfig::new(&issuer, "defter", Some("s3cret".into()), "orcid", "K")
        .unwrap();
    let s = server_admins(Some(ORCID), Some(cfg), true, &[BOB]).await;
    let (alice, _) = person(&s, ALICE).await;
    let alice_session = session_for(&s, alice);
    s.app.control.set_disabled(alice, true).await.unwrap();
    // Her session may not approve a Zotero login, nor mint a key.
    let created = body_json(
        s.call("POST", "/keys/sessions", None, &[], Body::empty())
            .await,
    )
    .await;
    let token = created["sessionToken"].as_str().unwrap().to_string();
    let approve = s
        .call(
            "POST",
            "/login",
            None,
            &[
                ("cookie", &alice_session),
                ("origin", PUBLIC),
                ("content-type", "application/x-www-form-urlencoded"),
            ],
            Body::from(format!("session={token}")),
        )
        .await;
    assert_ne!(approve.status(), StatusCode::SEE_OTHER);
    assert!(s.app.control.keys(alice).await.unwrap().is_empty());

    // An admin disabling someone ends their sessions at once.
    s.app.control.set_disabled(alice, false).await.unwrap();
    let alice_session = session_for(&s, alice);
    let crate::control::SignIn::User(bob) = s.app.control.sign_in(BOB, true, 1).await.unwrap()
    else {
        panic!("an admin");
    };
    let admin = session_for(&s, bob.id);
    let form = |body: String| {
        let s = &s;
        let admin = admin.clone();
        async move {
            s.call(
                "POST",
                "/ui/admin/user",
                None,
                &[
                    ("cookie", &admin),
                    ("origin", PUBLIC),
                    ("content-type", "application/x-www-form-urlencoded"),
                ],
                Body::from(body),
            )
            .await
            .status()
        }
    };
    assert_eq!(
        form(format!("id={alice}&disabled=true")).await,
        StatusCode::SEE_OTHER
    );
    s.app.control.set_disabled(alice, false).await.unwrap();
    let page = s
        .call(
            "GET",
            "/",
            None,
            &[("cookie", &alice_session)],
            Body::empty(),
        )
        .await;
    assert_eq!(
        page.status(),
        StatusCode::UNAUTHORIZED,
        "signed out, though enabled again"
    );
    // The owner, whose keys are configured here, cannot be disabled.
    assert_eq!(
        form("id=1&disabled=true".into()).await,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(s.get("/users/1/items").await.status(), StatusCode::OK);
}

#[tokio::test]
async fn uploads_authorized_at_once_cannot_add_up_past_the_quota() {
    let s = server().await;
    let (alice, key) = person(&s, ALICE).await;
    s.app.control.set_quota(alice, Some(1000)).await.unwrap();
    let attachments = json!([
        {"key": "FILEAAAA", "itemType": "attachment", "linkMode": "imported_file", "title": "a.pdf"},
        {"key": "FILEBBBB", "itemType": "attachment", "linkMode": "imported_file", "title": "b.pdf"},
    ]);
    let posted = s
        .call(
            "POST",
            &format!("/users/{alice}/items"),
            Some(&key),
            &[
                ("content-type", "application/json"),
                ("if-unmodified-since-version", "0"),
            ],
            Body::from(attachments.to_string()),
        )
        .await;
    assert_eq!(body_json(posted).await["failed"], json!({}));
    let bytes = vec![b'x'; 600];
    let md5 = format!("{:x}", md5::compute(&bytes));
    let mut uploads = Vec::new();
    // Each fits alone, so both are authorized.
    for item in ["FILEAAAA", "FILEBBBB"] {
        let form = serde_urlencoded::to_string([
            ("md5", md5.as_str()),
            ("filename", "a.pdf"),
            ("filesize", "600"),
            ("mtime", "1"),
        ])
        .unwrap();
        let resp = s
            .call(
                "POST",
                &format!("/users/{alice}/items/{item}/file"),
                Some(&key),
                &[
                    ("content-type", "application/x-www-form-urlencoded"),
                    ("if-none-match", "*"),
                ],
                Body::from(form),
            )
            .await;
        assert_eq!(resp.status(), StatusCode::OK, "{item}");
        let upload = body_json(resp).await["uploadKey"]
            .as_str()
            .unwrap()
            .to_string();
        let sent = s
            .call(
                "POST",
                &format!("/uploads/{upload}"),
                None,
                &[],
                Body::from(bytes.clone()),
            )
            .await;
        assert_eq!(sent.status(), StatusCode::CREATED);
        uploads.push((item, upload));
    }
    let register = |item: &'static str, upload: String| {
        let (s, key) = (&s, key.clone());
        async move {
            s.call(
                "POST",
                &format!("/users/{alice}/items/{item}/file"),
                Some(&key),
                &[("content-type", "application/x-www-form-urlencoded")],
                Body::from(format!("upload={upload}")),
            )
            .await
            .status()
        }
    };
    let (first, second) = (uploads[0].clone(), uploads[1].clone());
    assert_eq!(register(first.0, first.1).await, StatusCode::NO_CONTENT);
    assert_eq!(
        register(second.0, second.1).await,
        StatusCode::PAYLOAD_TOO_LARGE
    );
    // And the admin page counts what she uses.
    let users = s.app.control.users().await.unwrap();
    assert_eq!(
        users
            .iter()
            .find(|u| u.user.id == alice)
            .unwrap()
            .bytes_used,
        600
    );
}

// ── groups ───────────────────────────────────────────────────────────────────

const CAROL: &str = "0000-0003-0059-2205";

/// A group owned by user 1 (the owner, whose configured keys are `RW` and
/// `RO`), with Alice as an admin and Bob as a member. Returns the group's ID and
/// Alice's, Bob's and Carol's (not a member) IDs and keys.
async fn group_server() -> (Server, u64, [(u64, String); 3]) {
    let s = server().await;
    let alice = person(&s, ALICE).await;
    let bob = person(&s, BOB).await;
    let carol = person(&s, CAROL).await;
    let group = s.app.control.create_group(1, "Lab".into()).await.unwrap();
    use crate::control::Role;
    for (id, role) in [(alice.0, Role::Admin), (bob.0, Role::Member)] {
        s.app
            .control
            .set_member(group.id, id, role)
            .await
            .unwrap()
            .unwrap();
    }
    (s, group.id, [alice, bob, carol])
}

async fn post_group_item(s: &Server, key: &str, group: u64, item: Value) -> Response {
    s.call(
        "POST",
        &format!("/groups/{group}/items"),
        Some(key),
        &[("content-type", "application/json")],
        Body::from(json!([item]).to_string()),
    )
    .await
}

#[tokio::test]
async fn members_sync_a_group_library_that_others_cannot_see() {
    let (s, group, [(alice, alice_key), (bob, bob_key), (carol, carol_key)]) = group_server().await;

    // Each member's client finds the group and its version.
    for (user, key) in [
        (1, RW.to_string()),
        (alice, alice_key.clone()),
        (bob, bob_key.clone()),
    ] {
        let versions = body_json(
            s.call(
                "GET",
                &format!("/users/{user}/groups?format=versions"),
                Some(&key),
                &[],
                Body::empty(),
            )
            .await,
        )
        .await;
        assert_eq!(versions, json!({group.to_string(): 3}), "{user}");
    }
    let none = s
        .call(
            "GET",
            &format!("/users/{carol}/groups?format=versions"),
            Some(&carol_key),
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(body_json(none).await, json!({}));

    // The group's JSON, as zotero.org's.
    let resp = s
        .call(
            "GET",
            &format!("/groups/{group}"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(header_str(&resp, "last-modified-version"), "3");
    let json = body_json(resp).await;
    assert_eq!(json["id"], group);
    assert_eq!(json["version"], 3);
    let data = &json["data"];
    assert_eq!(data["name"], "Lab");
    assert_eq!(data["owner"], 1);
    assert_eq!(data["admins"], json!([alice]));
    assert_eq!(data["members"], json!([bob]));
    assert_eq!(data["libraryEditing"], "members");
    assert_eq!(data["fileEditing"], "members");
    assert_eq!(data["type"], "Private");
    assert!(data["description"].is_string());
    // The list form, for the Choose Libraries dialog.
    let list = body_json(
        s.call(
            "GET",
            &format!("/users/{bob}/groups"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert_eq!(list[0]["data"]["name"], "Lab");
    // keys/current says the key reaches its groups.
    let current = body_json(
        s.call("GET", "/keys/current", Some(&bob_key), &[], Body::empty())
            .await,
    )
    .await;
    assert_eq!(current["access"]["groups"]["all"]["library"], true);

    // Bob writes, Alice reads it; Carol can do neither.
    let item = json!({"key": "GRPAAAAA", "itemType": "book", "title": "Shared"});
    let resp = s
        .call(
            "POST",
            &format!("/groups/{group}/items"),
            Some(&bob_key),
            &[
                ("content-type", "application/json"),
                ("if-unmodified-since-version", "0"),
            ],
            Body::from(json!([item]).to_string()),
        )
        .await;
    assert_eq!(body_json(resp).await["failed"], json!({}));
    let read = s
        .call(
            "GET",
            &format!("/api/groups/{group}/items"),
            Some(&alice_key),
            &[],
            Body::empty(),
        )
        .await;
    assert!(body_text(read).await.contains("Shared"));
    for uri in [format!("/groups/{group}"), format!("/groups/{group}/items")] {
        let refused = s
            .call("GET", &uri, Some(&carol_key), &[], Body::empty())
            .await;
        assert_eq!(refused.status(), StatusCode::FORBIDDEN, "{uri}");
    }
    assert!(
        !body_text(
            s.call(
                "GET",
                &format!("/users/{bob}/items"),
                Some(&bob_key),
                &[],
                Body::empty()
            )
            .await
        )
        .await
        .contains("Shared"),
        "the group's items are not Bob's own"
    );

    // Only admins may edit: Bob reads only, and his write is refused.
    s.app
        .control
        .update_group(group, None, None, Some("admins".into()), None)
        .await
        .unwrap();
    let refused = post_group_item(
        &s,
        &bob_key,
        group,
        json!({"key": "GRPBBBBB", "itemType": "book"}),
    )
    .await;
    assert_eq!(refused.status(), StatusCode::FORBIDDEN);
    assert_eq!(
        s.call(
            "GET",
            &format!("/groups/{group}/items"),
            Some(&bob_key),
            &[],
            Body::empty()
        )
        .await
        .status(),
        StatusCode::OK
    );

    // Every change made a new version, which the clients see.
    let version = s.app.control.group(group).await.unwrap().unwrap().version;
    assert_eq!(version, 4);
    // Taken out, Bob's client no longer finds it, and cannot reach it.
    s.app
        .control
        .remove_member(group, bob)
        .await
        .unwrap()
        .unwrap();
    let versions = body_json(
        s.call(
            "GET",
            &format!("/users/{bob}/groups?format=versions"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert_eq!(versions, json!({}));
    assert_eq!(
        s.call(
            "GET",
            &format!("/groups/{group}/items"),
            Some(&bob_key),
            &[],
            Body::empty()
        )
        .await
        .status(),
        StatusCode::FORBIDDEN
    );
    // Deleted, it is gone for everyone.
    s.app.control.delete_group(group).await.unwrap();
    let versions = body_json(
        s.call(
            "GET",
            &format!("/users/{alice}/groups?format=versions"),
            Some(&alice_key),
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert_eq!(versions, json!({}));
    assert_eq!(
        s.call(
            "GET",
            &format!("/groups/{group}/items"),
            Some(&alice_key),
            &[],
            Body::empty()
        )
        .await
        .status(),
        StatusCode::FORBIDDEN
    );
}

/// Every route of a group library, with every method, for each kind of member
/// and for others, under each setting of who may edit it and its files.
#[tokio::test]
async fn every_group_route_allows_only_what_the_role_and_settings_do() {
    use crate::control::Role;
    let (s, group, [(_, alice_key), (_, bob_key), (_, carol_key)]) = group_server().await;
    // A marker in the group's library and one in Carol's own.
    let item = json!({"key": "MARKERAA", "itemType": "book", "title": "MARKER-group"});
    assert_eq!(
        body_json(
            s.call(
                "POST",
                &format!("/groups/{group}/items"),
                Some(RW),
                &[
                    ("content-type", "application/json"),
                    ("if-unmodified-since-version", "0")
                ],
                Body::from(json!([item]).to_string()),
            )
            .await
        )
        .await["failed"],
        json!({})
    );
    let callers: [(&str, Option<Role>, bool); 5] = [
        (RW, Some(Role::Owner), true),
        (RO, Some(Role::Owner), false),
        (alice_key.as_str(), Some(Role::Admin), true),
        (bob_key.as_str(), Some(Role::Member), true),
        (carol_key.as_str(), None, true),
    ];
    let mut checked = 0;
    for (library_editing, file_editing) in [
        ("members", "members"),
        ("admins", "admins"),
        ("members", "none"),
    ] {
        s.app
            .control
            .update_group(
                group,
                None,
                None,
                Some(library_editing.into()),
                Some(file_editing.into()),
            )
            .await
            .unwrap();
        let settings = s.app.control.group(group).await.unwrap().unwrap();
        for (key, role, key_writes) in callers {
            let access = role.map(|r| settings.access(r));
            for (path, methods, _) in crate::zotero::library_routes() {
                let path = path.replace("{key}", "MARKERAA");
                for prefix in ["", "/api"] {
                    for method in ["GET", "POST", "PUT", "PATCH", "DELETE"] {
                        let uri = format!("{prefix}/groups/{group}{path}");
                        let resp = s
                            .call(
                                method,
                                &uri,
                                Some(key),
                                &[("content-type", "application/json")],
                                Body::from("[]"),
                            )
                            .await;
                        let status = resp.status();
                        let body = body_text(resp).await;
                        let what =
                            format!("{method} {uri} as {role:?}, {library_editing}/{file_editing}");
                        let mutating = method != "GET";
                        let file_upload = method == "POST" && path.ends_with("/file");
                        let refused = match access {
                            None => true,
                            Some(a) => {
                                (mutating && (!key_writes || !a.write)) || (file_upload && !a.files)
                            }
                        };
                        if refused {
                            assert_eq!(status, StatusCode::FORBIDDEN, "{what}: {body}");
                            assert!(!body.contains("MARKER-group"), "{what}");
                        } else if !methods.contains(&method) {
                            assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{what}");
                        } else {
                            assert!(
                                status != StatusCode::FORBIDDEN && status.as_u16() < 500,
                                "{what}: {status} {body}"
                            );
                        }
                        checked += 1;
                    }
                }
            }
        }
    }
    assert!(checked > 2500, "{checked}");
}

#[tokio::test]
async fn a_groups_files_count_against_its_owners_quota() {
    let (s, group, [(alice, alice_key), (bob, bob_key), _]) = group_server().await;
    // Alice owns a group of her own, with Bob in it.
    let hers = s
        .app
        .control
        .create_group(alice, "Alice's".into())
        .await
        .unwrap()
        .id;
    s.app
        .control
        .set_member(hers, bob, crate::control::Role::Member)
        .await
        .unwrap()
        .unwrap();
    s.app.control.set_quota(alice, Some(1000)).await.unwrap();
    let authorize = |key: String, library: String| {
        let s = &s;
        async move {
            let attachment = json!({"key": "FILEAAAA", "itemType": "attachment",
                                    "linkMode": "imported_file", "title": "a.pdf"});
            let posted = s
                .call(
                    "POST",
                    &format!("/{library}/items"),
                    Some(&key),
                    &[("content-type", "application/json")],
                    Body::from(json!([attachment]).to_string()),
                )
                .await;
            assert_eq!(body_json(posted).await["failed"], json!({}), "{library}");
            let form = serde_urlencoded::to_string([
                ("md5", "0123456789abcdef0123456789abcdef"),
                ("filename", "a.pdf"),
                ("filesize", "600"),
                ("mtime", "1"),
            ])
            .unwrap();
            s.call(
                "POST",
                &format!("/{library}/items/FILEAAAA/file"),
                Some(&key),
                &[
                    ("content-type", "application/x-www-form-urlencoded"),
                    ("if-none-match", "*"),
                ],
                Body::from(form),
            )
            .await
        }
    };
    // Six hundred bytes of Alice's own count when Bob adds to her group.
    s.app
        .control
        .note_usage(crate::control::LibraryRef::User(alice), 600)
        .await
        .unwrap();
    let over = authorize(bob_key.clone(), format!("groups/{hers}")).await;
    assert_eq!(over.status(), StatusCode::PAYLOAD_TOO_LARGE);
    assert_eq!(
        header_str(&over, "zotero-storage-userid"),
        alice.to_string()
    );
    // In the owner's group, the owner's quota (none) applies, not Alice's.
    assert_eq!(
        authorize(alice_key.clone(), format!("groups/{group}"))
            .await
            .status(),
        StatusCode::OK
    );
}

#[tokio::test]
async fn members_manage_a_group_on_its_page_as_their_role_allows() {
    let s = server().await;
    let (alice, _) = person(&s, ALICE).await;
    let (bob, _) = person(&s, BOB).await;
    let (carol, _) = person(&s, CAROL).await;
    let post = |user: u64, path: String, form: String| {
        let s = &s;
        async move {
            s.call(
                "POST",
                &path,
                None,
                &[
                    ("cookie", &session_for(s, user)),
                    ("origin", PUBLIC),
                    ("content-type", "application/x-www-form-urlencoded"),
                ],
                Body::from(form),
            )
            .await
        }
    };
    // Alice creates a group and owns it.
    let created = post(alice, "/ui/groups".into(), "name=Reading+club".into()).await;
    assert_eq!(created.status(), StatusCode::SEE_OTHER);
    let page = header_str(&created, "location").to_string();
    let id: u64 = page.rsplit('/').next().unwrap().parse().unwrap();
    let dashboard = body_text(
        s.call(
            "GET",
            "/",
            None,
            &[("cookie", &session_for(&s, alice))],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert!(dashboard.contains("Reading club"));

    // She adds Bob as an admin and Carol as a member; an unknown iD is no user.
    let members = format!("/ui/groups/{id}/members");
    assert_eq!(
        post(alice, members.clone(), format!("orcid={BOB}&role=admin"))
            .await
            .status(),
        StatusCode::SEE_OTHER
    );
    assert_eq!(
        post(alice, members.clone(), format!("orcid={CAROL}"))
            .await
            .status(),
        StatusCode::SEE_OTHER
    );
    let unknown = post(alice, members.clone(), "orcid=0000-0002-1694-233X".into()).await;
    assert_eq!(
        header_str(&unknown, "location"),
        format!("/ui/groups/{id}?error=user")
    );
    let roles = |members: Vec<crate::control::Member>| -> Vec<(u64, &'static str)> {
        members
            .iter()
            .map(|m| (m.user.id, m.role.as_str()))
            .collect()
    };
    let (_, now) = s.app.control.group_with_members(id).await.unwrap().unwrap();
    assert_eq!(
        roles(now),
        [(alice, "owner"), (bob, "admin"), (carol, "member")]
    );

    // Bob, an admin, changes settings but may not make admins nor touch Alice.
    let settings = format!("/ui/groups/{id}/settings");
    assert_eq!(
        post(
            bob,
            settings.clone(),
            "name=Club&library_editing=admins&file_editing=none".into()
        )
        .await
        .status(),
        StatusCode::SEE_OTHER
    );
    let group = s.app.control.group(id).await.unwrap().unwrap();
    assert_eq!(
        (
            group.name.as_str(),
            group.library_editing.as_str(),
            group.file_editing.as_str()
        ),
        ("Club", "admins", "none")
    );
    assert_eq!(
        post(bob, members.clone(), format!("user={carol}&role=admin"))
            .await
            .status(),
        StatusCode::FORBIDDEN
    );
    let remove = format!("/ui/groups/{id}/remove");
    assert_eq!(
        post(bob, remove.clone(), format!("user={alice}"))
            .await
            .status(),
        StatusCode::FORBIDDEN
    );
    // Carol, a member, changes nothing, sees the page, and leaves.
    assert_eq!(
        post(carol, settings, "name=Mine".into()).await.status(),
        StatusCode::FORBIDDEN
    );
    let seen = s
        .call(
            "GET",
            &page,
            None,
            &[("cookie", &session_for(&s, carol))],
            Body::empty(),
        )
        .await;
    assert_eq!(seen.status(), StatusCode::OK);
    assert_eq!(
        post(carol, remove.clone(), String::new()).await.status(),
        StatusCode::SEE_OTHER
    );
    let outsider = s
        .call(
            "GET",
            &page,
            None,
            &[("cookie", &session_for(&s, carol))],
            Body::empty(),
        )
        .await;
    assert_eq!(outsider.status(), StatusCode::NOT_FOUND);
    // The owner cannot leave; only she deletes it.
    assert_eq!(
        post(alice, remove, String::new()).await.status(),
        StatusCode::FORBIDDEN
    );
    let delete = format!("/ui/groups/{id}/delete");
    assert_eq!(
        post(bob, delete.clone(), String::new()).await.status(),
        StatusCode::FORBIDDEN
    );
    assert_eq!(
        post(alice, delete, String::new()).await.status(),
        StatusCode::SEE_OTHER
    );
    assert!(s.app.control.group(id).await.unwrap().unwrap().deleted);
    // And no POST from another site.
    let foreign = s
        .call(
            "POST",
            "/ui/groups",
            None,
            &[
                ("cookie", &session_for(&s, alice)),
                ("origin", "https://evil.example"),
                ("content-type", "application/x-www-form-urlencoded"),
            ],
            Body::from("name=X"),
        )
        .await;
    assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn group_items_say_who_added_and_last_changed_them() {
    let (s, group, [(alice, alice_key), (bob, bob_key), _]) = group_server().await;
    s.app
        .control
        .set_display_name(bob, "Bob Example".into())
        .await
        .unwrap();
    let created = s
        .call(
            "POST",
            &format!("/groups/{group}/items"),
            Some(&bob_key),
            &[
                ("content-type", "application/json"),
                ("if-unmodified-since-version", "0"),
            ],
            Body::from(
                json!([{"key": "SHAREDAA", "itemType": "book", "title": "One"}]).to_string(),
            ),
        )
        .await;
    let created = body_json(created).await;
    assert_eq!(created["failed"], json!({}));
    let changed = s
        .call(
            "PATCH",
            &format!("/groups/{group}/items/SHAREDAA"),
            Some(&alice_key),
            &[
                ("content-type", "application/json"),
                ("if-unmodified-since-version", "1"),
            ],
            Body::from(json!({"title": "Two"}).to_string()),
        )
        .await;
    assert_eq!(changed.status(), StatusCode::NO_CONTENT);
    let item = body_json(
        s.call(
            "GET",
            &format!("/groups/{group}/items/SHAREDAA"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    let meta = &item["meta"];
    assert_eq!(meta["createdByUser"]["id"], bob);
    assert_eq!(meta["createdByUser"]["username"], BOB);
    assert_eq!(meta["createdByUser"]["name"], "Bob Example");
    assert_eq!(meta["lastModifiedByUser"]["id"], alice);
    assert_eq!(item["data"]["title"], "Two");
    // In listings too, as a client syncing reads them.
    let listed = body_json(
        s.call(
            "GET",
            &format!("/groups/{group}/items?itemKey=SHAREDAA"),
            Some(&alice_key),
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert_eq!(listed[0]["meta"]["createdByUser"]["id"], bob);

    // One's own library says nothing of the kind.
    assert_eq!(
        post_item(
            &s,
            &bob_key,
            bob,
            json!({"key": "MINEAAAA", "itemType": "book"})
        )
        .await,
        StatusCode::OK
    );
    let mine = body_json(
        s.call(
            "GET",
            &format!("/users/{bob}/items/MINEAAAA"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await,
    )
    .await;
    assert!(mine["meta"].get("createdByUser").is_none(), "{mine}");
}

#[tokio::test]
async fn a_deleted_group_frees_its_owners_quota_and_its_files() {
    let (s, group, [(alice, _), (bob, bob_key), _]) = group_server().await;
    use crate::control::{LibraryRef, Role};
    let hers = s
        .app
        .control
        .create_group(alice, "Hers".into())
        .await
        .unwrap()
        .id;
    s.app
        .control
        .set_member(hers, bob, Role::Member)
        .await
        .unwrap()
        .unwrap();
    s.app.control.set_quota(alice, Some(1000)).await.unwrap();
    // Her group's files take nearly all of it.
    s.app
        .control
        .note_usage(LibraryRef::Group(hers), 900)
        .await
        .unwrap();
    assert_eq!(
        s.app
            .control
            .usage_of(alice, LibraryRef::User(alice))
            .await
            .unwrap(),
        900
    );
    let admin_view = s.app.control.users().await.unwrap();
    assert_eq!(
        admin_view
            .iter()
            .find(|u| u.user.id == alice)
            .unwrap()
            .bytes_used,
        900
    );
    // A download link handed to Bob stops working once he is out.
    let attachment = json!({"key": "FILEAAAA", "itemType": "attachment",
                            "linkMode": "imported_file", "title": "a.pdf"});
    let posted = s
        .call(
            "POST",
            &format!("/groups/{group}/items"),
            Some(&bob_key),
            &[("content-type", "application/json")],
            Body::from(json!([attachment]).to_string()),
        )
        .await;
    assert_eq!(body_json(posted).await["failed"], json!({}));
    s.app
        .storage
        .put_bytes(&format!("groups/{group}/files/FILEAAAA"), b"pdf".to_vec())
        .await
        .unwrap();
    let lib = s.app.libraries.get(LibraryRef::Group(group)).await.unwrap();
    lib.db
        .write(|c| {
            c.execute(
                "INSERT INTO file (item_key, md5, filename, filesize, mtime, version)
                 VALUES ('FILEAAAA', 'm', 'a.pdf', 3, 0, 1)",
                [],
            )
        })
        .await
        .unwrap();
    drop(lib);
    let redirect = s
        .call(
            "GET",
            &format!("/groups/{group}/items/FILEAAAA/file"),
            Some(&bob_key),
            &[],
            Body::empty(),
        )
        .await;
    assert_eq!(redirect.status(), StatusCode::FOUND);
    let link = header_str(&redirect, "location").replace(PUBLIC, "");
    s.app
        .control
        .remove_member(group, bob)
        .await
        .unwrap()
        .unwrap();
    let late = s.call("GET", &link, None, &[], Body::empty()).await;
    assert_eq!(late.status(), StatusCode::NOT_FOUND);

    // Deleting her group gives her the space back.
    s.app.control.delete_group(hers).await.unwrap();
    assert_eq!(
        s.app
            .control
            .usage_of(alice, LibraryRef::User(alice))
            .await
            .unwrap(),
        0
    );
}

#[tokio::test]
async fn only_members_can_be_named_by_id_on_a_group_page() {
    let (s, group, [(alice, _), (_, _), (carol, _)]) = group_server().await;
    // Alice is an admin; Carol is not in the group.
    let add = s
        .call(
            "POST",
            &format!("/ui/groups/{group}/members"),
            None,
            &[
                ("cookie", &session_for(&s, alice)),
                ("origin", PUBLIC),
                ("content-type", "application/x-www-form-urlencoded"),
            ],
            Body::from(format!("user={carol}&role=member")),
        )
        .await;
    assert_eq!(
        header_str(&add, "location"),
        format!("/ui/groups/{group}?error=user")
    );
    let (_, members) = s
        .app
        .control
        .group_with_members(group)
        .await
        .unwrap()
        .unwrap();
    assert!(members.iter().all(|m| m.user.id != carol));
}