File: server_test.go

package info (click to toggle)
golang-github-henrybear327-go-proton-api 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,088 kB
  • sloc: sh: 55; makefile: 26
file content (2283 lines) | stat: -rw-r--r-- 71,158 bytes parent folder | download
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
package server

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/mail"
	"net/url"
	"os"
	"runtime"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/bradenaw/juniper/parallel"

	"github.com/Masterminds/semver/v3"
	"github.com/ProtonMail/gluon/async"
	"github.com/ProtonMail/gluon/rfc822"
	"github.com/ProtonMail/gopenpgp/v2/crypto"
	"github.com/bradenaw/juniper/iterator"
	"github.com/bradenaw/juniper/stream"
	"github.com/bradenaw/juniper/xslices"
	"github.com/google/uuid"
	"github.com/henrybear327/go-proton-api"
	"github.com/stretchr/testify/require"
	"golang.org/x/exp/slices"
)

func TestServer_LoginLogout(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)
			require.Equal(t, "user", user.Name)
			require.Equal(t, "user@"+s.GetDomain(), user.Email)

			// Logout from the test API.
			require.NoError(t, c.AuthDelete(ctx))

			// Future requests should fail.
			require.Error(t, c.AuthDelete(ctx))
		})
	})
}

func TestServerMulti(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		_, _, err := s.CreateUser("user", []byte("pass"))
		require.NoError(t, err)

		// Create one client.
		c1, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
		require.NoError(t, err)
		defer c1.Close()

		// Create another client.
		c2, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
		require.NoError(t, err)
		defer c2.Close()

		// Both clients should be able to make requests.
		must(c1.GetUser(ctx))
		must(c2.GetUser(ctx))

		// Logout the first client; it should no longer be able to make requests.
		require.NoError(t, c1.AuthDelete(ctx))
		require.Panics(t, func() { must(c1.GetUser(ctx)) })

		// The second client should still be able to make requests.
		must(c2.GetUser(ctx))
	})
}

func TestServer_Ping(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, _ *proton.Manager) {
		ctl := proton.NewNetCtl()

		m := proton.New(
			proton.WithHostURL(s.GetHostURL()),
			proton.WithTransport(ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true})),
		)

		var status proton.Status

		m.AddStatusObserver(func(s proton.Status) {
			status = s
		})

		// When the network goes down, ping should fail.
		ctl.Disable()
		require.Error(t, m.Ping(ctx))
		require.Equal(t, proton.StatusDown, status)

		// When the network goes up, ping should succeed.
		ctl.Enable()
		require.NoError(t, m.Ping(ctx))
		require.Equal(t, proton.StatusUp, status)

		// When the API is down, ping should still succeed if the API is at least reachable.
		s.SetOffline(true)
		require.NoError(t, m.Ping(ctx))
		require.Equal(t, proton.StatusUp, status)

		// When the API is down, ping should fail if the API cannot be reached.
		ctl.Disable()
		require.Error(t, m.Ping(ctx))
		require.Equal(t, proton.StatusDown, status)

		// When the network goes up, ping should succeed, even if the API is down.
		ctl.Enable()
		require.NoError(t, m.Ping(ctx))
		require.Equal(t, proton.StatusUp, status)

		// When the API comes back alive, ping should succeed.
		s.SetOffline(false)
		require.NoError(t, m.Ping(ctx))
		require.Equal(t, proton.StatusUp, status)
	})
}

func TestServer_Bool(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1, func([]string) {
				metadata, err := c.GetMessageMetadata(ctx, proton.MessageFilter{})
				require.NoError(t, err)

				// By default the message is unread.
				require.True(t, bool(must(c.GetMessage(ctx, metadata[0].ID)).Unread))

				// Mark the message as read.
				require.NoError(t, c.MarkMessagesRead(ctx, metadata[0].ID))

				// Now the message is read.
				require.False(t, bool(must(c.GetMessage(ctx, metadata[0].ID)).Unread))
			})
		})
	})
}

func TestServer_Messages(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1000, func(messageIDs []string) {
				// Get the messages.
				metadata, err := c.GetMessageMetadata(ctx, proton.MessageFilter{})
				require.NoError(t, err)

				// The messages should be the ones we created.
				require.ElementsMatch(t, messageIDs, xslices.Map(metadata, func(metadata proton.MessageMetadata) string {
					return metadata.ID
				}))

				// The messages should be in All Mail and should be unread.
				for _, message := range metadata {
					require.True(t, bool(message.Unread))
					require.Equal(t, []string{proton.AllMailLabel}, message.LabelIDs)
				}

				// Mark the first three messages as read and put them in archive.
				require.NoError(t, c.MarkMessagesRead(ctx, messageIDs[0], messageIDs[1], messageIDs[2]))
				require.NoError(t, c.LabelMessages(ctx, []string{messageIDs[0], messageIDs[1], messageIDs[2]}, proton.ArchiveLabel))

				// They should now be read.
				require.False(t, bool(must(c.GetMessage(ctx, messageIDs[0])).Unread))
				require.False(t, bool(must(c.GetMessage(ctx, messageIDs[1])).Unread))
				require.False(t, bool(must(c.GetMessage(ctx, messageIDs[2])).Unread))

				// They should now be in archive.
				require.ElementsMatch(t, []string{proton.ArchiveLabel, proton.AllMailLabel}, must(c.GetMessage(ctx, messageIDs[0])).LabelIDs)
				require.ElementsMatch(t, []string{proton.ArchiveLabel, proton.AllMailLabel}, must(c.GetMessage(ctx, messageIDs[1])).LabelIDs)
				require.ElementsMatch(t, []string{proton.ArchiveLabel, proton.AllMailLabel}, must(c.GetMessage(ctx, messageIDs[2])).LabelIDs)

				// Put them in inbox.
				require.NoError(t, c.LabelMessages(ctx, []string{messageIDs[0], messageIDs[1], messageIDs[2]}, proton.ArchiveLabel))
			})
		})
	})
}

func TestServer_GetMessageMetadataPage(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1000, func(messageIDs []string) {
				for _, chunk := range xslices.Chunk(messageIDs, 150) {
					// Get the messages.
					metadata, err := c.GetMessageMetadataPage(ctx, 0, 150, proton.MessageFilter{ID: chunk})
					require.NoError(t, err)

					// The messages should be the ones we created.
					require.ElementsMatch(t, chunk, xslices.Map(metadata, func(metadata proton.MessageMetadata) string {
						return metadata.ID
					}))

				}
			})
		})
	})
}

func TestServer_MessageFilter(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1000, func(messageIDs []string) {
				// Get the messages.
				metadata, err := c.GetMessageMetadata(ctx, proton.MessageFilter{})
				require.NoError(t, err)

				// The messages should be the ones we created.
				require.ElementsMatch(t, messageIDs, xslices.Map(metadata, func(metadata proton.MessageMetadata) string {
					return metadata.ID
				}))

				// Get metadata for just the first three messages.
				partial, err := c.GetMessageMetadata(ctx, proton.MessageFilter{
					ID: []string{
						metadata[0].ID,
						metadata[1].ID,
						metadata[2].ID,
					},
				})
				require.NoError(t, err)

				// The messages should be just the first three.
				require.Equal(t, metadata[:3], partial)
			})
		})
	})
}

func TestServer_MessageFilterDesc(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 100, func(messageIDs []string) {
				allMetadata := make([]proton.MessageMetadata, 0, 100)

				// first request.
				{
					metadata, err := c.GetMessageMetadataPage(ctx, 0, 10, proton.MessageFilter{Desc: true})
					require.NoError(t, err)

					allMetadata = append(allMetadata, metadata...)
				}

				for i := 1; i < 11; i++ {
					// Get the messages.
					metadata, err := c.GetMessageMetadataPage(ctx, 0, 10, proton.MessageFilter{Desc: true, EndID: allMetadata[len(allMetadata)-1].ID})
					require.NoError(t, err)
					require.NotEmpty(t, metadata)
					require.Equal(t, metadata[0].ID, allMetadata[len(allMetadata)-1].ID)
					allMetadata = append(allMetadata, metadata[1:]...)
				}

				// Final check. Asking for EndID as last message multiple times will always return the last id.
				metadata, err := c.GetMessageMetadataPage(ctx, 0, 10, proton.MessageFilter{Desc: true, EndID: allMetadata[len(allMetadata)-1].ID})
				require.NoError(t, err)
				require.Len(t, metadata, 1)
				require.Equal(t, metadata[0].ID, allMetadata[len(allMetadata)-1].ID)

				// The messages should be the ones we created.
				require.ElementsMatch(t, messageIDs, xslices.Map(allMetadata, func(metadata proton.MessageMetadata) string {
					return metadata.ID
				}))
			})
		})
	})
}

func TestServer_MessageIDs(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 10000, func(wantMessageIDs []string) {
				allMessageIDs, err := c.GetAllMessageIDs(ctx, "")
				require.NoError(t, err)
				require.ElementsMatch(t, wantMessageIDs, allMessageIDs)

				halfMessageIDs, err := c.GetAllMessageIDs(ctx, allMessageIDs[len(allMessageIDs)/2])
				require.NoError(t, err)
				require.ElementsMatch(t, allMessageIDs[len(allMessageIDs)/2+1:], halfMessageIDs)
			})
		})
	})
}

func TestServer_MessagesDelete(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1000, func(messageIDs []string) {
				// Get the messages.
				metadata, err := c.GetMessageMetadata(ctx, proton.MessageFilter{})
				require.NoError(t, err)

				// The messages should be the ones we created.
				require.ElementsMatch(t, messageIDs, xslices.Map(metadata, func(metadata proton.MessageMetadata) string {
					return metadata.ID
				}))

				// Delete half the messages.
				require.NoError(t, c.DeleteMessage(ctx, messageIDs[0:500]...))

				// Get the remaining messages.
				remaining, err := c.GetMessageMetadata(ctx, proton.MessageFilter{})
				require.NoError(t, err)

				// The remaining messages should be the ones we didn't delete.
				require.ElementsMatch(t, messageIDs[500:], xslices.Map(remaining, func(metadata proton.MessageMetadata) string {
					return metadata.ID
				}))
			})
		})
	})
}

func TestServer_MessagesDeleteAfterUpdate(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1000, func(messageIDs []string) {
				// Get the initial event ID.
				eventID, err := c.GetLatestEventID(ctx)
				require.NoError(t, err)

				// Put half the messages in archive.
				require.NoError(t, c.LabelMessages(ctx, messageIDs[0:500], proton.ArchiveLabel))

				// Delete half the messages.
				require.NoError(t, c.DeleteMessage(ctx, messageIDs[0:500]...))

				// Get the event reflecting this change.
				event, more, err := c.GetEvent(ctx, eventID)
				require.NoError(t, err)
				require.False(t, more)
				require.Equal(t, 1, len(event))

				// The event should have the correct number of message events.
				require.Len(t, event[0].Messages, 500)

				// All the events should be delete events.
				for _, message := range event[0].Messages {
					require.Equal(t, proton.EventDelete, message.Action)
				}
			})
		})
	})
}

func TestServer_Events(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 3, func(messageIDs []string) {
				// Get the latest event ID to stream from.
				fromEventID, err := c.GetLatestEventID(ctx)
				require.NoError(t, err)

				// Begin collecting events.
				eventCh := c.NewEventStream(ctx, time.Second, 0, fromEventID)

				// Mark a message as read.
				require.NoError(t, c.MarkMessagesRead(ctx, messageIDs[0]))

				// The message should eventually be read.
				require.Eventually(t, func() bool {
					event := <-eventCh

					if len(event.Messages) != 1 {
						return false
					}

					if event.Messages[0].ID != messageIDs[0] {
						return false
					}

					return !bool(event.Messages[0].Message.Unread)
				}, 5*time.Second, time.Millisecond*100)

				// Add another message to archive.
				require.NoError(t, c.LabelMessages(ctx, []string{messageIDs[1]}, proton.ArchiveLabel))

				// The message should eventually be in archive and all mail.
				require.Eventually(t, func() bool {
					event := <-eventCh

					if len(event.Messages) != 1 {
						return false
					}

					if event.Messages[0].ID != messageIDs[1] {
						return false
					}

					return elementsMatch([]string{proton.ArchiveLabel, proton.AllMailLabel}, event.Messages[0].Message.LabelIDs)
				}, 5*time.Second, time.Millisecond*100)

				// Perform a sequence of actions on the same message.
				require.NoError(t, c.LabelMessages(ctx, []string{messageIDs[2]}, proton.TrashLabel))
				require.NoError(t, c.UnlabelMessages(ctx, []string{messageIDs[2]}, proton.TrashLabel))
				require.NoError(t, c.MarkMessagesRead(ctx, messageIDs[2]))
				require.NoError(t, c.MarkMessagesUnread(ctx, messageIDs[2]))

				// The final state of the message should be correct.
				require.Eventually(t, func() bool {
					event := <-eventCh

					if len(event.Messages) != 1 {
						return false
					}

					if event.Messages[0].ID != messageIDs[2] {
						return false
					}

					return bool(event.Messages[0].Message.Unread) && elementsMatch([]string{proton.AllMailLabel}, event.Messages[0].Message.LabelIDs)
				}, 5*time.Second, time.Millisecond*100)

				// No more events should be sent.
				select {
				case <-eventCh:
					t.Fatal("unexpected event")

				default:
					// ....
				}
			})
		})
	})
}

func TestServer_Events_Multi(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		for i := 0; i < 10; i++ {
			withUser(ctx, t, s, m, fmt.Sprintf("user%v", i), "pass", func(c *proton.Client) {
				latest, err := c.GetLatestEventID(ctx)
				require.NoError(t, err)

				// Fetching latest again should return the same event ID.
				latestAgain, err := c.GetLatestEventID(ctx)
				require.NoError(t, err)
				require.Equal(t, latest, latestAgain)

				events, more, err := c.GetEvent(ctx, latest)
				require.NoError(t, err)
				require.False(t, more)

				// The event should be empty.
				require.Equal(t, []proton.Event{{EventID: events[0].EventID}}, events)

				// After fetching an empty event, its ID should still be the latest.
				eventAgain, more, err := c.GetEvent(ctx, events[0].EventID)
				require.NoError(t, err)
				require.False(t, more)
				require.Equal(t, eventAgain[0].EventID, events[0].EventID)
			})
		}
	})
}

func TestServer_Events_Refresh(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			// Get the latest event ID to stream from.
			fromEventID, err := c.GetLatestEventID(ctx)
			require.NoError(t, err)

			// Refresh the user's mail.
			require.NoError(t, s.RefreshUser(user.ID, proton.RefreshMail))

			// Begin collecting events.
			eventCh := c.NewEventStream(ctx, time.Second, 0, fromEventID)

			// The user should eventually be refreshed.
			require.Eventually(t, func() bool {
				return (<-eventCh).Refresh&proton.RefreshMail != 0
			}, 5*time.Second, time.Millisecond*100)
		})
	})
}

func TestServer_Events_UserSettings(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			_, err = s.b.SetUserSettingsTelemetry(user.ID, proton.SettingDisabled)
			require.NoError(t, err)

			// Get the latest event ID to stream from.
			fromEventID, err := c.GetLatestEventID(ctx)
			require.NoError(t, err)

			// Refresh the user's mail.
			_, err = s.b.SetUserSettingsTelemetry(user.ID, proton.SettingEnabled)
			require.NoError(t, err)

			// Begin collecting events.
			eventCh := c.NewEventStream(ctx, time.Second, 0, fromEventID)

			// The user should eventually be refreshed.
			require.Eventually(t, func() bool {
				e := <-eventCh
				return e.UserSettings != nil && e.UserSettings.Telemetry == proton.SettingEnabled
			}, 5*time.Second, time.Millisecond*100)
		})
	})
}

func TestServer_RevokeUser(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)
			require.Equal(t, "user", user.Name)
			require.Equal(t, "user@"+s.GetDomain(), user.Email)

			// Revoke the user's auth.
			require.NoError(t, s.RevokeUser(user.ID))

			// Future requests should fail.
			require.Error(t, c.AuthDelete(ctx))
		})
	})
}

func TestServer_Calls(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			var calls []Call

			// Watch calls that are made.
			s.AddCallWatcher(func(call Call) {
				calls = append(calls, call)
			})

			// Get the user.
			_, err := c.GetUser(ctx)
			require.NoError(t, err)

			// Logout the user.
			require.NoError(t, c.AuthDelete(ctx))

			// The user call should be correct.
			userCall := calls[0]
			require.Equal(t, "/core/v4/users", userCall.URL.Path)
			require.Equal(t, "GET", userCall.Method)
			require.Equal(t, http.StatusOK, userCall.Status)

			// The logout call should be correct.
			logoutCall := calls[1]
			require.Equal(t, "/auth/v4", logoutCall.URL.Path)
			require.Equal(t, "DELETE", logoutCall.Method)
			require.Equal(t, http.StatusOK, logoutCall.Status)
		})
	})
}

func TestServer_Calls_Status(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			var calls []Call

			// Watch calls that are made.
			s.AddCallWatcher(func(call Call) {
				calls = append(calls, call)
			})

			// Make a bad call.
			_, err := c.GetMessage(ctx, "no such message ID")
			require.Error(t, err)

			// The user call should have error status.
			require.Equal(t, http.StatusUnprocessableEntity, calls[0].Status)
		})
	})
}

func TestServer_Calls_Request(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		var calls []Call

		s.AddCallWatcher(func(call Call) {
			calls = append(calls, call)
		})

		withUser(ctx, t, s, m, "user", "pass", func(*proton.Client) {
			require.Equal(
				t,
				calls[0].RequestBody,
				must(json.Marshal(proton.AuthInfoReq{Username: "user"})),
			)
		})
	})
}

func TestServer_Calls_Response(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		var calls []Call

		s.AddCallWatcher(func(call Call) {
			calls = append(calls, call)
		})

		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			salts, err := c.GetSalts(ctx)
			require.NoError(t, err)

			require.Equal(
				t,
				calls[len(calls)-1].ResponseBody,
				must(json.Marshal(struct{ KeySalts []proton.Salt }{salts})),
			)
		})
	})
}

func TestServer_Calls_Cookies(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		var calls []Call

		s.AddCallWatcher(func(call Call) {
			calls = append(calls, call)
		})

		withUser(ctx, t, s, m, "user", "pass", func(*proton.Client) {
			// The header in the first call's response should set the Session-Id cookie.
			resHeader := (&http.Response{Header: calls[len(calls)-2].ResponseHeader})
			require.Len(t, resHeader.Cookies(), 1)
			require.Equal(t, "Session-Id", resHeader.Cookies()[0].Name)
			require.NotEmpty(t, resHeader.Cookies()[0].Value)

			// The cookie should be sent in the next call.
			reqHeader := (&http.Request{Header: calls[len(calls)-1].RequestHeader})
			require.Len(t, reqHeader.Cookies(), 1)
			require.Equal(t, "Session-Id", reqHeader.Cookies()[0].Name)
			require.NotEmpty(t, reqHeader.Cookies()[0].Value)

			// The cookie should be the same.
			require.Equal(t, resHeader.Cookies()[0].Value, reqHeader.Cookies()[0].Value)
		})
	})
}

func TestServer_Calls_Manager(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		var calls []Call

		// Watch calls that are made.
		s.AddCallWatcher(func(call Call) {
			calls = append(calls, call)
		})

		// Make a non-user request.
		require.NoError(t, m.ReportBug(ctx, proton.ReportBugReq{}))

		// The call should be correct.
		reportCall := calls[0]
		require.Equal(t, "/core/v4/reports/bug", reportCall.URL.Path)
		require.Equal(t, "POST", reportCall.Method)
		require.Equal(t, http.StatusOK, reportCall.Status)
	})
}

func TestServer_CreateMessage(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			draft, err := c.CreateDraft(ctx, addrKRs[addr[0].ID], proton.CreateDraftReq{
				Message: proton.DraftTemplate{
					Subject: "My subject",
					Sender:  &mail.Address{Address: addr[0].Email},
					ToList:  []*mail.Address{{Address: "recipient@example.com"}},
				},
			})
			require.NoError(t, err)

			require.Equal(t, addr[0].ID, draft.AddressID)
			require.Equal(t, "My subject", draft.Subject)
			require.Equal(t, &mail.Address{Address: "user@" + s.GetDomain()}, draft.Sender)
			require.Equal(t, []*mail.Address{{Address: "recipient@example.com"}}, draft.ToList)
			require.ElementsMatch(t, []string{proton.AllMailLabel, proton.AllDraftsLabel, proton.DraftsLabel}, draft.LabelIDs)
		})
	})
}

func TestServer_UpdateDraft(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			// Create the draft.
			draft, err := c.CreateDraft(ctx, addrKRs[addr[0].ID], proton.CreateDraftReq{
				Message: proton.DraftTemplate{
					Subject: "My subject",
					Sender:  &mail.Address{Address: addr[0].Email},
					ToList:  []*mail.Address{{Address: "recipient@example.com"}},
				},
			})
			require.NoError(t, err)
			require.Equal(t, addr[0].ID, draft.AddressID)
			require.Equal(t, "My subject", draft.Subject)
			require.Equal(t, &mail.Address{Address: "user@" + s.GetDomain()}, draft.Sender)
			require.Equal(t, []*mail.Address{{Address: "recipient@example.com"}}, draft.ToList)

			// Create an event stream to watch for an update event.
			fromEventID, err := c.GetLatestEventID(ctx)
			require.NoError(t, err)

			eventCh := c.NewEventStream(ctx, time.Second, 0, fromEventID)

			// Update the draft subject/to-list.
			msg, err := c.UpdateDraft(ctx, draft.ID, addrKRs[addr[0].ID], proton.UpdateDraftReq{
				Message: proton.DraftTemplate{
					Subject:  "Edited subject",
					Sender:   &mail.Address{Address: addr[0].Email},
					ToList:   []*mail.Address{{Address: "edited@example.com"}},
					MIMEType: rfc822.TextPlain,
				},
			})
			require.NoError(t, err)
			require.Equal(t, "Edited subject", msg.Subject)

			// We should eventually get an update event.
			require.Eventually(t, func() bool {
				event := <-eventCh

				if len(event.Messages) < 1 {
					return false
				}

				if event.Messages[0].ID != draft.ID {
					return false
				}

				if event.Messages[0].Action != proton.EventUpdate {
					return false
				}

				require.Equal(t, draft.ID, event.Messages[0].ID)
				require.Equal(t, "Edited subject", event.Messages[0].Message.Subject)
				require.Equal(t, []*mail.Address{{Address: "edited@example.com"}}, event.Messages[0].Message.ToList)

				return true
			}, 5*time.Second, time.Millisecond*100)
		})
	})
}

func TestServer_SendMessage(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			draft, err := c.CreateDraft(ctx, addrKRs[addr[0].ID], proton.CreateDraftReq{
				Message: proton.DraftTemplate{
					Subject: "My subject",
					Sender:  &mail.Address{Address: addr[0].Email},
					ToList:  []*mail.Address{{Address: "recipient@example.com"}},
				},
			})
			require.NoError(t, err)

			sent, err := c.SendDraft(ctx, draft.ID, proton.SendDraftReq{})
			require.NoError(t, err)

			require.Equal(t, draft.ID, sent.ID)
			require.Equal(t, addr[0].ID, sent.AddressID)
			require.Equal(t, "My subject", sent.Subject)
			require.Equal(t, []*mail.Address{{Address: "recipient@example.com"}}, sent.ToList)
			require.Contains(t, sent.LabelIDs, proton.SentLabel)
		})
	})
}

func TestServer_AuthDelete(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			require.NoError(t, c.AuthDelete(ctx))
		})
	})
}

func TestServer_ForceUpgrade(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	s := New()
	defer s.Close()

	s.SetMinAppVersion(semver.MustParse("1.0.0"))

	if _, _, err := s.CreateUser("user", []byte("pass")); err != nil {
		t.Fatal(err)
	}

	m := proton.New(
		proton.WithHostURL(s.GetHostURL()),
		proton.WithAppVersion("proton_0.9.0"),
		proton.WithTransport(proton.InsecureTransport()),
	)
	defer m.Close()

	var called bool

	m.AddErrorHandler(proton.AppVersionBadCode, func() {
		called = true
	})

	if _, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass")); err == nil {
		t.Fatal(err)
	}

	require.True(t, called)
}

func TestServer_Import(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			res := importMessages(ctx, t, c, addr[0].ID, addrKRs[addr[0].ID], []string{}, proton.MessageFlagReceived, 1)
			require.NoError(t, err)
			require.Len(t, res, 1)
			require.Equal(t, proton.SuccessCode, res[0].Code)

			message, err := c.GetMessage(ctx, res[0].MessageID)
			require.NoError(t, err)

			dec, err := message.Decrypt(addrKRs[message.AddressID])
			require.NoError(t, err)
			require.NotEmpty(t, dec)
		})
	})
}

func TestServer_Import_Dedup(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			subjectGenerator := func() string {
				return "my Subject"
			}

			res := importMessagesWithSubjectGenerator(
				ctx,
				t,
				c,
				addr[0].ID,
				addrKRs[addr[0].ID],
				[]string{},
				proton.MessageFlagReceived,
				1,
				subjectGenerator,
			)
			require.NoError(t, err)
			require.Len(t, res, 1)
			require.Equal(t, proton.SuccessCode, res[0].Code)

			message, err := c.GetMessage(ctx, res[0].MessageID)
			require.NoError(t, err)

			dec, err := message.Decrypt(addrKRs[message.AddressID])
			require.NoError(t, err)
			require.NotEmpty(t, dec)

			// Import message again should be deduped.
			resDedup := importMessagesWithSubjectGenerator(
				ctx,
				t,
				c,
				addr[0].ID,
				addrKRs[addr[0].ID],
				[]string{},
				proton.MessageFlagReceived,
				1,
				subjectGenerator,
			)
			require.NoError(t, err)
			require.Len(t, resDedup, 1)
			require.Equal(t, proton.SuccessCode, resDedup[0].Code)
			require.Equal(t, res[0].MessageID, resDedup[0].MessageID)
		})
	}, WithMessageDedup())
}

func TestServer_Labels(t *testing.T) {
	type add string
	type rem string

	tests := []struct {
		name         string
		flags        proton.MessageFlag
		actions      []any
		wantLabelIDs []string
		wantError    bool
	}{
		{
			name:         "received flag, no actions",
			flags:        proton.MessageFlagReceived,
			wantLabelIDs: []string{proton.AllMailLabel},
		},
		{
			name:         "sent flag, no actions",
			flags:        proton.MessageFlagSent,
			wantLabelIDs: []string{proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, no actions",
			flags:        proton.MessageFlagScheduledSend,
			wantLabelIDs: []string{proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel)},
			wantLabelIDs: []string{proton.InboxLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag, add sent",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.SentLabel)},
			wantLabelIDs: []string{proton.SentLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add scheduled",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.AllScheduledLabel)},
			wantLabelIDs: []string{proton.AllScheduledLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox then add archive",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel), add(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.ArchiveLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag, add sent then add archive",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.SentLabel), add(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.ArchiveLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add scheduled then add archive",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.AllScheduledLabel), add(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.ArchiveLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox then remove inbox",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel), rem(proton.InboxLabel)},
			wantLabelIDs: []string{proton.AllMailLabel},
		},
		{
			name:         "sent flag, add sent then remove sent",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.SentLabel), rem(proton.SentLabel)},
			wantLabelIDs: []string{proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add scheduled then remove scheduled",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.AllScheduledLabel), rem(proton.AllScheduledLabel)},
			wantLabelIDs: []string{proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox then remove archive",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel), rem(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.InboxLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag, add sent then remove archive",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.SentLabel), rem(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.SentLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add scheduled then remove archive",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.AllScheduledLabel), rem(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.AllScheduledLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox then remove inbox then add archive",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel), rem(proton.InboxLabel), add(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.ArchiveLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag, add sent then remove sent then add archive",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.SentLabel), rem(proton.SentLabel), add(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.ArchiveLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add scheduled then remove scheduled then add archive",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.AllScheduledLabel), rem(proton.AllScheduledLabel), add(proton.ArchiveLabel)},
			wantLabelIDs: []string{proton.ArchiveLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add starred",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.StarredLabel)},
			wantLabelIDs: []string{proton.StarredLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag, add starred",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.StarredLabel)},
			wantLabelIDs: []string{proton.StarredLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add starred",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.StarredLabel)},
			wantLabelIDs: []string{proton.StarredLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox, add starred, remove inbox",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel), add(proton.StarredLabel), rem(proton.InboxLabel)},
			wantLabelIDs: []string{proton.StarredLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag, add sent, add starred, remove sent",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.SentLabel), add(proton.StarredLabel), rem(proton.SentLabel)},
			wantLabelIDs: []string{proton.StarredLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add scheduled, add starred, remove scheduled",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.AllScheduledLabel), add(proton.StarredLabel), rem(proton.AllScheduledLabel)},
			wantLabelIDs: []string{proton.StarredLabel, proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add trash, remove trash",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.TrashLabel), rem(proton.TrashLabel)},
			wantLabelIDs: []string{proton.AllMailLabel},
		},
		{
			name:         "sent flag, add trash, remove trash",
			flags:        proton.MessageFlagSent,
			actions:      []any{add(proton.TrashLabel), rem(proton.TrashLabel)},
			wantLabelIDs: []string{proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "scheduled flag, add trash, remove trash",
			flags:        proton.MessageFlagScheduledSend,
			actions:      []any{add(proton.TrashLabel), rem(proton.TrashLabel)},
			wantLabelIDs: []string{proton.AllMailLabel, proton.AllSentLabel},
		},
		{
			name:         "received flag, add inbox, add trash, remove inbox",
			flags:        proton.MessageFlagReceived,
			actions:      []any{add(proton.InboxLabel), add(proton.TrashLabel), rem(proton.InboxLabel)},
			wantLabelIDs: []string{proton.AllMailLabel, proton.TrashLabel},
		},
		{
			name:         "scheduled & sent flags, add scheduled, add sent",
			flags:        proton.MessageFlagScheduledSend | proton.MessageFlagSent,
			actions:      []any{add(proton.AllScheduledLabel), add(proton.SentLabel)},
			wantLabelIDs: []string{proton.AllMailLabel, proton.SentLabel, proton.AllSentLabel},
		},
	}

	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			for _, tt := range tests {
				t.Run(tt.name, func(t *testing.T) {
					res := importMessages(ctx, t, c, addr[0].ID, addrKRs[addr[0].ID], []string{}, tt.flags, 1)

					require.True(t, (func() error {
						for _, action := range tt.actions {
							switch action := action.(type) {
							case add:
								if err := c.LabelMessages(ctx, []string{res[0].MessageID}, string(action)); err != nil {
									return err
								}

							case rem:
								if err := c.UnlabelMessages(ctx, []string{res[0].MessageID}, string(action)); err != nil {
									return err
								}
							}
						}

						return nil
					}() != nil) == tt.wantError)

					message, err := c.GetMessage(ctx, res[0].MessageID)
					require.NoError(t, err)

					// The message should be in the correct labels.
					require.ElementsMatch(t, tt.wantLabelIDs, message.LabelIDs)

					// The flags should be preserved after import.
					require.True(t, message.Flags&tt.flags == tt.flags)
				})
			}
		})
	})
}

func TestServer_Import_FlagsAndLabels(t *testing.T) {
	tests := []struct {
		name         string
		labelIDs     []string
		flags        proton.MessageFlag
		wantLabelIDs []string
		wantError    bool
	}{
		{
			name:         "received flag --> no label",
			flags:        proton.MessageFlagReceived,
			wantLabelIDs: []string{proton.AllMailLabel},
		},
		{
			name:         "received flag --> inbox",
			labelIDs:     []string{proton.InboxLabel},
			flags:        proton.MessageFlagReceived,
			wantLabelIDs: []string{proton.InboxLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag --> sent",
			labelIDs:     []string{proton.SentLabel},
			flags:        proton.MessageFlagSent,
			wantLabelIDs: []string{proton.SentLabel, proton.AllSentLabel, proton.AllMailLabel},
		},
		{
			name:         "received flag --> sent",
			labelIDs:     []string{proton.SentLabel},
			flags:        proton.MessageFlagReceived,
			wantLabelIDs: []string{proton.InboxLabel, proton.AllMailLabel},
		},
		{
			name:         "sent flag --> inbox",
			labelIDs:     []string{proton.InboxLabel},
			flags:        proton.MessageFlagSent,
			wantLabelIDs: []string{proton.SentLabel, proton.AllSentLabel, proton.AllMailLabel},
		},
		{
			name:         "no flag --> drafts",
			labelIDs:     []string{proton.DraftsLabel},
			wantLabelIDs: []string{proton.DraftsLabel, proton.AllDraftsLabel, proton.AllMailLabel},
		},
		{
			name:      "forbidden: received flag --> All Mail",
			labelIDs:  []string{proton.AllMailLabel},
			flags:     proton.MessageFlagReceived,
			wantError: true,
		},
		{
			name:      "forbidden: sent flag --> All Mail",
			labelIDs:  []string{proton.AllMailLabel},
			flags:     proton.MessageFlagSent,
			wantError: true,
		},
		{
			name:      "forbidden: received flag --> inbox and all mail",
			labelIDs:  []string{proton.InboxLabel, proton.AllMailLabel},
			flags:     proton.MessageFlagReceived,
			wantError: true,
		},
		{
			name:      "forbidden: sent flag --> sent and all mail",
			labelIDs:  []string{proton.SentLabel, proton.AllMailLabel},
			flags:     proton.MessageFlagSent,
			wantError: true,
		},
		{
			name:      "forbidden: received flag --> inbox and sent",
			labelIDs:  []string{proton.InboxLabel, proton.SentLabel},
			flags:     proton.MessageFlagReceived,
			wantError: true,
		},
		{
			name:      "forbidden: sent flag --> inbox and sent",
			labelIDs:  []string{proton.InboxLabel, proton.SentLabel},
			flags:     proton.MessageFlagSent,
			wantError: true,
		},
		{
			name:      "forbidden: received flag --> inbox and archive",
			labelIDs:  []string{proton.InboxLabel, proton.ArchiveLabel},
			flags:     proton.MessageFlagReceived,
			wantError: true,
		},
	}

	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			for _, tt := range tests {
				t.Run(tt.name, func(t *testing.T) {
					str, err := c.ImportMessages(ctx, addrKRs[addr[0].ID], runtime.NumCPU(), runtime.NumCPU(), []proton.ImportReq{{
						Metadata: proton.ImportMetadata{
							AddressID: addr[0].ID,
							Flags:     tt.flags,
							LabelIDs:  tt.labelIDs,
						},
						Message: newMessageLiteral("sender@example.com", "recipient@example.com"),
					}}...)
					require.NoError(t, err)

					res, err := stream.Collect(ctx, str)
					if tt.wantError {
						require.Error(t, err)
					} else {
						require.NoError(t, err)
						require.Equal(t, proton.SuccessCode, res[0].Code)

						message, err := c.GetMessage(ctx, res[0].MessageID)
						require.NoError(t, err)

						// The message should be in the correct labels.
						require.ElementsMatch(t, tt.wantLabelIDs, message.LabelIDs)

						// The flags should be preserved after import.
						require.True(t, message.Flags&tt.flags == tt.flags)
					}
				})
			}
		})
	})
}

func TestServer_PublicKeys(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		if _, _, err := s.CreateUser("other", []byte("pass")); err != nil {
			t.Fatal(err)
		}

		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			intKeys, intType, err := c.GetPublicKeys(ctx, "other@"+s.GetDomain())
			require.NoError(t, err)
			require.Equal(t, proton.RecipientTypeInternal, intType)
			require.Len(t, intKeys, 1)

			extKeys, extType, err := c.GetPublicKeys(ctx, "other@example.com")
			require.NoError(t, err)
			require.Equal(t, proton.RecipientTypeExternal, extType)
			require.Len(t, extKeys, 0)
		})
	})
}

func TestServer_Proxy(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		var calls []Call

		s.AddCallWatcher(func(call Call) {
			calls = append(calls, call)
		})

		withUser(ctx, t, s, m, "user", "pass", func(_ *proton.Client) {
			proxy := New(
				WithProxyOrigin(s.GetHostURL()),
				WithProxyTransport(proton.InsecureTransport()),
			)
			defer proxy.Close()

			m := proton.New(
				proton.WithHostURL(proxy.GetProxyURL()),
				proton.WithTransport(proton.InsecureTransport()),
			)
			defer m.Close()

			// Login -- the call should be proxied to the upstream server.
			c, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
			require.NoError(t, err)
			defer c.Close()

			// The results of the call should be correct.
			user, err := c.GetUser(ctx)
			require.NoError(t, err)
			require.Equal(t, "user", user.Name)
		})

		// Assert that the calls were proxied.
		require.Greater(t, len(calls), 0)
	})
}

func TestServer_Proxy_Cache(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(_ *proton.Client) {
			proxy := New(
				WithProxyOrigin(s.GetHostURL()),
				WithProxyTransport(proton.InsecureTransport()),
				WithAuthCacher(NewAuthCache()),
			)
			defer proxy.Close()

			// Need to skip verifying the server proofs for the proxy cache feature to work!
			m := proton.New(
				proton.WithHostURL(proxy.GetProxyURL()),
				proton.WithTransport(proton.InsecureTransport()),
				proton.WithSkipVerifyProofs(),
			)
			defer m.Close()

			// Login 3 times; we should produce 1 unique auth.
			require.Len(t, xslices.Unique(iterator.Collect(iterator.Map(iterator.Counter(3), func(int) string {
				c, auth, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
				require.NoError(t, err)
				defer c.Close()

				return auth.UID
			}))), 1)
		})
	})
}

func TestServer_Proxy_AuthDelete(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(_ *proton.Client) {
			proxy := New(
				WithProxyOrigin(s.GetHostURL()),
				WithProxyTransport(proton.InsecureTransport()),
				WithAuthCacher(NewAuthCache()),
			)
			defer proxy.Close()

			// Need to skip verifying the server proofs for the proxy cache feature to work!
			m := proton.New(
				proton.WithHostURL(proxy.GetProxyURL()),
				proton.WithTransport(proton.InsecureTransport()),
			)
			defer m.Close()

			// Watch for login -- the calls should be proxied.
			var login []Call

			s.AddCallWatcher(func(call Call) {
				login = append(login, call)
			})

			// Login -- the call should be proxied to the upstream server.
			c, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
			require.NoError(t, err)
			defer c.Close()

			// Assert that the login was proxied.
			require.NotEmpty(t, len(login))

			// Watch for logout -- logout should not be proxied to the upstream server.
			var logout []Call

			s.AddCallWatcher(func(call Call) {
				logout = append(logout, call)
			})

			// Logout -- the call should not be proxied to the upstream server.
			require.NoError(t, c.AuthDelete(ctx))

			// Assert that the logout was not proxied!
			require.Empty(t, len(logout))
		})
	})
}

func TestServer_RealProxy(t *testing.T) {
	username := os.Getenv("GO_PROTON_API_TEST_USERNAME")
	password := os.Getenv("GO_PROTON_API_TEST_PASSWORD")

	if username == "" || password == "" {
		t.Skip("skipping test, set the username and password to run")
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	proxy := New()
	defer proxy.Close()

	m := proton.New(
		proton.WithHostURL(proxy.GetProxyURL()),
		proton.WithTransport(proton.InsecureTransport()),
	)
	defer m.Close()

	// Login -- the call should be proxied to the upstream server.
	c, _, err := m.NewClientWithLogin(ctx, username, []byte(password))
	require.NoError(t, err)
	defer c.Close()

	// The results of the call should be correct.
	user, err := c.GetUser(ctx)
	require.NoError(t, err)
	require.Equal(t, username, user.Name)
}

func TestServer_RealProxy_Cache(t *testing.T) {
	username := os.Getenv("GO_PROTON_API_TEST_USERNAME")
	password := os.Getenv("GO_PROTON_API_TEST_PASSWORD")

	if username == "" || password == "" {
		t.Skip("skipping test, set the username and password to run")
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	proxy := New(WithAuthCacher(NewAuthCache()))
	defer proxy.Close()

	m := proton.New(
		proton.WithHostURL(proxy.GetProxyURL()),
		proton.WithTransport(proton.InsecureTransport()),
		proton.WithSkipVerifyProofs(),
	)
	defer m.Close()

	// Login 3 times; we should produce 1 unique auth.
	require.Len(t, xslices.Unique(iterator.Collect(iterator.Map(iterator.Counter(3), func(int) string {
		c, auth, err := m.NewClientWithLogin(ctx, username, []byte(password))
		require.NoError(t, err)
		defer c.Close()

		return auth.UID
	}))), 1)
}

func TestServer_Messages_Fetch(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			withMessages(ctx, t, c, "pass", 1000, func(messageIDs []string) {
				ctl := proton.NewNetCtl()

				mm := proton.New(
					proton.WithHostURL(s.GetHostURL()),
					proton.WithTransport(ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true})),
				)
				defer mm.Close()

				cc, _, err := mm.NewClientWithLogin(ctx, "user", []byte("pass"))
				require.NoError(t, err)
				defer cc.Close()

				total := countBytesRead(ctl, func() {
					res, err := stream.Collect(ctx, getFullMessages(ctx, cc, runtime.NumCPU(), runtime.NumCPU(), messageIDs...))
					require.NoError(t, err)
					require.NotEmpty(t, res)
				})

				ctl.SetReadLimit(total / 2)

				require.Less(t, countBytesRead(ctl, func() {
					res, err := stream.Collect(ctx, getFullMessages(ctx, cc, runtime.NumCPU(), runtime.NumCPU(), messageIDs...))
					require.Error(t, err)
					require.Empty(t, res)
				}), total)

				ctl.SetReadLimit(0)

				require.Equal(t, countBytesRead(ctl, func() {
					res, err := stream.Collect(ctx, getFullMessages(ctx, cc, runtime.NumCPU(), runtime.NumCPU(), messageIDs...))
					require.NoError(t, err)
					require.NotEmpty(t, res)
				}), total)
			})
		})
	}, WithTLS(false))
}

func TestServer_Status(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(*proton.Client) {
			ctl := proton.NewNetCtl()

			mm := proton.New(
				proton.WithHostURL(s.GetHostURL()),
				proton.WithTransport(ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true})),
			)
			defer mm.Close()

			statusCh := make(chan proton.Status, 1)

			mm.AddStatusObserver(func(status proton.Status) {
				statusCh <- status
			})

			cc, _, err := mm.NewClientWithLogin(ctx, "user", []byte("pass"))
			require.NoError(t, err)
			defer cc.Close()

			{
				user, err := cc.GetUser(ctx)
				require.NoError(t, err)
				require.Equal(t, "user", user.Name)
			}

			ctl.SetCanRead(false)

			{
				_, err := cc.GetUser(ctx)
				require.Error(t, err)
			}

			require.Equal(t, proton.StatusDown, <-statusCh)
		})
	}, WithTLS(false))
}

func TestServer_Labels_Duplicates(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			req := proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeLabel,
			}

			label, err := c.CreateLabel(context.Background(), req)
			require.NoError(t, err)
			require.Equal(t, req.Name, label.Name)

			_, err = c.CreateLabel(context.Background(), req)
			require.Error(t, err)
		})
	})
}

func TestServer_Labels_Duplicates_Update(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			label1, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeLabel,
			})
			require.NoError(t, err)

			label2, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeLabel,
			})
			require.NoError(t, err)

			// Updating label1 with label2's name should fail.
			_, err = c.UpdateLabel(context.Background(), label1.ID, proton.UpdateLabelReq{
				Name:  label2.Name,
				Color: label1.Color,
			})
			require.Error(t, err)

			// Updating label1's color while preserving its name should succeed.
			_, err = c.UpdateLabel(context.Background(), label1.ID, proton.UpdateLabelReq{
				Name:  label1.Name,
				Color: "#f00",
			})
			require.NoError(t, err)

			// Updating label1 with a new name should succeed.
			_, err = c.UpdateLabel(context.Background(), label1.ID, proton.UpdateLabelReq{
				Name:  uuid.NewString(),
				Color: label1.Color,
			})
			require.NoError(t, err)
		})
	})
}

func TestServer_Labels_Subfolders(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			parent, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeFolder,
			})
			require.NoError(t, err)

			child, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:     uuid.NewString(),
				ParentID: parent.ID,
				Color:    "#f66",
				Type:     proton.LabelTypeFolder,
			})
			require.NoError(t, err)
			require.Equal(t, []string{parent.Name, child.Name}, child.Path)

			child2, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:     uuid.NewString(),
				ParentID: child.ID,
				Color:    "#f66",
				Type:     proton.LabelTypeFolder,
			})
			require.NoError(t, err)
			require.Equal(t, []string{parent.Name, child.Name, child2.Name}, child2.Path)
		})
	})
}

func TestServer_Labels_Subfolders_Reassign(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			parent1, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeFolder,
			})
			require.NoError(t, err)

			parent2, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeFolder,
			})
			require.NoError(t, err)

			// Create a child initially under parent1.
			child, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:     uuid.NewString(),
				ParentID: parent1.ID,
				Color:    "#f66",
				Type:     proton.LabelTypeFolder,
			})
			require.NoError(t, err)
			require.Equal(t, []string{parent1.Name, child.Name}, child.Path)

			// Reassign the child to parent2.
			child2, err := c.UpdateLabel(context.Background(), child.ID, proton.UpdateLabelReq{
				Name:     child.Name,
				Color:    child.Color,
				ParentID: parent2.ID,
			})
			require.NoError(t, err)
			require.Equal(t, []string{parent2.Name, child.Name}, child2.Path)

			// Reassign the child to no parent.
			child3, err := c.UpdateLabel(context.Background(), child.ID, proton.UpdateLabelReq{
				Name:     child2.Name,
				Color:    child2.Color,
				ParentID: "",
			})
			require.NoError(t, err)
			require.Equal(t, []string{child3.Name}, child3.Path)
		})
	})
}

func TestServer_Labels_Subfolders_DeleteParentWithChildren(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			parent, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeFolder,
			})
			require.NoError(t, err)

			child, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:     uuid.NewString(),
				ParentID: parent.ID,
				Color:    "#f66",
				Type:     proton.LabelTypeFolder,
			})
			require.NoError(t, err)
			require.Equal(t, []string{parent.Name, child.Name}, child.Path)

			other, err := c.CreateLabel(context.Background(), proton.CreateLabelReq{
				Name:  uuid.NewString(),
				Color: "#f66",
				Type:  proton.LabelTypeFolder,
			})
			require.NoError(t, err)

			// Get labels before.
			before, err := c.GetLabels(context.Background(), proton.LabelTypeFolder)
			require.NoError(t, err)

			// Delete the parent.
			require.NoError(t, c.DeleteLabel(context.Background(), parent.ID))

			// Get labels after.
			after, err := c.GetLabels(context.Background(), proton.LabelTypeFolder)
			require.NoError(t, err)

			// Both parent and child are deleted.
			require.Equal(t, len(before)-2, len(after))

			// The only label left is the other one.
			require.Equal(t, other.ID, after[0].ID)
		})
	})
}

func TestServer_AddressCreateDelete(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(context.Background())
			require.NoError(t, err)

			// Create an address.
			alias, err := s.CreateAddress(user.ID, "alias@example.com", []byte("pass"))
			require.NoError(t, err)

			// The user should have two addresses, both enabled.
			{
				addr, err := c.GetAddresses(context.Background())
				require.NoError(t, err)
				require.Len(t, addr, 2)
				require.Equal(t, addr[0].Status, proton.AddressStatusEnabled)
				require.Equal(t, addr[1].Status, proton.AddressStatusEnabled)
			}

			// Disable the alias.
			require.NoError(t, c.DisableAddress(context.Background(), alias))

			// The user should have two addresses, the primary enabled and the alias disabled.
			{
				addr, err := c.GetAddresses(context.Background())
				require.NoError(t, err)
				require.Len(t, addr, 2)
				require.Equal(t, addr[0].Status, proton.AddressStatusEnabled)
				require.Equal(t, addr[1].Status, proton.AddressStatusDisabled)
			}

			// Delete the alias.
			require.NoError(t, c.DeleteAddress(context.Background(), alias))

			// The user should have one address, the primary enabled.
			{
				addr, err := c.GetAddresses(context.Background())
				require.NoError(t, err)
				require.Len(t, addr, 1)
				require.Equal(t, addr[0].Status, proton.AddressStatusEnabled)
			}
		})
	})
}

func TestServer_AddressOrder(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			user, err := c.GetUser(context.Background())
			require.NoError(t, err)

			primary, err := c.GetAddresses(context.Background())
			require.NoError(t, err)

			// Create 3 additional addresses.
			addr1, err := s.CreateAddress(user.ID, "addr1@example.com", []byte("pass"))
			require.NoError(t, err)

			addr2, err := s.CreateAddress(user.ID, "addr2@example.com", []byte("pass"))
			require.NoError(t, err)

			addr3, err := s.CreateAddress(user.ID, "addr3@example.com", []byte("pass"))
			require.NoError(t, err)

			addresses, err := c.GetAddresses(context.Background())
			require.NoError(t, err)

			// Check the order.
			require.Equal(t, primary[0].ID, addresses[0].ID)
			require.Equal(t, addr1, addresses[1].ID)
			require.Equal(t, addr2, addresses[2].ID)
			require.Equal(t, addr3, addresses[3].ID)

			// Update the order.
			require.NoError(t, c.OrderAddresses(ctx, proton.OrderAddressesReq{
				AddressIDs: []string{addr3, addr2, addr1, primary[0].ID},
			}))

			// Check the order.
			addresses, err = c.GetAddresses(context.Background())
			require.NoError(t, err)

			require.Equal(t, addr3, addresses[0].ID)
			require.Equal(t, addr2, addresses[1].ID)
			require.Equal(t, addr1, addresses[2].ID)
			require.Equal(t, primary[0].ID, addresses[3].ID)
		})
	})
}

func TestServer_MailSettings(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			settings, err := c.GetMailSettings(context.Background())
			require.NoError(t, err)
			require.Equal(t, proton.Bool(false), settings.AttachPublicKey)

			updated, err := c.SetAttachPublicKey(context.Background(), proton.SetAttachPublicKeyReq{AttachPublicKey: true})
			require.NoError(t, err)
			require.Equal(t, proton.Bool(true), updated.AttachPublicKey)
		})
	})
}

func TestServer_UserSettings(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			settings, err := c.GetUserSettings(context.Background())
			require.NoError(t, err)
			require.Equal(t, proton.SettingEnabled, settings.Telemetry)
			require.Equal(t, proton.SettingEnabled, settings.CrashReports)

			settings, err = c.SetUserSettingsTelemetry(context.Background(), proton.SetTelemetryReq{Telemetry: proton.SettingDisabled})
			require.NoError(t, err)
			require.Equal(t, proton.SettingDisabled, settings.Telemetry)
			require.Equal(t, proton.SettingEnabled, settings.CrashReports)

			settings, err = c.SetUserSettingsCrashReports(context.Background(), proton.SetCrashReportReq{CrashReports: proton.SettingDisabled})
			require.NoError(t, err)
			require.Equal(t, proton.SettingDisabled, settings.Telemetry)
			require.Equal(t, proton.SettingDisabled, settings.CrashReports)

			settings, err = c.SetUserSettingsTelemetry(context.Background(), proton.SetTelemetryReq{Telemetry: 2})
			require.Error(t, err)

			settings, err = c.SetUserSettingsCrashReports(context.Background(), proton.SetCrashReportReq{CrashReports: 2})
			require.Error(t, err)

			settings, err = c.GetUserSettings(context.Background())
			require.NoError(t, err)
			require.Equal(t, proton.SettingDisabled, settings.Telemetry)
			require.Equal(t, proton.SettingDisabled, settings.CrashReports)

		})
	})
}

func TestServer_Domains(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		domains, err := m.GetDomains(ctx)
		require.NoError(t, err)
		require.Equal(t, []string{s.GetDomain()}, domains)
	})
}

func TestServer_StatusHooks(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		s.AddStatusHook(func(req *http.Request) (int, bool) {
			if req.URL.Path == "/core/v4/addresses" {
				return http.StatusBadRequest, true
			}

			return 0, false
		})

		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			addr, err := c.GetAddresses(context.Background())
			require.Error(t, err)
			require.Nil(t, addr)

			if apiErr := new(proton.APIError); errors.As(err, &apiErr) {
				require.Equal(t, http.StatusBadRequest, apiErr.Status)
			} else {
				require.Fail(t, "expected APIError")
			}
		})
	})
}

func TestServer_SendDataEvent(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			// Send data event minimal
			err := c.SendDataEvent(context.Background(), proton.SendStatsReq{MeasurementGroup: "proton.any.test"})
			require.NoError(t, err)

			// Send data event Full.
			var req proton.SendStatsReq
			req.MeasurementGroup = "proton.any.test"
			req.Event = "test"
			req.Values = map[string]any{"string": "string", "integer": 42}
			req.Dimensions = map[string]any{"string": "string", "integer": 42}
			err = c.SendDataEvent(context.Background(), req)
			require.NoError(t, err)

			// Send bad data event.
			err = c.SendDataEvent(context.Background(), proton.SendStatsReq{})
			require.Error(t, err)
		})
	})
}

func TestServer_SendDataEventMultiple(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			// Send multiple minimal data event.
			var req proton.SendStatsMultiReq
			req.EventInfo = append(req.EventInfo, proton.SendStatsReq{MeasurementGroup: "proton.any.test"})
			req.EventInfo = append(req.EventInfo, proton.SendStatsReq{MeasurementGroup: "proton.any.test2"})
			err := c.SendDataEventMultiple(context.Background(), req)
			require.NoError(t, err)

			// send empty multiple data event.
			err = c.SendDataEventMultiple(context.Background(), proton.SendStatsMultiReq{})
			require.NoError(t, err)

			// Send bad multiple data event.
			var badReq proton.SendStatsMultiReq
			badReq.EventInfo = append(badReq.EventInfo, proton.SendStatsReq{})
			err = c.SendDataEventMultiple(context.Background(), badReq)
			require.Error(t, err)
		})
	})
}

func TestServer_GetMessageGroupCount(t *testing.T) {
	withServer(t, func(ctx context.Context, s *Server, m *proton.Manager) {
		withUser(ctx, t, s, m, "user", "pass", func(c *proton.Client) {
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			user, err := c.GetUser(ctx)
			require.NoError(t, err)

			addr, err := c.GetAddresses(ctx)
			require.NoError(t, err)

			salt, err := c.GetSalts(ctx)
			require.NoError(t, err)

			pass, err := salt.SaltForKey([]byte("pass"), user.Keys.Primary().ID)
			require.NoError(t, err)

			_, addrKRs, err := proton.Unlock(user, addr, pass, async.NoopPanicHandler{})
			require.NoError(t, err)

			expected := []proton.MessageGroupCount{
				{
					LabelID: proton.InboxLabel,
					Total:   10,
					Unread:  4,
				},
				{
					LabelID: proton.SentLabel,
					Total:   4,
					Unread:  0,
				},
				{
					LabelID: proton.ArchiveLabel,
					Total:   3,
					Unread:  0,
				},
				{
					LabelID: proton.TrashLabel,
					Total:   6,
					Unread:  0,
				},
				{
					LabelID: proton.AllMailLabel,
					Total:   23,
					Unread:  4,
				},
			}

			for _, st := range expected {
				if st.LabelID == proton.AllMailLabel {
					continue
				}

				var flags proton.MessageFlag
				if st.LabelID == proton.InboxLabel {
					flags = proton.MessageFlagReceived
				} else if st.LabelID == proton.SentLabel {
					flags = proton.MessageFlagSent
				}

				res := importMessages(ctx, t, c, addr[0].ID, addrKRs[addr[0].ID], []string{}, flags, st.Total)
				msgIDs := xslices.Map(res, func(r proton.ImportRes) string {
					return r.MessageID
				})
				require.NoError(t, c.LabelMessages(ctx, msgIDs, st.LabelID))
				if st.Unread == 0 {
					require.NoError(t, c.MarkMessagesRead(ctx, msgIDs...))
				} else {
					require.NoError(t, c.MarkMessagesRead(ctx, msgIDs[st.Unread:]...))
				}
			}

			counts, err := c.GetGroupedMessageCount(ctx)
			require.NoError(t, err)

			counts = xslices.Filter(counts, func(t proton.MessageGroupCount) bool {
				switch t.LabelID {
				case proton.InboxLabel, proton.TrashLabel, proton.ArchiveLabel, proton.AllMailLabel, proton.SentLabel:
					return true
				default:
					return false
				}
			})
			require.NotEmpty(t, counts)
			require.ElementsMatch(t, expected, counts)

		})
	})
}

func withServer(t *testing.T, fn func(ctx context.Context, s *Server, m *proton.Manager), opts ...Option) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	s := New(opts...)
	defer s.Close()

	m := proton.New(
		proton.WithHostURL(s.GetHostURL()),
		proton.WithCookieJar(newTestCookieJar()),
		proton.WithTransport(proton.InsecureTransport()),
	)
	defer m.Close()

	fn(ctx, s, m)
}

func withUser(ctx context.Context, t *testing.T, s *Server, m *proton.Manager, user, pass string, fn func(c *proton.Client)) {
	_, _, err := s.CreateUser(user, []byte(pass))
	require.NoError(t, err)

	c, _, err := m.NewClientWithLogin(ctx, user, []byte(pass))
	require.NoError(t, err)
	defer c.Close()

	fn(c)
}

func withMessages(ctx context.Context, t *testing.T, c *proton.Client, pass string, count int, fn func([]string)) {
	user, err := c.GetUser(ctx)
	require.NoError(t, err)

	addr, err := c.GetAddresses(ctx)
	require.NoError(t, err)

	salt, err := c.GetSalts(ctx)
	require.NoError(t, err)

	keyPass, err := salt.SaltForKey([]byte(pass), user.Keys.Primary().ID)
	require.NoError(t, err)

	_, addrKRs, err := proton.Unlock(user, addr, keyPass, async.NoopPanicHandler{})
	require.NoError(t, err)

	fn(xslices.Map(importMessages(ctx, t, c, addr[0].ID, addrKRs[addr[0].ID], []string{}, proton.MessageFlagReceived, count), func(res proton.ImportRes) string {
		return res.MessageID
	}))
}

func importMessagesWithSubjectGenerator(
	ctx context.Context,
	t *testing.T,
	c *proton.Client,
	addrID string,
	addrKR *crypto.KeyRing,
	labelIDs []string,
	flags proton.MessageFlag,
	count int,
	subjectGenerator func() string,
) []proton.ImportRes {
	req := iterator.Collect(iterator.Map(iterator.Counter(count), func(int) proton.ImportReq {
		return proton.ImportReq{
			Metadata: proton.ImportMetadata{
				AddressID: addrID,
				LabelIDs:  labelIDs,
				Flags:     flags,
				Unread:    true,
			},
			Message: newMessageLiteralWithSubject("sender@example.com", "recipient@example.com", subjectGenerator()),
		}
	}))

	str, err := c.ImportMessages(ctx, addrKR, runtime.NumCPU(), runtime.NumCPU(), req...)
	require.NoError(t, err)

	res, err := stream.Collect(ctx, str)
	require.NoError(t, err)

	return res
}

func importMessages(
	ctx context.Context,
	t *testing.T,
	c *proton.Client,
	addrID string,
	addrKR *crypto.KeyRing,
	labelIDs []string,
	flags proton.MessageFlag,
	count int,
) []proton.ImportRes {
	return importMessagesWithSubjectGenerator(ctx, t, c, addrID, addrKR, labelIDs, flags, count, func() string {
		return uuid.NewString()
	})
}

func countBytesRead(ctl *proton.NetCtl, fn func()) uint64 {
	var read uint64

	ctl.OnRead(func(b []byte) {
		atomic.AddUint64(&read, uint64(len(b)))
	})

	fn()

	return read
}

type testCookieJar struct {
	cookies map[string][]*http.Cookie
	lock    sync.RWMutex
}

func newTestCookieJar() *testCookieJar {
	return &testCookieJar{
		cookies: make(map[string][]*http.Cookie),
	}
}

func (j *testCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
	j.lock.Lock()
	defer j.lock.Unlock()

	j.cookies[u.Host] = cookies
}

func (j *testCookieJar) Cookies(u *url.URL) []*http.Cookie {
	j.lock.RLock()
	defer j.lock.RUnlock()

	return j.cookies[u.Host]
}

func must[T any](t T, err error) T {
	if err != nil {
		panic(err)
	}

	return t
}

func elementsMatch[T comparable](want, got []T) bool {
	if len(want) != len(got) {
		return false
	}

	for _, w := range want {
		if !slices.Contains(got, w) {
			return false
		}
	}

	return true
}

func getFullMessages(ctx context.Context,
	c *proton.Client,
	workers, buffer int,
	messageIDs ...string) stream.Stream[proton.FullMessage] {
	scheduler := proton.NewSequentialScheduler()
	attachmentStorageProvider := proton.NewDefaultAttachmentAllocator()
	return parallel.MapStream(
		ctx,
		stream.FromIterator(iterator.Slice(messageIDs)),
		workers,
		buffer,
		func(ctx context.Context, messageID string) (proton.FullMessage, error) {
			return c.GetFullMessage(ctx, messageID, scheduler, attachmentStorageProvider)
		},
	)
}