summary refs log tree commit diff
path: root/develop/print.html
blob: a767926a340d973b5fcc186a8a197fe3e3d32f17 (plain) (blame)
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
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Synapse</title>
        <meta name="robots" content="noindex" />
        <!-- Custom HTML head -->
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">
        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">
        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        <link rel="stylesheet" href="docs/website_files/table-of-contents.css">
        <link rel="stylesheet" href="docs/website_files/remove-nav-buttons.css">
        <link rel="stylesheet" href="docs/website_files/indent-section-headers.css">
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');
                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }
                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><li class="part-title">Introduction</li><li class="chapter-item expanded "><a href="welcome_and_overview.html">Welcome and Overview</a></li><li class="chapter-item expanded affix "><li class="part-title">Setup</li><li class="chapter-item expanded "><a href="setup/installation.html">Installation</a></li><li class="chapter-item expanded "><a href="postgres.html">Using Postgres</a></li><li class="chapter-item expanded "><a href="reverse_proxy.html">Configuring a Reverse Proxy</a></li><li class="chapter-item expanded "><a href="setup/forward_proxy.html">Configuring a Forward/Outbound Proxy</a></li><li class="chapter-item expanded "><a href="turn-howto.html">Configuring a Turn Server</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="setup/turn/coturn.html">coturn TURN server</a></li><li class="chapter-item expanded "><a href="setup/turn/eturnal.html">eturnal TURN server</a></li></ol></li><li class="chapter-item expanded "><a href="delegate.html">Delegation</a></li><li class="chapter-item expanded affix "><li class="part-title">Upgrading</li><li class="chapter-item expanded "><a href="upgrade.html">Upgrading between Synapse Versions</a></li><li class="chapter-item expanded affix "><li class="part-title">Usage</li><li class="chapter-item expanded "><a href="federate.html">Federation</a></li><li class="chapter-item expanded "><a href="usage/configuration/index.html">Configuration</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="usage/configuration/config_documentation.html">Configuration Manual</a></li><li class="chapter-item expanded "><a href="usage/configuration/homeserver_sample_config.html">Homeserver Sample Config File</a></li><li class="chapter-item expanded "><a href="usage/configuration/logging_sample_config.html">Logging Sample Config File</a></li><li class="chapter-item expanded "><a href="structured_logging.html">Structured Logging</a></li><li class="chapter-item expanded "><a href="templates.html">Templates</a></li><li class="chapter-item expanded "><a href="usage/configuration/user_authentication/index.html">User Authentication</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="usage/configuration/user_authentication/single_sign_on/index.html">Single-Sign On</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="openid.html">OpenID Connect</a></li><li class="chapter-item expanded "><a href="usage/configuration/user_authentication/single_sign_on/saml.html">SAML</a></li><li class="chapter-item expanded "><a href="usage/configuration/user_authentication/single_sign_on/cas.html">CAS</a></li><li class="chapter-item expanded "><a href="sso_mapping_providers.html">SSO Mapping Providers</a></li></ol></li><li class="chapter-item expanded "><a href="password_auth_providers.html">Password Auth Providers</a></li><li class="chapter-item expanded "><a href="jwt.html">JSON Web Tokens</a></li><li class="chapter-item expanded "><a href="usage/configuration/user_authentication/refresh_tokens.html">Refresh Tokens</a></li></ol></li><li class="chapter-item expanded "><a href="CAPTCHA_SETUP.html">Registration Captcha</a></li><li class="chapter-item expanded "><a href="application_services.html">Application Services</a></li><li class="chapter-item expanded "><a href="server_notices.html">Server Notices</a></li><li class="chapter-item expanded "><a href="consent_tracking.html">Consent Tracking</a></li><li class="chapter-item expanded "><a href="user_directory.html">User Directory</a></li><li class="chapter-item expanded "><a href="message_retention_policies.html">Message Retention Policies</a></li><li class="chapter-item expanded "><a href="modules/index.html">Pluggable Modules</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="modules/writing_a_module.html">Writing a module</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="modules/spam_checker_callbacks.html">Spam checker callbacks</a></li><li class="chapter-item expanded "><a href="modules/third_party_rules_callbacks.html">Third-party rules callbacks</a></li><li class="chapter-item expanded "><a href="modules/presence_router_callbacks.html">Presence router callbacks</a></li><li class="chapter-item expanded "><a href="modules/account_validity_callbacks.html">Account validity callbacks</a></li><li class="chapter-item expanded "><a href="modules/password_auth_provider_callbacks.html">Password auth provider callbacks</a></li><li class="chapter-item expanded "><a href="modules/background_update_controller_callbacks.html">Background update controller callbacks</a></li><li class="chapter-item expanded "><a href="modules/account_data_callbacks.html">Account data callbacks</a></li><li class="chapter-item expanded "><a href="modules/porting_legacy_module.html">Porting a legacy module to the new interface</a></li></ol></li></ol></li><li class="chapter-item expanded "><a href="workers.html">Workers</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="synctl_workers.html">Using synctl with Workers</a></li><li class="chapter-item expanded "><a href="systemd-with-workers/index.html">Systemd</a></li></ol></li></ol></li><li class="chapter-item expanded "><a href="usage/administration/index.html">Administration</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="usage/administration/admin_api/index.html">Admin API</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="admin_api/account_validity.html">Account Validity</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_api/background_updates.html">Background Updates</a></li><li class="chapter-item expanded "><a href="admin_api/event_reports.html">Event Reports</a></li><li class="chapter-item expanded "><a href="admin_api/experimental_features.html">Experimental Features</a></li><li class="chapter-item expanded "><a href="admin_api/media_admin_api.html">Media</a></li><li class="chapter-item expanded "><a href="admin_api/purge_history_api.html">Purge History</a></li><li class="chapter-item expanded "><a href="admin_api/register_api.html">Register Users</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_api/registration_tokens.html">Registration Tokens</a></li><li class="chapter-item expanded "><a href="admin_api/room_membership.html">Manipulate Room Membership</a></li><li class="chapter-item expanded "><a href="admin_api/rooms.html">Rooms</a></li><li class="chapter-item expanded "><a href="admin_api/server_notices.html">Server Notices</a></li><li class="chapter-item expanded "><a href="admin_api/statistics.html">Statistics</a></li><li class="chapter-item expanded "><a href="admin_api/user_admin_api.html">Users</a></li><li class="chapter-item expanded "><a href="admin_api/version_api.html">Server Version</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_api/federation.html">Federation</a></li></ol></li><li class="chapter-item expanded "><a href="manhole.html">Manhole</a></li><li class="chapter-item expanded "><a href="metrics-howto.html">Monitoring</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="usage/administration/monitoring/reporting_homeserver_usage_statistics.html">Reporting Homeserver Usage Statistics</a></li></ol></li><li class="chapter-item expanded "><a href="usage/administration/monthly_active_users.html">Monthly Active Users</a></li><li class="chapter-item expanded "><a href="usage/administration/understanding_synapse_through_grafana_graphs.html">Understanding Synapse Through Grafana Graphs</a></li><li class="chapter-item expanded "><a href="usage/administration/useful_sql_for_admins.html">Useful SQL for Admins</a></li><li class="chapter-item expanded "><a href="usage/administration/database_maintenance_tools.html">Database Maintenance Tools</a></li><li class="chapter-item expanded "><a href="usage/administration/state_groups.html">State Groups</a></li><li class="chapter-item expanded "><a href="usage/administration/request_log.html">Request log format</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_faq.html">Admin FAQ</a></li><li class="chapter-item expanded "><div>Scripts</div></li></ol></li><li class="chapter-item expanded "><li class="part-title">Development</li><li class="chapter-item expanded "><a href="development/contributing_guide.html">Contributing Guide</a></li><li class="chapter-item expanded "><a href="code_style.html">Code Style</a></li><li class="chapter-item expanded "><a href="development/reviews.html">Reviewing Code</a></li><li class="chapter-item expanded "><a href="development/releases.html">Release Cycle</a></li><li class="chapter-item expanded "><a href="development/git.html">Git Usage</a></li><li class="chapter-item expanded "><div>Testing</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/demo.html">Demo scripts</a></li></ol></li><li class="chapter-item expanded "><a href="opentracing.html">OpenTracing</a></li><li class="chapter-item expanded "><a href="development/database_schema.html">Database Schemas</a></li><li class="chapter-item expanded "><a href="development/experimental_features.html">Experimental features</a></li><li class="chapter-item expanded "><a href="development/dependencies.html">Dependency management</a></li><li class="chapter-item expanded "><div>Synapse Architecture</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/synapse_architecture/cancellation.html">Cancellation</a></li><li class="chapter-item expanded "><a href="log_contexts.html">Log Contexts</a></li><li class="chapter-item expanded "><a href="replication.html">Replication</a></li><li class="chapter-item expanded "><a href="development/synapse_architecture/streams.html">Streams</a></li><li class="chapter-item expanded "><a href="tcp_replication.html">TCP Replication</a></li><li class="chapter-item expanded "><a href="development/synapse_architecture/faster_joins.html">Faster remote joins</a></li></ol></li><li class="chapter-item expanded "><a href="development/internal_documentation/index.html">Internal Documentation</a></li><li><ol class="section"><li class="chapter-item expanded "><div>Single Sign-On</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/saml.html">SAML</a></li><li class="chapter-item expanded "><a href="development/cas.html">CAS</a></li></ol></li><li class="chapter-item expanded "><a href="development/room-dag-concepts.html">Room DAG concepts</a></li><li class="chapter-item expanded "><div>State Resolution</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="auth_chain_difference_algorithm.html">The Auth Chain Difference Algorithm</a></li></ol></li><li class="chapter-item expanded "><a href="media_repository.html">Media Repository</a></li><li class="chapter-item expanded "><a href="room_and_user_statistics.html">Room and User Statistics</a></li></ol></li><li class="chapter-item expanded "><div>Scripts</div></li><li class="chapter-item expanded affix "><li class="part-title">Other</li><li class="chapter-item expanded "><a href="deprecation_policy.html">Dependency Deprecation Policy</a></li><li class="chapter-item expanded "><a href="other/running_synapse_on_single_board_computers.html">Running Synapse on a Single-Board Computer</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Synapse</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        <a href="https://github.com/matrix-org/synapse" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>
                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <!-- Page table of contents -->
                        <div class="sidetoc">
                            <nav class="pagetoc"></nav>
                        </div>

                        <div style="break-before: page; page-break-before: always;"></div><h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
<p>Welcome to the documentation repository for Synapse, a 
<a href="https://matrix.org">Matrix</a> homeserver implementation developed by the matrix.org core 
team.</p>
<h2 id="installing-and-using-synapse"><a class="header" href="#installing-and-using-synapse">Installing and using Synapse</a></h2>
<p>This documentation covers topics for <strong>installation</strong>, <strong>configuration</strong> and
<strong>maintenance</strong> of your Synapse process:</p>
<ul>
<li>
<p>Learn how to <a href="setup/installation.html">install</a> and
<a href="usage/configuration/config_documentation.html">configure</a> your own instance, perhaps with <a href="usage/configuration/user_authentication/index.html">Single
Sign-On</a>.</p>
</li>
<li>
<p>See how to <a href="upgrade.html">upgrade</a> between Synapse versions.</p>
</li>
<li>
<p>Administer your instance using the <a href="usage/administration/admin_api/index.html">Admin
API</a>, installing <a href="modules/index.html">pluggable
modules</a>, or by accessing the <a href="manhole.html">manhole</a>.</p>
</li>
<li>
<p>Learn how to <a href="usage/administration/request_log.html">read log lines</a>, configure
<a href="usage/configuration/logging_sample_config.html">logging</a> or set up <a href="structured_logging.html">structured
logging</a>.</p>
</li>
<li>
<p>Scale Synapse through additional <a href="workers.html">worker processes</a>.</p>
</li>
<li>
<p>Set up <a href="metrics-howto.html">monitoring and metrics</a> to keep an eye on your
Synapse instance's performance.</p>
</li>
</ul>
<h2 id="developing-on-synapse"><a class="header" href="#developing-on-synapse">Developing on Synapse</a></h2>
<p>Contributions are welcome! Synapse is primarily written in
<a href="https://python.org">Python</a>. As a developer, you may be interested in the
following documentation:</p>
<ul>
<li>
<p>Read the <a href="development/contributing_guide.html">Contributing Guide</a>. It is meant
to walk new contributors through the process of developing and submitting a
change to the Synapse codebase (which is <a href="https://github.com/matrix-org/synapse">hosted on
GitHub</a>).</p>
</li>
<li>
<p>Set up your <a href="development/contributing_guide.html#2-what-do-i-need">development
environment</a>, then learn
how to <a href="development/contributing_guide.html#run-the-linters">lint</a> and
<a href="development/contributing_guide.html#8-test-test-test">test</a> your code.</p>
</li>
<li>
<p>Look at <a href="https://github.com/matrix-org/synapse/issues">the issue tracker</a> for
bugs to fix or features to add. If you're new, it may be best to start with
those labeled <a href="https://github.com/matrix-org/synapse/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22">good first
issue</a>.</p>
</li>
<li>
<p>Understand <a href="development/internal_documentation/index.html">how Synapse is
built</a>, how to <a href="development/database_schema.html">migrate
database schemas</a>, learn about
<a href="federate.html">federation</a> and how to <a href="federate.html#running-a-demo-federation-of-synapses">set up a local
federation</a> for development.</p>
</li>
<li>
<p>We like to keep our <code>git</code> history clean. <a href="development/git.html">Learn</a> how to
do so!</p>
</li>
<li>
<p>And finally, contribute to this documentation! The source for which is
<a href="https://github.com/matrix-org/synapse/tree/develop/docs">located here</a>.</p>
</li>
</ul>
<h2 id="donating-to-synapse-development"><a class="header" href="#donating-to-synapse-development">Donating to Synapse development</a></h2>
<p>Want to help keep Synapse going but don't know how to code? Synapse is a
<a href="https://matrix.org">Matrix.org Foundation</a> project. Consider becoming a
supporter on <a href="https://liberapay.com/matrixdotorg">Liberapay</a>,
<a href="https://patreon.com/matrixdotorg">Patreon</a> or through
<a href="https://paypal.me/matrixdotorg">PayPal</a> via a one-time donation.</p>
<p>If you are an organisation or enterprise and would like to sponsor development,
reach out to us over email at: support (at) matrix.org</p>
<h2 id="reporting-a-security-vulnerability"><a class="header" href="#reporting-a-security-vulnerability">Reporting a security vulnerability</a></h2>
<p>If you've found a security issue in Synapse or any other Matrix.org Foundation
project, please report it to us in accordance with our <a href="https://www.matrix.org/security-disclosure-policy/">Security Disclosure
Policy</a>. Thank you!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="installation-instructions"><a class="header" href="#installation-instructions">Installation Instructions</a></h1>
<h2 id="choosing-your-server-name"><a class="header" href="#choosing-your-server-name">Choosing your server name</a></h2>
<p>It is important to choose the name for your server before you install Synapse,
because it cannot be changed later.</p>
<p>The server name determines the &quot;domain&quot; part of user-ids for users on your
server: these will all be of the format <code>@user:my.domain.name</code>. It also
determines how other matrix servers will reach yours for federation.</p>
<p>For a test configuration, set this to the hostname of your server. For a more
production-ready setup, you will probably want to specify your domain
(<code>example.com</code>) rather than a matrix-specific hostname here (in the same way
that your email address is probably <code>user@example.com</code> rather than
<code>user@email.example.com</code>) - but doing so may require more advanced setup: see
<a href="setup/../federate.html">Setting up Federation</a>.</p>
<h2 id="installing-synapse"><a class="header" href="#installing-synapse">Installing Synapse</a></h2>
<h3 id="prebuilt-packages"><a class="header" href="#prebuilt-packages">Prebuilt packages</a></h3>
<p>Prebuilt packages are available for a number of platforms. These are recommended
for most users.</p>
<h4 id="docker-images-and-ansible-playbooks"><a class="header" href="#docker-images-and-ansible-playbooks">Docker images and Ansible playbooks</a></h4>
<p>There is an official synapse image available at
<a href="https://hub.docker.com/r/matrixdotorg/synapse">https://hub.docker.com/r/matrixdotorg/synapse</a> or at <a href="https://ghcr.io/matrix-org/synapse"><code>ghcr.io/matrix-org/synapse</code></a>
which can be used with the docker-compose file available at
<a href="https://github.com/matrix-org/synapse/tree/develop/contrib/docker">contrib/docker</a>.
Further information on this including configuration options is available in the README
on hub.docker.com.</p>
<p>Alternatively, Andreas Peters (previously Silvio Fricke) has contributed a
Dockerfile to automate a synapse server in a single Docker image, at
<a href="https://hub.docker.com/r/avhost/docker-matrix/tags/">https://hub.docker.com/r/avhost/docker-matrix/tags/</a></p>
<p>Slavi Pantaleev has created an Ansible playbook,
which installs the offical Docker image of Matrix Synapse
along with many other Matrix-related services (Postgres database, Element, coturn,
ma1sd, SSL support, etc.).
For more details, see
<a href="https://github.com/spantaleev/matrix-docker-ansible-deploy">https://github.com/spantaleev/matrix-docker-ansible-deploy</a></p>
<h4 id="debianubuntu"><a class="header" href="#debianubuntu">Debian/Ubuntu</a></h4>
<h5 id="matrixorg-packages"><a class="header" href="#matrixorg-packages">Matrix.org packages</a></h5>
<p>Matrix.org provides Debian/Ubuntu packages of Synapse, for the amd64
architecture via <a href="https://packages.matrix.org/debian/">https://packages.matrix.org/debian/</a>.</p>
<p>To install the latest release:</p>
<pre><code class="language-sh">sudo apt install -y lsb-release wget apt-transport-https
sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main&quot; |
    sudo tee /etc/apt/sources.list.d/matrix-org.list
sudo apt update
sudo apt install matrix-synapse-py3
</code></pre>
<p>Packages are also published for release candidates. To enable the prerelease
channel, add <code>prerelease</code> to the <code>sources.list</code> line. For example:</p>
<pre><code class="language-sh">sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main prerelease&quot; |
    sudo tee /etc/apt/sources.list.d/matrix-org.list
sudo apt update
sudo apt install matrix-synapse-py3
</code></pre>
<p>The fingerprint of the repository signing key (as shown by <code>gpg /usr/share/keyrings/matrix-org-archive-keyring.gpg</code>) is
<code>AAF9AE843A7584B5A3E4CD2BCF45A512DE2DA058</code>.</p>
<p>When installing with Debian packages, you might prefer to place files in
<code>/etc/matrix-synapse/conf.d/</code> to override your configuration without editing
the main configuration file at <code>/etc/matrix-synapse/homeserver.yaml</code>.
By doing that, you won't be asked if you want to replace your configuration
file when you upgrade the Debian package to a later version.</p>
<h5 id="downstream-debian-packages"><a class="header" href="#downstream-debian-packages">Downstream Debian packages</a></h5>
<p>Andrej Shadura maintains a
<a href="https://packages.debian.org/sid/matrix-synapse"><code>matrix-synapse</code></a> package in
the Debian repositories.
For <code>bookworm</code> and <code>sid</code>, it can be installed simply with:</p>
<pre><code class="language-sh">sudo apt install matrix-synapse
</code></pre>
<p>Synapse is also avaliable in <code>bullseye-backports</code>.  Please
see the <a href="https://backports.debian.org/Instructions/">Debian documentation</a>
for information on how to use backports.</p>
<p><code>matrix-synapse</code> is no longer maintained for <code>buster</code> and older.</p>
<h5 id="downstream-ubuntu-packages"><a class="header" href="#downstream-ubuntu-packages">Downstream Ubuntu packages</a></h5>
<p>We do not recommend using the packages in the default Ubuntu repository
at this time, as they are <a href="https://bugs.launchpad.net/ubuntu/+source/matrix-synapse/+bug/1848709">old and suffer from known security vulnerabilities</a>.
The latest version of Synapse can be installed from <a href="setup/installation.html#matrixorg-packages">our repository</a>.</p>
<h4 id="fedora"><a class="header" href="#fedora">Fedora</a></h4>
<p>Synapse is in the Fedora repositories as
<a href="https://src.fedoraproject.org/rpms/matrix-synapse"><code>matrix-synapse</code></a>:</p>
<pre><code class="language-sh">sudo dnf install matrix-synapse
</code></pre>
<p>Additionally, Oleg Girko provides Fedora RPMs at
<a href="https://obs.infoserver.lv/project/monitor/matrix-synapse">https://obs.infoserver.lv/project/monitor/matrix-synapse</a></p>
<h4 id="opensuse"><a class="header" href="#opensuse">OpenSUSE</a></h4>
<p>Synapse is in the OpenSUSE repositories as
<a href="https://software.opensuse.org/package/matrix-synapse"><code>matrix-synapse</code></a>:</p>
<pre><code class="language-sh">sudo zypper install matrix-synapse
</code></pre>
<h4 id="suse-linux-enterprise-server"><a class="header" href="#suse-linux-enterprise-server">SUSE Linux Enterprise Server</a></h4>
<p>Unofficial package are built for SLES 15 in the openSUSE:Backports:SLE-15 repository at
<a href="https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/">https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/</a></p>
<h4 id="archlinux"><a class="header" href="#archlinux">ArchLinux</a></h4>
<p>The quickest way to get up and running with ArchLinux is probably with the package provided by ArchLinux
<a href="https://archlinux.org/packages/extra/x86_64/matrix-synapse/">https://archlinux.org/packages/extra/x86_64/matrix-synapse/</a>, which should pull in most of
the necessary dependencies.</p>
<p>pip may be outdated (6.0.7-1 and needs to be upgraded to 6.0.8-1 ):</p>
<pre><code class="language-sh">sudo pip install --upgrade pip
</code></pre>
<p>If you encounter an error with lib bcrypt causing an Wrong ELF Class:
ELFCLASS32 (x64 Systems), you may need to reinstall py-bcrypt to correctly
compile it under the right architecture. (This should not be needed if
installing under virtualenv):</p>
<pre><code class="language-sh">sudo pip uninstall py-bcrypt
sudo pip install py-bcrypt
</code></pre>
<h4 id="void-linux"><a class="header" href="#void-linux">Void Linux</a></h4>
<p>Synapse can be found in the void repositories as
<a href="https://github.com/void-linux/void-packages/tree/master/srcpkgs/synapse">'synapse'</a>:</p>
<pre><code class="language-sh">xbps-install -Su
xbps-install -S synapse
</code></pre>
<h4 id="freebsd"><a class="header" href="#freebsd">FreeBSD</a></h4>
<p>Synapse can be installed via FreeBSD Ports or Packages contributed by Brendan Molloy from:</p>
<ul>
<li>Ports: <code>cd /usr/ports/net-im/py-matrix-synapse &amp;&amp; make install clean</code></li>
<li>Packages: <code>pkg install py38-matrix-synapse</code></li>
</ul>
<h4 id="openbsd"><a class="header" href="#openbsd">OpenBSD</a></h4>
<p>As of OpenBSD 6.7 Synapse is available as a pre-compiled binary. The filesystem
underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
<p>Installing Synapse:</p>
<pre><code class="language-sh">doas pkg_add synapse
</code></pre>
<h4 id="nixos"><a class="header" href="#nixos">NixOS</a></h4>
<p>Robin Lambertz has packaged Synapse for NixOS at:
<a href="https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/matrix/synapse.nix">https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/matrix/synapse.nix</a></p>
<h3 id="installing-as-a-python-module-from-pypi"><a class="header" href="#installing-as-a-python-module-from-pypi">Installing as a Python module from PyPI</a></h3>
<p>It's also possible to install Synapse as a Python module from PyPI.</p>
<p>When following this route please make sure that the <a href="setup/installation.html#platform-specific-prerequisites">Platform-specific prerequisites</a> are already installed.</p>
<p>System requirements:</p>
<ul>
<li>POSIX-compliant system (tested on Linux &amp; OS X)</li>
<li>Python 3.8 or later, up to Python 3.11.</li>
<li>At least 1GB of free RAM if you want to join large public rooms like #matrix:matrix.org</li>
</ul>
<p>If building on an uncommon architecture for which pre-built wheels are
unavailable, you will need to have a recent Rust compiler installed. The easiest
way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
<p>To install the Synapse homeserver run:</p>
<pre><code class="language-sh">mkdir -p ~/synapse
virtualenv -p python3 ~/synapse/env
source ~/synapse/env/bin/activate
pip install --upgrade pip
pip install --upgrade setuptools
pip install matrix-synapse
</code></pre>
<p>This will download Synapse from <a href="https://pypi.org/project/matrix-synapse">PyPI</a>
and install it, along with the python libraries it uses, into a virtual environment
under <code>~/synapse/env</code>.  Feel free to pick a different directory if you
prefer.</p>
<p>This Synapse installation can then be later upgraded by using pip again with the
update flag:</p>
<pre><code class="language-sh">source ~/synapse/env/bin/activate
pip install -U matrix-synapse
</code></pre>
<p>Before you can start Synapse, you will need to generate a configuration
file. To do this, run (in your virtualenv, as before):</p>
<pre><code class="language-sh">cd ~/synapse
python -m synapse.app.homeserver \
    --server-name my.domain.name \
    --config-path homeserver.yaml \
    --generate-config \
    --report-stats=[yes|no]
</code></pre>
<p>... substituting an appropriate value for <code>--server-name</code> and choosing whether
or not to report usage statistics (hostname, Synapse version, uptime, total
users, etc.) to the developers via the <code>--report-stats</code> argument.</p>
<p>This command will generate you a config file that you can then customise, but it will
also generate a set of keys for you. These keys will allow your homeserver to
identify itself to other homeserver, so don't lose or delete them. It would be
wise to back them up somewhere safe. (If, for whatever reason, you do need to
change your homeserver's keys, you may find that other homeserver have the
old key cached. If you update the signing key, you should change the name of the
key in the <code>&lt;server name&gt;.signing.key</code> file (the second word) to something
different. See the <a href="https://matrix.org/docs/spec/server_server/latest.html#retrieving-server-keys">spec</a> for more information on key management).</p>
<p>To actually run your new homeserver, pick a working directory for Synapse to
run (e.g. <code>~/synapse</code>), and:</p>
<pre><code class="language-sh">cd ~/synapse
source env/bin/activate
synctl start
</code></pre>
<h4 id="platform-specific-prerequisites"><a class="header" href="#platform-specific-prerequisites">Platform-specific prerequisites</a></h4>
<p>Synapse is written in Python but some of the libraries it uses are written in
C. So before we can install Synapse itself we need a working C compiler and the
header files for Python C extensions.</p>
<h5 id="debianubunturaspbian"><a class="header" href="#debianubunturaspbian">Debian/Ubuntu/Raspbian</a></h5>
<p>Installing prerequisites on Ubuntu or Debian:</p>
<pre><code class="language-sh">sudo apt install build-essential python3-dev libffi-dev \
                     python3-pip python3-setuptools sqlite3 \
                     libssl-dev virtualenv libjpeg-dev libxslt1-dev libicu-dev
</code></pre>
<h5 id="archlinux-1"><a class="header" href="#archlinux-1">ArchLinux</a></h5>
<p>Installing prerequisites on ArchLinux:</p>
<pre><code class="language-sh">sudo pacman -S base-devel python python-pip \
               python-setuptools python-virtualenv sqlite3 icu
</code></pre>
<h5 id="centosfedora"><a class="header" href="#centosfedora">CentOS/Fedora</a></h5>
<p>Installing prerequisites on CentOS or Fedora Linux:</p>
<pre><code class="language-sh">sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
                 libwebp-devel libxml2-devel libxslt-devel libpq-devel \
                 python3-virtualenv libffi-devel openssl-devel python3-devel \
                 libicu-devel
sudo dnf groupinstall &quot;Development Tools&quot;
</code></pre>
<h5 id="macos"><a class="header" href="#macos">macOS</a></h5>
<p>Installing prerequisites on macOS:</p>
<p>You may need to install the latest Xcode developer tools:</p>
<pre><code class="language-sh">xcode-select --install
</code></pre>
<p>Some extra dependencies may be needed. You can use Homebrew (https://brew.sh) for them.</p>
<p>You may need to install icu, and make the icu binaries and libraries accessible.
Please follow <a href="https://pypi.org/project/PyICU/">the official instructions of PyICU</a> to do so.</p>
<p>On ARM-based Macs you may also need to install libjpeg and libpq:</p>
<pre><code class="language-sh"> brew install jpeg libpq
</code></pre>
<p>On macOS Catalina (10.15) you may need to explicitly install OpenSSL
via brew and inform <code>pip</code> about it so that <code>psycopg2</code> builds:</p>
<pre><code class="language-sh">brew install openssl@1.1
export LDFLAGS=&quot;-L/usr/local/opt/openssl/lib&quot;
export CPPFLAGS=&quot;-I/usr/local/opt/openssl/include&quot;
</code></pre>
<h5 id="opensuse-1"><a class="header" href="#opensuse-1">OpenSUSE</a></h5>
<p>Installing prerequisites on openSUSE:</p>
<pre><code class="language-sh">sudo zypper in -t pattern devel_basis
sudo zypper in python-pip python-setuptools sqlite3 python-virtualenv \
               python-devel libffi-devel libopenssl-devel libjpeg62-devel \
               libicu-devel
</code></pre>
<h5 id="openbsd-1"><a class="header" href="#openbsd-1">OpenBSD</a></h5>
<p>A port of Synapse is available under <code>net/synapse</code>. The filesystem
underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
<p>To be able to build Synapse's dependency on python the <code>WRKOBJDIR</code>
(cf. <code>bsd.port.mk(5)</code>) for building python, too, needs to be on a filesystem
mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>).</p>
<p>Creating a <code>WRKOBJDIR</code> for building python under <code>/usr/local</code> (which on a
default OpenBSD installation is mounted with <code>wxallowed</code>):</p>
<pre><code class="language-sh">doas mkdir /usr/local/pobj_wxallowed
</code></pre>
<p>Assuming <code>PORTS_PRIVSEP=Yes</code> (cf. <code>bsd.port.mk(5)</code>) and <code>SUDO=doas</code> are
configured in <code>/etc/mk.conf</code>:</p>
<pre><code class="language-sh">doas chown _pbuild:_pbuild /usr/local/pobj_wxallowed
</code></pre>
<p>Setting the <code>WRKOBJDIR</code> for building python:</p>
<pre><code class="language-sh">echo WRKOBJDIR_lang/python/3.7=/usr/local/pobj_wxallowed  \\nWRKOBJDIR_lang/python/2.7=/usr/local/pobj_wxallowed &gt;&gt; /etc/mk.conf
</code></pre>
<p>Building Synapse:</p>
<pre><code class="language-sh">cd /usr/ports/net/synapse
make install
</code></pre>
<h5 id="windows"><a class="header" href="#windows">Windows</a></h5>
<p>Running Synapse natively on Windows is not officially supported.</p>
<p>If you wish to run or develop Synapse on Windows, the Windows Subsystem for
Linux provides a Linux environment which is capable of using the Debian, Fedora,
or source installation methods. More information about WSL can be found at
<a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a> for Windows 10/11 and
<a href="https://docs.microsoft.com/en-us/windows/wsl/install-on-server">https://docs.microsoft.com/en-us/windows/wsl/install-on-server</a> for
Windows Server.</p>
<h2 id="setting-up-synapse"><a class="header" href="#setting-up-synapse">Setting up Synapse</a></h2>
<p>Once you have installed synapse as above, you will need to configure it.</p>
<h3 id="using-postgresql"><a class="header" href="#using-postgresql">Using PostgreSQL</a></h3>
<p>By default Synapse uses an <a href="https://sqlite.org/">SQLite</a> database and in doing so trades
performance for convenience. Almost all installations should opt to use <a href="https://www.postgresql.org">PostgreSQL</a>
instead. Advantages include:</p>
<ul>
<li>significant performance improvements due to the superior threading and
caching model, smarter query optimiser</li>
<li>allowing the DB to be run on separate hardware</li>
</ul>
<p>For information on how to install and use PostgreSQL in Synapse, please see
<a href="setup/../postgres.html">Using Postgres</a></p>
<p>SQLite is only acceptable for testing purposes. SQLite should not be used in
a production server. Synapse will perform poorly when using
SQLite, especially when participating in large rooms.</p>
<h3 id="tls-certificates"><a class="header" href="#tls-certificates">TLS certificates</a></h3>
<p>The default configuration exposes a single HTTP port on the local
interface: <code>http://localhost:8008</code>. It is suitable for local testing,
but for any practical use, you will need Synapse's APIs to be served
over HTTPS.</p>
<p>The recommended way to do so is to set up a reverse proxy on port
<code>8448</code>. You can find documentation on doing so in
<a href="setup/../reverse_proxy.html">the reverse proxy documentation</a>.</p>
<p>Alternatively, you can configure Synapse to expose an HTTPS port. To do
so, you will need to edit <code>homeserver.yaml</code>, as follows:</p>
<ul>
<li>First, under the <code>listeners</code> option, add the configuration for the
TLS-enabled listener like so:</li>
</ul>
<pre><code class="language-yaml">listeners:
  - port: 8448
    type: http
    tls: true
    resources:
      - names: [client, federation]
</code></pre>
<ul>
<li>
<p>You will also need to add the options <code>tls_certificate_path</code> and
<code>tls_private_key_path</code>. to your configuration file. You will need to manage provisioning of 
these certificates yourself.</p>
</li>
<li>
<p>You can find more information about these options as well as how to configure synapse in the 
<a href="setup/../usage/configuration/config_documentation.html">configuration manual</a>.</p>
<p>If you are using your own certificate, be sure to use a <code>.pem</code> file that
includes the full certificate chain including any intermediate certificates
(for instance, if using certbot, use <code>fullchain.pem</code> as your certificate, not
<code>cert.pem</code>).</p>
</li>
</ul>
<p>For a more detailed guide to configuring your server for federation, see
<a href="setup/../federate.html">Federation</a>.</p>
<h3 id="client-well-known-uri"><a class="header" href="#client-well-known-uri">Client Well-Known URI</a></h3>
<p>Setting up the client Well-Known URI is optional but if you set it up, it will
allow users to enter their full username (e.g. <code>@user:&lt;server_name&gt;</code>) into clients
which support well-known lookup to automatically configure the homeserver and
identity server URLs. This is useful so that users don't have to memorize or think
about the actual homeserver URL you are using.</p>
<p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/client</code> should return JSON in
the following format.</p>
<pre><code class="language-json">{
  &quot;m.homeserver&quot;: {
    &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  }
}
</code></pre>
<p>It can optionally contain identity server information as well.</p>
<pre><code class="language-json">{
  &quot;m.homeserver&quot;: {
    &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  },
  &quot;m.identity_server&quot;: {
    &quot;base_url&quot;: &quot;https://&lt;identity.example.com&gt;&quot;
  }
}
</code></pre>
<p>To work in browser based clients, the file must be served with the appropriate
Cross-Origin Resource Sharing (CORS) headers. A recommended value would be
<code>Access-Control-Allow-Origin: *</code> which would allow all browser based clients to
view it.</p>
<p>In nginx this would be something like:</p>
<pre><code class="language-nginx">location /.well-known/matrix/client {
    return 200 '{&quot;m.homeserver&quot;: {&quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;}}';
    default_type application/json;
    add_header Access-Control-Allow-Origin *;
}
</code></pre>
<p>You should also ensure the <code>public_baseurl</code> option in <code>homeserver.yaml</code> is set
correctly. <code>public_baseurl</code> should be set to the URL that clients will use to
connect to your server. This is the same URL you put for the <code>m.homeserver</code>
<code>base_url</code> above.</p>
<pre><code class="language-yaml">public_baseurl: &quot;https://&lt;matrix.example.com&gt;&quot;
</code></pre>
<h3 id="email"><a class="header" href="#email">Email</a></h3>
<p>It is desirable for Synapse to have the capability to send email. This allows
Synapse to send password reset emails, send verifications when an email address
is added to a user's account, and send email notifications to users when they
receive new messages.</p>
<p>To configure an SMTP server for Synapse, modify the configuration section
headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>, <code>smtp_port</code>
and <code>notif_from</code> fields filled out.  You may also need to set <code>smtp_user</code>,
<code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
<p>If email is not configured, password reset, registration and notifications via
email will be disabled.</p>
<h3 id="registering-a-user"><a class="header" href="#registering-a-user">Registering a user</a></h3>
<p>One way to create a new user is to do so from a client like
<a href="https://element.io/">Element</a>.  This requires registration to be enabled via
the
<a href="setup/../usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a>
setting.</p>
<p>Alternatively, you can create new users from the command line. This can be done as follows:</p>
<ol>
<li>If synapse was installed via pip, activate the virtualenv as follows (if Synapse was
installed via a prebuilt package, <code>register_new_matrix_user</code> should already be
on the search path):
<pre><code class="language-sh">cd ~/synapse
source env/bin/activate
synctl start # if not already running
</code></pre>
</li>
<li>Run the following command:
<pre><code class="language-sh">register_new_matrix_user -c homeserver.yaml
</code></pre>
</li>
</ol>
<p>This will prompt you to add details for the new user, and will then connect to
the running Synapse to create the new user. For example:</p>
<pre><code>New user localpart: erikj
Password:
Confirm password:
Make admin [no]:
Success!
</code></pre>
<p>This process uses a setting
<a href="setup/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>,
which is shared between Synapse itself and the <code>register_new_matrix_user</code>
script. It doesn't matter what it is (a random value is generated by
<code>--generate-config</code>), but it should be kept secret, as anyone with knowledge of
it can register users, including admin accounts, on your server even if
<code>enable_registration</code> is <code>false</code>.</p>
<h3 id="setting-up-a-turn-server"><a class="header" href="#setting-up-a-turn-server">Setting up a TURN server</a></h3>
<p>For reliable VoIP calls to be routed via this homeserver, you MUST configure
a TURN server. See <a href="setup/../turn-howto.html">TURN setup</a> for details.</p>
<h3 id="url-previews"><a class="header" href="#url-previews">URL previews</a></h3>
<p>Synapse includes support for previewing URLs, which is disabled by default.  To
turn it on you must enable the <code>url_preview_enabled: True</code> config parameter
and explicitly specify the IP ranges that Synapse is not allowed to spider for
previewing in the <code>url_preview_ip_range_blacklist</code> configuration parameter.
This is critical from a security perspective to stop arbitrary Matrix users
spidering 'internal' URLs on your network. At the very least we recommend that
your loopback and RFC1918 IP addresses are blacklisted.</p>
<p>This also requires the optional <code>lxml</code> python dependency to be  installed. This
in turn requires the <code>libxml2</code> library to be available - on  Debian/Ubuntu this
means <code>apt-get install libxml2-dev</code>, or equivalent for your OS.</p>
<h3 id="troubleshooting-installation"><a class="header" href="#troubleshooting-installation">Troubleshooting Installation</a></h3>
<p><code>pip</code> seems to leak <em>lots</em> of memory during installation. For instance, a Linux
host with 512MB of RAM may run out of memory whilst installing Twisted. If this
happens, you will have to individually install the dependencies which are
failing, e.g.:</p>
<pre><code class="language-sh">pip install twisted
</code></pre>
<p>If you have any other problems, feel free to ask in
<a href="https://matrix.to/#/#synapse:matrix.org">#synapse:matrix.org</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="using-postgres"><a class="header" href="#using-postgres">Using Postgres</a></h1>
<p>The minimum supported version of PostgreSQL is determined by the <a href="deprecation_policy.html">Dependency
Deprecation Policy</a>.</p>
<h2 id="install-postgres-client-libraries"><a class="header" href="#install-postgres-client-libraries">Install postgres client libraries</a></h2>
<p>Synapse will require the python postgres client library in order to
connect to a postgres database.</p>
<ul>
<li>
<p>If you are using the <a href="setup/installation.html#matrixorg-packages">matrix.org debian/ubuntu
packages</a>, the necessary python
library will already be installed, but you will need to ensure the
low-level postgres library is installed, which you can do with
<code>apt install libpq5</code>.</p>
</li>
<li>
<p>For other pre-built packages, please consult the documentation from
the relevant package.</p>
</li>
<li>
<p>If you installed synapse <a href="setup/installation.html#installing-as-a-python-module-from-pypi">in a
virtualenv</a>, you can install
the library with:</p>
<pre><code>~/synapse/env/bin/pip install &quot;matrix-synapse[postgres]&quot;
</code></pre>
<p>(substituting the path to your virtualenv for <code>~/synapse/env</code>, if
you used a different path). You will require the postgres
development files. These are in the <code>libpq-dev</code> package on
Debian-derived distributions.</p>
</li>
</ul>
<h2 id="set-up-database"><a class="header" href="#set-up-database">Set up database</a></h2>
<p>Assuming your PostgreSQL database user is called <code>postgres</code>, first authenticate as the database user with:</p>
<pre><code class="language-sh">su - postgres
# Or, if your system uses sudo to get administrative rights
sudo -u postgres bash
</code></pre>
<p>Then, create a postgres user and a database with:</p>
<pre><code class="language-sh"># this will prompt for a password for the new user
createuser --pwprompt synapse_user

createdb --encoding=UTF8 --locale=C --template=template0 --owner=synapse_user synapse
</code></pre>
<p>The above will create a user called <code>synapse_user</code>, and a database called
<code>synapse</code>.</p>
<p>Note that the PostgreSQL database <em>must</em> have the correct encoding set
(as shown above), otherwise it will not be able to store UTF8 strings.</p>
<p>You may need to enable password authentication so <code>synapse_user</code> can
connect to the database. See
<a href="https://www.postgresql.org/docs/current/auth-pg-hba-conf.html">https://www.postgresql.org/docs/current/auth-pg-hba-conf.html</a>.</p>
<h2 id="synapse-config"><a class="header" href="#synapse-config">Synapse config</a></h2>
<p>When you are ready to start using PostgreSQL, edit the <code>database</code>
section in your config file to match the following lines:</p>
<pre><code class="language-yaml">database:
  name: psycopg2
  args:
    user: &lt;user&gt;
    password: &lt;pass&gt;
    database: &lt;db&gt;
    host: &lt;host&gt;
    cp_min: 5
    cp_max: 10
</code></pre>
<p>All key, values in <code>args</code> are passed to the <code>psycopg2.connect(..)</code>
function, except keys beginning with <code>cp_</code>, which are consumed by the
twisted adbapi connection pool. See the <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">libpq
documentation</a>
for a list of options which can be passed.</p>
<p>You should consider tuning the <code>args.keepalives_*</code> options if there is any danger of
the connection between your homeserver and database dropping, otherwise Synapse
may block for an extended period while it waits for a response from the
database server. Example values might be:</p>
<pre><code class="language-yaml">database:
  args:
    # ... as above

    # seconds of inactivity after which TCP should send a keepalive message to the server
    keepalives_idle: 10

    # the number of seconds after which a TCP keepalive message that is not
    # acknowledged by the server should be retransmitted
    keepalives_interval: 10

    # the number of TCP keepalives that can be lost before the client's connection
    # to the server is considered dead
    keepalives_count: 3
</code></pre>
<h2 id="tuning-postgres"><a class="header" href="#tuning-postgres">Tuning Postgres</a></h2>
<p>The default settings should be fine for most deployments. For larger
scale deployments tuning some of the settings is recommended, details of
which can be found at
<a href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server">https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server</a>.</p>
<p>In particular, we've found tuning the following values helpful for
performance:</p>
<ul>
<li><code>shared_buffers</code></li>
<li><code>effective_cache_size</code></li>
<li><code>work_mem</code></li>
<li><code>maintenance_work_mem</code></li>
<li><code>autovacuum_work_mem</code></li>
</ul>
<p>Note that the appropriate values for those fields depend on the amount
of free memory the database host has available.</p>
<p>Additionally, admins of large deployments might want to consider using huge pages
to help manage memory, especially when using large values of <code>shared_buffers</code>. You
can read more about that <a href="https://www.postgresql.org/docs/10/kernel-resources.html#LINUX-HUGE-PAGES">here</a>.</p>
<h2 id="porting-from-sqlite"><a class="header" href="#porting-from-sqlite">Porting from SQLite</a></h2>
<h3 id="overview"><a class="header" href="#overview">Overview</a></h3>
<p>The script <code>synapse_port_db</code> allows porting an existing synapse server
backed by SQLite to using PostgreSQL. This is done in as a two phase
process:</p>
<ol>
<li>Copy the existing SQLite database to a separate location and run
the port script against that offline database.</li>
<li>Shut down the server. Rerun the port script to port any data that
has come in since taking the first snapshot. Restart server against
the PostgreSQL database.</li>
</ol>
<p>The port script is designed to be run repeatedly against newer snapshots
of the SQLite database file. This makes it safe to repeat step 1 if
there was a delay between taking the previous snapshot and being ready
to do step 2.</p>
<p>It is safe to at any time kill the port script and restart it.</p>
<p>However, under no circumstances should the SQLite database be <code>VACUUM</code>ed between
multiple runs of the script. Doing so can lead to an inconsistent copy of your database
into Postgres.
To avoid accidental error, the script will check that SQLite's <code>auto_vacuum</code> mechanism
is disabled, but the script is not able to protect against a manual <code>VACUUM</code> operation
performed either by the administrator or by any automated task that the administrator
may have configured.</p>
<p>Note that the database may take up significantly more (25% - 100% more)
space on disk after porting to Postgres.</p>
<h3 id="using-the-port-script"><a class="header" href="#using-the-port-script">Using the port script</a></h3>
<p>Firstly, shut down the currently running synapse server and copy its
database file (typically <code>homeserver.db</code>) to another location. Once the
copy is complete, restart synapse. For instance:</p>
<pre><code class="language-sh">synctl stop
cp homeserver.db homeserver.db.snapshot
synctl start
</code></pre>
<p>Copy the old config file into a new config file:</p>
<pre><code class="language-sh">cp homeserver.yaml homeserver-postgres.yaml
</code></pre>
<p>Edit the database section as described in the section <em>Synapse config</em>
above and with the SQLite snapshot located at <code>homeserver.db.snapshot</code>
simply run:</p>
<pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db.snapshot \
    --postgres-config homeserver-postgres.yaml
</code></pre>
<p>The flag <code>--curses</code> displays a coloured curses progress UI.</p>
<p>If the script took a long time to complete, or time has otherwise passed
since the original snapshot was taken, repeat the previous steps with a
newer snapshot.</p>
<p>To complete the conversion shut down the synapse server and run the port
script one last time, e.g. if the SQLite database is at <code>homeserver.db</code>
run:</p>
<pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db \
    --postgres-config homeserver-postgres.yaml
</code></pre>
<p>Once that has completed, change the synapse config to point at the
PostgreSQL database configuration file <code>homeserver-postgres.yaml</code>:</p>
<pre><code class="language-sh">synctl stop
mv homeserver.yaml homeserver-old-sqlite.yaml
mv homeserver-postgres.yaml homeserver.yaml
synctl start
</code></pre>
<p>Synapse should now be running against PostgreSQL.</p>
<h2 id="troubleshooting"><a class="header" href="#troubleshooting">Troubleshooting</a></h2>
<h3 id="alternative-auth-methods"><a class="header" href="#alternative-auth-methods">Alternative auth methods</a></h3>
<p>If you get an error along the lines of <code>FATAL:  Ident authentication failed for user &quot;synapse_user&quot;</code>, you may need to use an authentication method other than
<code>ident</code>:</p>
<ul>
<li>
<p>If the <code>synapse_user</code> user has a password, add the password to the <code>database:</code>
section of <code>homeserver.yaml</code>. Then add the following to <code>pg_hba.conf</code>:</p>
<pre><code>host    synapse     synapse_user    ::1/128     md5  # or `scram-sha-256` instead of `md5` if you use that
</code></pre>
</li>
<li>
<p>If the <code>synapse_user</code> user does not have a password, then a password doesn't
have to be added to <code>homeserver.yaml</code>. But the following does need to be added
to <code>pg_hba.conf</code>:</p>
<pre><code>host    synapse     synapse_user    ::1/128     trust
</code></pre>
</li>
</ul>
<p>Note that line order matters in <code>pg_hba.conf</code>, so make sure that if you do add a
new line, it is inserted before:</p>
<pre><code>host    all         all             ::1/128     ident
</code></pre>
<h3 id="fixing-incorrect-collate-or-ctype"><a class="header" href="#fixing-incorrect-collate-or-ctype">Fixing incorrect <code>COLLATE</code> or <code>CTYPE</code></a></h3>
<p>Synapse will refuse to set up a new database if it has the wrong values of
<code>COLLATE</code> and <code>CTYPE</code> set. Synapse will also refuse to start an existing database with incorrect values
of <code>COLLATE</code> and <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the 
<code>database</code> section of the config, is set to true. Using different locales can cause issues if the locale library is updated from
underneath the database, or if a different version of the locale is used on any
replicas.</p>
<p>If you have a databse with an unsafe locale, the safest way to fix the issue is to dump the database and recreate it with
the correct locale parameter (as shown above). It is also possible to change the
parameters on a live database and run a <code>REINDEX</code> on the entire database,
however extreme care must be taken to avoid database corruption.</p>
<p>Note that the above may fail with an error about duplicate rows if corruption
has already occurred, and such duplicate rows will need to be manually removed.</p>
<h3 id="fixing-inconsistent-sequences-error"><a class="header" href="#fixing-inconsistent-sequences-error">Fixing inconsistent sequences error</a></h3>
<p>Synapse uses Postgres sequences to generate IDs for various tables. A sequence
and associated table can get out of sync if, for example, Synapse has been
downgraded and then upgraded again.</p>
<p>To fix the issue shut down Synapse (including any and all workers) and run the
SQL command included in the error message. Once done Synapse should start
successfully.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="using-a-reverse-proxy-with-synapse"><a class="header" href="#using-a-reverse-proxy-with-synapse">Using a reverse proxy with Synapse</a></h1>
<p>It is recommended to put a reverse proxy such as
<a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">nginx</a>,
<a href="https://httpd.apache.org/docs/current/mod/mod_proxy_http.html">Apache</a>,
<a href="https://caddyserver.com/docs/quick-starts/reverse-proxy">Caddy</a>,
<a href="https://www.haproxy.org/">HAProxy</a> or
<a href="https://man.openbsd.org/relayd.8">relayd</a> in front of Synapse. One advantage
of doing so is that it means that you can expose the default https port
(443) to Matrix clients without needing to run Synapse with root
privileges.</p>
<p>You should configure your reverse proxy to forward requests to <code>/_matrix</code> or
<code>/_synapse/client</code> to Synapse, and have it set the <code>X-Forwarded-For</code> and
<code>X-Forwarded-Proto</code> request headers.</p>
<p>You should remember that Matrix clients and other Matrix servers do not
necessarily need to connect to your server via the same server name or
port. Indeed, clients will use port 443 by default, whereas servers default to
port 8448. Where these are different, we refer to the 'client port' and the
'federation port'. See <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
specification</a>
for more details of the algorithm used for federation connections, and
<a href="delegate.html">Delegation</a> for instructions on setting up delegation.</p>
<p><strong>NOTE</strong>: Your reverse proxy must not <code>canonicalise</code> or <code>normalise</code>
the requested URI in any way (for example, by decoding <code>%xx</code> escapes).
Beware that Apache <em>will</em> canonicalise URIs unless you specify
<code>nocanon</code>.</p>
<p>Let's assume that we expect clients to connect to our server at
<code>https://matrix.example.com</code>, and other servers to connect at
<code>https://example.com:8448</code>.  The following sections detail the configuration of
the reverse proxy and the homeserver.</p>
<h2 id="homeserver-configuration"><a class="header" href="#homeserver-configuration">Homeserver Configuration</a></h2>
<p>The HTTP configuration will need to be updated for Synapse to correctly record 
client IP addresses and generate redirect URLs while behind a reverse proxy. </p>
<p>In <code>homeserver.yaml</code> set <code>x_forwarded: true</code> in the port 8008 section and 
consider setting <code>bind_addresses: ['127.0.0.1']</code> so that the server only
listens to traffic on localhost. (Do not change <code>bind_addresses</code> to <code>127.0.0.1</code> 
when using a containerized Synapse, as that will prevent it from responding
to proxied traffic.)</p>
<p>Optionally, you can also set
<a href="./usage/configuration/config_documentation.html#listeners"><code>request_id_header</code></a>
so that the server extracts and re-uses the same request ID format that the
reverse proxy is using.</p>
<h2 id="reverse-proxy-configuration-examples"><a class="header" href="#reverse-proxy-configuration-examples">Reverse-proxy configuration examples</a></h2>
<p><strong>NOTE</strong>: You only need one of these.</p>
<h3 id="nginx"><a class="header" href="#nginx">nginx</a></h3>
<pre><code class="language-nginx">server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # For the federation port
    listen 8448 ssl http2 default_server;
    listen [::]:8448 ssl http2 default_server;

    server_name matrix.example.com;

    location ~ ^(/_matrix|/_synapse/client) {
        # note: do not add a path (even a single /) after the port in `proxy_pass`,
        # otherwise nginx will canonicalise the URI and cause signature verification
        # errors.
        proxy_pass http://localhost:8008;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;

        # Nginx by default only allows file uploads up to 1M in size
        # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
        client_max_body_size 50M;
	
	# Synapse responses may be chunked, which is an HTTP/1.1 feature.
	proxy_http_version 1.1;
    }
}
</code></pre>
<h3 id="caddy-v2"><a class="header" href="#caddy-v2">Caddy v2</a></h3>
<pre><code>matrix.example.com {
  reverse_proxy /_matrix/* localhost:8008
  reverse_proxy /_synapse/client/* localhost:8008
}

example.com:8448 {
  reverse_proxy /_matrix/* localhost:8008
}
</code></pre>
<p><a href="delegate.html">Delegation</a> example:</p>
<pre><code>example.com {
	header /.well-known/matrix/* Content-Type application/json
	header /.well-known/matrix/* Access-Control-Allow-Origin *
	respond /.well-known/matrix/server `{&quot;m.server&quot;: &quot;matrix.example.com:443&quot;}`
	respond /.well-known/matrix/client `{&quot;m.homeserver&quot;:{&quot;base_url&quot;:&quot;https://matrix.example.com&quot;},&quot;m.identity_server&quot;:{&quot;base_url&quot;:&quot;https://identity.example.com&quot;}}`
}

matrix.example.com {
    reverse_proxy /_matrix/* localhost:8008
    reverse_proxy /_synapse/client/* localhost:8008
}
</code></pre>
<h3 id="apache"><a class="header" href="#apache">Apache</a></h3>
<pre><code class="language-apache">&lt;VirtualHost *:443&gt;
    SSLEngine on
    ServerName matrix.example.com

    RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
    AllowEncodedSlashes NoDecode
    ProxyPreserveHost on
    ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
    ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
    ProxyPass /_synapse/client http://127.0.0.1:8008/_synapse/client nocanon
    ProxyPassReverse /_synapse/client http://127.0.0.1:8008/_synapse/client
&lt;/VirtualHost&gt;

&lt;VirtualHost *:8448&gt;
    SSLEngine on
    ServerName example.com

    RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
    AllowEncodedSlashes NoDecode
    ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
    ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
&lt;/VirtualHost&gt;
</code></pre>
<p><strong>NOTE</strong>: ensure the  <code>nocanon</code> options are included.</p>
<p><strong>NOTE 2</strong>: It appears that Synapse is currently incompatible with the ModSecurity module for Apache (<code>mod_security2</code>). If you need it enabled for other services on your web server, you can disable it for Synapse's two VirtualHosts by including the following lines before each of the two <code>&lt;/VirtualHost&gt;</code> above:</p>
<pre><code class="language-apache">&lt;IfModule security2_module&gt;
    SecRuleEngine off
&lt;/IfModule&gt;
</code></pre>
<p><strong>NOTE 3</strong>: Missing <code>ProxyPreserveHost on</code> can lead to a redirect loop.</p>
<h3 id="haproxy"><a class="header" href="#haproxy">HAProxy</a></h3>
<pre><code>frontend https
  bind *:443,[::]:443 ssl crt /etc/ssl/haproxy/ strict-sni alpn h2,http/1.1
  http-request set-header X-Forwarded-Proto https if { ssl_fc }
  http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  http-request set-header X-Forwarded-For %[src]

  # Matrix client traffic
  acl matrix-host hdr(host) -i matrix.example.com matrix.example.com:443
  acl matrix-path path_beg /_matrix
  acl matrix-path path_beg /_synapse/client

  use_backend matrix if matrix-host matrix-path

frontend matrix-federation
  bind *:8448,[::]:8448 ssl crt /etc/ssl/haproxy/synapse.pem alpn h2,http/1.1
  http-request set-header X-Forwarded-Proto https if { ssl_fc }
  http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  http-request set-header X-Forwarded-For %[src]

  default_backend matrix

backend matrix
  server matrix 127.0.0.1:8008
</code></pre>
<p><a href="delegate.html">Delegation</a> example:</p>
<pre><code>frontend https
  acl matrix-well-known-client-path path /.well-known/matrix/client
  acl matrix-well-known-server-path path /.well-known/matrix/server
  use_backend matrix-well-known-client if matrix-well-known-client-path
  use_backend matrix-well-known-server if matrix-well-known-server-path
 
backend matrix-well-known-client
  http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  http-request return status 200 content-type application/json string '{&quot;m.homeserver&quot;:{&quot;base_url&quot;:&quot;https://matrix.example.com&quot;},&quot;m.identity_server&quot;:{&quot;base_url&quot;:&quot;https://identity.example.com&quot;}}'

backend matrix-well-known-server
  http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  http-request return status 200 content-type application/json string '{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}'
</code></pre>
<h3 id="relayd"><a class="header" href="#relayd">Relayd</a></h3>
<pre><code>table &lt;webserver&gt;    { 127.0.0.1 }
table &lt;matrixserver&gt; { 127.0.0.1 }

http protocol &quot;https&quot; {
    tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
    tls keypair &quot;example.com&quot;
    match header set &quot;X-Forwarded-For&quot;   value &quot;$REMOTE_ADDR&quot;
    match header set &quot;X-Forwarded-Proto&quot; value &quot;https&quot;

    # set CORS header for .well-known/matrix/server, .well-known/matrix/client
    # httpd does not support setting headers, so do it here
    match request path &quot;/.well-known/matrix/*&quot; tag &quot;matrix-cors&quot;
    match response tagged &quot;matrix-cors&quot; header set &quot;Access-Control-Allow-Origin&quot; value &quot;*&quot;

    pass quick path &quot;/_matrix/*&quot;         forward to &lt;matrixserver&gt;
    pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;

    # pass on non-matrix traffic to webserver
    pass                                 forward to &lt;webserver&gt;
}

relay &quot;https_traffic&quot; {
    listen on egress port 443 tls
    protocol &quot;https&quot;
    forward to &lt;matrixserver&gt; port 8008 check tcp
    forward to &lt;webserver&gt;    port 8080 check tcp
}

http protocol &quot;matrix&quot; {
    tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
    tls keypair &quot;example.com&quot;
    block
    pass quick path &quot;/_matrix/*&quot;         forward to &lt;matrixserver&gt;
    pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
}

relay &quot;matrix_federation&quot; {
    listen on egress port 8448 tls
    protocol &quot;matrix&quot;
    forward to &lt;matrixserver&gt; port 8008 check tcp
}
</code></pre>
<h2 id="health-check-endpoint"><a class="header" href="#health-check-endpoint">Health check endpoint</a></h2>
<p>Synapse exposes a health check endpoint for use by reverse proxies.
Each configured HTTP listener has a <code>/health</code> endpoint which always returns
200 OK (and doesn't get logged).</p>
<h2 id="synapse-administration-endpoints"><a class="header" href="#synapse-administration-endpoints">Synapse administration endpoints</a></h2>
<p>Endpoints for administering your Synapse instance are placed under
<code>/_synapse/admin</code>. These require authentication through an access token of an
admin user. However as access to these endpoints grants the caller a lot of power,
we do not recommend exposing them to the public internet without good reason.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="using-a-forward-proxy-with-synapse"><a class="header" href="#using-a-forward-proxy-with-synapse">Using a forward proxy with Synapse</a></h1>
<p>You can use Synapse with a forward or outbound proxy. An example of when
this is necessary is in corporate environments behind a DMZ (demilitarized zone).
Synapse supports routing outbound HTTP(S) requests via a proxy. Only HTTP(S)
proxy is supported, not SOCKS proxy or anything else.</p>
<h2 id="configure"><a class="header" href="#configure">Configure</a></h2>
<p>The <code>http_proxy</code>, <code>https_proxy</code>, <code>no_proxy</code> environment variables are used to
specify proxy settings. The environment variable is not case sensitive.</p>
<ul>
<li><code>http_proxy</code>: Proxy server to use for HTTP requests.</li>
<li><code>https_proxy</code>: Proxy server to use for HTTPS requests.</li>
<li><code>no_proxy</code>: Comma-separated list of hosts, IP addresses, or IP ranges in CIDR
format which should not use the proxy. Synapse will directly connect to these hosts.</li>
</ul>
<p>The <code>http_proxy</code> and <code>https_proxy</code> environment variables have the form: <code>[scheme://][&lt;username&gt;:&lt;password&gt;@]&lt;host&gt;[:&lt;port&gt;]</code></p>
<ul>
<li>
<p>Supported schemes are <code>http://</code> and <code>https://</code>. The default scheme is <code>http://</code>
for compatibility reasons; it is recommended to set a scheme. If scheme is set
to <code>https://</code> the connection uses TLS between Synapse and the proxy.</p>
<p><strong>NOTE</strong>: Synapse validates the certificates. If the certificate is not
valid, then the connection is dropped.</p>
</li>
<li>
<p>Default port if not given is <code>1080</code>.</p>
</li>
<li>
<p>Username and password are optional and will be used to authenticate against
the proxy.</p>
</li>
</ul>
<p><strong>Examples</strong></p>
<ul>
<li>HTTP_PROXY=http://USERNAME:PASSWORD@10.0.1.1:8080/</li>
<li>HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.example.com:8080/</li>
<li>NO_PROXY=master.hostname.example.com,10.1.0.0/16,172.30.0.0/16</li>
</ul>
<p><strong>NOTE</strong>:
Synapse does not apply the IP blacklist to connections through the proxy (since
the DNS resolution is done by the proxy). It is expected that the proxy or firewall
will apply blacklisting of IP addresses.</p>
<h2 id="connection-types"><a class="header" href="#connection-types">Connection types</a></h2>
<p>The proxy will be <strong>used</strong> for:</p>
<ul>
<li>push</li>
<li>url previews</li>
<li>phone-home stats</li>
<li>recaptcha validation</li>
<li>CAS auth validation</li>
<li>OpenID Connect</li>
<li>Outbound federation</li>
<li>Federation (checking public key revocation)</li>
<li>Fetching public keys of other servers</li>
<li>Downloading remote media</li>
</ul>
<p>It will <strong>not be used</strong> for:</p>
<ul>
<li>Application Services</li>
<li>Identity servers</li>
<li>In worker configurations
<ul>
<li>connections between workers</li>
<li>connections from workers to Redis</li>
</ul>
</li>
</ul>
<h2 id="troubleshooting-1"><a class="header" href="#troubleshooting-1">Troubleshooting</a></h2>
<p>If a proxy server is used with TLS (HTTPS) and no connections are established,
it is most likely due to the proxy's certificates. To test this, the validation
in Synapse can be deactivated.</p>
<p><strong>NOTE</strong>: This has an impact on security and is for testing purposes only!</p>
<p>To deactivate the certificate validation, the following setting must be added to
your <a href="setup/../usage/configuration/homeserver_sample_config.html">homserver.yaml</a>.</p>
<pre><code class="language-yaml">use_insecure_ssl_client_just_for_testing_do_not_use: true
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="overview-1"><a class="header" href="#overview-1">Overview</a></h1>
<p>This document explains how to enable VoIP relaying on your homeserver with
TURN.</p>
<p>The synapse Matrix homeserver supports integration with TURN server via the
<a href="https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00">TURN server REST API</a>. This
allows the homeserver to generate credentials that are valid for use on the
TURN server through the use of a secret shared between the homeserver and the
TURN server.</p>
<p>This documentation provides two TURN server configuration examples:</p>
<ul>
<li><a href="setup/turn/coturn.html">coturn</a></li>
<li><a href="setup/turn/eturnal.html">eturnal</a></li>
</ul>
<h2 id="requirements"><a class="header" href="#requirements">Requirements</a></h2>
<p>For TURN relaying to work, the TURN service must be hosted on a server/endpoint with a public IP.</p>
<p>Hosting TURN behind NAT requires port forwaring and for the NAT gateway to have a public IP.
However, even with appropriate configuration, NAT is known to cause issues and to often not work.</p>
<p>Afterwards, the homeserver needs some further configuration.</p>
<h2 id="synapse-setup"><a class="header" href="#synapse-setup">Synapse setup</a></h2>
<p>Your homeserver configuration file needs the following extra keys:</p>
<ol>
<li><a href="usage/configuration/config_documentation.html#turn_uris"><code>turn_uris</code></a></li>
<li><a href="usage/configuration/config_documentation.html#turn_shared_secret"><code>turn_shared_secret</code></a></li>
<li><a href="usage/configuration/config_documentation.html#turn_user_lifetime"><code>turn_user_lifetime</code></a></li>
<li><a href="usage/configuration/config_documentation.html#turn_allow_guests"><code>turn_allow_guests</code></a></li>
</ol>
<p>As an example, here is the relevant section of the config file for <code>matrix.org</code>. The
<code>turn_uris</code> are appropriate for TURN servers listening on the default ports, with no TLS.</p>
<pre><code>turn_uris: [ &quot;turn:turn.matrix.org?transport=udp&quot;, &quot;turn:turn.matrix.org?transport=tcp&quot; ]
turn_shared_secret: &quot;n0t4ctuAllymatr1Xd0TorgSshar3d5ecret4obvIousreAsons&quot;
turn_user_lifetime: 86400000
turn_allow_guests: true
</code></pre>
<p>After updating the homeserver configuration, you must restart synapse:</p>
<ul>
<li>If you use synctl:
<pre><code class="language-sh"># Depending on how Synapse is installed, synctl may already be on
# your PATH. If not, you may need to activate a virtual environment.
synctl restart
</code></pre>
</li>
<li>If you use systemd:
<pre><code class="language-sh">systemctl restart matrix-synapse.service
</code></pre>
</li>
</ul>
<p>... and then reload any clients (or wait an hour for them to refresh their
settings).</p>
<h2 id="troubleshooting-2"><a class="header" href="#troubleshooting-2">Troubleshooting</a></h2>
<p>The normal symptoms of a misconfigured TURN server are that calls between
devices on different networks ring, but get stuck at &quot;call
connecting&quot;. Unfortunately, troubleshooting this can be tricky.</p>
<p>Here are a few things to try:</p>
<ul>
<li>
<p>Check that you have opened your firewall to allow TCP and UDP traffic to the
TURN ports (normally 3478 and 5349).</p>
</li>
<li>
<p>Check that you have opened your firewall to allow UDP traffic to the UDP
relay ports (49152-65535 by default).</p>
</li>
<li>
<p>Try disabling TLS/DTLS listeners and enable only its (unencrypted)
TCP/UDP listeners. (This will only leave signaling traffic unencrypted;
voice &amp; video WebRTC traffic is always encrypted.)</p>
</li>
<li>
<p>Some WebRTC implementations (notably, that of Google Chrome) appear to get
confused by TURN servers which are reachable over IPv6 (this appears to be
an unexpected side-effect of its handling of multiple IP addresses as
defined by
<a href="https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12"><code>draft-ietf-rtcweb-ip-handling</code></a>).</p>
<p>Try removing any AAAA records for your TURN server, so that it is only
reachable over IPv4.</p>
</li>
<li>
<p>If your TURN server is behind NAT:</p>
<ul>
<li>
<p>double-check that your NAT gateway is correctly forwarding all TURN
ports (normally 3478 &amp; 5349 for TCP &amp; UDP TURN traffic, and 49152-65535 for the UDP
relay) to the NAT-internal address of your TURN server. If advertising
both IPv4 and IPv6 external addresses via the <code>external-ip</code> option, ensure
that the NAT is forwarding both IPv4 and IPv6 traffic to the IPv4 and IPv6
internal addresses of your TURN server. When in doubt, remove AAAA records
for your TURN server and specify only an IPv4 address as your <code>external-ip</code>.</p>
</li>
<li>
<p>ensure that your TURN server uses the NAT gateway as its default route.</p>
</li>
</ul>
</li>
<li>
<p>Enable more verbose logging, in <code>coturn</code> via the <code>verbose</code> setting:</p>
<pre><code>verbose
</code></pre>
<p>or with <code>eturnal</code> with the shell command <code>eturnalctl loglevel debug</code> or in the configuration file (the service needs to <a href="https://eturnal.net/documentation/#Operation">reload</a> for it to become effective):</p>
<pre><code class="language-yaml">    ## Logging configuration:
        log_level: debug
</code></pre>
<p>... and then see if there are any clues in its logs.</p>
</li>
<li>
<p>If you are using a browser-based client under Chrome, check
<code>chrome://webrtc-internals/</code> for insights into the internals of the
negotiation. On Firefox, check the &quot;Connection Log&quot; on <code>about:webrtc</code>.</p>
<p>(Understanding the output is beyond the scope of this document!)</p>
</li>
<li>
<p>You can test your Matrix homeserver TURN setup with <a href="https://test.voip.librepush.net/">https://test.voip.librepush.net/</a>.
Note that this test is not fully reliable yet, so don't be discouraged if
the test fails.
<a href="https://github.com/matrix-org/voip-tester">Here</a> is the github repo of the
source of the tester, where you can file bug reports.</p>
</li>
<li>
<p>There is a WebRTC test tool at
<a href="https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/">https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/</a>. To
use it, you will need a username/password for your TURN server. You can
either:</p>
<ul>
<li>
<p>look for the <code>GET /_matrix/client/r0/voip/turnServer</code> request made by a
matrix client to your homeserver in your browser's network inspector. In
the response you should see <code>username</code> and <code>password</code>. Or:</p>
</li>
<li>
<p>Use the following shell commands for <code>coturn</code>:</p>
<pre><code class="language-sh">secret=staticAuthSecretHere

u=$((`date +%s` + 3600)):test
p=$(echo -n $u | openssl dgst -hmac $secret -sha1 -binary | base64)
echo -e &quot;username: $u\npassword: $p&quot;
</code></pre>
<p>or for <code>eturnal</code></p>
<pre><code class="language-sh">eturnalctl credentials
</code></pre>
</li>
<li>
<p>Or (<strong>coturn only</strong>): Temporarily configure <code>coturn</code> to accept a static
username/password. To do this, comment out <code>use-auth-secret</code> and
<code>static-auth-secret</code> and add the following:</p>
<pre><code>lt-cred-mech
user=username:password
</code></pre>
<p><strong>Note</strong>: these settings will not take effect unless <code>use-auth-secret</code>
and <code>static-auth-secret</code> are disabled.</p>
<p>Restart coturn after changing the configuration file.</p>
<p>Remember to restore the original settings to go back to testing with
Matrix clients!</p>
</li>
</ul>
<p>If the TURN server is working correctly, you should see at least one <code>relay</code>
entry in the results.</p>
</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="coturn-turn-server"><a class="header" href="#coturn-turn-server">coturn TURN server</a></h1>
<p>The following sections describe how to install <a href="https://github.com/coturn/coturn">coturn</a> (which implements the TURN REST API).</p>
<h2 id="coturn-setup"><a class="header" href="#coturn-setup"><code>coturn</code> setup</a></h2>
<h3 id="initial-installation"><a class="header" href="#initial-installation">Initial installation</a></h3>
<p>The TURN daemon <code>coturn</code> is available from a variety of sources such as native package managers, or installation from source.</p>
<h4 id="debian-and-ubuntu-based-distributions"><a class="header" href="#debian-and-ubuntu-based-distributions">Debian and Ubuntu based distributions</a></h4>
<p>Just install the debian package:</p>
<pre><code class="language-sh">sudo apt install coturn
</code></pre>
<p>This will install and start a systemd service called <code>coturn</code>.</p>
<h4 id="source-installation"><a class="header" href="#source-installation">Source installation</a></h4>
<ol>
<li>
<p>Download the <a href="https://github.com/coturn/coturn/releases/latest">latest release</a> from github.  Unpack it and <code>cd</code> into the directory.</p>
</li>
<li>
<p>Configure it:</p>
<pre><code class="language-sh">./configure
</code></pre>
<p>You may need to install <code>libevent2</code>: if so, you should do so in
the way recommended by your operating system. You can ignore
warnings about lack of database support: a database is unnecessary
for this purpose.</p>
</li>
<li>
<p>Build and install it:</p>
<pre><code class="language-sh">make
sudo make install
</code></pre>
</li>
</ol>
<h3 id="configuration"><a class="header" href="#configuration">Configuration</a></h3>
<ol>
<li>
<p>Create or edit the config file in <code>/etc/turnserver.conf</code>. The relevant
lines, with example values, are:</p>
<pre><code>use-auth-secret
static-auth-secret=[your secret key here]
realm=turn.myserver.org
</code></pre>
<p>See <code>turnserver.conf</code> for explanations of the options. One way to generate
the <code>static-auth-secret</code> is with <code>pwgen</code>:</p>
<pre><code class="language-sh">pwgen -s 64 1
</code></pre>
<p>A <code>realm</code> must be specified, but its value is somewhat arbitrary. (It is
sent to clients as part of the authentication flow.) It is conventional to
set it to be your server name.</p>
</li>
<li>
<p>You will most likely want to configure <code>coturn</code> to write logs somewhere. The
easiest way is normally to send them to the syslog:</p>
<pre><code class="language-sh">syslog
</code></pre>
<p>(in which case, the logs will be available via <code>journalctl -u coturn</code> on a
systemd system). Alternatively, <code>coturn</code> can be configured to write to a
logfile - check the example config file supplied with <code>coturn</code>.</p>
</li>
<li>
<p>Consider your security settings. TURN lets users request a relay which will
connect to arbitrary IP addresses and ports. The following configuration is
suggested as a minimum starting point:</p>
<pre><code># VoIP traffic is all UDP. There is no reason to let users connect to arbitrary TCP endpoints via the relay.
no-tcp-relay

# don't let the relay ever try to connect to private IP address ranges within your network (if any)
# given the turn server is likely behind your firewall, remember to include any privileged public IPs too.
denied-peer-ip=10.0.0.0-10.255.255.255
denied-peer-ip=192.168.0.0-192.168.255.255
denied-peer-ip=172.16.0.0-172.31.255.255

# recommended additional local peers to block, to mitigate external access to internal services.
# https://www.rtcsec.com/article/slack-webrtc-turn-compromise-and-bug-bounty/#how-to-fix-an-open-turn-relay-to-address-this-vulnerability
no-multicast-peers
denied-peer-ip=0.0.0.0-0.255.255.255
denied-peer-ip=100.64.0.0-100.127.255.255
denied-peer-ip=127.0.0.0-127.255.255.255
denied-peer-ip=169.254.0.0-169.254.255.255
denied-peer-ip=192.0.0.0-192.0.0.255
denied-peer-ip=192.0.2.0-192.0.2.255
denied-peer-ip=192.88.99.0-192.88.99.255
denied-peer-ip=198.18.0.0-198.19.255.255
denied-peer-ip=198.51.100.0-198.51.100.255
denied-peer-ip=203.0.113.0-203.0.113.255
denied-peer-ip=240.0.0.0-255.255.255.255

# special case the turn server itself so that client-&gt;TURN-&gt;TURN-&gt;client flows work
# this should be one of the turn server's listening IPs
allowed-peer-ip=10.0.0.1

# consider whether you want to limit the quota of relayed streams per user (or total) to avoid risk of DoS.
user-quota=12 # 4 streams per video call, so 12 streams = 3 simultaneous relayed calls per user.
total-quota=1200
</code></pre>
</li>
<li>
<p>Also consider supporting TLS/DTLS. To do this, add the following settings
to <code>turnserver.conf</code>:</p>
<pre><code># TLS certificates, including intermediate certs.
# For Let's Encrypt certificates, use `fullchain.pem` here.
cert=/path/to/fullchain.pem

# TLS private key file
pkey=/path/to/privkey.pem

# Ensure the configuration lines that disable TLS/DTLS are commented-out or removed
#no-tls
#no-dtls
</code></pre>
<p>In this case, replace the <code>turn:</code> schemes in the <code>turn_uris</code> settings below
with <code>turns:</code>.</p>
<p>We recommend that you only try to set up TLS/DTLS once you have set up a
basic installation and got it working.</p>
<p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
not work with any Matrix client that uses Chromium's WebRTC library. This
currently includes Element Android &amp; iOS; for more details, see their
<a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
<a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
<a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
</li>
<li>
<p>Ensure your firewall allows traffic into the TURN server on the ports
you've configured it to listen on (By default: 3478 and 5349 for TURN
traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
for the UDP relay.)</p>
</li>
<li>
<p>If your TURN server is behind NAT, the NAT gateway must have an external,
publicly-reachable IP address. You must configure <code>coturn</code> to advertise that
address to connecting clients:</p>
<pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
</code></pre>
<p>You may optionally limit the TURN server to listen only on the local
address that is mapped by NAT to the external address:</p>
<pre><code>listening-ip=INTERNAL_TURNSERVER_IPv4_ADDRESS
</code></pre>
<p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
configure <code>coturn</code> to advertise each available address:</p>
<pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
external-ip=EXTERNAL_NAT_IPv6_ADDRESS
</code></pre>
<p>When advertising an external IPv6 address, ensure that the firewall and
network settings of the system running your TURN server are configured to
accept IPv6 traffic, and that the TURN server is listening on the local
IPv6 address that is mapped by NAT to the external IPv6 address.</p>
</li>
<li>
<p>(Re)start the turn server:</p>
<ul>
<li>
<p>If you used the Debian package (or have set up a systemd unit yourself):</p>
<pre><code class="language-sh">sudo systemctl restart coturn
</code></pre>
</li>
<li>
<p>If you built from source:</p>
<pre><code class="language-sh">/usr/local/bin/turnserver -o
</code></pre>
</li>
</ul>
</li>
</ol>
<div style="break-before: page; page-break-before: always;"></div><h1 id="eturnal-turn-server"><a class="header" href="#eturnal-turn-server">eturnal TURN server</a></h1>
<p>The following sections describe how to install <a href="https://github.com/processone/eturnal">eturnal</a> 
(which implements the TURN REST API).</p>
<h2 id="eturnal-setup"><a class="header" href="#eturnal-setup"><code>eturnal</code> setup</a></h2>
<h3 id="initial-installation-1"><a class="header" href="#initial-installation-1">Initial installation</a></h3>
<p>The <code>eturnal</code> TURN server implementation is available from a variety of sources 
such as native package managers, binary packages, installation from source or 
<a href="https://eturnal.net/documentation/code/docker.html">container image</a>. They are 
all described <a href="https://github.com/processone/eturnal#installation">here</a>.</p>
<p>Quick-Test instructions in a <a href="https://github.com/processone/eturnal/blob/master/QUICK-TEST.md">Linux Shell</a> 
or with <a href="https://github.com/processone/eturnal/blob/master/docker-k8s/QUICK-TEST.md">Docker</a> 
are available as well.</p>
<h3 id="configuration-1"><a class="header" href="#configuration-1">Configuration</a></h3>
<p>After installation, <code>eturnal</code> usually ships a <a href="https://github.com/processone/eturnal/blob/master/config/eturnal.yml">default configuration file</a> 
here: <code>/etc/eturnal.yml</code> (and, if not found there, there is a backup file here: 
<code>/opt/eturnal/etc/eturnal.yml</code>). It uses the (indentation-sensitive!) <a href="https://en.wikipedia.org/wiki/YAML">YAML</a> 
format. The file contains further explanations.</p>
<p>Here are some hints how to configure eturnal on your <a href="https://github.com/processone/eturnal#configuration">host machine</a> 
or when using e.g. <a href="https://eturnal.net/documentation/code/docker.html">Docker</a>.
You may also further deep dive into the <a href="https://eturnal.net/documentation/">reference documentation</a>.</p>
<p><code>eturnal</code> runs out of the box with the default configuration. To enable TURN and 
to integrate it with your homeserver, some aspects in <code>eturnal</code>'s default configuration file 
must be edited:</p>
<ol>
<li>
<p>Homeserver's <a href="setup/turn/../../usage/configuration/config_documentation.html#turn_shared_secret"><code>turn_shared_secret</code></a> 
and eturnal's shared <code>secret</code> for authentication</p>
<p>Both need to have the same value. Uncomment and adjust this line in <code>eturnal</code>'s 
configuration file:</p>
<pre><code class="language-yaml">secret: &quot;long-and-cryptic&quot;     # Shared secret, CHANGE THIS.
</code></pre>
<p>One way to generate a <code>secret</code> is with <code>pwgen</code>:</p>
<pre><code class="language-sh">pwgen -s 64 1
</code></pre>
</li>
<li>
<p>Public IP address</p>
<p>If your TURN server is behind NAT, the NAT gateway must have an external,
publicly-reachable IP address. <code>eturnal</code> tries to autodetect the public IP address, 
however, it may also be configured by uncommenting and adjusting this line, so 
<code>eturnal</code> advertises that address to connecting clients:</p>
<pre><code class="language-yaml">relay_ipv4_addr: &quot;203.0.113.4&quot; # The server's public IPv4 address.
</code></pre>
<p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
configure <code>eturnal</code> to advertise each available address:</p>
<pre><code class="language-yaml">relay_ipv4_addr: &quot;203.0.113.4&quot; # The server's public IPv4 address.
relay_ipv6_addr: &quot;2001:db8::4&quot; # The server's public IPv6 address (optional).
</code></pre>
<p>When advertising an external IPv6 address, ensure that the firewall and
network settings of the system running your TURN server are configured to
accept IPv6 traffic, and that the TURN server is listening on the local
IPv6 address that is mapped by NAT to the external IPv6 address.</p>
</li>
<li>
<p>Logging</p>
<p>If <code>eturnal</code> was started by systemd, log files are written into the
<code>/var/log/eturnal</code> directory by default. In order to log to the <a href="https://www.freedesktop.org/software/systemd/man/systemd-journald.service.html">journal</a>
instead, the <code>log_dir</code> option can be set to <code>stdout</code> in the configuration file.</p>
</li>
<li>
<p>Security considerations</p>
<p>Consider your security settings. TURN lets users request a relay which will
connect to arbitrary IP addresses and ports. The following configuration is
suggested as a minimum starting point, <a href="https://eturnal.net/documentation/#blacklist">see also the official documentation</a>:</p>
<pre><code class="language-yaml">## Reject TURN relaying from/to the following addresses/networks:
blacklist:                 # This is the default blacklist.
    - &quot;127.0.0.0/8&quot;        # IPv4 loopback.
    - &quot;::1&quot;                # IPv6 loopback.
    - recommended          # Expands to a number of networks recommended to be
                           # blocked, but includes private networks. Those
                           # would have to be 'whitelist'ed if eturnal serves
                           # local clients/peers within such networks.
</code></pre>
<p>To whitelist IP addresses or specific (private) networks, you need to <strong>add</strong> a 
whitelist part into the configuration file, e.g.:</p>
<pre><code class="language-yaml">whitelist:
    - &quot;192.168.0.0/16&quot;
    - &quot;203.0.113.113&quot;
    - &quot;2001:db8::/64&quot;
</code></pre>
<p>The more specific, the better.</p>
</li>
<li>
<p>TURNS (TURN via TLS/DTLS)</p>
<p>Also consider supporting TLS/DTLS. To do this, adjust the following settings
in the <code>eturnal.yml</code> configuration file (TLS parts should not be commented anymore):</p>
<pre><code class="language-yaml">listen:
    - ip: &quot;::&quot;
      port: 3478
      transport: udp
    - ip: &quot;::&quot;
      port: 3478
      transport: tcp
    - ip: &quot;::&quot;
      port: 5349
      transport: tls

## TLS certificate/key files (must be readable by 'eturnal' user!):
tls_crt_file: /etc/eturnal/tls/crt.pem
tls_key_file: /etc/eturnal/tls/key.pem
</code></pre>
<p>In this case, replace the <code>turn:</code> schemes in homeserver's <code>turn_uris</code> settings
with <code>turns:</code>. More is described <a href="setup/turn/../../usage/configuration/config_documentation.html#turn_uris">here</a>.</p>
<p>We recommend that you only try to set up TLS/DTLS once you have set up a
basic installation and got it working.</p>
<p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
not work with any Matrix client that uses Chromium's WebRTC library. This
currently includes Element Android &amp; iOS; for more details, see their
<a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
<a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
<a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
</li>
<li>
<p>Firewall</p>
<p>Ensure your firewall allows traffic into the TURN server on the ports
you've configured it to listen on (By default: 3478 and 5349 for TURN
traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
for the UDP relay.)</p>
</li>
<li>
<p>Reload/ restarting <code>eturnal</code></p>
<p>Changes in the configuration file require <code>eturnal</code> to reload/ restart, this
can be achieved by:</p>
<pre><code class="language-sh">eturnalctl reload
</code></pre>
<p><code>eturnal</code> performs a configuration check before actually reloading/ restarting
and provides hints, if something is not correctly configured.</p>
</li>
</ol>
<h3 id="eturnalctl-opterations-script"><a class="header" href="#eturnalctl-opterations-script">eturnalctl opterations script</a></h3>
<p><code>eturnal</code> offers a handy <a href="https://eturnal.net/documentation/#Operation">operations script</a> 
which can be called e.g. to check, whether the service is up, to restart the service, 
to query how many active sessions exist, to change logging behaviour and so on.</p>
<p>Hint: If <code>eturnalctl</code> is not part of your <code>$PATH</code>, consider either sym-linking it (e.g. ´ln -s /opt/eturnal/bin/eturnalctl /usr/local/bin/eturnalctl´) or call it from the default <code>eturnal</code> directory directly: e.g. <code>/opt/eturnal/bin/eturnalctl info</code></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="delegation-of-incoming-federation-traffic"><a class="header" href="#delegation-of-incoming-federation-traffic">Delegation of incoming federation traffic</a></h1>
<p>In the following documentation, we use the term <code>server_name</code> to refer to that setting
in your homeserver configuration file. It appears at the ends of user ids, and tells
other homeservers where they can find your server.</p>
<p>By default, other homeservers will expect to be able to reach yours via
your <code>server_name</code>, on port 8448. For example, if you set your <code>server_name</code>
to <code>example.com</code> (so that your user names look like <code>@user:example.com</code>),
other servers will try to connect to yours at <code>https://example.com:8448/</code>.</p>
<p>Delegation is a Matrix feature allowing a homeserver admin to retain a
<code>server_name</code> of <code>example.com</code> so that user IDs, room aliases, etc continue
to look like <code>*:example.com</code>, whilst having federation traffic routed
to a different server and/or port (e.g. <code>synapse.example.com:443</code>).</p>
<h2 id="well-known-delegation"><a class="header" href="#well-known-delegation">.well-known delegation</a></h2>
<p>To use this method, you need to be able to configure the server at
<code>https://&lt;server_name&gt;</code> to serve a file at
<code>https://&lt;server_name&gt;/.well-known/matrix/server</code>.  There are two ways to do this, shown below.</p>
<p>Note that the <code>.well-known</code> file is hosted on the default port for <code>https</code> (port 443).</p>
<h3 id="external-server"><a class="header" href="#external-server">External server</a></h3>
<p>For maximum flexibility, you need to configure an external server such as nginx, Apache
or HAProxy to serve the <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> file. Setting
up such a server is out of the scope of this documentation, but note that it is often
possible to configure your <a href="reverse_proxy.html">reverse proxy</a> for this.</p>
<p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> should be configured
return a JSON structure containing the key <code>m.server</code> like this:</p>
<pre><code class="language-json">{
    &quot;m.server&quot;: &quot;&lt;synapse.server.name&gt;[:&lt;yourport&gt;]&quot;
}
</code></pre>
<p>In our example (where we want federation traffic to be routed to
<code>https://synapse.example.com</code>, on port 443), this would mean that
<code>https://example.com/.well-known/matrix/server</code> should return:</p>
<pre><code class="language-json">{
    &quot;m.server&quot;: &quot;synapse.example.com:443&quot;
}
</code></pre>
<p>Note, specifying a port is optional. If no port is specified, then it defaults
to 8448.</p>
<h3 id="serving-a-well-knownmatrixserver-file-with-synapse"><a class="header" href="#serving-a-well-knownmatrixserver-file-with-synapse">Serving a <code>.well-known/matrix/server</code> file with Synapse</a></h3>
<p>If you are able to set up your domain so that <code>https://&lt;server_name&gt;</code> is routed to
Synapse (i.e., the only change needed is to direct federation traffic to port 443
instead of port 8448), then it is possible to configure Synapse to serve a suitable
<code>.well-known/matrix/server</code> file. To do so, add the following to your <code>homeserver.yaml</code>
file:</p>
<pre><code class="language-yaml">serve_server_wellknown: true
</code></pre>
<p><strong>Note</strong>: this <em>only</em> works if <code>https://&lt;server_name&gt;</code> is routed to Synapse, so is
generally not suitable if Synapse is hosted at a subdomain such as
<code>https://synapse.example.com</code>.</p>
<h2 id="srv-dns-record-delegation"><a class="header" href="#srv-dns-record-delegation">SRV DNS record delegation</a></h2>
<p>It is also possible to do delegation using a SRV DNS record. However, that is generally
not recommended, as it can be difficult to configure the TLS certificates correctly in
this case, and it offers little advantage over <code>.well-known</code> delegation.</p>
<p>Please keep in mind that server delegation is a function of server-server communication,
and as such using SRV DNS records will not cover use cases involving client-server comms.
This means setting global client settings (such as a Jitsi endpoint, or disabling
creating new rooms as encrypted by default, etc) will still require that you serve a file
from the <code>https://&lt;server_name&gt;/.well-known/</code> endpoints defined in the spec! If you are
considering using SRV DNS delegation to avoid serving files from this endpoint, consider
the impact that you will not be able to change those client-based default values globally,
and will be relegated to the featureset of the configuration of each individual client.</p>
<p>However, if you really need it, you can find some documentation on what such a
record should look like and how Synapse will use it in <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
specification</a>.</p>
<h2 id="delegation-faq"><a class="header" href="#delegation-faq">Delegation FAQ</a></h2>
<h3 id="when-do-i-need-delegation"><a class="header" href="#when-do-i-need-delegation">When do I need delegation?</a></h3>
<p>If your homeserver's APIs are accessible on the default federation port (8448)
and the domain your <code>server_name</code> points to, you do not need any delegation.</p>
<p>For instance, if you registered <code>example.com</code> and pointed its DNS A record at a
fresh server, you could install Synapse on that host, giving it a <code>server_name</code>
of <code>example.com</code>, and once a reverse proxy has been set up to proxy all requests
sent to the port <code>8448</code> and serve TLS certificates for <code>example.com</code>, you
wouldn't need any delegation set up.</p>
<p><strong>However</strong>, if your homeserver's APIs aren't accessible on port 8448 and on the
domain <code>server_name</code> points to, you will need to let other servers know how to
find it using delegation.</p>
<h3 id="should-i-use-a-reverse-proxy-for-federation-traffic"><a class="header" href="#should-i-use-a-reverse-proxy-for-federation-traffic">Should I use a reverse proxy for federation traffic?</a></h3>
<p>Generally, using a reverse proxy for both the federation and client traffic is a good
idea, since it saves handling TLS traffic in Synapse. See
<a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a
reverse proxy.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="upgrading-synapse"><a class="header" href="#upgrading-synapse">Upgrading Synapse</a></h1>
<p>Before upgrading check if any special steps are required to upgrade from
the version you currently have installed to the current version of
Synapse. The extra instructions that may be required are listed later in
this document.</p>
<ul>
<li>
<p>Check that your versions of Python and PostgreSQL are still
supported.</p>
<p>Synapse follows upstream lifecycles for <a href="https://endoflife.date/python">Python</a> and
<a href="https://endoflife.date/postgresql">PostgreSQL</a>, and removes support for versions
which are no longer maintained.</p>
<p>The website <a href="https://endoflife.date">https://endoflife.date</a> also offers convenient
summaries.</p>
</li>
<li>
<p>If Synapse was installed using <a href="setup/installation.html#prebuilt-packages">prebuilt packages</a>,
you will need to follow the normal process for upgrading those packages.</p>
</li>
<li>
<p>If Synapse was installed using pip then upgrade to the latest
version by running:</p>
<pre><code class="language-bash">pip install --upgrade matrix-synapse
</code></pre>
</li>
<li>
<p>If Synapse was installed from source, then:</p>
<ol>
<li>
<p>Obtain the latest version of the source code. Git users can run
<code>git pull</code> to do this.</p>
</li>
<li>
<p>If you're running Synapse in a virtualenv, make sure to activate it before
upgrading. For example, if Synapse is installed in a virtualenv in <code>~/synapse/env</code> then
run:</p>
<pre><code class="language-bash">source ~/synapse/env/bin/activate
pip install --upgrade .
</code></pre>
<p>Include any relevant extras between square brackets, e.g. <code>pip install --upgrade &quot;.[postgres,oidc]&quot;</code>.</p>
</li>
<li>
<p>If you're using <code>poetry</code> to manage a Synapse installation, run:</p>
<pre><code class="language-bash">poetry install
</code></pre>
<p>Include any relevant extras with <code>--extras</code>, e.g. <code>poetry install --extras postgres --extras oidc</code>.
It's probably easiest to run <code>poetry install --extras all</code>.</p>
</li>
<li>
<p>Restart Synapse:</p>
<pre><code class="language-bash">synctl restart
</code></pre>
</li>
</ol>
</li>
</ul>
<p>To check whether your update was successful, you can check the running
server version with:</p>
<pre><code class="language-bash"># you may need to replace 'localhost:8008' if synapse is not configured
# to listen on port 8008.

curl http://localhost:8008/_synapse/admin/v1/server_version
</code></pre>
<h2 id="rolling-back-to-older-versions"><a class="header" href="#rolling-back-to-older-versions">Rolling back to older versions</a></h2>
<p>Rolling back to previous releases can be difficult, due to database
schema changes between releases. Where we have been able to test the
rollback process, this will be noted below.</p>
<p>In general, you will need to undo any changes made during the upgrade
process, for example:</p>
<ul>
<li>
<p>pip:</p>
<pre><code class="language-bash">source env/bin/activate
# replace `1.3.0` accordingly:
pip install matrix-synapse==1.3.0
</code></pre>
</li>
<li>
<p>Debian:</p>
<pre><code class="language-bash"># replace `1.3.0` and `stretch` accordingly:
wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
</code></pre>
</li>
</ul>
<h1 id="upgrading-to-v1900"><a class="header" href="#upgrading-to-v1900">Upgrading to v1.90.0</a></h1>
<h2 id="app-service-query-parameter-authorization-is-now-a-configuration-option"><a class="header" href="#app-service-query-parameter-authorization-is-now-a-configuration-option">App service query parameter authorization is now a configuration option</a></h2>
<p>Synapse v1.81.0 deprecated application service authorization via query parameters as this is
considered insecure - and from Synapse v1.71.0 forwards the application service token has also been sent via 
<a href="https://spec.matrix.org/v1.6/application-service-api/#authorization">the <code>Authorization</code> header</a>], making the insecure
query parameter authorization redundant. Since removing the ability to continue to use query parameters could break 
backwards compatibility it has now been put behind a configuration option, <code>use_appservice_legacy_authorization</code>.<br />
This option defaults to false, but can be activated by adding </p>
<pre><code class="language-yaml">use_appservice_legacy_authorization: true 
</code></pre>
<p>to your configuration.</p>
<h1 id="upgrading-to-v1890"><a class="header" href="#upgrading-to-v1890">Upgrading to v1.89.0</a></h1>
<h2 id="removal-of-unspecced-user-property-for-register"><a class="header" href="#removal-of-unspecced-user-property-for-register">Removal of unspecced <code>user</code> property for <code>/register</code></a></h2>
<p>Application services can no longer call <code>/register</code> with a <code>user</code> property to create new users.
The standard <code>username</code> property should be used instead. See the
<a href="https://spec.matrix.org/v1.7/application-service-api/#server-admin-style-permissions">Application Service specification</a>
for more information.</p>
<h1 id="upgrading-to-v1880"><a class="header" href="#upgrading-to-v1880">Upgrading to v1.88.0</a></h1>
<h2 id="minimum-supported-python-version"><a class="header" href="#minimum-supported-python-version">Minimum supported Python version</a></h2>
<p>The minimum supported Python version has been increased from v3.7 to v3.8.
You will need Python 3.8 to run Synapse v1.88.0 (due out July 18th, 2023).</p>
<p>If you use current versions of the Matrix.org-distributed Debian
packages or Docker images, no action is required.</p>
<h2 id="removal-of-worker_replication_-settings"><a class="header" href="#removal-of-worker_replication_-settings">Removal of <code>worker_replication_*</code> settings</a></h2>
<p>As mentioned previously in <a href="upgrade.html#upgrading-to-v1840">Upgrading to v1.84.0</a>, the following deprecated settings
are being removed in this release of Synapse:</p>
<ul>
<li><a href="https://matrix-org.github.io/synapse/v1.86/usage/configuration/config_documentation.html#worker_replication_host"><code>worker_replication_host</code></a></li>
<li><a href="https://matrix-org.github.io/synapse/v1.86/usage/configuration/config_documentation.html#worker_replication_http_port"><code>worker_replication_http_port</code></a></li>
<li><a href="https://matrix-org.github.io/synapse/v1.86/usage/configuration/config_documentation.html#worker_replication_http_tls"><code>worker_replication_http_tls</code></a></li>
</ul>
<p>Please ensure that you have migrated to using <code>main</code> on your shared configuration's <code>instance_map</code>
(or create one if necessary). This is required if you have <em><strong>any</strong></em> workers at all;
administrators of single-process (monolith) installations don't need to do anything.</p>
<p>For an illustrative example, please see <a href="upgrade.html#upgrading-to-v1840">Upgrading to v1.84.0</a> below.</p>
<h1 id="upgrading-to-v1860"><a class="header" href="#upgrading-to-v1860">Upgrading to v1.86.0</a></h1>
<h2 id="minimum-supported-rust-version"><a class="header" href="#minimum-supported-rust-version">Minimum supported Rust version</a></h2>
<p>The minimum supported Rust version has been increased from v1.58.1 to v1.60.0.
Users building from source will need to ensure their <code>rustc</code> version is up to
date.</p>
<h1 id="upgrading-to-v1850"><a class="header" href="#upgrading-to-v1850">Upgrading to v1.85.0</a></h1>
<h2 id="application-service-registration-with-user-property-deprecation"><a class="header" href="#application-service-registration-with-user-property-deprecation">Application service registration with &quot;user&quot; property deprecation</a></h2>
<p>Application services should ensure they call the <code>/register</code> endpoint with a
<code>username</code> property. The legacy <code>user</code> property is considered deprecated and
should no longer be included.</p>
<p>A future version of Synapse (v1.88.0 or later) will remove support for legacy
application service login.</p>
<h1 id="upgrading-to-v1840"><a class="header" href="#upgrading-to-v1840">Upgrading to v1.84.0</a></h1>
<h2 id="deprecation-of-worker_replication_-configuration-settings"><a class="header" href="#deprecation-of-worker_replication_-configuration-settings">Deprecation of <code>worker_replication_*</code> configuration settings</a></h2>
<p>When using workers,</p>
<ul>
<li><code>worker_replication_host</code></li>
<li><code>worker_replication_http_port</code></li>
<li><code>worker_replication_http_tls</code></li>
</ul>
<p>should now be removed from individual worker YAML configurations and the main process should instead be added to the <code>instance_map</code>
in the shared YAML configuration, using the name <code>main</code>.</p>
<p>The old <code>worker_replication_*</code> settings are now considered deprecated and are expected to be removed in Synapse v1.88.0.</p>
<h3 id="example-change"><a class="header" href="#example-change">Example change</a></h3>
<h4 id="before"><a class="header" href="#before">Before:</a></h4>
<p>Shared YAML</p>
<pre><code class="language-yaml">instance_map:
  generic_worker1:
    host: localhost
    port: 5678
    tls: false
</code></pre>
<p>Worker YAML</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
worker_name: generic_worker1

worker_replication_host: localhost
worker_replication_http_port: 3456
worker_replication_http_tls: false

worker_listeners:
  - type: http
    port: 1234
    resources:
      - names: [client, federation]
  - type: http
    port: 5678
    resources:
      - names: [replication]

worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
</code></pre>
<h4 id="after"><a class="header" href="#after">After:</a></h4>
<p>Shared YAML</p>
<pre><code class="language-yaml">instance_map:
  main:
    host: localhost
    port: 3456
    tls: false
  generic_worker1:
    host: localhost
    port: 5678
    tls: false
</code></pre>
<p>Worker YAML</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
worker_name: generic_worker1

worker_listeners:
  - type: http
    port: 1234
    resources:
      - names: [client, federation]
  - type: http
    port: 5678
    resources:
      - names: [replication]

worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml

</code></pre>
<p>Notes: </p>
<ul>
<li><code>tls</code> is optional but mirrors the functionality of <code>worker_replication_http_tls</code></li>
</ul>
<h1 id="upgrading-to-v1810"><a class="header" href="#upgrading-to-v1810">Upgrading to v1.81.0</a></h1>
<h2 id="application-service-path--authentication-deprecations"><a class="header" href="#application-service-path--authentication-deprecations">Application service path &amp; authentication deprecations</a></h2>
<p>Synapse now attempts the versioned appservice paths before falling back to the
<a href="https://spec.matrix.org/v1.6/application-service-api/#legacy-routes">legacy paths</a>.
Usage of the legacy routes should be considered deprecated.</p>
<p>Additionally, Synapse has supported sending the application service access token
via <a href="https://spec.matrix.org/v1.6/application-service-api/#authorization">the <code>Authorization</code> header</a>
since v1.70.0. For backwards compatibility it is <em>also</em> sent as the <code>access_token</code>
query parameter. This is insecure and should be considered deprecated.</p>
<p>A future version of Synapse (v1.88.0 or later) will remove support for legacy
application service routes and query parameter authorization.</p>
<h1 id="upgrading-to-v1800"><a class="header" href="#upgrading-to-v1800">Upgrading to v1.80.0</a></h1>
<h2 id="reporting-events-error-code-change"><a class="header" href="#reporting-events-error-code-change">Reporting events error code change</a></h2>
<p>Before this update, the
<a href="https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3roomsroomidreporteventid"><code>POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}</code></a>
endpoint would return a <code>403</code> if a user attempted to report an event that they did not have access to.
This endpoint will now return a <code>404</code> in this case instead.</p>
<p>Clients that implement event reporting should check that their error handling code will handle this
change.</p>
<h1 id="upgrading-to-v1790"><a class="header" href="#upgrading-to-v1790">Upgrading to v1.79.0</a></h1>
<h2 id="the-on_threepid_bind-module-callback-method-has-been-deprecated"><a class="header" href="#the-on_threepid_bind-module-callback-method-has-been-deprecated">The <code>on_threepid_bind</code> module callback method has been deprecated</a></h2>
<p>Synapse v1.79.0 deprecates the
<a href="modules/third_party_rules_callbacks.html#on_threepid_bind"><code>on_threepid_bind</code></a>
&quot;third-party rules&quot; Synapse module callback method in favour of a new module method,
<a href="modules/third_party_rules_callbacks.html#on_add_user_third_party_identifier"><code>on_add_user_third_party_identifier</code></a>.
<code>on_threepid_bind</code> will be removed in a future version of Synapse. You should check whether any Synapse
modules in use in your deployment are making use of <code>on_threepid_bind</code>, and update them where possible.</p>
<p>The arguments and functionality of the new method are the same.</p>
<p>The justification behind the name change is that the old method's name, <code>on_threepid_bind</code>, was
misleading. A user is considered to &quot;bind&quot; their third-party ID to their Matrix ID only if they
do so via an <a href="https://spec.matrix.org/latest/identity-service-api/">identity server</a>
(so that users on other homeservers may find them). But this method was not called in that case -
it was only called when a user added a third-party identifier on the local homeserver.</p>
<p>Module developers may also be interested in the related
<a href="modules/third_party_rules_callbacks.html#on_remove_user_third_party_identifier"><code>on_remove_user_third_party_identifier</code></a>
module callback method that was also added in Synapse v1.79.0. This new method is called when a
user removes a third-party identifier from their account.</p>
<h1 id="upgrading-to-v1780"><a class="header" href="#upgrading-to-v1780">Upgrading to v1.78.0</a></h1>
<h2 id="deprecate-the-_synapseadminv1mediaserver_namedelete-admin-api"><a class="header" href="#deprecate-the-_synapseadminv1mediaserver_namedelete-admin-api">Deprecate the <code>/_synapse/admin/v1/media/&lt;server_name&gt;/delete</code> admin API</a></h2>
<p>Synapse 1.78.0 replaces the <code>/_synapse/admin/v1/media/&lt;server_name&gt;/delete</code>
admin API with an identical endpoint at <code>/_synapse/admin/v1/media/delete</code>. Please
update your tooling to use the new endpoint. The deprecated version will be removed
in a future release.</p>
<h1 id="upgrading-to-v1760"><a class="header" href="#upgrading-to-v1760">Upgrading to v1.76.0</a></h1>
<h2 id="faster-joins-are-enabled-by-default"><a class="header" href="#faster-joins-are-enabled-by-default">Faster joins are enabled by default</a></h2>
<p>When joining a room for the first time, Synapse 1.76.0 will request a partial join from the other server by default. Previously, server admins had to opt-in to this using an experimental config flag.</p>
<p>Server admins can opt out of this feature for the time being by setting</p>
<pre><code class="language-yaml">experimental:
    faster_joins: false
</code></pre>
<p>in their server config.</p>
<h2 id="changes-to-the-account-data-replication-streams"><a class="header" href="#changes-to-the-account-data-replication-streams">Changes to the account data replication streams</a></h2>
<p>Synapse has changed the format of the account data and devices replication
streams (between workers). This is a forwards- and backwards-incompatible
change: v1.75 workers cannot process account data replicated by v1.76 workers,
and vice versa.</p>
<p>Once all workers are upgraded to v1.76 (or downgraded to v1.75), account data
and device replication will resume as normal.</p>
<h2 id="minimum-version-of-poetry-is-now-132"><a class="header" href="#minimum-version-of-poetry-is-now-132">Minimum version of Poetry is now 1.3.2</a></h2>
<p>The minimum supported version of Poetry is now 1.3.2 (previously 1.2.0, <a href="upgrade.html#upgrading-to-v1670">since 
Synapse 1.67</a>). If you have used <code>poetry install</code> to 
install Synapse from a source checkout, you should upgrade poetry: see its
<a href="https://python-poetry.org/docs/#installation">installation instructions</a>.
For all other installation methods, no acction is required.</p>
<h1 id="upgrading-to-v1740"><a class="header" href="#upgrading-to-v1740">Upgrading to v1.74.0</a></h1>
<h2 id="unicode-support-in-user-search"><a class="header" href="#unicode-support-in-user-search">Unicode support in user search</a></h2>
<p>This version introduces optional support for an <a href="https://github.com/matrix-org/synapse/pull/14464">improved user search dealing with Unicode characters</a>.</p>
<p>If you want to take advantage of this feature you need to install PyICU,
the ICU native dependency and its development headers
so that PyICU can build since no prebuilt wheels are available.</p>
<p>You can follow <a href="https://pypi.org/project/PyICU/">the PyICU documentation</a> to do so,
and then do <code>pip install matrix-synapse[user-search]</code> for a PyPI install.</p>
<p>Docker images and Debian packages need nothing specific as they already
include or specify ICU as an explicit dependency.</p>
<h2 id="user-directory-rebuild"><a class="header" href="#user-directory-rebuild">User directory rebuild</a></h2>
<p>Synapse 1.74 queues a background update
<a href="https://github.com/matrix-org/synapse/pull/14643">to rebuild the user directory</a>,
in order to fix missing or erroneous entries.</p>
<p>When this update begins, the user directory will be cleared out and rebuilt from
scratch. User directory lookups will be incomplete until the rebuild completes.
Admins can monitor the rebuild's progress by using the
<a href="usage/administration/admin_api/background_updates.html#status">Background update Admin API</a>.</p>
<h1 id="upgrading-to-v1730"><a class="header" href="#upgrading-to-v1730">Upgrading to v1.73.0</a></h1>
<h2 id="legacy-prometheus-metric-names-have-now-been-removed"><a class="header" href="#legacy-prometheus-metric-names-have-now-been-removed">Legacy Prometheus metric names have now been removed</a></h2>
<p>Synapse v1.69.0 included the deprecation of legacy Prometheus metric names
and offered an option to disable them.
Synapse v1.71.0 disabled legacy Prometheus metric names by default.</p>
<p>This version, v1.73.0, removes those legacy Prometheus metric names entirely.
This also means that the <code>enable_legacy_metrics</code> configuration option has been
removed; it will no longer be possible to re-enable the legacy metric names.</p>
<p>If you use metrics and have not yet updated your Grafana dashboard(s),
Prometheus console(s) or alerting rule(s), please consider doing so when upgrading
to this version.
Note that the included Grafana dashboard was updated in v1.72.0 to correct some
metric names which were missed when legacy metrics were disabled by default.</p>
<p>See <a href="upgrade.html#deprecation-of-legacy-prometheus-metric-names">v1.69.0: Deprecation of legacy Prometheus metric names</a>
for more context.</p>
<h1 id="upgrading-to-v1720"><a class="header" href="#upgrading-to-v1720">Upgrading to v1.72.0</a></h1>
<h2 id="dropping-support-for-postgresql-10"><a class="header" href="#dropping-support-for-postgresql-10">Dropping support for PostgreSQL 10</a></h2>
<p>In line with our <a href="deprecation_policy.html">deprecation policy</a>, we've dropped
support for PostgreSQL 10, as it is no longer supported upstream.</p>
<p>This release of Synapse requires PostgreSQL 11+.</p>
<h1 id="upgrading-to-v1710"><a class="header" href="#upgrading-to-v1710">Upgrading to v1.71.0</a></h1>
<h2 id="removal-of-the-generate_short_term_login_token-module-api-method"><a class="header" href="#removal-of-the-generate_short_term_login_token-module-api-method">Removal of the <code>generate_short_term_login_token</code> module API method</a></h2>
<p>As announced with the release of <a href="upgrade.html#deprecation-of-the-generate_short_term_login_token-module-api-method">Synapse 1.69.0</a>, the deprecated <code>generate_short_term_login_token</code> module method has been removed.</p>
<p>Modules relying on it can instead use the <code>create_login_token</code> method.</p>
<h2 id="changes-to-the-events-received-by-application-services-interest"><a class="header" href="#changes-to-the-events-received-by-application-services-interest">Changes to the events received by application services (interest)</a></h2>
<p>To align with spec (changed in
<a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3905">MSC3905</a>), Synapse now
only considers local users to be interesting. In other words, the <code>users</code> namespace
regex is only be applied against local users of the homeserver.</p>
<p>Please note, this probably doesn't affect the expected behavior of your application
service, since an interesting local user in a room still means all messages in the room
(from local or remote users) will still be considered interesting. And matching a room
with the <code>rooms</code> or <code>aliases</code> namespace regex will still consider all events sent in the
room to be interesting to the application service.</p>
<p>If one of your application service's <code>users</code> regex was intending to match a remote user,
this will no longer match as you expect. The behavioral mismatch between matching all
local users and some remote users is why the spec was changed/clarified and this
caveat is no longer supported.</p>
<h2 id="legacy-prometheus-metric-names-are-now-disabled-by-default"><a class="header" href="#legacy-prometheus-metric-names-are-now-disabled-by-default">Legacy Prometheus metric names are now disabled by default</a></h2>
<p>Synapse v1.71.0 disables legacy Prometheus metric names by default.
For administrators that still rely on them and have not yet had chance to update their
uses of the metrics, it's still possible to specify <code>enable_legacy_metrics: true</code> in
the configuration to re-enable them temporarily.</p>
<p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and at that point,
it will no longer be possible to re-enable them.</p>
<p>If you do not use metrics or you have already updated your Grafana dashboard(s),
Prometheus console(s) and alerting rule(s), there is no action needed.</p>
<p>See <a href="upgrade.html#deprecation-of-legacy-prometheus-metric-names">v1.69.0: Deprecation of legacy Prometheus metric names</a>.</p>
<h1 id="upgrading-to-v1690"><a class="header" href="#upgrading-to-v1690">Upgrading to v1.69.0</a></h1>
<h2 id="changes-to-the-receipts-replication-streams"><a class="header" href="#changes-to-the-receipts-replication-streams">Changes to the receipts replication streams</a></h2>
<p>Synapse now includes information indicating if a receipt applies to a thread when
replicating it to other workers. This is a forwards- and backwards-incompatible
change: v1.68 and workers cannot process receipts replicated by v1.69 workers, and
vice versa.</p>
<p>Once all workers are upgraded to v1.69 (or downgraded to v1.68), receipts
replication will resume as normal.</p>
<h2 id="deprecation-of-legacy-prometheus-metric-names"><a class="header" href="#deprecation-of-legacy-prometheus-metric-names">Deprecation of legacy Prometheus metric names</a></h2>
<p>In current versions of Synapse, some Prometheus metrics are emitted under two different names,
with one of the names being older but non-compliant with OpenMetrics and Prometheus conventions
and one of the names being newer but compliant.</p>
<p>Synapse v1.71.0 will turn the old metric names off <em>by default</em>.
For administrators that still rely on them and have not had chance to update their
uses of the metrics, it's possible to specify <code>enable_legacy_metrics: true</code> in
the configuration to re-enable them temporarily.</p>
<p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and it will no longer
be possible to re-enable them.</p>
<p>The Grafana dashboard, Prometheus recording rules and Prometheus Consoles included
in the <code>contrib</code> directory in the Synapse repository have been updated to no longer
rely on the legacy names. These can be used on a current version of Synapse
because current versions of Synapse emit both old and new names.</p>
<p>You may need to update your alerting rules or any other rules that depend on
the names of Prometheus metrics.
If you want to test your changes before legacy names are disabled by default,
you may specify <code>enable_legacy_metrics: false</code> in your homeserver configuration.</p>
<p>A list of affected metrics is available on the <a href="https://matrix-org.github.io/synapse/v1.69/metrics-howto.html?highlight=metrics%20deprecated#renaming-of-metrics--deprecation-of-old-names-in-12">Metrics How-to page</a>.</p>
<h2 id="deprecation-of-the-generate_short_term_login_token-module-api-method"><a class="header" href="#deprecation-of-the-generate_short_term_login_token-module-api-method">Deprecation of the <code>generate_short_term_login_token</code> module API method</a></h2>
<p>The following method of the module API has been deprecated, and is scheduled to
be remove in v1.71.0:</p>
<pre><code class="language-python">def generate_short_term_login_token(
    self,
    user_id: str,
    duration_in_ms: int = (2 * 60 * 1000),
    auth_provider_id: str = &quot;&quot;,
    auth_provider_session_id: Optional[str] = None,
) -&gt; str:
    ...
</code></pre>
<p>It has been replaced by an asynchronous equivalent:</p>
<pre><code class="language-python">async def create_login_token(
    self,
    user_id: str,
    duration_in_ms: int = (2 * 60 * 1000),
    auth_provider_id: Optional[str] = None,
    auth_provider_session_id: Optional[str] = None,
) -&gt; str:
    ...
</code></pre>
<p>Synapse will log a warning when a module uses the deprecated method, to help
administrators find modules using it.</p>
<h1 id="upgrading-to-v1680"><a class="header" href="#upgrading-to-v1680">Upgrading to v1.68.0</a></h1>
<p>Two changes announced in the upgrade notes for v1.67.0 have now landed in v1.68.0.</p>
<h2 id="sqlite-version-requirement"><a class="header" href="#sqlite-version-requirement">SQLite version requirement</a></h2>
<p>Synapse now requires a SQLite version of 3.27.0 or higher if SQLite is configured as
Synapse's database.</p>
<p>Installations using</p>
<ul>
<li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
<li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
<li>a PostgreSQL database</li>
</ul>
<p>are not affected.</p>
<h2 id="rust-requirement-when-building-from-source"><a class="header" href="#rust-requirement-when-building-from-source">Rust requirement when building from source.</a></h2>
<p>Building from a source checkout of Synapse now requires a recent Rust compiler
(currently Rust 1.58.1, but see also the
<a href="https://matrix-org.github.io/synapse/latest/deprecation_policy.html">Platform Dependency Policy</a>).</p>
<p>Installations using</p>
<ul>
<li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
<li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
<li>PyPI wheels via <code>pip install matrix-synapse</code> (on supported platforms and architectures)</li>
</ul>
<p>will not be affected.</p>
<h1 id="upgrading-to-v1670"><a class="header" href="#upgrading-to-v1670">Upgrading to v1.67.0</a></h1>
<h2 id="direct-tcp-replication-is-no-longer-supported-migrate-to-redis"><a class="header" href="#direct-tcp-replication-is-no-longer-supported-migrate-to-redis">Direct TCP replication is no longer supported: migrate to Redis</a></h2>
<p>Redis support was added in v1.13.0 with it becoming the recommended method in
v1.18.0. It replaced the old direct TCP connections (which was deprecated as of
v1.18.0) to the main process. With Redis, rather than all the workers connecting
to the main process, all the workers and the main process connect to Redis,
which relays replication commands between processes. This can give a significant
CPU saving on the main process and is a prerequisite for upcoming
performance improvements.</p>
<p>To migrate to Redis add the <a href="./workers.html#shared-configuration"><code>redis</code> config</a>,
and remove the TCP <code>replication</code> listener from config of the master and
<code>worker_replication_port</code> from worker config. Note that a HTTP listener with a
<code>replication</code> resource is still required.</p>
<h2 id="minimum-version-of-poetry-is-now-v120"><a class="header" href="#minimum-version-of-poetry-is-now-v120">Minimum version of Poetry is now v1.2.0</a></h2>
<p>The minimum supported version of poetry is now 1.2. This should only affect
those installing from a source checkout.</p>
<h2 id="rust-requirement-in-the-next-release"><a class="header" href="#rust-requirement-in-the-next-release">Rust requirement in the next release</a></h2>
<p>From the next major release (v1.68.0) installing Synapse from a source checkout
will require a recent Rust compiler. Those using packages or
<code>pip install matrix-synapse</code> will not be affected.</p>
<p>The simplest way of installing Rust is via <a href="https://rustup.rs/">rustup.rs</a></p>
<h2 id="sqlite-version-requirement-in-the-next-release"><a class="header" href="#sqlite-version-requirement-in-the-next-release">SQLite version requirement in the next release</a></h2>
<p>From the next major release (v1.68.0) Synapse will require SQLite 3.27.0 or
higher. Synapse v1.67.0 will be the last major release supporting SQLite
versions 3.22 to 3.26.</p>
<p>Those using Docker images or Debian packages from Matrix.org will not be
affected. If you have installed from source, you should check the version of
SQLite used by Python with:</p>
<pre><code class="language-shell">python -c &quot;import sqlite3; print(sqlite3.sqlite_version)&quot;
</code></pre>
<p>If this is too old, refer to your distribution for advice on upgrading.</p>
<h1 id="upgrading-to-v1660"><a class="header" href="#upgrading-to-v1660">Upgrading to v1.66.0</a></h1>
<h2 id="delegation-of-email-validation-no-longer-supported"><a class="header" href="#delegation-of-email-validation-no-longer-supported">Delegation of email validation no longer supported</a></h2>
<p>As of this version, Synapse no longer allows the tasks of verifying email address
ownership, and password reset confirmation, to be delegated to an identity server.
This removal was previously planned for Synapse 1.64.0, but was
<a href="https://github.com/matrix-org/synapse/issues/13421">delayed</a> until now to give
homeserver administrators more notice of the change.</p>
<p>To continue to allow users to add email addresses to their homeserver accounts,
and perform password resets, make sure that Synapse is configured with a working
email server in the <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email"><code>email</code> configuration
section</a>
(including, at a minimum, a <code>notif_from</code> setting.)</p>
<p>Specifying an <code>email</code> setting under <code>account_threepid_delegates</code> will now cause
an error at startup.</p>
<h1 id="upgrading-to-v1640"><a class="header" href="#upgrading-to-v1640">Upgrading to v1.64.0</a></h1>
<h2 id="deprecation-of-the-ability-to-delegate-e-mail-verification-to-identity-servers"><a class="header" href="#deprecation-of-the-ability-to-delegate-e-mail-verification-to-identity-servers">Deprecation of the ability to delegate e-mail verification to identity servers</a></h2>
<p>Synapse v1.66.0 will remove the ability to delegate the tasks of verifying email address ownership, and password reset confirmation, to an identity server.</p>
<p>If you require your homeserver to verify e-mail addresses or to support password resets via e-mail, please configure your homeserver with SMTP access so that it can send e-mails on its own behalf.
<a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email">Consult the configuration documentation for more information.</a></p>
<p>The option that will be removed is <code>account_threepid_delegates.email</code>.</p>
<h2 id="changes-to-the-event-replication-streams"><a class="header" href="#changes-to-the-event-replication-streams">Changes to the event replication streams</a></h2>
<p>Synapse now includes a flag indicating if an event is an outlier when
replicating it to other workers. This is a forwards- and backwards-incompatible
change: v1.63 and workers cannot process events replicated by v1.64 workers, and
vice versa.</p>
<p>Once all workers are upgraded to v1.64 (or downgraded to v1.63), event
replication will resume as normal.</p>
<h2 id="frozendict-release"><a class="header" href="#frozendict-release">frozendict release</a></h2>
<p><a href="https://github.com/Marco-Sulla/python-frozendict/releases/tag/v2.3.3">frozendict 2.3.3</a>
has recently been released, which fixes a memory leak that occurs during <code>/sync</code>
requests. We advise server administrators who installed Synapse via pip to upgrade
frozendict with <code>pip install --upgrade frozendict</code>. The Docker image
<code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> already
include the updated library.</p>
<h1 id="upgrading-to-v1620"><a class="header" href="#upgrading-to-v1620">Upgrading to v1.62.0</a></h1>
<h2 id="new-signatures-for-spam-checker-callbacks"><a class="header" href="#new-signatures-for-spam-checker-callbacks">New signatures for spam checker callbacks</a></h2>
<p>As a followup to changes in v1.60.0, the following spam-checker callbacks have changed signature:</p>
<ul>
<li><code>user_may_join_room</code></li>
<li><code>user_may_invite</code></li>
<li><code>user_may_send_3pid_invite</code></li>
<li><code>user_may_create_room</code></li>
<li><code>user_may_create_room_alias</code></li>
<li><code>user_may_publish_room</code></li>
<li><code>check_media_file_for_spam</code></li>
</ul>
<p>For each of these methods, the previous callback signature has been deprecated.</p>
<p>Whereas callbacks used to return <code>bool</code>, they should now return <code>Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;]</code>.</p>
<p>For instance, if your module implements <code>user_may_join_room</code> as follows:</p>
<pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
    if ...:
        # Request is spam
        return False
    # Request is not spam
    return True
</code></pre>
<p>you should rewrite it as follows:</p>
<pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
    if ...:
        # Request is spam, mark it as forbidden (you may use some more precise error
        # code if it is useful).
        return synapse.module_api.errors.Codes.FORBIDDEN
    # Request is not spam, mark it as such.
    return synapse.module_api.NOT_SPAM
</code></pre>
<h1 id="upgrading-to-v1610"><a class="header" href="#upgrading-to-v1610">Upgrading to v1.61.0</a></h1>
<h2 id="removal-of-deprecated-communitygroups"><a class="header" href="#removal-of-deprecated-communitygroups">Removal of deprecated community/groups</a></h2>
<p>This release of Synapse will remove deprecated community/groups from codebase.</p>
<h3 id="worker-endpoints"><a class="header" href="#worker-endpoints">Worker endpoints</a></h3>
<p>For those who have deployed workers, following worker endpoints will no longer
exist and they can be removed from the reverse proxy configuration:</p>
<ul>
<li><code>^/_matrix/federation/v1/get_groups_publicised$</code></li>
<li><code>^/_matrix/client/(r0|v3|unstable)/joined_groups$</code></li>
<li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups$</code></li>
<li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups/</code></li>
<li><code>^/_matrix/federation/v1/groups/</code></li>
<li><code>^/_matrix/client/(r0|v3|unstable)/groups/</code></li>
</ul>
<h1 id="upgrading-to-v1600"><a class="header" href="#upgrading-to-v1600">Upgrading to v1.60.0</a></h1>
<h2 id="adding-a-new-unique-index-to-state_group_edges-could-fail-if-your-database-is-corrupted"><a class="header" href="#adding-a-new-unique-index-to-state_group_edges-could-fail-if-your-database-is-corrupted">Adding a new unique index to <code>state_group_edges</code> could fail if your database is corrupted</a></h2>
<p>This release of Synapse will add a unique index to the <code>state_group_edges</code> table, in order
to prevent accidentally introducing duplicate information (for example, because a database
backup was restored multiple times).</p>
<p>Duplicate rows being present in this table could cause drastic performance problems; see
<a href="https://github.com/matrix-org/synapse/issues/11779">issue 11779</a> for more details.</p>
<p>If your Synapse database already has had duplicate rows introduced into this table,
this could fail, with either of these errors:</p>
<p><strong>On Postgres:</strong></p>
<pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
...
psycopg2.errors.UniqueViolation: could not create unique index &quot;state_group_edges_unique_idx&quot;
DETAIL:  Key (state_group, prev_state_group)=(2, 1) is duplicated.
</code></pre>
<p>(The numbers may be different.)</p>
<p><strong>On SQLite:</strong></p>
<pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
...
sqlite3.IntegrityError: UNIQUE constraint failed: state_group_edges.state_group, state_group_edges.prev_state_group
</code></pre>
<details>
<summary><b>Expand this section for steps to resolve this problem</b></summary>
<h3 id="on-postgres"><a class="header" href="#on-postgres">On Postgres</a></h3>
<p>Connect to your database with <code>psql</code>.</p>
<pre><code class="language-sql">BEGIN;
DELETE FROM state_group_edges WHERE (ctid, state_group, prev_state_group) IN (
  SELECT row_id, state_group, prev_state_group
  FROM (
    SELECT
      ctid AS row_id,
      MIN(ctid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
      state_group,
      prev_state_group
    FROM state_group_edges
  ) AS t1
  WHERE row_id &lt;&gt; min_row_id
);
COMMIT;
</code></pre>
<h3 id="on-sqlite"><a class="header" href="#on-sqlite">On SQLite</a></h3>
<p>At the command-line, use <code>sqlite3 path/to/your-homeserver-database.db</code>:</p>
<pre><code class="language-sql">BEGIN;
DELETE FROM state_group_edges WHERE (rowid, state_group, prev_state_group) IN (
  SELECT row_id, state_group, prev_state_group
  FROM (
    SELECT
      rowid AS row_id,
      MIN(rowid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
      state_group,
      prev_state_group
    FROM state_group_edges
  )
  WHERE row_id &lt;&gt; min_row_id
);
COMMIT;
</code></pre>
<h3 id="for-more-details"><a class="header" href="#for-more-details">For more details</a></h3>
<p><a href="https://github.com/matrix-org/synapse/issues/11779#issuecomment-1131545970">This comment on issue 11779</a>
has queries that can be used to check a database for this problem in advance.</p>
</details>
<h2 id="new-signature-for-the-spam-checker-callback-check_event_for_spam"><a class="header" href="#new-signature-for-the-spam-checker-callback-check_event_for_spam">New signature for the spam checker callback <code>check_event_for_spam</code></a></h2>
<p>The previous signature has been deprecated.</p>
<p>Whereas <code>check_event_for_spam</code> callbacks used to return <code>Union[str, bool]</code>, they should now return <code>Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;]</code>.</p>
<p>This is part of an ongoing refactoring of the SpamChecker API to make it less ambiguous and more powerful.</p>
<p>If your module implements <code>check_event_for_spam</code> as follows:</p>
<pre><code class="language-python">async def check_event_for_spam(event):
    if ...:
        # Event is spam
        return True
    # Event is not spam
    return False
</code></pre>
<p>you should rewrite it as follows:</p>
<pre><code class="language-python">async def check_event_for_spam(event):
    if ...:
        # Event is spam, mark it as forbidden (you may use some more precise error
        # code if it is useful).
        return synapse.module_api.errors.Codes.FORBIDDEN
    # Event is not spam, mark it as such.
    return synapse.module_api.NOT_SPAM
</code></pre>
<h1 id="upgrading-to-v1590"><a class="header" href="#upgrading-to-v1590">Upgrading to v1.59.0</a></h1>
<h2 id="device-name-lookup-over-federation-has-been-disabled-by-default"><a class="header" href="#device-name-lookup-over-federation-has-been-disabled-by-default">Device name lookup over federation has been disabled by default</a></h2>
<p>The names of user devices are no longer visible to users on other homeservers by default.
Device IDs are unaffected, as these are necessary to facilitate end-to-end encryption.</p>
<p>To re-enable this functionality, set the
<a href="https://matrix-org.github.io/synapse/v1.59/usage/configuration/config_documentation.html#federation"><code>allow_device_name_lookup_over_federation</code></a>
homeserver config option to <code>true</code>.</p>
<h2 id="deprecation-of-the-synapseappappservice-and-synapseappuser_dir-worker-application-types"><a class="header" href="#deprecation-of-the-synapseappappservice-and-synapseappuser_dir-worker-application-types">Deprecation of the <code>synapse.app.appservice</code> and <code>synapse.app.user_dir</code> worker application types</a></h2>
<p>The <code>synapse.app.appservice</code> worker application type allowed you to configure a
single worker to use to notify application services of new events, as long
as this functionality was disabled on the main process with <code>notify_appservices: False</code>.
Further, the <code>synapse.app.user_dir</code> worker application type allowed you to configure
a single worker to be responsible for updating the user directory, as long as this
was disabled on the main process with <code>update_user_directory: False</code>.</p>
<p>To unify Synapse's worker types, the <code>synapse.app.appservice</code> worker application
type and the <code>notify_appservices</code> configuration option have been deprecated.
The <code>synapse.app.user_dir</code> worker application type and <code>update_user_directory</code>
configuration option have also been deprecated.</p>
<p>To get the same functionality as was provided by the deprecated options, it's now recommended that the <code>synapse.app.generic_worker</code>
worker application type is used and that the <code>notify_appservices_from_worker</code> and/or
<code>update_user_directory_from_worker</code> options are set to the name of a worker.</p>
<p>For the time being, the old options can be used alongside the new options to make
it easier to transition between the two configurations, however please note that:</p>
<ul>
<li>the options must not contradict each other (otherwise Synapse won't start); and</li>
<li>the <code>notify_appservices</code> and <code>update_user_directory</code> options will be removed in a future release of Synapse.</li>
</ul>
<p>Please see the <a href="workers.html#notifying-application-services"><em>Notifying Application Services</em></a> and
<a href="workers.html#updating-the-user-directory"><em>Updating the User Directory</em></a> sections of the worker
documentation for more information.</p>
<h1 id="upgrading-to-v1580"><a class="header" href="#upgrading-to-v1580">Upgrading to v1.58.0</a></h1>
<h2 id="groupscommunities-feature-has-been-disabled-by-default"><a class="header" href="#groupscommunities-feature-has-been-disabled-by-default">Groups/communities feature has been disabled by default</a></h2>
<p>The non-standard groups/communities feature in Synapse has been disabled by default
and will be removed in Synapse v1.61.0.</p>
<h1 id="upgrading-to-v1570"><a class="header" href="#upgrading-to-v1570">Upgrading to v1.57.0</a></h1>
<h2 id="changes-to-database-schema-for-application-services"><a class="header" href="#changes-to-database-schema-for-application-services">Changes to database schema for application services</a></h2>
<p>Synapse v1.57.0 includes a <a href="https://github.com/matrix-org/synapse/pull/12209">change</a> to the
way transaction IDs are managed for application services. If your deployment uses a dedicated
worker for application service traffic, <strong>it must be stopped</strong> when the database is upgraded
(which normally happens when the main process is upgraded), to ensure the change is made safely
without any risk of reusing transaction IDs.</p>
<p>Deployments which do not use separate worker processes can be upgraded as normal. Similarly,
deployments where no application services are in use can be upgraded as normal.</p>
<details>
<summary><b>Recovering from an incorrect upgrade</b></summary>
<p>If the database schema is upgraded <em>without</em> stopping the worker responsible
for AS traffic, then the following error may be given when attempting to start
a Synapse worker or master process:</p>
<pre><code>**********************************************************************************
 Error during initialisation:

 Postgres sequence 'application_services_txn_id_seq' is inconsistent with associated
 table 'application_services_txns'. This can happen if Synapse has been downgraded and
 then upgraded again, or due to a bad migration.

 To fix this error, shut down Synapse (including any and all workers)
 and run the following SQL:

     SELECT setval('application_services_txn_id_seq', (
         SELECT GREATEST(MAX(txn_id), 0) FROM application_services_txns
     ));

 See docs/postgres.md for more information.

 There may be more information in the logs.
**********************************************************************************
</code></pre>
<p>This error may also be seen if Synapse is <em>downgraded</em> to an earlier version,
and then upgraded again to v1.57.0 or later.</p>
<p>In either case:</p>
<ol>
<li>Ensure that the worker responsible for AS traffic is stopped.</li>
<li>Run the SQL command given in the error message via <code>psql</code>.</li>
</ol>
<p>Synapse should then start correctly.</p>
</details>
<h1 id="upgrading-to-v1560"><a class="header" href="#upgrading-to-v1560">Upgrading to v1.56.0</a></h1>
<h2 id="open-registration-without-verification-is-now-disabled-by-default"><a class="header" href="#open-registration-without-verification-is-now-disabled-by-default">Open registration without verification is now disabled by default</a></h2>
<p>Synapse will refuse to start if registration is enabled without email, captcha, or token-based verification unless the new config
flag <code>enable_registration_without_verification</code> is set to &quot;true&quot;.</p>
<h2 id="groupscommunities-feature-has-been-deprecated"><a class="header" href="#groupscommunities-feature-has-been-deprecated">Groups/communities feature has been deprecated</a></h2>
<p>The non-standard groups/communities feature in Synapse has been deprecated and will
be disabled by default in Synapse v1.58.0.</p>
<p>You can test disabling it by adding the following to your homeserver configuration:</p>
<pre><code class="language-yaml">experimental_features:
  groups_enabled: false
</code></pre>
<h2 id="change-in-behaviour-for-postgresql-databases-with-unsafe-locale"><a class="header" href="#change-in-behaviour-for-postgresql-databases-with-unsafe-locale">Change in behaviour for PostgreSQL databases with unsafe locale</a></h2>
<p>Synapse now refuses to start when using PostgreSQL with non-<code>C</code> values for <code>COLLATE</code> and
<code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the database section of
the configuration file, is set to <code>true</code>. See the <a href="https://matrix-org.github.io/synapse/latest/postgres.html#fixing-incorrect-collate-or-ctype">PostgreSQL documentation</a>
for more information and instructions on how to fix a database with incorrect values.</p>
<h1 id="upgrading-to-v1550"><a class="header" href="#upgrading-to-v1550">Upgrading to v1.55.0</a></h1>
<h2 id="synctl-script-has-been-moved"><a class="header" href="#synctl-script-has-been-moved"><code>synctl</code> script has been moved</a></h2>
<p>The <code>synctl</code> script
<a href="https://github.com/matrix-org/synapse/pull/12140">has been made</a> an
<a href="https://packaging.python.org/en/latest/specifications/entry-points/">entry point</a>
and no longer exists at the root of Synapse's source tree. If you wish to use
<code>synctl</code> to manage your homeserver, you should invoke <code>synctl</code> directly, e.g.
<code>synctl start</code> instead of <code>./synctl start</code> or <code>/path/to/synctl start</code>.</p>
<p>You will need to ensure <code>synctl</code> is on your <code>PATH</code>.</p>
<ul>
<li>This is automatically the case when using
<a href="https://packages.matrix.org/debian/">Debian packages</a> or
<a href="https://hub.docker.com/r/matrixdotorg/synapse">docker images</a>
provided by Matrix.org.</li>
<li>When installing from a wheel, sdist, or PyPI, a <code>synctl</code> executable is added
to your Python installation's <code>bin</code>. This should be on your <code>PATH</code>
automatically, though you might need to activate a virtual environment
depending on how you installed Synapse.</li>
</ul>
<h2 id="compatibility-dropped-for-mjolnir-131-and-earlier"><a class="header" href="#compatibility-dropped-for-mjolnir-131-and-earlier">Compatibility dropped for Mjolnir 1.3.1 and earlier</a></h2>
<p>Synapse v1.55.0 drops support for Mjolnir 1.3.1 and earlier.
If you use the Mjolnir module to moderate your homeserver,
please upgrade Mjolnir to version 1.3.2 or later before upgrading Synapse.</p>
<h1 id="upgrading-to-v1540"><a class="header" href="#upgrading-to-v1540">Upgrading to v1.54.0</a></h1>
<h2 id="legacy-structured-logging-configuration-removal"><a class="header" href="#legacy-structured-logging-configuration-removal">Legacy structured logging configuration removal</a></h2>
<p>This release removes support for the <code>structured: true</code> logging configuration
which was deprecated in Synapse v1.23.0. If your logging configuration contains
<code>structured: true</code> then it should be modified based on the
<a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
<h1 id="upgrading-to-v1530"><a class="header" href="#upgrading-to-v1530">Upgrading to v1.53.0</a></h1>
<h2 id="dropping-support-for-webclient-listeners-and-non-https-web_client_location"><a class="header" href="#dropping-support-for-webclient-listeners-and-non-https-web_client_location">Dropping support for <code>webclient</code> listeners and non-HTTP(S) <code>web_client_location</code></a></h2>
<p>Per the deprecation notice in Synapse v1.51.0, listeners of type  <code>webclient</code>
are no longer supported and configuring them is a now a configuration error.</p>
<p>Configuring a non-HTTP(S) <code>web_client_location</code> configuration is is now a
configuration error. Since the <code>webclient</code> listener is no longer supported, this
setting only applies to the root path <code>/</code> of Synapse's web server and no longer
the <code>/_matrix/client/</code> path.</p>
<h2 id="stablisation-of-msc3231"><a class="header" href="#stablisation-of-msc3231">Stablisation of MSC3231</a></h2>
<p>The unstable validity-check endpoint for the
<a href="https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity">Registration Tokens</a>
feature has been stabilised and moved from:</p>
<p><code>/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity</code></p>
<p>to:</p>
<p><code>/_matrix/client/v1/register/m.login.registration_token/validity</code></p>
<p>Please update any relevant reverse proxy or firewall configurations appropriately.</p>
<h2 id="time-based-cache-expiry-is-now-enabled-by-default"><a class="header" href="#time-based-cache-expiry-is-now-enabled-by-default">Time-based cache expiry is now enabled by default</a></h2>
<p>Formerly, entries in the cache were not evicted regardless of whether they were accessed after storing.
This behavior has now changed. By default entries in the cache are now evicted after 30m of not being accessed.
To change the default behavior, go to the <code>caches</code> section of the config and change the <code>expire_caches</code> and
<code>cache_entry_ttl</code> flags as necessary. Please note that these flags replace the <code>expiry_time</code> flag in the config.
The <code>expiry_time</code> flag will still continue to work, but it has been deprecated and will be removed in the future.</p>
<h2 id="deprecation-of-capability-orgmatrixmsc3283"><a class="header" href="#deprecation-of-capability-orgmatrixmsc3283">Deprecation of <code>capability</code> <code>org.matrix.msc3283.*</code></a></h2>
<p>The <code>capabilities</code> of MSC3283 from the REST API <code>/_matrix/client/r0/capabilities</code>
becomes stable.</p>
<p>The old <code>capabilities</code></p>
<ul>
<li><code>org.matrix.msc3283.set_displayname</code>,</li>
<li><code>org.matrix.msc3283.set_avatar_url</code> and</li>
<li><code>org.matrix.msc3283.3pid_changes</code></li>
</ul>
<p>are deprecated and scheduled to be removed in Synapse v1.54.0.</p>
<p>The new <code>capabilities</code></p>
<ul>
<li><code>m.set_displayname</code>,</li>
<li><code>m.set_avatar_url</code> and</li>
<li><code>m.3pid_changes</code></li>
</ul>
<p>are now active by default.</p>
<h2 id="removal-of-user_may_create_room_with_invites"><a class="header" href="#removal-of-user_may_create_room_with_invites">Removal of <code>user_may_create_room_with_invites</code></a></h2>
<p>As announced with the release of <a href="upgrade.html#deprecation-of-the-user_may_create_room_with_invites-module-callback">Synapse 1.47.0</a>,
the deprecated <code>user_may_create_room_with_invites</code> module callback has been removed.</p>
<p>Modules relying on it can instead implement <a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
and use the <a href="https://github.com/matrix-org/synapse/blob/872f23b95fa980a61b0866c1475e84491991fa20/synapse/module_api/__init__.py#L869-L876"><code>get_room_state</code></a>
module API to infer whether the invite is happening while creating a room (see <a href="https://github.com/matrix-org/synapse-domain-rule-checker/blob/e7d092dd9f2a7f844928771dbfd9fd24c2332e48/synapse_domain_rule_checker/__init__.py#L56-L89">this function</a>
as an example). Alternately, modules can also implement <a href="https://matrix-org.github.io/synapse/latest/modules/third_party_rules_callbacks.html#on_create_room"><code>on_create_room</code></a>.</p>
<h1 id="upgrading-to-v1520"><a class="header" href="#upgrading-to-v1520">Upgrading to v1.52.0</a></h1>
<h2 id="twisted-security-release"><a class="header" href="#twisted-security-release">Twisted security release</a></h2>
<p>Note that <a href="https://github.com/twisted/twisted/releases/tag/twisted-22.1.0">Twisted 22.1.0</a>
has recently been released, which fixes a <a href="https://github.com/twisted/twisted/security/advisories/GHSA-92x2-jw7w-xvvx">security issue</a>
within the Twisted library. We do not believe Synapse is affected by this vulnerability,
though we advise server administrators who installed Synapse via pip to upgrade Twisted
with <code>pip install --upgrade Twisted treq</code> as a matter of good practice. The Docker image
<code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> are using the
updated library.</p>
<h1 id="upgrading-to-v1510"><a class="header" href="#upgrading-to-v1510">Upgrading to v1.51.0</a></h1>
<h2 id="deprecation-of-webclient-listeners-and-non-https-web_client_location"><a class="header" href="#deprecation-of-webclient-listeners-and-non-https-web_client_location">Deprecation of <code>webclient</code> listeners and non-HTTP(S) <code>web_client_location</code></a></h2>
<p>Listeners of type  <code>webclient</code> are deprecated and scheduled to be removed in
Synapse v1.53.0.</p>
<p>Similarly, a non-HTTP(S) <code>web_client_location</code> configuration is deprecated and
will become a configuration error in Synapse v1.53.0.</p>
<h1 id="upgrading-to-v1500"><a class="header" href="#upgrading-to-v1500">Upgrading to v1.50.0</a></h1>
<h2 id="dropping-support-for-old-python-and-postgres-versions"><a class="header" href="#dropping-support-for-old-python-and-postgres-versions">Dropping support for old Python and Postgres versions</a></h2>
<p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
we've dropped support for Python 3.6 and PostgreSQL 9.6, as they are no
longer supported upstream.</p>
<p>This release of Synapse requires Python 3.7+ and PostgreSQL 10+.</p>
<h1 id="upgrading-to-v1470"><a class="header" href="#upgrading-to-v1470">Upgrading to v1.47.0</a></h1>
<h2 id="removal-of-old-room-admin-api"><a class="header" href="#removal-of-old-room-admin-api">Removal of old Room Admin API</a></h2>
<p>The following admin APIs were deprecated in <a href="https://github.com/matrix-org/synapse/blob/v1.34.0/CHANGES.md#deprecations-and-removals">Synapse 1.34</a>
(released on 2021-05-17) and have now been removed:</p>
<ul>
<li><code>POST /_synapse/admin/v1/&lt;room_id&gt;/delete</code></li>
</ul>
<p>Any scripts still using the above APIs should be converted to use the
<a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
<h2 id="deprecation-of-the-user_may_create_room_with_invites-module-callback"><a class="header" href="#deprecation-of-the-user_may_create_room_with_invites-module-callback">Deprecation of the <code>user_may_create_room_with_invites</code> module callback</a></h2>
<p>The <code>user_may_create_room_with_invites</code> is deprecated and will be removed in a future
version of Synapse. Modules implementing this callback can instead implement
<a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
and use the <a href="https://github.com/matrix-org/synapse/blob/872f23b95fa980a61b0866c1475e84491991fa20/synapse/module_api/__init__.py#L869-L876"><code>get_room_state</code></a>
module API method to infer whether the invite is happening in the context of creating a
room.</p>
<p>We plan to remove this callback in January 2022.</p>
<h1 id="upgrading-to-v1450"><a class="header" href="#upgrading-to-v1450">Upgrading to v1.45.0</a></h1>
<h2 id="changes-required-to-media-storage-provider-modules-when-reading-from-the-synapse-configuration-object"><a class="header" href="#changes-required-to-media-storage-provider-modules-when-reading-from-the-synapse-configuration-object">Changes required to media storage provider modules when reading from the Synapse configuration object</a></h2>
<p>Media storage provider modules that read from the Synapse configuration object (i.e. that
read the value of <code>hs.config.[...]</code>) now need to specify the configuration section they're
reading from. This means that if a module reads the value of e.g. <code>hs.config.media_store_path</code>,
it needs to replace it with <code>hs.config.media.media_store_path</code>.</p>
<h1 id="upgrading-to-v1440"><a class="header" href="#upgrading-to-v1440">Upgrading to v1.44.0</a></h1>
<h2 id="the-url-preview-cache-is-no-longer-mirrored-to-storage-providers"><a class="header" href="#the-url-preview-cache-is-no-longer-mirrored-to-storage-providers">The URL preview cache is no longer mirrored to storage providers</a></h2>
<p>The <code>url_cache/</code> and <code>url_cache_thumbnails/</code> directories in the media store are
no longer mirrored to storage providers. These two directories can be safely
deleted from any configured storage providers to reclaim space.</p>
<h1 id="upgrading-to-v1430"><a class="header" href="#upgrading-to-v1430">Upgrading to v1.43.0</a></h1>
<h2 id="the-spaces-summary-apis-can-now-be-handled-by-workers"><a class="header" href="#the-spaces-summary-apis-can-now-be-handled-by-workers">The spaces summary APIs can now be handled by workers</a></h2>
<p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#available-worker-applications">available worker applications documentation</a>
has been updated to reflect that calls to the <code>/spaces</code>, <code>/hierarchy</code>, and
<code>/summary</code> endpoints can now be routed to workers for both client API and
federation requests.</p>
<h1 id="upgrading-to-v1420"><a class="header" href="#upgrading-to-v1420">Upgrading to v1.42.0</a></h1>
<h2 id="removal-of-old-room-admin-api-1"><a class="header" href="#removal-of-old-room-admin-api-1">Removal of old Room Admin API</a></h2>
<p>The following admin APIs were deprecated in <a href="https://github.com/matrix-org/synapse/blob/v1.25.0/CHANGES.md#removal-warning">Synapse 1.25</a>
(released on 2021-01-13) and have now been removed:</p>
<ul>
<li><code>POST /_synapse/admin/v1/purge_room</code></li>
<li><code>POST /_synapse/admin/v1/shutdown_room/&lt;room_id&gt;</code></li>
</ul>
<p>Any scripts still using the above APIs should be converted to use the
<a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
<h2 id="user-interactive-authentication-fallback-templates-can-now-display-errors"><a class="header" href="#user-interactive-authentication-fallback-templates-can-now-display-errors">User-interactive authentication fallback templates can now display errors</a></h2>
<p>This may affect you if you make use of custom HTML templates for the
<a href="https://github.com/matrix-org/synapse/tree/develop/synapse/res/templates/recaptcha.html">reCAPTCHA (<code>synapse/res/templates/recaptcha.html</code>)</a> or
<a href="https://github.com/matrix-org/synapse/tree/develop/synapse/res/templates/terms.html">terms (<code>synapse/res/templates/terms.html</code>)</a> fallback pages.</p>
<p>The template is now provided an <code>error</code> variable if the authentication
process failed. See the default templates linked above for an example.</p>
<h2 id="removal-of-out-of-date-email-pushers"><a class="header" href="#removal-of-out-of-date-email-pushers">Removal of out-of-date email pushers</a></h2>
<p>Users will stop receiving message updates via email for addresses that were
once, but not still, linked to their account.</p>
<h1 id="upgrading-to-v1410"><a class="header" href="#upgrading-to-v1410">Upgrading to v1.41.0</a></h1>
<h2 id="add-support-for-routing-outbound-http-requests-via-a-proxy-for-federation"><a class="header" href="#add-support-for-routing-outbound-http-requests-via-a-proxy-for-federation">Add support for routing outbound HTTP requests via a proxy for federation</a></h2>
<p>Since Synapse 1.6.0 (2019-11-26) you can set a proxy for outbound HTTP requests via
http_proxy/https_proxy environment variables. This proxy was set for:</p>
<ul>
<li>push</li>
<li>url previews</li>
<li>phone-home stats</li>
<li>recaptcha validation</li>
<li>CAS auth validation</li>
<li>OpenID Connect</li>
<li>Federation (checking public key revocation)</li>
</ul>
<p>In this version we have added support for outbound requests for:</p>
<ul>
<li>Outbound federation</li>
<li>Downloading remote media</li>
<li>Fetching public keys of other servers</li>
</ul>
<p>These requests use the same proxy configuration. If you have a proxy configuration we
recommend to verify the configuration. It may be necessary to adjust the <code>no_proxy</code>
environment variable.</p>
<p>See <a href="setup/forward_proxy.html">using a forward proxy with Synapse documentation</a> for
details.</p>
<h2 id="deprecation-of-template_dir"><a class="header" href="#deprecation-of-template_dir">Deprecation of <code>template_dir</code></a></h2>
<p>The <code>template_dir</code> settings in the <code>sso</code>, <code>account_validity</code> and <code>email</code> sections of the
configuration file are now deprecated. Server admins should use the new
<code>templates.custom_template_directory</code> setting in the configuration file and use one single
custom template directory for all aforementioned features. Template file names remain
unchanged. See <a href="https://matrix-org.github.io/synapse/latest/templates.html">the related documentation</a>
for more information and examples.</p>
<p>We plan to remove support for these settings in October 2021.</p>
<h2 id="_synapseadminv1usersuseridmedia-must-be-handled-by-media-workers"><a class="header" href="#_synapseadminv1usersuseridmedia-must-be-handled-by-media-workers"><code>/_synapse/admin/v1/users/{userId}/media</code> must be handled by media workers</a></h2>
<p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#synapseappmedia_repository">media repository worker documentation</a>
has been updated to reflect that calls to <code>/_synapse/admin/v1/users/{userId}/media</code>
must now be handled by media repository workers. This is due to the new <code>DELETE</code> method
of this endpoint modifying the media store.</p>
<h1 id="upgrading-to-v1390"><a class="header" href="#upgrading-to-v1390">Upgrading to v1.39.0</a></h1>
<h2 id="deprecation-of-the-current-third-party-rules-module-interface"><a class="header" href="#deprecation-of-the-current-third-party-rules-module-interface">Deprecation of the current third-party rules module interface</a></h2>
<p>The current third-party rules module interface is deprecated in favour of the new generic
modules system introduced in Synapse v1.37.0. Authors of third-party rules modules can refer
to <a href="modules/porting_legacy_module.html">this documentation</a>
to update their modules. Synapse administrators can refer to <a href="modules/index.html">this documentation</a>
to update their configuration once the modules they are using have been updated.</p>
<p>We plan to remove support for the current third-party rules interface in September 2021.</p>
<h1 id="upgrading-to-v1380"><a class="header" href="#upgrading-to-v1380">Upgrading to v1.38.0</a></h1>
<h2 id="re-indexing-of-events-table-on-postgres-databases"><a class="header" href="#re-indexing-of-events-table-on-postgres-databases">Re-indexing of <code>events</code> table on Postgres databases</a></h2>
<p>This release includes a database schema update which requires re-indexing one of
the larger tables in the database, <code>events</code>. This could result in increased
disk I/O for several hours or days after upgrading while the migration
completes. Furthermore, because we have to keep the old indexes until the new
indexes are ready, it could result in a significant, temporary, increase in
disk space.</p>
<p>To get a rough idea of the disk space required, check the current size of one
of the indexes. For example, from a <code>psql</code> shell, run the following sql:</p>
<pre><code class="language-sql">SELECT pg_size_pretty(pg_relation_size('events_order_room'));
</code></pre>
<p>We need to rebuild <strong>four</strong> indexes, so you will need to multiply this result
by four to give an estimate of the disk space required. For example, on one
particular server:</p>
<pre><code>synapse=# select pg_size_pretty(pg_relation_size('events_order_room'));
 pg_size_pretty
----------------
 288 MB
(1 row)
</code></pre>
<p>On this server, it would be wise to ensure that at least 1152MB are free.</p>
<p>The additional disk space will be freed once the migration completes.</p>
<p>SQLite databases are unaffected by this change.</p>
<h1 id="upgrading-to-v1370"><a class="header" href="#upgrading-to-v1370">Upgrading to v1.37.0</a></h1>
<h2 id="deprecation-of-the-current-spam-checker-interface"><a class="header" href="#deprecation-of-the-current-spam-checker-interface">Deprecation of the current spam checker interface</a></h2>
<p>The current spam checker interface is deprecated in favour of a new generic modules system.
Authors of spam checker modules can refer to [this
documentation](modules/porting_legacy_module.md
to update their modules. Synapse administrators can refer to <a href="modules/index.html">this
documentation</a>
to update their configuration once the modules they are using have been updated.</p>
<p>We plan to remove support for the current spam checker interface in August 2021.</p>
<p>More module interfaces will be ported over to this new generic system in future versions
of Synapse.</p>
<h1 id="upgrading-to-v1340"><a class="header" href="#upgrading-to-v1340">Upgrading to v1.34.0</a></h1>
<h2 id="room_invite_state_types-configuration-setting"><a class="header" href="#room_invite_state_types-configuration-setting"><code>room_invite_state_types</code> configuration setting</a></h2>
<p>The <code>room_invite_state_types</code> configuration setting has been deprecated
and replaced with <code>room_prejoin_state</code>. See the <a href="https://github.com/matrix-org/synapse/blob/v1.34.0/docs/sample_config.yaml#L1515">sample configuration
file</a>.</p>
<p>If you have set <code>room_invite_state_types</code> to the default value you
should simply remove it from your configuration file. The default value
used to be:</p>
<pre><code class="language-yaml">room_invite_state_types:
   - &quot;m.room.join_rules&quot;
   - &quot;m.room.canonical_alias&quot;
   - &quot;m.room.avatar&quot;
   - &quot;m.room.encryption&quot;
   - &quot;m.room.name&quot;
</code></pre>
<p>If you have customised this value, you should remove
<code>room_invite_state_types</code> and configure <code>room_prejoin_state</code> instead.</p>
<h1 id="upgrading-to-v1330"><a class="header" href="#upgrading-to-v1330">Upgrading to v1.33.0</a></h1>
<h2 id="account-validity-html-templates-can-now-display-a-users-expiration-date"><a class="header" href="#account-validity-html-templates-can-now-display-a-users-expiration-date">Account Validity HTML templates can now display a user's expiration date</a></h2>
<p>This may affect you if you have enabled the account validity feature,
and have made use of a custom HTML template specified by the
<code>account_validity.template_dir</code> or
<code>account_validity.account_renewed_html_path</code> Synapse config options.</p>
<p>The template can now accept an <code>expiration_ts</code> variable, which
represents the unix timestamp in milliseconds for the future date of
which their account has been renewed until. See the <a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_renewed.html">default
template</a>
for an example of usage.</p>
<p>ALso note that a new HTML template, <code>account_previously_renewed.html</code>,
has been added. This is is shown to users when they attempt to renew
their account with a valid renewal token that has already been used
before. The default template contents can been found
<a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_previously_renewed.html">here</a>,
and can also accept an <code>expiration_ts</code> variable. This template replaces
the error message users would previously see upon attempting to use a
valid renewal token more than once.</p>
<h1 id="upgrading-to-v1320"><a class="header" href="#upgrading-to-v1320">Upgrading to v1.32.0</a></h1>
<h2 id="regression-causing-connected-prometheus-instances-to-become-overwhelmed"><a class="header" href="#regression-causing-connected-prometheus-instances-to-become-overwhelmed">Regression causing connected Prometheus instances to become overwhelmed</a></h2>
<p>This release introduces <a href="https://github.com/matrix-org/synapse/issues/9853">a
regression</a> that can
overwhelm connected Prometheus instances. This issue is not present in
Synapse v1.32.0rc1.</p>
<p>If you have been affected, please downgrade to 1.31.0. You then may need
to remove excess writeahead logs in order for Prometheus to recover.
Instructions for doing so are provided
<a href="https://github.com/matrix-org/synapse/pull/9854#issuecomment-823472183">here</a>.</p>
<h2 id="dropping-support-for-old-python-postgres-and-sqlite-versions"><a class="header" href="#dropping-support-for-old-python-postgres-and-sqlite-versions">Dropping support for old Python, Postgres and SQLite versions</a></h2>
<p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
we've dropped support for Python 3.5 and PostgreSQL 9.5, as they are no
longer supported upstream.</p>
<p>This release of Synapse requires Python 3.6+ and PostgresSQL 9.6+ or
SQLite 3.22+.</p>
<h2 id="removal-of-old-list-accounts-admin-api"><a class="header" href="#removal-of-old-list-accounts-admin-api">Removal of old List Accounts Admin API</a></h2>
<p>The deprecated v1 &quot;list accounts&quot; admin API
(<code>GET /_synapse/admin/v1/users/&lt;user_id&gt;</code>) has been removed in this
version.</p>
<p>The <a href="admin_api/user_admin_api.html#list-accounts">v2 list accounts API</a>
has been available since Synapse 1.7.0 (2019-12-13), and is accessible
under <code>GET /_synapse/admin/v2/users</code>.</p>
<p>The deprecation of the old endpoint was announced with Synapse 1.28.0
(released on 2021-02-25).</p>
<h2 id="application-services-must-use-type-mloginapplication_service-when-registering-users"><a class="header" href="#application-services-must-use-type-mloginapplication_service-when-registering-users">Application Services must use type <code>m.login.application_service</code> when registering users</a></h2>
<p>In compliance with the <a href="https://matrix.org/docs/spec/application_service/r0.1.2#server-admin-style-permissions">Application Service
spec</a>,
Application Services are now required to use the
<code>m.login.application_service</code> type when registering users via the
<code>/_matrix/client/r0/register</code> endpoint. This behaviour was deprecated in
Synapse v1.30.0.</p>
<p>Please ensure your Application Services are up to date.</p>
<h1 id="upgrading-to-v1290"><a class="header" href="#upgrading-to-v1290">Upgrading to v1.29.0</a></h1>
<h2 id="requirement-for-x-forwarded-proto-header"><a class="header" href="#requirement-for-x-forwarded-proto-header">Requirement for X-Forwarded-Proto header</a></h2>
<p>When using Synapse with a reverse proxy (in particular, when using the
<code>x_forwarded</code> option on an HTTP listener), Synapse now
expects to receive an <code>X-Forwarded-Proto</code> header on incoming
HTTP requests. If it is not set, Synapse will log a warning on each
received request.</p>
<p>To avoid the warning, administrators using a reverse proxy should ensure
that the reverse proxy sets <code>X-Forwarded-Proto</code> header to
<code>https</code> or <code>http</code> to indicate the protocol used
by the client.</p>
<p>Synapse also requires the <code>Host</code> header to be preserved.</p>
<p>See the <a href="reverse_proxy.html">reverse proxy documentation</a>, where the
example configurations have been updated to show how to set these
headers.</p>
<p>(Users of <a href="https://caddyserver.com/">Caddy</a> are unaffected, since we
believe it sets <code>X-Forwarded-Proto</code> by default.)</p>
<h1 id="upgrading-to-v1270"><a class="header" href="#upgrading-to-v1270">Upgrading to v1.27.0</a></h1>
<h2 id="changes-to-callback-uri-for-oauth2--openid-connect-and-saml2"><a class="header" href="#changes-to-callback-uri-for-oauth2--openid-connect-and-saml2">Changes to callback URI for OAuth2 / OpenID Connect and SAML2</a></h2>
<p>This version changes the URI used for callbacks from OAuth2 and SAML2
identity providers:</p>
<ul>
<li>
<p>If your server is configured for single sign-on via an OpenID
Connect or OAuth2 identity provider, you will need to add
<code>[synapse public baseurl]/_synapse/client/oidc/callback</code> to the list
of permitted &quot;redirect URIs&quot; at the identity provider.</p>
<p>See the <a href="openid.html">OpenID docs</a> for more information on setting
up OpenID Connect.</p>
</li>
<li>
<p>If your server is configured for single sign-on via a SAML2 identity
provider, you will need to add
<code>[synapse public baseurl]/_synapse/client/saml2/authn_response</code> as a
permitted &quot;ACS location&quot; (also known as &quot;allowed callback URLs&quot;)
at the identity provider.</p>
<p>The &quot;Issuer&quot; in the &quot;AuthnRequest&quot; to the SAML2 identity
provider is also updated to
<code>[synapse public baseurl]/_synapse/client/saml2/metadata.xml</code>. If
your SAML2 identity provider uses this property to validate or
otherwise identify Synapse, its configuration will need to be
updated to use the new URL. Alternatively you could create a new,
separate &quot;EntityDescriptor&quot; in your SAML2 identity provider with
the new URLs and leave the URLs in the existing &quot;EntityDescriptor&quot;
as they were.</p>
</li>
</ul>
<h2 id="changes-to-html-templates"><a class="header" href="#changes-to-html-templates">Changes to HTML templates</a></h2>
<p>The HTML templates for SSO and email notifications now have <a href="https://jinja.palletsprojects.com/en/2.11.x/api/#autoescaping">Jinja2's
autoescape</a>
enabled for files ending in <code>.html</code>, <code>.htm</code>, and <code>.xml</code>. If you have
customised these templates and see issues when viewing them you might
need to update them. It is expected that most configurations will need
no changes.</p>
<p>If you have customised the templates <em>names</em> for these templates, it is
recommended to verify they end in <code>.html</code> to ensure autoescape is
enabled.</p>
<p>The above applies to the following templates:</p>
<ul>
<li><code>add_threepid.html</code></li>
<li><code>add_threepid_failure.html</code></li>
<li><code>add_threepid_success.html</code></li>
<li><code>notice_expiry.html</code></li>
<li><code>notice_expiry.html</code></li>
<li><code>notif_mail.html</code> (which, by default, includes <code>room.html</code> and
<code>notif.html</code>)</li>
<li><code>password_reset.html</code></li>
<li><code>password_reset_confirmation.html</code></li>
<li><code>password_reset_failure.html</code></li>
<li><code>password_reset_success.html</code></li>
<li><code>registration.html</code></li>
<li><code>registration_failure.html</code></li>
<li><code>registration_success.html</code></li>
<li><code>sso_account_deactivated.html</code></li>
<li><code>sso_auth_bad_user.html</code></li>
<li><code>sso_auth_confirm.html</code></li>
<li><code>sso_auth_success.html</code></li>
<li><code>sso_error.html</code></li>
<li><code>sso_login_idp_picker.html</code></li>
<li><code>sso_redirect_confirm.html</code></li>
</ul>
<h1 id="upgrading-to-v1260"><a class="header" href="#upgrading-to-v1260">Upgrading to v1.26.0</a></h1>
<h2 id="rolling-back-to-v1250-after-a-failed-upgrade"><a class="header" href="#rolling-back-to-v1250-after-a-failed-upgrade">Rolling back to v1.25.0 after a failed upgrade</a></h2>
<p>v1.26.0 includes a lot of large changes. If something problematic
occurs, you may want to roll-back to a previous version of Synapse.
Because v1.26.0 also includes a new database schema version, reverting
that version is also required alongside the generic rollback
instructions mentioned above. In short, to roll back to v1.25.0 you need
to:</p>
<ol>
<li>
<p>Stop the server</p>
</li>
<li>
<p>Decrease the schema version in the database:</p>
<pre><code class="language-sql">UPDATE schema_version SET version = 58;
</code></pre>
</li>
<li>
<p>Delete the ignored users &amp; chain cover data:</p>
<pre><code class="language-sql">DROP TABLE IF EXISTS ignored_users;
UPDATE rooms SET has_auth_chain_index = false;
</code></pre>
<p>For PostgreSQL run:</p>
<pre><code class="language-sql">TRUNCATE event_auth_chain_links;
TRUNCATE event_auth_chains;
</code></pre>
<p>For SQLite run:</p>
<pre><code class="language-sql">DELETE FROM event_auth_chain_links;
DELETE FROM event_auth_chains;
</code></pre>
</li>
<li>
<p>Mark the deltas as not run (so they will re-run on upgrade).</p>
<pre><code class="language-sql">DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/01ignored_user.py&quot;;
DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/06chain_cover_index.sql&quot;;
</code></pre>
</li>
<li>
<p>Downgrade Synapse by following the instructions for your
installation method in the &quot;Rolling back to older versions&quot;
section above.</p>
</li>
</ol>
<h1 id="upgrading-to-v1250"><a class="header" href="#upgrading-to-v1250">Upgrading to v1.25.0</a></h1>
<h2 id="last-release-supporting-python-35"><a class="header" href="#last-release-supporting-python-35">Last release supporting Python 3.5</a></h2>
<p>This is the last release of Synapse which guarantees support with Python
3.5, which passed its upstream End of Life date several months ago.</p>
<p>We will attempt to maintain support through March 2021, but without
guarantees.</p>
<p>In the future, Synapse will follow upstream schedules for ending support
of older versions of Python and PostgreSQL. Please upgrade to at least
Python 3.6 and PostgreSQL 9.6 as soon as possible.</p>
<h2 id="blacklisting-ip-ranges"><a class="header" href="#blacklisting-ip-ranges">Blacklisting IP ranges</a></h2>
<p>Synapse v1.25.0 includes new settings, <code>ip_range_blacklist</code> and
<code>ip_range_whitelist</code>, for controlling outgoing requests from Synapse for
federation, identity servers, push, and for checking key validity for
third-party invite events. The previous setting,
<code>federation_ip_range_blacklist</code>, is deprecated. The new
<code>ip_range_blacklist</code> defaults to private IP ranges if it is not defined.</p>
<p>If you have never customised <code>federation_ip_range_blacklist</code> it is
recommended that you remove that setting.</p>
<p>If you have customised <code>federation_ip_range_blacklist</code> you should update
the setting name to <code>ip_range_blacklist</code>.</p>
<p>If you have a custom push server that is reached via private IP space
you may need to customise <code>ip_range_blacklist</code> or <code>ip_range_whitelist</code>.</p>
<h1 id="upgrading-to-v1240"><a class="header" href="#upgrading-to-v1240">Upgrading to v1.24.0</a></h1>
<h2 id="custom-openid-connect-mapping-provider-breaking-change"><a class="header" href="#custom-openid-connect-mapping-provider-breaking-change">Custom OpenID Connect mapping provider breaking change</a></h2>
<p>This release allows the OpenID Connect mapping provider to perform
normalisation of the localpart of the Matrix ID. This allows for the
mapping provider to specify different algorithms, instead of the
<a href="https://matrix.org/docs/spec/appendices#mapping-from-other-character-sets">default
way</a>.</p>
<p>If your Synapse configuration uses a custom mapping provider
(<code>oidc_config.user_mapping_provider.module</code> is specified and
not equal to
<code>synapse.handlers.oidc_handler.JinjaOidcMappingProvider</code>)
then you <em>must</em> ensure that <code>map_user_attributes</code> of the
mapping provider performs some normalisation of the
<code>localpart</code> returned. To match previous behaviour you can
use the <code>map_username_to_mxid_localpart</code> function provided
by Synapse. An example is shown below:</p>
<pre><code class="language-python">from synapse.types import map_username_to_mxid_localpart

class MyMappingProvider:
    def map_user_attributes(self, userinfo, token):
        # ... your custom logic ...
        sso_user_id = ...
        localpart = map_username_to_mxid_localpart(sso_user_id)

        return {&quot;localpart&quot;: localpart}
</code></pre>
<h2 id="removal-historical-synapse-admin-api"><a class="header" href="#removal-historical-synapse-admin-api">Removal historical Synapse Admin API</a></h2>
<p>Historically, the Synapse Admin API has been accessible under:</p>
<ul>
<li><code>/_matrix/client/api/v1/admin</code></li>
<li><code>/_matrix/client/unstable/admin</code></li>
<li><code>/_matrix/client/r0/admin</code></li>
<li><code>/_synapse/admin/v1</code></li>
</ul>
<p>The endpoints with <code>/_matrix/client/*</code> prefixes have been removed as of
v1.24.0. The Admin API is now only accessible under:</p>
<ul>
<li><code>/_synapse/admin/v1</code></li>
</ul>
<p>The only exception is the <code>/admin/whois</code> endpoint, which is
<a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">also available via the client-server
API</a>.</p>
<p>The deprecation of the old endpoints was announced with Synapse 1.20.0
(released on 2020-09-22) and makes it easier for homeserver admins to
lock down external access to the Admin API endpoints.</p>
<h1 id="upgrading-to-v1230"><a class="header" href="#upgrading-to-v1230">Upgrading to v1.23.0</a></h1>
<h2 id="structured-logging-configuration-breaking-changes"><a class="header" href="#structured-logging-configuration-breaking-changes">Structured logging configuration breaking changes</a></h2>
<p>This release deprecates use of the <code>structured: true</code> logging
configuration for structured logging. If your logging configuration
contains <code>structured: true</code> then it should be modified based on the
<a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
<p>The <code>structured</code> and <code>drains</code> logging options are now deprecated and
should be replaced by standard logging configuration of <code>handlers</code> and
<code>formatters</code>.</p>
<p>A future will release of Synapse will make using <code>structured: true</code> an
error.</p>
<h1 id="upgrading-to-v1220"><a class="header" href="#upgrading-to-v1220">Upgrading to v1.22.0</a></h1>
<h2 id="thirdpartyeventrules-breaking-changes"><a class="header" href="#thirdpartyeventrules-breaking-changes">ThirdPartyEventRules breaking changes</a></h2>
<p>This release introduces a backwards-incompatible change to modules
making use of <code>ThirdPartyEventRules</code> in Synapse. If you make use of a
module defined under the <code>third_party_event_rules</code> config option, please
make sure it is updated to handle the below change:</p>
<p>The <code>http_client</code> argument is no longer passed to modules as they are
initialised. Instead, modules are expected to make use of the
<code>http_client</code> property on the <code>ModuleApi</code> class. Modules are now passed
a <code>module_api</code> argument during initialisation, which is an instance of
<code>ModuleApi</code>. <code>ModuleApi</code> instances have a <code>http_client</code> property which
acts the same as the <code>http_client</code> argument previously passed to
<code>ThirdPartyEventRules</code> modules.</p>
<h1 id="upgrading-to-v1210"><a class="header" href="#upgrading-to-v1210">Upgrading to v1.21.0</a></h1>
<h2 id="forwarding-_synapseclient-through-your-reverse-proxy"><a class="header" href="#forwarding-_synapseclient-through-your-reverse-proxy">Forwarding <code>/_synapse/client</code> through your reverse proxy</a></h2>
<p>The <a href="reverse_proxy.html">reverse proxy documentation</a>
has been updated to include reverse proxy directives for
<code>/_synapse/client/*</code> endpoints. As the user password reset flow now uses
endpoints under this prefix, <strong>you must update your reverse proxy
configurations for user password reset to work</strong>.</p>
<p>Additionally, note that the <a href="workers.html">Synapse worker documentation</a> has been updated to</p>
<p>:   state that the <code>/_synapse/client/password_reset/email/submit_token</code>
endpoint can be handled</p>
<p>by all workers. If you make use of Synapse's worker feature, please
update your reverse proxy configuration to reflect this change.</p>
<h2 id="new-html-templates"><a class="header" href="#new-html-templates">New HTML templates</a></h2>
<p>A new HTML template,
<a href="https://github.com/matrix-org/synapse/blob/develop/synapse/res/templates/password_reset_confirmation.html">password_reset_confirmation.html</a>,
has been added to the <code>synapse/res/templates</code> directory. If you are
using a custom template directory, you may want to copy the template
over and modify it.</p>
<p>Note that as of v1.20.0, templates do not need to be included in custom
template directories for Synapse to start. The default templates will be
used if a custom template cannot be found.</p>
<p>This page will appear to the user after clicking a password reset link
that has been emailed to them.</p>
<p>To complete password reset, the page must include a way to make a
<code>POST</code> request to
<code>/_synapse/client/password_reset/{medium}/submit_token</code> with the query
parameters from the original link, presented as a URL-encoded form. See
the file itself for more details.</p>
<h2 id="updated-single-sign-on-html-templates"><a class="header" href="#updated-single-sign-on-html-templates">Updated Single Sign-on HTML Templates</a></h2>
<p>The <code>saml_error.html</code> template was removed from Synapse and replaced
with the <code>sso_error.html</code> template. If your Synapse is configured to use
SAML and a custom <code>sso_redirect_confirm_template_dir</code> configuration then
any customisations of the <code>saml_error.html</code> template will need to be
merged into the <code>sso_error.html</code> template. These templates are similar,
but the parameters are slightly different:</p>
<ul>
<li>The <code>msg</code> parameter should be renamed to <code>error_description</code>.</li>
<li>There is no longer a <code>code</code> parameter for the response code.</li>
<li>A string <code>error</code> parameter is available that includes a short hint
of why a user is seeing the error page.</li>
</ul>
<h1 id="upgrading-to-v1180"><a class="header" href="#upgrading-to-v1180">Upgrading to v1.18.0</a></h1>
<h2 id="docker--py3-suffix-will-be-removed-in-future-versions"><a class="header" href="#docker--py3-suffix-will-be-removed-in-future-versions">Docker <code>-py3</code> suffix will be removed in future versions</a></h2>
<p>From 10th August 2020, we will no longer publish Docker images with the
<code>-py3</code> tag suffix. The images tagged with the
<code>-py3</code> suffix have been identical to the non-suffixed tags
since release 0.99.0, and the suffix is obsolete.</p>
<p>On 10th August, we will remove the <code>latest-py3</code> tag.
Existing per-release tags (such as <code>v1.18.0-py3</code> will not
be removed, but no new <code>-py3</code> tags will be added.</p>
<p>Scripts relying on the <code>-py3</code> suffix will need to be
updated.</p>
<h2 id="redis-replication-is-now-recommended-in-lieu-of-tcp-replication"><a class="header" href="#redis-replication-is-now-recommended-in-lieu-of-tcp-replication">Redis replication is now recommended in lieu of TCP replication</a></h2>
<p>When setting up worker processes, we now recommend the use of a Redis
server for replication. <strong>The old direct TCP connection method is
deprecated and will be removed in a future release.</strong> See
the <a href="https://matrix-org.github.io/synapse/v1.66/workers.html">worker documentation</a> for more details.</p>
<h1 id="upgrading-to-v1140"><a class="header" href="#upgrading-to-v1140">Upgrading to v1.14.0</a></h1>
<p>This version includes a database update which is run as part of the
upgrade, and which may take a couple of minutes in the case of a large
server. Synapse will not respond to HTTP requests while this update is
taking place.</p>
<h1 id="upgrading-to-v1130"><a class="header" href="#upgrading-to-v1130">Upgrading to v1.13.0</a></h1>
<h2 id="incorrect-database-migration-in-old-synapse-versions"><a class="header" href="#incorrect-database-migration-in-old-synapse-versions">Incorrect database migration in old synapse versions</a></h2>
<p>A bug was introduced in Synapse 1.4.0 which could cause the room
directory to be incomplete or empty if Synapse was upgraded directly
from v1.2.1 or earlier, to versions between v1.4.0 and v1.12.x.</p>
<p>This will <em>not</em> be a problem for Synapse installations which were:</p>
<p>:   -   created at v1.4.0 or later,
-   upgraded via v1.3.x, or
-   upgraded straight from v1.2.1 or earlier to v1.13.0 or later.</p>
<p>If completeness of the room directory is a concern, installations which
are affected can be repaired as follows:</p>
<ol>
<li>
<p>Run the following sql from a <code>psql</code> or
<code>sqlite3</code> console:</p>
<pre><code class="language-sql">INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
   ('populate_stats_process_rooms', '{}', 'current_state_events_membership');

INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
   ('populate_stats_process_users', '{}', 'populate_stats_process_rooms');
</code></pre>
</li>
<li>
<p>Restart synapse.</p>
</li>
</ol>
<h2 id="new-single-sign-on-html-templates"><a class="header" href="#new-single-sign-on-html-templates">New Single Sign-on HTML Templates</a></h2>
<p>New templates (<code>sso_auth_confirm.html</code>, <code>sso_auth_success.html</code>, and
<code>sso_account_deactivated.html</code>) were added to Synapse. If your Synapse
is configured to use SSO and a custom
<code>sso_redirect_confirm_template_dir</code> configuration then these templates
will need to be copied from
<a href="https://github.com/matrix-org/synapse/tree/develop/synapse/res/templates"><code>synapse/res/templates</code></a> into that directory.</p>
<h2 id="synapse-sso-plugins-method-deprecation"><a class="header" href="#synapse-sso-plugins-method-deprecation">Synapse SSO Plugins Method Deprecation</a></h2>
<p>Plugins using the <code>complete_sso_login</code> method of
<code>synapse.module_api.ModuleApi</code> should update to using the async/await
version <code>complete_sso_login_async</code> which includes additional checks. The
non-async version is considered deprecated.</p>
<h2 id="rolling-back-to-v1124-after-a-failed-upgrade"><a class="header" href="#rolling-back-to-v1124-after-a-failed-upgrade">Rolling back to v1.12.4 after a failed upgrade</a></h2>
<p>v1.13.0 includes a lot of large changes. If something problematic
occurs, you may want to roll-back to a previous version of Synapse.
Because v1.13.0 also includes a new database schema version, reverting
that version is also required alongside the generic rollback
instructions mentioned above. In short, to roll back to v1.12.4 you need
to:</p>
<ol>
<li>
<p>Stop the server</p>
</li>
<li>
<p>Decrease the schema version in the database:</p>
<pre><code class="language-sql">UPDATE schema_version SET version = 57;
</code></pre>
</li>
<li>
<p>Downgrade Synapse by following the instructions for your
installation method in the &quot;Rolling back to older versions&quot;
section above.</p>
</li>
</ol>
<h1 id="upgrading-to-v1120"><a class="header" href="#upgrading-to-v1120">Upgrading to v1.12.0</a></h1>
<p>This version includes a database update which is run as part of the
upgrade, and which may take some time (several hours in the case of a
large server). Synapse will not respond to HTTP requests while this
update is taking place.</p>
<p>This is only likely to be a problem in the case of a server which is
participating in many rooms.</p>
<ol start="0">
<li>
<p>As with all upgrades, it is recommended that you have a recent
backup of your database which can be used for recovery in the event
of any problems.</p>
</li>
<li>
<p>As an initial check to see if you will be affected, you can try
running the following query from the <code>psql</code> or
<code>sqlite3</code> console. It is safe to run it while Synapse is
still running.</p>
<pre><code class="language-sql">SELECT MAX(q.v) FROM (
  SELECT (
    SELECT ej.json AS v
    FROM state_events se INNER JOIN event_json ej USING (event_id)
    WHERE se.room_id=rooms.room_id AND se.type='m.room.create' AND se.state_key=''
    LIMIT 1
  ) FROM rooms WHERE rooms.room_version IS NULL
) q;
</code></pre>
<p>This query will take about the same amount of time as the upgrade
process: ie, if it takes 5 minutes, then it is likely that Synapse
will be unresponsive for 5 minutes during the upgrade.</p>
<p>If you consider an outage of this duration to be acceptable, no
further action is necessary and you can simply start Synapse 1.12.0.</p>
<p>If you would prefer to reduce the downtime, continue with the steps
below.</p>
</li>
<li>
<p>The easiest workaround for this issue is to manually create a new
index before upgrading. On PostgreSQL, his can be done as follows:</p>
<pre><code class="language-sql">CREATE INDEX CONCURRENTLY tmp_upgrade_1_12_0_index
ON state_events(room_id) WHERE type = 'm.room.create';
</code></pre>
<p>The above query may take some time, but is also safe to run while
Synapse is running.</p>
<p>We assume that no SQLite users have databases large enough to be
affected. If you <em>are</em> affected, you can run a similar query,
omitting the <code>CONCURRENTLY</code> keyword. Note however that this
operation may in itself cause Synapse to stop running for some time.
Synapse admins are reminded that <a href="postgres.html">SQLite is not recommended for use
outside a test environment</a>.</p>
</li>
<li>
<p>Once the index has been created, the <code>SELECT</code> query in step 1 above
should complete quickly. It is therefore safe to upgrade to Synapse
1.12.0.</p>
</li>
<li>
<p>Once Synapse 1.12.0 has successfully started and is responding to
HTTP requests, the temporary index can be removed:</p>
<pre><code class="language-sql">DROP INDEX tmp_upgrade_1_12_0_index;
</code></pre>
</li>
</ol>
<h1 id="upgrading-to-v1100"><a class="header" href="#upgrading-to-v1100">Upgrading to v1.10.0</a></h1>
<p>Synapse will now log a warning on start up if used with a PostgreSQL
database that has a non-recommended locale set.</p>
<p>See <a href="postgres.html">Postgres</a> for details.</p>
<h1 id="upgrading-to-v180"><a class="header" href="#upgrading-to-v180">Upgrading to v1.8.0</a></h1>
<p>Specifying a <code>log_file</code> config option will now cause Synapse to refuse
to start, and should be replaced by with the <code>log_config</code> option.
Support for the <code>log_file</code> option was removed in v1.3.0 and has since
had no effect.</p>
<h1 id="upgrading-to-v170"><a class="header" href="#upgrading-to-v170">Upgrading to v1.7.0</a></h1>
<p>In an attempt to configure Synapse in a privacy preserving way, the
default behaviours of <code>allow_public_rooms_without_auth</code> and
<code>allow_public_rooms_over_federation</code> have been inverted. This means that
by default, only authenticated users querying the Client/Server API will
be able to query the room directory, and relatedly that the server will
not share room directory information with other servers over federation.</p>
<p>If your installation does not explicitly set these settings one way or
the other and you want either setting to be <code>true</code> then it will
necessary to update your homeserver configuration file accordingly.</p>
<p>For more details on the surrounding context see our
<a href="https://matrix.org/blog/2019/11/09/avoiding-unwelcome-visitors-on-private-matrix-servers">explainer</a>.</p>
<h1 id="upgrading-to-v150"><a class="header" href="#upgrading-to-v150">Upgrading to v1.5.0</a></h1>
<p>This release includes a database migration which may take several
minutes to complete if there are a large number (more than a million or
so) of entries in the <code>devices</code> table. This is only likely to a be a
problem on very large installations.</p>
<h1 id="upgrading-to-v140"><a class="header" href="#upgrading-to-v140">Upgrading to v1.4.0</a></h1>
<h2 id="new-custom-templates"><a class="header" href="#new-custom-templates">New custom templates</a></h2>
<p>If you have configured a custom template directory with the
<code>email.template_dir</code> option, be aware that there are new templates
regarding registration and threepid management (see below) that must be
included.</p>
<ul>
<li><code>registration.html</code> and <code>registration.txt</code></li>
<li><code>registration_success.html</code> and <code>registration_failure.html</code></li>
<li><code>add_threepid.html</code> and <code>add_threepid.txt</code></li>
<li><code>add_threepid_failure.html</code> and <code>add_threepid_success.html</code></li>
</ul>
<p>Synapse will expect these files to exist inside the configured template
directory, and <strong>will fail to start</strong> if they are absent. To view the
default templates, see
<a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">synapse/res/templates</a>.</p>
<h2 id="3pid-verification-changes"><a class="header" href="#3pid-verification-changes">3pid verification changes</a></h2>
<p><strong>Note: As of this release, users will be unable to add phone numbers or
email addresses to their accounts, without changes to the Synapse
configuration. This includes adding an email address during
registration.</strong></p>
<p>It is possible for a user to associate an email address or phone number
with their account, for a number of reasons:</p>
<ul>
<li>for use when logging in, as an alternative to the user id.</li>
<li>in the case of email, as an alternative contact to help with account
recovery.</li>
<li>in the case of email, to receive notifications of missed messages.</li>
</ul>
<p>Before an email address or phone number can be added to a user's
account, or before such an address is used to carry out a
password-reset, Synapse must confirm the operation with the owner of the
email address or phone number. It does this by sending an email or text
giving the user a link or token to confirm receipt. This process is
known as '3pid verification'. ('3pid', or 'threepid', stands for
third-party identifier, and we use it to refer to external identifiers
such as email addresses and phone numbers.)</p>
<p>Previous versions of Synapse delegated the task of 3pid verification to
an identity server by default. In most cases this server is <code>vector.im</code>
or <code>matrix.org</code>.</p>
<p>In Synapse 1.4.0, for security and privacy reasons, the homeserver will
no longer delegate this task to an identity server by default. Instead,
the server administrator will need to explicitly decide how they would
like the verification messages to be sent.</p>
<p>In the medium term, the <code>vector.im</code> and <code>matrix.org</code> identity servers
will disable support for delegated 3pid verification entirely. However,
in order to ease the transition, they will retain the capability for a
limited period. Delegated email verification will be disabled on Monday
2nd December 2019 (giving roughly 2 months notice). Disabling delegated
SMS verification will follow some time after that once SMS verification
support lands in Synapse.</p>
<p>Once delegated 3pid verification support has been disabled in the
<code>vector.im</code> and <code>matrix.org</code> identity servers, all Synapse versions that
depend on those instances will be unable to verify email and phone
numbers through them. There are no imminent plans to remove delegated
3pid verification from Sydent generally. (Sydent is the identity server
project that backs the <code>vector.im</code> and <code>matrix.org</code> instances).</p>
<h3 id="email-1"><a class="header" href="#email-1">Email</a></h3>
<p>Following upgrade, to continue verifying email (e.g. as part of the
registration process), admins can either:-</p>
<ul>
<li>Configure Synapse to use an email server.</li>
<li>Run or choose an identity server which allows delegated email
verification and delegate to it.</li>
</ul>
<h4 id="configure-smtp-in-synapse"><a class="header" href="#configure-smtp-in-synapse">Configure SMTP in Synapse</a></h4>
<p>To configure an SMTP server for Synapse, modify the configuration
section headed <code>email</code>, and be sure to have at least the
<code>smtp_host, smtp_port</code> and <code>notif_from</code> fields filled out.</p>
<p>You may also need to set <code>smtp_user</code>, <code>smtp_pass</code>, and
<code>require_transport_security</code>.</p>
<p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
for more details on these settings.</p>
<h4 id="delegate-email-to-an-identity-server"><a class="header" href="#delegate-email-to-an-identity-server">Delegate email to an identity server</a></h4>
<p>Some admins will wish to continue using email verification as part of
the registration process, but will not immediately have an appropriate
SMTP server at hand.</p>
<p>To this end, we will continue to support email verification delegation
via the <code>vector.im</code> and <code>matrix.org</code> identity servers for two months.
Support for delegated email verification will be disabled on Monday 2nd
December.</p>
<p>The <code>account_threepid_delegates</code> dictionary defines whether the
homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
server</a>) to handle
sending confirmation messages via email and SMS.</p>
<p>So to delegate email verification, in <code>homeserver.yaml</code>, set
<code>account_threepid_delegates.email</code> to the base URL of an identity
server. For example:</p>
<pre><code class="language-yaml">account_threepid_delegates:
    email: https://example.com     # Delegate email sending to example.com
</code></pre>
<p>Note that <code>account_threepid_delegates.email</code> replaces the deprecated
<code>email.trust_identity_server_for_password_resets</code>: if
<code>email.trust_identity_server_for_password_resets</code> is set to <code>true</code>, and
<code>account_threepid_delegates.email</code> is not set, then the first entry in
<code>trusted_third_party_id_servers</code> will be used as the
<code>account_threepid_delegate</code> for email. This is to ensure compatibility
with existing Synapse installs that set up external server handling for
these tasks before v1.4.0. If
<code>email.trust_identity_server_for_password_resets</code> is <code>true</code> and no
trusted identity server domains are configured, Synapse will report an
error and refuse to start.</p>
<p>If <code>email.trust_identity_server_for_password_resets</code> is <code>false</code> or
absent and no <code>email</code> delegate is configured in
<code>account_threepid_delegates</code>, then Synapse will send email verification
messages itself, using the configured SMTP server (see above). that
type.</p>
<h3 id="phone-numbers"><a class="header" href="#phone-numbers">Phone numbers</a></h3>
<p>Synapse does not support phone-number verification itself, so the only
way to maintain the ability for users to add phone numbers to their
accounts will be by continuing to delegate phone number verification to
the <code>matrix.org</code> and <code>vector.im</code> identity servers (or another identity
server that supports SMS sending).</p>
<p>The <code>account_threepid_delegates</code> dictionary defines whether the
homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
server</a>) to handle
sending confirmation messages via email and SMS.</p>
<p>So to delegate phone number verification, in <code>homeserver.yaml</code>, set
<code>account_threepid_delegates.msisdn</code> to the base URL of an identity
server. For example:</p>
<pre><code class="language-yaml">account_threepid_delegates:
    msisdn: https://example.com     # Delegate sms sending to example.com
</code></pre>
<p>The <code>matrix.org</code> and <code>vector.im</code> identity servers will continue to
support delegated phone number verification via SMS until such time as
it is possible for admins to configure their servers to perform phone
number verification directly. More details will follow in a future
release.</p>
<h2 id="rolling-back-to-v131"><a class="header" href="#rolling-back-to-v131">Rolling back to v1.3.1</a></h2>
<p>If you encounter problems with v1.4.0, it should be possible to roll
back to v1.3.1, subject to the following:</p>
<ul>
<li>
<p>The 'room statistics' engine was heavily reworked in this release
(see <a href="https://github.com/matrix-org/synapse/pull/5971">#5971</a>),
including significant changes to the database schema, which are not
easily reverted. This will cause the room statistics engine to stop
updating when you downgrade.</p>
<p>The room statistics are essentially unused in v1.3.1 (in future
versions of Synapse, they will be used to populate the room
directory), so there should be no loss of functionality. However,
the statistics engine will write errors to the logs, which can be
avoided by setting the following in <code>homeserver.yaml</code>:</p>
<pre><code class="language-yaml">stats:
  enabled: false
</code></pre>
<p>Don't forget to re-enable it when you upgrade again, in preparation
for its use in the room directory!</p>
</li>
</ul>
<h1 id="upgrading-to-v120"><a class="header" href="#upgrading-to-v120">Upgrading to v1.2.0</a></h1>
<p>Some counter metrics have been renamed, with the old names deprecated.
See <a href="metrics-howto.html#renaming-of-metrics--deprecation-of-old-names-in-12">the metrics
documentation</a>
for details.</p>
<h1 id="upgrading-to-v110"><a class="header" href="#upgrading-to-v110">Upgrading to v1.1.0</a></h1>
<p>Synapse v1.1.0 removes support for older Python and PostgreSQL versions,
as outlined in <a href="https://matrix.org/blog/2019/04/08/synapse-deprecating-postgres-9-4-and-python-2-x">our deprecation
notice</a>.</p>
<h2 id="minimum-python-version"><a class="header" href="#minimum-python-version">Minimum Python Version</a></h2>
<p>Synapse v1.1.0 has a minimum Python requirement of Python 3.5. Python
3.6 or Python 3.7 are recommended as they have improved internal string
handling, significantly reducing memory usage.</p>
<p>If you use current versions of the Matrix.org-distributed Debian
packages or Docker images, action is not required.</p>
<p>If you install Synapse in a Python virtual environment, please see
&quot;Upgrading to v0.34.0&quot; for notes on setting up a new virtualenv under
Python 3.</p>
<h2 id="minimum-postgresql-version"><a class="header" href="#minimum-postgresql-version">Minimum PostgreSQL Version</a></h2>
<p>If using PostgreSQL under Synapse, you will need to use PostgreSQL 9.5
or above. Please see the <a href="https://www.postgresql.org/docs/11/upgrading.html">PostgreSQL
documentation</a> for
more details on upgrading your database.</p>
<h1 id="upgrading-to-v10"><a class="header" href="#upgrading-to-v10">Upgrading to v1.0</a></h1>
<h2 id="validation-of-tls-certificates"><a class="header" href="#validation-of-tls-certificates">Validation of TLS certificates</a></h2>
<p>Synapse v1.0 is the first release to enforce validation of TLS
certificates for the federation API. It is therefore essential that your
certificates are correctly configured.</p>
<p>Note, v1.0 installations will also no longer be able to federate with
servers that have not correctly configured their certificates.</p>
<p>In rare cases, it may be desirable to disable certificate checking: for
example, it might be essential to be able to federate with a given
legacy server in a closed federation. This can be done in one of two
ways:-</p>
<ul>
<li>Configure the global switch <code>federation_verify_certificates</code> to
<code>false</code>.</li>
<li>Configure a whitelist of server domains to trust via
<code>federation_certificate_verification_whitelist</code>.</li>
</ul>
<p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
for more details on these settings.</p>
<h2 id="email-2"><a class="header" href="#email-2">Email</a></h2>
<p>When a user requests a password reset, Synapse will send an email to the
user to confirm the request.</p>
<p>Previous versions of Synapse delegated the job of sending this email to
an identity server. If the identity server was somehow malicious or
became compromised, it would be theoretically possible to hijack an
account through this means.</p>
<p>Therefore, by default, Synapse v1.0 will send the confirmation email
itself. If Synapse is not configured with an SMTP server, password reset
via email will be disabled.</p>
<p>To configure an SMTP server for Synapse, modify the configuration
section headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>,
<code>smtp_port</code> and <code>notif_from</code> fields filled out. You may also need to set
<code>smtp_user</code>, <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
<p>If you are absolutely certain that you wish to continue using an
identity server for password resets, set
<code>trust_identity_server_for_password_resets</code> to <code>true</code>.</p>
<p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
for more details on these settings.</p>
<h2 id="new-email-templates"><a class="header" href="#new-email-templates">New email templates</a></h2>
<p>Some new templates have been added to the default template directory for the purpose of
the homeserver sending its own password reset emails. If you have configured a
custom <code>template_dir</code> in your Synapse config, these files will need to be added.</p>
<p><code>password_reset.html</code> and <code>password_reset.txt</code> are HTML and plain text
templates respectively that contain the contents of what will be emailed
to the user upon attempting to reset their password via email.
<code>password_reset_success.html</code> and <code>password_reset_failure.html</code> are HTML
files that the content of which (assuming no redirect URL is set) will
be shown to the user after they attempt to click the link in the email
sent to them.</p>
<h1 id="upgrading-to-v0990"><a class="header" href="#upgrading-to-v0990">Upgrading to v0.99.0</a></h1>
<p>Please be aware that, before Synapse v1.0 is released around March 2019,
you will need to replace any self-signed certificates with those
verified by a root CA. Information on how to do so can be found at the
ACME docs.</p>
<h1 id="upgrading-to-v0340"><a class="header" href="#upgrading-to-v0340">Upgrading to v0.34.0</a></h1>
<ol>
<li>
<p>This release is the first to fully support Python 3. Synapse will
now run on Python versions 3.5, or 3.6 (as well as 2.7). We
recommend switching to Python 3, as it has been shown to give
performance improvements.</p>
<p>For users who have installed Synapse into a virtualenv, we recommend
doing this by creating a new virtualenv. For example:</p>
<pre><code class="language-sh">virtualenv -p python3 ~/synapse/env3
source ~/synapse/env3/bin/activate
pip install matrix-synapse
</code></pre>
<p>You can then start synapse as normal, having activated the new
virtualenv:</p>
<pre><code class="language-sh">cd ~/synapse
source env3/bin/activate
synctl start
</code></pre>
<p>Users who have installed from distribution packages should see the
relevant package documentation. See below for notes on Debian
packages.</p>
<ul>
<li>
<p>When upgrading to Python 3, you <strong>must</strong> make sure that your log
files are configured as UTF-8, by adding <code>encoding: utf8</code> to the
<code>RotatingFileHandler</code> configuration (if you have one) in your
<code>&lt;server&gt;.log.config</code> file. For example, if your <code>log.config</code>
file contains:</p>
<pre><code class="language-yaml">handlers:
  file:
    class: logging.handlers.RotatingFileHandler
    formatter: precise
    filename: homeserver.log
    maxBytes: 104857600
    backupCount: 10
    filters: [context]
  console:
    class: logging.StreamHandler
    formatter: precise
    filters: [context]
</code></pre>
<p>Then you should update this to be:</p>
<pre><code class="language-yaml">handlers:
  file:
    class: logging.handlers.RotatingFileHandler
    formatter: precise
    filename: homeserver.log
    maxBytes: 104857600
    backupCount: 10
    filters: [context]
    encoding: utf8
  console:
    class: logging.StreamHandler
    formatter: precise
    filters: [context]
</code></pre>
<p>There is no need to revert this change if downgrading to
Python 2.</p>
</li>
</ul>
<p>We are also making available Debian packages which will run Synapse
on Python 3. You can switch to these packages with
<code>apt-get install matrix-synapse-py3</code>, however, please read
<a href="https://github.com/matrix-org/synapse/blob/release-v0.34.0/debian/NEWS">debian/NEWS</a>
before doing so. The existing <code>matrix-synapse</code> packages will
continue to use Python 2 for the time being.</p>
</li>
<li>
<p>This release removes the <code>riot.im</code> from the default list of trusted
identity servers.</p>
<p>If <code>riot.im</code> is in your homeserver's list of
<code>trusted_third_party_id_servers</code>, you should remove it. It was added
in case a hypothetical future identity server was put there. If you
don't remove it, users may be unable to deactivate their accounts.</p>
</li>
<li>
<p>This release no longer installs the (unmaintained) Matrix Console
web client as part of the default installation. It is possible to
re-enable it by installing it separately and setting the
<code>web_client_location</code> config option, but please consider switching
to another client.</p>
</li>
</ol>
<h1 id="upgrading-to-v0337"><a class="header" href="#upgrading-to-v0337">Upgrading to v0.33.7</a></h1>
<p>This release removes the example email notification templates from
<code>res/templates</code> (they are now internal to the python package). This
should only affect you if you (a) deploy your Synapse instance from a
git checkout or a github snapshot URL, and (b) have email notifications
enabled.</p>
<p>If you have email notifications enabled, you should ensure that
<code>email.template_dir</code> is either configured to point at a directory where
you have installed customised templates, or leave it unset to use the
default templates.</p>
<h1 id="upgrading-to-v0273"><a class="header" href="#upgrading-to-v0273">Upgrading to v0.27.3</a></h1>
<p>This release expands the anonymous usage stats sent if the opt-in
<code>report_stats</code> configuration is set to <code>true</code>. We now capture RSS memory
and cpu use at a very coarse level. This requires administrators to
install the optional <code>psutil</code> python module.</p>
<p>We would appreciate it if you could assist by ensuring this module is
available and <code>report_stats</code> is enabled. This will let us see if
performance changes to synapse are having an impact to the general
community.</p>
<h1 id="upgrading-to-v0150"><a class="header" href="#upgrading-to-v0150">Upgrading to v0.15.0</a></h1>
<p>If you want to use the new URL previewing API
(<code>/_matrix/media/r0/preview_url</code>) then you have to explicitly enable it
in the config and update your dependencies dependencies. See README.rst
for details.</p>
<h1 id="upgrading-to-v0110"><a class="header" href="#upgrading-to-v0110">Upgrading to v0.11.0</a></h1>
<p>This release includes the option to send anonymous usage stats to
matrix.org, and requires that administrators explictly opt in or out by
setting the <code>report_stats</code> option to either <code>true</code> or <code>false</code>.</p>
<p>We would really appreciate it if you could help our project out by
reporting anonymized usage statistics from your homeserver. Only very
basic aggregate data (e.g. number of users) will be reported, but it
helps us to track the growth of the Matrix community, and helps us to
make Matrix a success, as well as to convince other networks that they
should peer with us.</p>
<h1 id="upgrading-to-v090"><a class="header" href="#upgrading-to-v090">Upgrading to v0.9.0</a></h1>
<p>Application services have had a breaking API change in this version.</p>
<p>They can no longer register themselves with a home server using the AS
HTTP API. This decision was made because a compromised application
service with free reign to register any regex in effect grants full
read/write access to the home server if a regex of <code>.*</code> is used. An
attack where a compromised AS re-registers itself with <code>.*</code> was deemed
too big of a security risk to ignore, and so the ability to register
with the HS remotely has been removed.</p>
<p>It has been replaced by specifying a list of application service
registrations in <code>homeserver.yaml</code>:</p>
<pre><code class="language-yaml">app_service_config_files: [&quot;registration-01.yaml&quot;, &quot;registration-02.yaml&quot;]
</code></pre>
<p>Where <code>registration-01.yaml</code> looks like:</p>
<pre><code class="language-yaml">url: &lt;String&gt;  # e.g. &quot;https://my.application.service.com&quot;
as_token: &lt;String&gt;
hs_token: &lt;String&gt;
sender_localpart: &lt;String&gt;  # This is a new field which denotes the user_id localpart when using the AS token
namespaces:
  users:
    - exclusive: &lt;Boolean&gt;
      regex: &lt;String&gt;  # e.g. &quot;@prefix_.*&quot;
  aliases:
    - exclusive: &lt;Boolean&gt;
      regex: &lt;String&gt;
  rooms:
    - exclusive: &lt;Boolean&gt;
      regex: &lt;String&gt;
</code></pre>
<h1 id="upgrading-to-v080"><a class="header" href="#upgrading-to-v080">Upgrading to v0.8.0</a></h1>
<p>Servers which use captchas will need to add their public key to:</p>
<pre><code>static/client/register/register_config.js

  window.matrixRegistrationConfig = {
      recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  };
</code></pre>
<p>This is required in order to support registration fallback (typically
used on mobile devices).</p>
<h1 id="upgrading-to-v070"><a class="header" href="#upgrading-to-v070">Upgrading to v0.7.0</a></h1>
<p>New dependencies are:</p>
<ul>
<li>pydenticon</li>
<li>simplejson</li>
<li>syutil</li>
<li>matrix-angular-sdk</li>
</ul>
<p>To pull in these dependencies in a virtual env, run:</p>
<pre><code>python synapse/python_dependencies.py | xargs -n 1 pip install
</code></pre>
<h1 id="upgrading-to-v060"><a class="header" href="#upgrading-to-v060">Upgrading to v0.6.0</a></h1>
<p>To pull in new dependencies, run:</p>
<pre><code>python setup.py develop --user
</code></pre>
<p>This update includes a change to the database schema. To upgrade you
first need to upgrade the database by running:</p>
<pre><code>python scripts/upgrade_db_to_v0.6.0.py &lt;db&gt; &lt;server_name&gt; &lt;signing_key&gt;
</code></pre>
<p>Where <code>&lt;db&gt;</code> is the location of the database,
<code>&lt;server_name&gt;</code> is the server name as specified in the
synapse configuration, and <code>&lt;signing_key&gt;</code> is the location
of the signing key as specified in the synapse configuration.</p>
<p>This may take some time to complete. Failures of signatures and content
hashes can safely be ignored.</p>
<h1 id="upgrading-to-v051"><a class="header" href="#upgrading-to-v051">Upgrading to v0.5.1</a></h1>
<p>Depending on precisely when you installed v0.5.0 you may have ended up
with a stale release of the reference matrix webclient installed as a
python module. To uninstall it and ensure you are depending on the
latest module, please run:</p>
<pre><code>$ pip uninstall syweb
</code></pre>
<h1 id="upgrading-to-v050"><a class="header" href="#upgrading-to-v050">Upgrading to v0.5.0</a></h1>
<p>The webclient has been split out into a seperate repository/pacakage in
this release. Before you restart your homeserver you will need to pull
in the webclient package by running:</p>
<pre><code>python setup.py develop --user
</code></pre>
<p>This release completely changes the database schema and so requires
upgrading it before starting the new version of the homeserver.</p>
<p>The script &quot;database-prepare-for-0.5.0.sh&quot; should be used to upgrade
the database. This will save all user information, such as logins and
profiles, but will otherwise purge the database. This includes messages,
which rooms the home server was a member of and room alias mappings.</p>
<p>If you would like to keep your history, please take a copy of your
database file and ask for help in #matrix:matrix.org. The upgrade
process is, unfortunately, non trivial and requires human intervention
to resolve any resulting conflicts during the upgrade process.</p>
<p>Before running the command the homeserver should be first completely
shutdown. To run it, simply specify the location of the database, e.g.:</p>
<blockquote>
<p>./scripts/database-prepare-for-0.5.0.sh &quot;homeserver.db&quot;</p>
</blockquote>
<p>Once this has successfully completed it will be safe to restart the
homeserver. You may notice that the homeserver takes a few seconds
longer to restart than usual as it reinitializes the database.</p>
<p>On startup of the new version, users can either rejoin remote rooms
using room aliases or by being reinvited. Alternatively, if any other
homeserver sends a message to a room that the homeserver was previously
in the local HS will automatically rejoin the room.</p>
<h1 id="upgrading-to-v040"><a class="header" href="#upgrading-to-v040">Upgrading to v0.4.0</a></h1>
<p>This release needs an updated syutil version. Run:</p>
<pre><code>python setup.py develop
</code></pre>
<p>You will also need to upgrade your configuration as the signing key
format has changed. Run:</p>
<pre><code>python -m synapse.app.homeserver --config-path &lt;CONFIG&gt; --generate-config
</code></pre>
<h1 id="upgrading-to-v030"><a class="header" href="#upgrading-to-v030">Upgrading to v0.3.0</a></h1>
<p>This registration API now closely matches the login API. This introduces
a bit more backwards and forwards between the HS and the client, but
this improves the overall flexibility of the API. You can now GET on
/register to retrieve a list of valid registration flows. Upon choosing
one, they are submitted in the same way as login, e.g:</p>
<pre><code>{
  type: m.login.password,
  user: foo,
  password: bar
}
</code></pre>
<p>The default HS supports 2 flows, with and without Identity Server email
authentication. Enabling captcha on the HS will add in an extra step to
all flows: <code>m.login.recaptcha</code> which must be completed before you can
transition to the next stage. There is a new login type:
<code>m.login.email.identity</code> which contains the <code>threepidCreds</code> key which
were previously sent in the original register request. For more
information on this, see the specification.</p>
<h2 id="web-client"><a class="header" href="#web-client">Web Client</a></h2>
<p>The VoIP specification has changed between v0.2.0 and v0.3.0. Users
should refresh any browser tabs to get the latest web client code. Users
on v0.2.0 of the web client will not be able to call those on v0.3.0 and
vice versa.</p>
<h1 id="upgrading-to-v020"><a class="header" href="#upgrading-to-v020">Upgrading to v0.2.0</a></h1>
<p>The home server now requires setting up of SSL config before it can run.
To automatically generate default config use:</p>
<pre><code>$ python synapse/app/homeserver.py \
    --server-name machine.my.domain.name \
    --bind-port 8448 \
    --config-path homeserver.config \
    --generate-config
</code></pre>
<p>This config can be edited if desired, for example to specify a different
SSL certificate to use. Once done you can run the home server using:</p>
<pre><code>$ python synapse/app/homeserver.py --config-path homeserver.config
</code></pre>
<p>See the README.rst for more information.</p>
<p>Also note that some config options have been renamed, including:</p>
<ul>
<li>&quot;host&quot; to &quot;server-name&quot;</li>
<li>&quot;database&quot; to &quot;database-path&quot;</li>
<li>&quot;port&quot; to &quot;bind-port&quot; and &quot;unsecure-port&quot;</li>
</ul>
<h1 id="upgrading-to-v001"><a class="header" href="#upgrading-to-v001">Upgrading to v0.0.1</a></h1>
<p>This release completely changes the database schema and so requires
upgrading it before starting the new version of the homeserver.</p>
<p>The script &quot;database-prepare-for-0.0.1.sh&quot; should be used to upgrade
the database. This will save all user information, such as logins and
profiles, but will otherwise purge the database. This includes messages,
which rooms the home server was a member of and room alias mappings.</p>
<p>Before running the command the homeserver should be first completely
shutdown. To run it, simply specify the location of the database, e.g.:</p>
<blockquote>
<p>./scripts/database-prepare-for-0.0.1.sh &quot;homeserver.db&quot;</p>
</blockquote>
<p>Once this has successfully completed it will be safe to restart the
homeserver. You may notice that the homeserver takes a few seconds
longer to restart than usual as it reinitializes the database.</p>
<p>On startup of the new version, users can either rejoin remote rooms
using room aliases or by being reinvited. Alternatively, if any other
homeserver sends a message to a room that the homeserver was previously
in the local HS will automatically rejoin the room.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="setting-up-federation"><a class="header" href="#setting-up-federation">Setting up federation</a></h1>
<p>Federation is the process by which users on different servers can participate
in the same room. For this to work, those other servers must be able to contact
yours to send messages.</p>
<p>The <code>server_name</code> configured in the Synapse configuration file (often
<code>homeserver.yaml</code>) defines how resources (users, rooms, etc.) will be
identified (eg: <code>@user:example.com</code>, <code>#room:example.com</code>). By default,
it is also the domain that other servers will use to try to reach your
server (via port 8448). This is easy to set up and will work provided
you set the <code>server_name</code> to match your machine's public DNS hostname.</p>
<p>For this default configuration to work, you will need to listen for TLS
connections on port 8448. The preferred way to do that is by using a
reverse proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions
on how to correctly set one up.</p>
<p>In some cases you might not want to run Synapse on the machine that has
the <code>server_name</code> as its public DNS hostname, or you might want federation
traffic to use a different port than 8448. For example, you might want to
have your user names look like <code>@user:example.com</code>, but you want to run
Synapse on <code>synapse.example.com</code> on port 443. This can be done using
delegation, which allows an admin to control where federation traffic should
be sent. See <a href="delegate.html">the delegation documentation</a> for instructions on how to set this up.</p>
<p>Once federation has been configured, you should be able to join a room over
federation. A good place to start is <code>#synapse:matrix.org</code> - a room for
Synapse admins.</p>
<h2 id="troubleshooting-3"><a class="header" href="#troubleshooting-3">Troubleshooting</a></h2>
<p>You can use the <a href="https://matrix.org/federationtester">federation tester</a>
to check if your homeserver is configured correctly. Alternatively try the
<a href="https://matrix.org/federationtester/api/report?server_name=DOMAIN">JSON API used by the federation tester</a>.
Note that you'll have to modify this URL to replace <code>DOMAIN</code> with your
<code>server_name</code>. Hitting the API directly provides extra detail.</p>
<p>The typical failure mode for federation is that when the server tries to join
a room, it is rejected with &quot;401: Unauthorized&quot;. Generally this means that other
servers in the room could not access yours. (Joining a room over federation is
a complicated dance which requires connections in both directions).</p>
<p>Another common problem is that people on other servers can't join rooms that
you invite them to. This can be caused by an incorrectly-configured reverse
proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions on how
to correctly configure a reverse proxy.</p>
<h3 id="known-issues"><a class="header" href="#known-issues">Known issues</a></h3>
<p><strong>HTTP <code>308 Permanent Redirect</code> redirects are not followed</strong>: Due to missing features
in the HTTP library used by Synapse, 308 redirects are currently not followed by
federating servers, which can cause <code>M_UNKNOWN</code> or <code>401 Unauthorized</code> errors. This
may affect users who are redirecting apex-to-www (e.g. <code>example.com</code> -&gt; <code>www.example.com</code>),
and especially users of the Kubernetes <em>Nginx Ingress</em> module, which uses 308 redirect
codes by default. For those Kubernetes users, <a href="https://stackoverflow.com/a/52617528/5096871">this Stackoverflow post</a> 
might be helpful. For other users, switching to a <code>301 Moved Permanently</code> code may be
an option. 308 redirect codes will be supported properly in a future
release of Synapse.</p>
<h2 id="running-a-demo-federation-of-synapses"><a class="header" href="#running-a-demo-federation-of-synapses">Running a demo federation of Synapses</a></h2>
<p>If you want to get up and running quickly with a trio of homeservers in a
private federation, there is a script in the <code>demo</code> directory. This is mainly
useful just for development purposes. See
<a href="https://matrix-org.github.io/synapse/develop/development/demo.html">demo scripts</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="configuration-2"><a class="header" href="#configuration-2">Configuration</a></h1>
<p>This section contains information on tweaking Synapse via the various options in the configuration file. A configuration
file should have been generated when you <a href="usage/configuration/../../setup/installation.html">installed Synapse</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="configuring-synapse"><a class="header" href="#configuring-synapse">Configuring Synapse</a></h1>
<p>This is intended as a guide to the Synapse configuration. The behavior of a Synapse instance can be modified
through the many configuration settings documented here — each config option is explained,
including what the default is, how to change the default and what sort of behaviour the setting governs.
Also included is an example configuration for each setting. If you don't want to spend a lot of time
thinking about options, the config as generated sets sensible defaults for all values. Do note however that the
database defaults to SQLite, which is not recommended for production usage. You can read more on this subject
<a href="usage/configuration/../../setup/installation.html#using-postgresql">here</a>.</p>
<h2 id="config-conventions"><a class="header" href="#config-conventions">Config Conventions</a></h2>
<p>Configuration options that take a time period can be set using a number
followed by a letter. Letters have the following meanings:</p>
<ul>
<li><code>s</code> = second</li>
<li><code>m</code> = minute</li>
<li><code>h</code> = hour</li>
<li><code>d</code> = day</li>
<li><code>w</code> = week</li>
<li><code>y</code> = year</li>
</ul>
<p>For example, setting <code>redaction_retention_period: 5m</code> would remove redacted
messages from the database after 5 minutes, rather than 5 months.</p>
<p>In addition, configuration options referring to size use the following suffixes:</p>
<ul>
<li><code>M</code> = MiB, or 1,048,576 bytes</li>
<li><code>K</code> = KiB, or 1024 bytes</li>
</ul>
<p>For example, setting <code>max_avatar_size: 10M</code> means that Synapse will not accept files larger than 10,485,760 bytes
for a user avatar.</p>
<h3 id="yaml"><a class="header" href="#yaml">YAML</a></h3>
<p>The configuration file is a <a href="https://yaml.org/">YAML</a> file, which means that certain syntax rules
apply if you want your config file to be read properly. A few helpful things to know:</p>
<ul>
<li>
<p><code>#</code> before any option in the config will comment out that setting and either a default (if available) will
be applied or Synapse will ignore the setting. Thus, in example #1 below, the setting will be read and
applied, but in example #2 the setting will not be read and a default will be applied.</p>
<p>Example #1:</p>
<pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
</code></pre>
<p>Example #2:</p>
<pre><code class="language-yaml">#pid_file: DATADIR/homeserver.pid
</code></pre>
</li>
<li>
<p>Indentation matters! The indentation before a setting
will determine whether a given setting is read as part of another
setting, or considered on its own. Thus, in example #1, the <code>enabled</code> setting
is read as a sub-option of the <code>presence</code> setting, and will be properly applied.</p>
<p>However, the lack of indentation before the <code>enabled</code> setting in example #2 means
that when reading the config, Synapse will consider both <code>presence</code> and <code>enabled</code> as
different settings. In this case, <code>presence</code> has no value, and thus a default applied, and <code>enabled</code>
is an option that Synapse doesn't recognize and thus ignores.</p>
<p>Example #1:</p>
<pre><code class="language-yaml">presence:
  enabled: false
</code></pre>
<p>Example #2:</p>
<pre><code class="language-yaml">presence:
enabled: false
</code></pre>
<p>In this manual, all top-level settings (ones with no indentation) are identified
at the beginning of their section (i.e. &quot;### <code>example_setting</code>&quot;) and
the sub-options, if any, are identified and listed in the body of the section.
In addition, each setting has an example of its usage, with the proper indentation
shown.</p>
</li>
</ul>
<h2 id="modules"><a class="header" href="#modules">Modules</a></h2>
<p>Server admins can expand Synapse's functionality with external modules.</p>
<p>See <a href="usage/configuration/../../modules/index.html">here</a> for more
documentation on how to configure or create custom modules for Synapse.</p>
<hr />
<h3 id="modules-1"><a class="header" href="#modules-1"><code>modules</code></a></h3>
<p>Use the <code>module</code> sub-option to add modules under this option to extend functionality.
The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
for the <code>module</code>.</p>
<p>Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">modules:
  - module: my_super_module.MySuperClass
    config:
      do_thing: true
  - module: my_other_super_module.SomeClass
    config: {}
</code></pre>
<hr />
<h2 id="server"><a class="header" href="#server">Server</a></h2>
<p>Define your homeserver name and other base options.</p>
<hr />
<h3 id="server_name"><a class="header" href="#server_name"><code>server_name</code></a></h3>
<p>This sets the public-facing domain of the server.</p>
<p>The <code>server_name</code> name will appear at the end of usernames and room addresses
created on your server. For example if the <code>server_name</code> was example.com,
usernames on your server would be in the format <code>@user:example.com</code></p>
<p>In most cases you should avoid using a matrix specific subdomain such as
matrix.example.com or synapse.example.com as the <code>server_name</code> for the same
reasons you wouldn't use user@email.example.com as your email address.
See <a href="usage/configuration/../../delegate.html">here</a>
for information on how to host Synapse on a subdomain while preserving
a clean <code>server_name</code>.</p>
<p>The <code>server_name</code> cannot be changed later so it is important to
configure this correctly before you start Synapse. It should be all
lowercase and may contain an explicit port.</p>
<p>There is no default for this option.</p>
<p>Example configuration #1:</p>
<pre><code class="language-yaml">server_name: matrix.org
</code></pre>
<p>Example configuration #2:</p>
<pre><code class="language-yaml">server_name: localhost:8080
</code></pre>
<hr />
<h3 id="pid_file"><a class="header" href="#pid_file"><code>pid_file</code></a></h3>
<p>When running Synapse as a daemon, the file to store the pid in. Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
</code></pre>
<hr />
<h3 id="web_client_location"><a class="header" href="#web_client_location"><code>web_client_location</code></a></h3>
<p>The absolute URL to the web client which <code>/</code> will redirect to. Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">web_client_location: https://riot.example.com/
</code></pre>
<hr />
<h3 id="public_baseurl"><a class="header" href="#public_baseurl"><code>public_baseurl</code></a></h3>
<p>The public-facing base URL that clients use to access this Homeserver (not
including _matrix/...). This is the same URL a user might enter into the
'Custom Homeserver URL' field on their client. If you use Synapse with a
reverse proxy, this should be the URL to reach Synapse via the proxy.
Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
<a href="usage/configuration/config_documentation.html#listeners">'listeners'</a> below).</p>
<p>Defaults to <code>https://&lt;server_name&gt;/</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">public_baseurl: https://example.com/
</code></pre>
<hr />
<h3 id="serve_server_wellknown"><a class="header" href="#serve_server_wellknown"><code>serve_server_wellknown</code></a></h3>
<p>By default, other servers will try to reach our server on port 8448, which can
be inconvenient in some environments.</p>
<p>Provided <code>https://&lt;server_name&gt;/</code> on port 443 is routed to Synapse, this
option configures Synapse to serve a file at <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>.
This will tell other servers to send traffic to port 443 instead.</p>
<p>This option currently defaults to false.</p>
<p>See <a href="usage/configuration/../../delegate.html">Delegation of incoming federation traffic</a> for more
information.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">serve_server_wellknown: true
</code></pre>
<hr />
<h3 id="extra_well_known_client_content"><a class="header" href="#extra_well_known_client_content"><code>extra_well_known_client_content </code></a></h3>
<p>This option allows server runners to add arbitrary key-value pairs to the <a href="https://spec.matrix.org/latest/client-server-api/#well-known-uri">client-facing <code>.well-known</code> response</a>.
Note that the <code>public_baseurl</code> config option must be provided for Synapse to serve a response to <code>/.well-known/matrix/client</code> at all.</p>
<p>If this option is provided, it parses the given yaml to json and
serves it on <code>/.well-known/matrix/client</code> endpoint
alongside the standard properties.</p>
<p><em>Added in Synapse 1.62.0.</em></p>
<p>Example configuration:</p>
<pre><code class="language-yaml">extra_well_known_client_content :
  option1: value1
  option2: value2
</code></pre>
<hr />
<h3 id="soft_file_limit"><a class="header" href="#soft_file_limit"><code>soft_file_limit</code></a></h3>
<p>Set the soft limit on the number of file descriptors synapse can use.
Zero is used to indicate synapse should set the soft limit to the hard limit.
Defaults to 0.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">soft_file_limit: 3
</code></pre>
<hr />
<h3 id="presence"><a class="header" href="#presence"><code>presence</code></a></h3>
<p>Presence tracking allows users to see the state (e.g online/offline)
of other local and remote users. Set the <code>enabled</code> sub-option to false to
disable presence tracking on this homeserver. Defaults to true.
This option replaces the previous top-level 'use_presence' option.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">presence:
  enabled: false
</code></pre>
<hr />
<h3 id="require_auth_for_profile_requests"><a class="header" href="#require_auth_for_profile_requests"><code>require_auth_for_profile_requests</code></a></h3>
<p>Whether to require authentication to retrieve profile data (avatars, display names) of other
users through the client API. Defaults to false. Note that profile data is also available
via the federation API, unless <code>allow_profile_lookup_over_federation</code> is set to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">require_auth_for_profile_requests: true
</code></pre>
<hr />
<h3 id="limit_profile_requests_to_users_who_share_rooms"><a class="header" href="#limit_profile_requests_to_users_who_share_rooms"><code>limit_profile_requests_to_users_who_share_rooms</code></a></h3>
<p>Use this option to require a user to share a room with another user in order
to retrieve their profile information. Only checked on Client-Server
requests. Profile requests from other servers should be checked by the
requesting server. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">limit_profile_requests_to_users_who_share_rooms: true
</code></pre>
<hr />
<h3 id="include_profile_data_on_invite"><a class="header" href="#include_profile_data_on_invite"><code>include_profile_data_on_invite</code></a></h3>
<p>Use this option to prevent a user's profile data from being retrieved and
displayed in a room until they have joined it. By default, a user's
profile data is included in an invite event, regardless of the values
of the above two settings, and whether or not the users share a server.
Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">include_profile_data_on_invite: false
</code></pre>
<hr />
<h3 id="allow_public_rooms_without_auth"><a class="header" href="#allow_public_rooms_without_auth"><code>allow_public_rooms_without_auth</code></a></h3>
<p>If set to true, removes the need for authentication to access the server's
public rooms directory through the client API, meaning that anyone can
query the room directory. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allow_public_rooms_without_auth: true
</code></pre>
<hr />
<h3 id="allow_public_rooms_over_federation"><a class="header" href="#allow_public_rooms_over_federation"><code>allow_public_rooms_over_federation</code></a></h3>
<p>If set to true, allows any other homeserver to fetch the server's public
rooms directory via federation. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allow_public_rooms_over_federation: true
</code></pre>
<hr />
<h3 id="default_room_version"><a class="header" href="#default_room_version"><code>default_room_version</code></a></h3>
<p>The default room version for newly created rooms on this server.</p>
<p>Known room versions are listed <a href="https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions">here</a></p>
<p>For example, for room version 1, <code>default_room_version</code> should be set
to &quot;1&quot;.</p>
<p>Currently defaults to <a href="https://spec.matrix.org/v1.5/rooms/v10/">&quot;10&quot;</a>.</p>
<p><em>Changed in Synapse 1.76:</em> the default version room version was increased from <a href="https://spec.matrix.org/v1.5/rooms/v9/">9</a> to <a href="https://spec.matrix.org/v1.5/rooms/v10/">10</a>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">default_room_version: &quot;8&quot;
</code></pre>
<hr />
<h3 id="gc_thresholds"><a class="header" href="#gc_thresholds"><code>gc_thresholds</code></a></h3>
<p>The garbage collection threshold parameters to pass to <code>gc.set_threshold</code>, if defined.
Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">gc_thresholds: [700, 10, 10]
</code></pre>
<hr />
<h3 id="gc_min_interval"><a class="header" href="#gc_min_interval"><code>gc_min_interval</code></a></h3>
<p>The minimum time in seconds between each GC for a generation, regardless of
the GC thresholds. This ensures that we don't do GC too frequently. A value of <code>[1s, 10s, 30s]</code>
indicates that a second must pass between consecutive generation 0 GCs, etc.</p>
<p>Defaults to <code>[1s, 10s, 30s]</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">gc_min_interval: [0.5s, 30s, 1m]
</code></pre>
<hr />
<h3 id="filter_timeline_limit"><a class="header" href="#filter_timeline_limit"><code>filter_timeline_limit</code></a></h3>
<p>Set the limit on the returned events in the timeline in the get
and sync operations. Defaults to 100. A value of -1 means no upper limit.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">filter_timeline_limit: 5000
</code></pre>
<hr />
<h3 id="block_non_admin_invites"><a class="header" href="#block_non_admin_invites"><code>block_non_admin_invites</code></a></h3>
<p>Whether room invites to users on this server should be blocked
(except those sent by local server admins). Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">block_non_admin_invites: true
</code></pre>
<hr />
<h3 id="enable_search"><a class="header" href="#enable_search"><code>enable_search</code></a></h3>
<p>If set to false, new messages will not be indexed for searching and users
will receive errors when searching for messages. Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_search: false
</code></pre>
<hr />
<h3 id="ip_range_blacklist"><a class="header" href="#ip_range_blacklist"><code>ip_range_blacklist</code></a></h3>
<p>This option prevents outgoing requests from being sent to the specified blacklisted IP address
CIDR ranges. If this option is not specified then it defaults to private IP
address ranges (see the example below).</p>
<p>The blacklist applies to the outbound requests for federation, identity servers,
push servers, and for checking key validity for third-party invite events.</p>
<p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
listed here, since they correspond to unroutable addresses.)</p>
<p>This option replaces <code>federation_ip_range_blacklist</code> in Synapse v1.25.0.</p>
<p>Note: The value is ignored when an HTTP proxy is in use.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">ip_range_blacklist:
  - '127.0.0.0/8'
  - '10.0.0.0/8'
  - '172.16.0.0/12'
  - '192.168.0.0/16'
  - '100.64.0.0/10'
  - '192.0.0.0/24'
  - '169.254.0.0/16'
  - '192.88.99.0/24'
  - '198.18.0.0/15'
  - '192.0.2.0/24'
  - '198.51.100.0/24'
  - '203.0.113.0/24'
  - '224.0.0.0/4'
  - '::1/128'
  - 'fe80::/10'
  - 'fc00::/7'
  - '2001:db8::/32'
  - 'ff00::/8'
  - 'fec0::/10'
</code></pre>
<hr />
<h3 id="ip_range_whitelist"><a class="header" href="#ip_range_whitelist"><code>ip_range_whitelist</code></a></h3>
<p>List of IP address CIDR ranges that should be allowed for federation,
identity servers, push servers, and for checking key validity for
third-party invite events. This is useful for specifying exceptions to
wide-ranging blacklisted target IP ranges - e.g. for communication with
a push server only visible in your network.</p>
<p>This whitelist overrides <code>ip_range_blacklist</code> and defaults to an empty
list.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">ip_range_whitelist:
   - '192.168.1.1'
</code></pre>
<hr />
<h3 id="listeners"><a class="header" href="#listeners"><code>listeners</code></a></h3>
<p>List of ports that Synapse should listen on, their purpose and their
configuration.</p>
<p>Sub-options for each listener include:</p>
<ul>
<li>
<p><code>port</code>: the TCP port to bind to.</p>
</li>
<li>
<p><code>tag</code>: An alias for the port in the logger name. If set the tag is logged instead
of the port. Default to <code>None</code>, is optional and only valid for listener with <code>type: http</code>.
See the docs <a href="usage/configuration/../administration/request_log.html">request log format</a>.</p>
</li>
<li>
<p><code>bind_addresses</code>: a list of local addresses to listen on. The default is
'all local interfaces'.</p>
</li>
<li>
<p><code>type</code>: the type of listener. Normally <code>http</code>, but other valid options are:</p>
<ul>
<li>
<p><code>manhole</code>: (see the docs <a href="usage/configuration/../../manhole.html">here</a>),</p>
</li>
<li>
<p><code>metrics</code>: (see the docs <a href="usage/configuration/../../metrics-howto.html">here</a>),</p>
</li>
</ul>
</li>
<li>
<p><code>tls</code>: set to true to enable TLS for this listener. Will use the TLS key/cert specified in tls_private_key_path / tls_certificate_path.</p>
</li>
<li>
<p><code>x_forwarded</code>: Only valid for an 'http' listener. Set to true to use the X-Forwarded-For header as the client IP. Useful when Synapse is
behind a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
</li>
<li>
<p><code>request_id_header</code>: The header extracted from each incoming request that is
used as the basis for the request ID. The request ID is used in
<a href="usage/configuration/../administration/request_log.html#request-log-format">logs</a> and tracing to
correlate and match up requests. When unset, Synapse will automatically
generate sequential request IDs. This option is useful when Synapse is behind
a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
<p><em>Added in Synapse 1.68.0.</em></p>
</li>
<li>
<p><code>resources</code>: Only valid for an 'http' listener. A list of resources to host
on this port. Sub-options for each resource are:</p>
<ul>
<li>
<p><code>names</code>: a list of names of HTTP resources. See below for a list of valid resource names.</p>
</li>
<li>
<p><code>compress</code>: set to true to enable gzip compression on HTTP bodies for this resource. This is currently only supported with the
<code>client</code>, <code>consent</code>, <code>metrics</code> and <code>federation</code> resources.</p>
</li>
</ul>
</li>
<li>
<p><code>additional_resources</code>: Only valid for an 'http' listener. A map of
additional endpoints which should be loaded via dynamic modules.</p>
</li>
</ul>
<p>Unix socket support (<em>Added in Synapse 1.89.0</em>):</p>
<ul>
<li><code>path</code>: A path and filename for a Unix socket. Make sure it is located in a
directory with read and write permissions, and that it already exists (the directory
will not be created). Defaults to <code>None</code>.
<ul>
<li><strong>Note</strong>: The use of both <code>path</code> and <code>port</code> options for the same <code>listener</code> is not
compatible.</li>
<li>The <code>x_forwarded</code> option defaults to true  when using Unix sockets and can be omitted.</li>
<li>Other options that would not make sense to use with a UNIX socket, such as 
<code>bind_addresses</code> and <code>tls</code> will be ignored and can be removed.</li>
</ul>
</li>
<li><code>mode</code>: The file permissions to set on the UNIX socket. Defaults to <code>666</code></li>
<li><strong>Note:</strong> Must be set as <code>type: http</code> (does not support <code>metrics</code> and <code>manhole</code>). 
Also make sure that <code>metrics</code> is not included in <code>resources</code> -&gt; <code>names</code></li>
</ul>
<p>Valid resource names are:</p>
<ul>
<li>
<p><code>client</code>: the client-server API (/_matrix/client), and the synapse admin API (/_synapse/admin). Also implies <code>media</code> and <code>static</code>.</p>
</li>
<li>
<p><code>consent</code>: user consent forms (/_matrix/consent). See <a href="usage/configuration/../../consent_tracking.html">here</a> for more.</p>
</li>
<li>
<p><code>federation</code>: the server-server API (/_matrix/federation). Also implies <code>media</code>, <code>keys</code>, <code>openid</code></p>
</li>
<li>
<p><code>keys</code>: the key discovery API (/_matrix/key).</p>
</li>
<li>
<p><code>media</code>: the media API (/_matrix/media).</p>
</li>
<li>
<p><code>metrics</code>: the metrics interface. See <a href="usage/configuration/../../metrics-howto.html">here</a>. (Not compatible with Unix sockets)</p>
</li>
<li>
<p><code>openid</code>: OpenID authentication. See <a href="usage/configuration/../../openid.html">here</a>.</p>
</li>
<li>
<p><code>replication</code>: the HTTP replication API (/_synapse/replication). See <a href="usage/configuration/../../workers.html">here</a>.</p>
</li>
<li>
<p><code>static</code>: static resources under synapse/static (/_matrix/static). (Mostly useful for 'fallback authentication'.)</p>
</li>
<li>
<p><code>health</code>: the <a href="usage/configuration/../../reverse_proxy.html#health-check-endpoint">health check endpoint</a>. This endpoint
is by default active for all other resources and does not have to be activated separately.
This is only useful if you want to use the health endpoint explicitly on a dedicated port or
for <a href="usage/configuration/../../workers.html">workers</a> and containers without listener e.g.
<a href="usage/configuration/../../workers.html#notifying-application-services">application services</a>.</p>
</li>
</ul>
<p>Example configuration #1:</p>
<pre><code class="language-yaml">listeners:
  # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  #
  # (Note that you will also need to give Synapse a TLS key and certificate: see the TLS section
  # below.)
  #
  - port: 8448
    type: http
    tls: true
    resources:
      - names: [client, federation]
</code></pre>
<p>Example configuration #2:</p>
<pre><code class="language-yaml">listeners:
  # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  # that unwraps TLS.
  #
  # If you plan to use a reverse proxy, please see
  # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  #
  - port: 8008
    tls: false
    type: http
    x_forwarded: true
    bind_addresses: ['::1', '127.0.0.1']

    resources:
      - names: [client, federation]
        compress: false

    # example additional_resources:
    additional_resources:
      &quot;/_matrix/my/custom/endpoint&quot;:
        module: my_module.CustomRequestHandler
        config: {}

  # Turn on the twisted ssh manhole service on localhost on the given
  # port.
  - port: 9000
    bind_addresses: ['::1', '127.0.0.1']
    type: manhole
</code></pre>
<p>Example configuration #3:</p>
<pre><code class="language-yaml">listeners:
  # Unix socket listener: Ideal for Synapse deployments behind a reverse proxy, offering
  # lightweight interprocess communication without TCP/IP overhead, avoid port
  # conflicts, and providing enhanced security through system file permissions.
  #
  # Note that x_forwarded will default to true, when using a UNIX socket. Please see
  # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  #
  - path: /var/run/synapse/main_public.sock
    type: http
    resources:
      - names: [client, federation]
</code></pre>
<hr />
<h3 id="manhole_settings"><a class="header" href="#manhole_settings"><code>manhole_settings</code></a></h3>
<p>Connection settings for the manhole. You can find more information
on the manhole <a href="usage/configuration/../../manhole.html">here</a>. Manhole sub-options include:</p>
<ul>
<li><code>username</code> : the username for the manhole. This defaults to 'matrix'.</li>
<li><code>password</code>: The password for the manhole. This defaults to 'rabbithole'.</li>
<li><code>ssh_priv_key_path</code> and <code>ssh_pub_key_path</code>: The private and public SSH key pair used to encrypt the manhole traffic.
If these are left unset, then hardcoded and non-secret keys are used,
which could allow traffic to be intercepted if sent over a public network.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">manhole_settings:
  username: manhole
  password: mypassword
  ssh_priv_key_path: CONFDIR/id_rsa
  ssh_pub_key_path: CONFDIR/id_rsa.pub
</code></pre>
<hr />
<h3 id="dummy_events_threshold"><a class="header" href="#dummy_events_threshold"><code>dummy_events_threshold</code></a></h3>
<p>Forward extremities can build up in a room due to networking delays between
homeservers. Once this happens in a large room, calculation of the state of
that room can become quite expensive. To mitigate this, once the number of
forward extremities reaches a given threshold, Synapse will send an
<code>org.matrix.dummy_event</code> event, which will reduce the forward extremities
in the room.</p>
<p>This setting defines the threshold (i.e. number of forward extremities in the room) at which dummy events are sent.
The default value is 10.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">dummy_events_threshold: 5
</code></pre>
<hr />
<h3 id="delete_stale_devices_after"><a class="header" href="#delete_stale_devices_after"><code>delete_stale_devices_after</code></a></h3>
<p>An optional duration. If set, Synapse will run a daily background task to log out and
delete any device that hasn't been accessed for more than the specified amount of time.</p>
<p>Defaults to no duration, which means devices are never pruned.</p>
<p><strong>Note:</strong> This task will always run on the main process, regardless of the value of
<code>run_background_tasks_on</code>. This is due to workers currently not having the ability to
delete devices.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">delete_stale_devices_after: 1y
</code></pre>
<hr />
<h3 id="email-3"><a class="header" href="#email-3"><code>email</code></a></h3>
<p>Configuration for sending emails from Synapse.</p>
<p>Server admins can configure custom templates for email content. See
<a href="usage/configuration/../../templates.html">here</a> for more information.</p>
<p>This setting has the following sub-options:</p>
<ul>
<li>
<p><code>smtp_host</code>: The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.</p>
</li>
<li>
<p><code>smtp_port</code>: The port on the mail server for outgoing SMTP. Defaults to 465 if <code>force_tls</code> is true, else 25.</p>
<p><em>Changed in Synapse 1.64.0:</em> the default port is now aware of <code>force_tls</code>.</p>
</li>
<li>
<p><code>smtp_user</code> and <code>smtp_pass</code>: Username/password for authentication to the SMTP server. By default, no
authentication is attempted.</p>
</li>
<li>
<p><code>force_tls</code>: By default, Synapse connects over plain text and then optionally upgrades
to TLS via STARTTLS. If this option is set to true, TLS is used from the start (Implicit TLS),
and the option <code>require_transport_security</code> is ignored.
It is recommended to enable this if supported by your mail server.</p>
<p><em>New in Synapse 1.64.0.</em></p>
</li>
<li>
<p><code>require_transport_security</code>: Set to true to require TLS transport security for SMTP.
By default, Synapse will connect over plain text, and will then switch to
TLS via STARTTLS <em>if the SMTP server supports it</em>. If this option is set,
Synapse will refuse to connect unless the server supports STARTTLS.</p>
</li>
<li>
<p><code>enable_tls</code>: By default, if the server supports TLS, it will be used, and the server
must present a certificate that is valid for 'smtp_host'. If this option
is set to false, TLS will not be used.</p>
</li>
<li>
<p><code>notif_from</code>: defines the &quot;From&quot; address to use when sending emails.
It must be set if email sending is enabled. The placeholder '%(app)s' will be replaced by the application name,
which is normally set in <code>app_name</code>, but may be overridden by the
Matrix client application. Note that the placeholder must be written '%(app)s', including the
trailing 's'.</p>
</li>
<li>
<p><code>app_name</code>: <code>app_name</code> defines the default value for '%(app)s' in <code>notif_from</code> and email
subjects. It defaults to 'Matrix'.</p>
</li>
<li>
<p><code>enable_notifs</code>: Set to true to enable sending emails for messages that the user
has missed. Disabled by default.</p>
</li>
<li>
<p><code>notif_for_new_users</code>: Set to false to disable automatic subscription to email
notifications for new users. Enabled by default.</p>
</li>
<li>
<p><code>client_base_url</code>: Custom URL for client links within the email notifications. By default
links will be based on &quot;https://matrix.to&quot;. (This setting used to be called <code>riot_base_url</code>;
the old name is still supported for backwards-compatibility but is now deprecated.)</p>
</li>
<li>
<p><code>validation_token_lifetime</code>: Configures the time that a validation email will expire after sending.
Defaults to 1h.</p>
</li>
<li>
<p><code>invite_client_location</code>: The web client location to direct users to during an invite. This is passed
to the identity server as the <code>org.matrix.web_client_location</code> key. Defaults
to unset, giving no guidance to the identity server.</p>
</li>
<li>
<p><code>subjects</code>: Subjects to use when sending emails from Synapse. The placeholder '%(app)s' will
be replaced with the value of the <code>app_name</code> setting, or by a value dictated by the Matrix client application.
In addition, each subject can use the following placeholders: '%(person)s', which will be replaced by the displayname
of the user(s) that sent the message(s), e.g. &quot;Alice and Bob&quot;, and '%(room)s', which will be replaced by the name of the room the
message(s) have been sent to, e.g. &quot;My super room&quot;. In addition, emails related to account administration will
can use the '%(server_name)s' placeholder, which will be replaced by the value of the
<code>server_name</code> setting in your Synapse configuration.</p>
<p>Here is a list of subjects for notification emails that can be set:</p>
<ul>
<li><code>message_from_person_in_room</code>: Subject to use to notify about one message from one or more user(s) in a
room which has a name. Defaults to &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;</li>
<li><code>message_from_person</code>: Subject to use to notify about one message from one or more user(s) in a
room which doesn't have a name. Defaults to &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;</li>
<li><code>messages_from_person</code>: Subject to use to notify about multiple messages from one or more users in
a room which doesn't have a name. Defaults to &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;</li>
<li><code>messages_in_room</code>: Subject to use to notify about multiple messages in a room which has a
name. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;</li>
<li><code>messages_in_room_and_others</code>: Subject to use to notify about multiple messages in multiple rooms.
Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;</li>
<li><code>messages_from_person_and_others</code>: Subject to use to notify about multiple messages from multiple persons in
multiple rooms. This is similar to the setting above except it's used when
the room in which the notification was triggered has no name. Defaults to
&quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;</li>
<li><code>invite_from_person_to_room</code>: Subject to use to notify about an invite to a room which has a name.
Defaults to  &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;</li>
<li><code>invite_from_person</code>: Subject to use to notify about an invite to a room which doesn't have a
name. Defaults to &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;</li>
<li><code>password_reset</code>: Subject to use when sending a password reset email. Defaults to &quot;[%(server_name)s] Password reset&quot;</li>
<li><code>email_validation</code>: Subject to use when sending a verification email to assert an address's
ownership. Defaults to &quot;[%(server_name)s] Validate your email&quot;</li>
</ul>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">email:
  smtp_host: mail.server
  smtp_port: 587
  smtp_user: &quot;exampleusername&quot;
  smtp_pass: &quot;examplepassword&quot;
  force_tls: true
  require_transport_security: true
  enable_tls: false
  notif_from: &quot;Your Friendly %(app)s homeserver &lt;noreply@example.com&gt;&quot;
  app_name: my_branded_matrix_server
  enable_notifs: true
  notif_for_new_users: false
  client_base_url: &quot;http://localhost/riot&quot;
  validation_token_lifetime: 15m
  invite_client_location: https://app.element.io

  subjects:
    message_from_person_in_room: &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;
    message_from_person: &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;
    messages_from_person: &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;
    messages_in_room: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;
    messages_in_room_and_others: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;
    messages_from_person_and_others: &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;
    invite_from_person_to_room: &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;
    invite_from_person: &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;
    password_reset: &quot;[%(server_name)s] Password reset&quot;
    email_validation: &quot;[%(server_name)s] Validate your email&quot;
</code></pre>
<h2 id="homeserver-blocking"><a class="header" href="#homeserver-blocking">Homeserver blocking</a></h2>
<p>Useful options for Synapse admins.</p>
<hr />
<h3 id="admin_contact"><a class="header" href="#admin_contact"><code>admin_contact</code></a></h3>
<p>How to reach the server admin, used in <code>ResourceLimitError</code>. Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">admin_contact: 'mailto:admin@server.com'
</code></pre>
<hr />
<h3 id="hs_disabled-and-hs_disabled_message"><a class="header" href="#hs_disabled-and-hs_disabled_message"><code>hs_disabled</code> and <code>hs_disabled_message</code></a></h3>
<p>Blocks users from connecting to the homeserver and provides a human-readable reason
why the connection was blocked. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">hs_disabled: true
hs_disabled_message: 'Reason for why the HS is blocked'
</code></pre>
<hr />
<h3 id="limit_usage_by_mau"><a class="header" href="#limit_usage_by_mau"><code>limit_usage_by_mau</code></a></h3>
<p>This option disables/enables monthly active user blocking. Used in cases where the admin or
server owner wants to limit to the number of monthly active users. When enabled and a limit is
reached the server returns a <code>ResourceLimitError</code> with error type <code>Codes.RESOURCE_LIMIT_EXCEEDED</code>.
Defaults to false. If this is enabled, a value for <code>max_mau_value</code> must also be set.</p>
<p>See <a href="usage/configuration/../administration/monthly_active_users.html">Monthly Active Users</a> for details on how to configure MAU.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">limit_usage_by_mau: true
</code></pre>
<hr />
<h3 id="max_mau_value"><a class="header" href="#max_mau_value"><code>max_mau_value</code></a></h3>
<p>This option sets the hard limit of monthly active users above which the server will start
blocking user actions if <code>limit_usage_by_mau</code> is enabled. Defaults to 0.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">max_mau_value: 50
</code></pre>
<hr />
<h3 id="mau_trial_days"><a class="header" href="#mau_trial_days"><code>mau_trial_days</code></a></h3>
<p>The option <code>mau_trial_days</code> is a means to add a grace period for active users. It
means that users must be active for the specified number of days before they
can be considered active and guards against the case where lots of users
sign up in a short space of time never to return after their initial
session. Defaults to 0.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">mau_trial_days: 5
</code></pre>
<hr />
<h3 id="mau_appservice_trial_days"><a class="header" href="#mau_appservice_trial_days"><code>mau_appservice_trial_days</code></a></h3>
<p>The option <code>mau_appservice_trial_days</code> is similar to <code>mau_trial_days</code>, but applies a different
trial number if the user was registered by an appservice. A value
of 0 means no trial days are applied. Appservices not listed in this dictionary
use the value of <code>mau_trial_days</code> instead.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">mau_appservice_trial_days:
  my_appservice_id: 3
  another_appservice_id: 6
</code></pre>
<hr />
<h3 id="mau_limit_alerting"><a class="header" href="#mau_limit_alerting"><code>mau_limit_alerting</code></a></h3>
<p>The option <code>mau_limit_alerting</code> is a means of limiting client-side alerting
should the mau limit be reached. This is useful for small instances
where the admin has 5 mau seats (say) for 5 specific people and no
interest increasing the mau limit further. Defaults to true, which
means that alerting is enabled.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">mau_limit_alerting: false
</code></pre>
<hr />
<h3 id="mau_stats_only"><a class="header" href="#mau_stats_only"><code>mau_stats_only</code></a></h3>
<p>If enabled, the metrics for the number of monthly active users will
be populated, however no one will be limited based on these numbers. If <code>limit_usage_by_mau</code>
is true, this is implied to be true. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">mau_stats_only: true
</code></pre>
<hr />
<h3 id="mau_limit_reserved_threepids"><a class="header" href="#mau_limit_reserved_threepids"><code>mau_limit_reserved_threepids</code></a></h3>
<p>Sometimes the server admin will want to ensure certain accounts are
never blocked by mau checking. These accounts are specified by this option.
Defaults to none. Add accounts by specifying the <code>medium</code> and <code>address</code> of the
reserved threepid (3rd party identifier).</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">mau_limit_reserved_threepids:
  - medium: 'email'
    address: 'reserved_user@example.com'
</code></pre>
<hr />
<h3 id="server_context"><a class="header" href="#server_context"><code>server_context</code></a></h3>
<p>This option is used by phonehome stats to group together related servers.
Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">server_context: context
</code></pre>
<hr />
<h3 id="limit_remote_rooms"><a class="header" href="#limit_remote_rooms"><code>limit_remote_rooms</code></a></h3>
<p>When this option is enabled, the room &quot;complexity&quot; will be checked before a user
joins a new remote room. If it is above the complexity limit, the server will
disallow joining, or will instantly leave. This is useful for homeservers that are
resource-constrained. Options for this setting include:</p>
<ul>
<li><code>enabled</code>: whether this check is enabled. Defaults to false.</li>
<li><code>complexity</code>: the limit above which rooms cannot be joined. The default is 1.0.</li>
<li><code>complexity_error</code>: override the error which is returned when the room is too complex with a
custom message.</li>
<li><code>admins_can_join</code>: allow server admins to join complex rooms. Default is false.</li>
</ul>
<p>Room complexity is an arbitrary measure based on factors such as the number of
users in the room.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">limit_remote_rooms:
  enabled: true
  complexity: 0.5
  complexity_error: &quot;I can't let you do that, Dave.&quot;
  admins_can_join: true
</code></pre>
<hr />
<h3 id="require_membership_for_aliases"><a class="header" href="#require_membership_for_aliases"><code>require_membership_for_aliases</code></a></h3>
<p>Whether to require a user to be in the room to add an alias to it.
Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">require_membership_for_aliases: false
</code></pre>
<hr />
<h3 id="allow_per_room_profiles"><a class="header" href="#allow_per_room_profiles"><code>allow_per_room_profiles</code></a></h3>
<p>Whether to allow per-room membership profiles through the sending of membership
events with profile information that differs from the target's global profile.
Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allow_per_room_profiles: false
</code></pre>
<hr />
<h3 id="max_avatar_size"><a class="header" href="#max_avatar_size"><code>max_avatar_size</code></a></h3>
<p>The largest permissible file size in bytes for a user avatar. Defaults to no restriction.
Use M for MB and K for KB.</p>
<p>Note that user avatar changes will not work if this is set without using Synapse's media repository.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">max_avatar_size: 10M
</code></pre>
<hr />
<h3 id="allowed_avatar_mimetypes"><a class="header" href="#allowed_avatar_mimetypes"><code>allowed_avatar_mimetypes</code></a></h3>
<p>The MIME types allowed for user avatars. Defaults to no restriction.</p>
<p>Note that user avatar changes will not work if this is set without
using Synapse's media repository.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allowed_avatar_mimetypes: [&quot;image/png&quot;, &quot;image/jpeg&quot;, &quot;image/gif&quot;]
</code></pre>
<hr />
<h3 id="redaction_retention_period"><a class="header" href="#redaction_retention_period"><code>redaction_retention_period</code></a></h3>
<p>How long to keep redacted events in unredacted form in the database. After
this period redacted events get replaced with their redacted form in the DB.</p>
<p>Synapse will check whether the rentention period has concluded for redacted
events every 5 minutes. Thus, even if this option is set to <code>0</code>, Synapse may
still take up to 5 minutes to purge redacted events from the database.</p>
<p>Defaults to <code>7d</code>. Set to <code>null</code> to disable.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">redaction_retention_period: 28d
</code></pre>
<hr />
<h3 id="user_ips_max_age"><a class="header" href="#user_ips_max_age"><code>user_ips_max_age</code></a></h3>
<p>How long to track users' last seen time and IPs in the database.</p>
<p>Defaults to <code>28d</code>. Set to <code>null</code> to disable clearing out of old rows.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">user_ips_max_age: 14d
</code></pre>
<hr />
<h3 id="request_token_inhibit_3pid_errors"><a class="header" href="#request_token_inhibit_3pid_errors"><code>request_token_inhibit_3pid_errors</code></a></h3>
<p>Inhibits the <code>/requestToken</code> endpoints from returning an error that might leak
information about whether an e-mail address is in use or not on this
homeserver. Defaults to false.
Note that for some endpoints the error situation is the e-mail already being
used, and for others the error is entering the e-mail being unused.
If this option is enabled, instead of returning an error, these endpoints will
act as if no error happened and return a fake session ID ('sid') to clients.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">request_token_inhibit_3pid_errors: true
</code></pre>
<hr />
<h3 id="next_link_domain_whitelist"><a class="header" href="#next_link_domain_whitelist"><code>next_link_domain_whitelist</code></a></h3>
<p>A list of domains that the domain portion of <code>next_link</code> parameters
must match.</p>
<p>This parameter is optionally provided by clients while requesting
validation of an email or phone number, and maps to a link that
users will be automatically redirected to after validation
succeeds. Clients can make use this parameter to aid the validation
process.</p>
<p>The whitelist is applied whether the homeserver or an identity server is handling validation.</p>
<p>The default value is no whitelist functionality; all domains are
allowed. Setting this value to an empty list will instead disallow
all domains.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">next_link_domain_whitelist: [&quot;matrix.org&quot;]
</code></pre>
<hr />
<h3 id="templates-and-custom_template_directory"><a class="header" href="#templates-and-custom_template_directory"><code>templates</code> and <code>custom_template_directory</code></a></h3>
<p>These options define templates to use when generating email or HTML page contents.
The <code>custom_template_directory</code> determines which directory Synapse will try to
find template files in to use to generate email or HTML page contents.
If not set, or a file is not found within the template directory, a default
template from within the Synapse package will be used.</p>
<p>See <a href="usage/configuration/../../templates.html">here</a> for more
information about using custom templates.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">templates:
  custom_template_directory: /path/to/custom/templates/
</code></pre>
<hr />
<h3 id="retention"><a class="header" href="#retention"><code>retention</code></a></h3>
<p>This option and the associated options determine message retention policy at the
server level.</p>
<p>Room admins and mods can define a retention period for their rooms using the
<code>m.room.retention</code> state event, and server admins can cap this period by setting
the <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> config options.</p>
<p>If this feature is enabled, Synapse will regularly look for and purge events
which are older than the room's maximum retention period. Synapse will also
filter events received over federation so that events that should have been
purged are ignored and not stored again.</p>
<p>The message retention policies feature is disabled by default. Please be advised
that enabling this feature carries some risk. There are known bugs with the implementation
which can cause database corruption. Setting retention to delete older history
is less risky than deleting newer history but in general caution is advised when enabling this
experimental feature. You can read more about this feature <a href="usage/configuration/../../message_retention_policies.html">here</a>.</p>
<p>This setting has the following sub-options:</p>
<ul>
<li>
<p><code>default_policy</code>: Default retention policy. If set, Synapse will apply it to rooms that lack the
'm.room.retention' state event. This option is further specified by the
<code>min_lifetime</code> and <code>max_lifetime</code> sub-options associated with it. Note that the
value of <code>min_lifetime</code> doesn't matter much because Synapse doesn't take it into account yet.</p>
</li>
<li>
<p><code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code>: Retention policy limits. If
set, and the state of a room contains a <code>m.room.retention</code> event in its state
which contains a <code>min_lifetime</code> or a <code>max_lifetime</code> that's out of these bounds,
Synapse will cap the room's policy to these limits when running purge jobs.</p>
</li>
<li>
<p><code>purge_jobs</code> and the associated <code>shortest_max_lifetime</code> and <code>longest_max_lifetime</code> sub-options:
Server admins can define the settings of the background jobs purging the
events whose lifetime has expired under the <code>purge_jobs</code> section.</p>
<p>If no configuration is provided for this option, a single job will be set up to delete
expired events in every room daily.</p>
<p>Each job's configuration defines which range of message lifetimes the job
takes care of. For example, if <code>shortest_max_lifetime</code> is '2d' and
<code>longest_max_lifetime</code> is '3d', the job will handle purging expired events in
rooms whose state defines a <code>max_lifetime</code> that's both higher than 2 days, and
lower than or equal to 3 days. Both the minimum and the maximum value of a
range are optional, e.g. a job with no <code>shortest_max_lifetime</code> and a
<code>longest_max_lifetime</code> of '3d' will handle every room with a retention policy
whose <code>max_lifetime</code> is lower than or equal to three days.</p>
<p>The rationale for this per-job configuration is that some rooms might have a
retention policy with a low <code>max_lifetime</code>, where history needs to be purged
of outdated messages on a more frequent basis than for the rest of the rooms
(e.g. every 12h), but not want that purge to be performed by a job that's
iterating over every room it knows, which could be heavy on the server.</p>
<p>If any purge job is configured, it is strongly recommended to have at least
a single job with neither <code>shortest_max_lifetime</code> nor <code>longest_max_lifetime</code>
set, or one job without <code>shortest_max_lifetime</code> and one job without
<code>longest_max_lifetime</code> set. Otherwise some rooms might be ignored, even if
<code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> are set, because capping a
room's policy to these values is done after the policies are retrieved from
Synapse's database (which is done using the range specified in a purge job's
configuration).</p>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">retention:
  enabled: true
  default_policy:
    min_lifetime: 1d
    max_lifetime: 1y
  allowed_lifetime_min: 1d
  allowed_lifetime_max: 1y
  purge_jobs:
    - longest_max_lifetime: 3d
      interval: 12h
    - shortest_max_lifetime: 3d
      interval: 1d
</code></pre>
<hr />
<h2 id="tls"><a class="header" href="#tls">TLS</a></h2>
<p>Options related to TLS.</p>
<hr />
<h3 id="tls_certificate_path"><a class="header" href="#tls_certificate_path"><code>tls_certificate_path</code></a></h3>
<p>This option specifies a PEM-encoded X509 certificate for TLS.
This certificate, as of Synapse 1.0, will need to be a valid and verifiable
certificate, signed by a recognised Certificate Authority. Defaults to none.</p>
<p>Be sure to use a <code>.pem</code> file that includes the full certificate chain including
any intermediate certificates (for instance, if using certbot, use
<code>fullchain.pem</code> as your certificate, not <code>cert.pem</code>).</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">tls_certificate_path: &quot;CONFDIR/SERVERNAME.tls.crt&quot;
</code></pre>
<hr />
<h3 id="tls_private_key_path"><a class="header" href="#tls_private_key_path"><code>tls_private_key_path</code></a></h3>
<p>PEM-encoded private key for TLS. Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">tls_private_key_path: &quot;CONFDIR/SERVERNAME.tls.key&quot;
</code></pre>
<hr />
<h3 id="federation_verify_certificates"><a class="header" href="#federation_verify_certificates"><code>federation_verify_certificates</code></a></h3>
<p>Whether to verify TLS server certificates for outbound federation requests.</p>
<p>Defaults to true. To disable certificate verification, set the option to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_verify_certificates: false
</code></pre>
<hr />
<h3 id="federation_client_minimum_tls_version"><a class="header" href="#federation_client_minimum_tls_version"><code>federation_client_minimum_tls_version</code></a></h3>
<p>The minimum TLS version that will be used for outbound federation requests.</p>
<p>Defaults to <code>1</code>. Configurable to <code>1</code>, <code>1.1</code>, <code>1.2</code>, or <code>1.3</code>. Note
that setting this value higher than <code>1.2</code> will prevent federation to most
of the public Matrix network: only configure it to <code>1.3</code> if you have an
entirely private federation setup and you can ensure TLS 1.3 support.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_client_minimum_tls_version: 1.2
</code></pre>
<hr />
<h3 id="federation_certificate_verification_whitelist"><a class="header" href="#federation_certificate_verification_whitelist"><code>federation_certificate_verification_whitelist</code></a></h3>
<p>Skip federation certificate verification on a given whitelist
of domains.</p>
<p>This setting should only be used in very specific cases, such as
federation over Tor hidden services and similar. For private networks
of homeservers, you likely want to use a private CA instead.</p>
<p>Only effective if <code>federation_verify_certificates</code> is <code>true</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_certificate_verification_whitelist:
  - lon.example.com
  - &quot;*.domain.com&quot;
  - &quot;*.onion&quot;
</code></pre>
<hr />
<h3 id="federation_custom_ca_list"><a class="header" href="#federation_custom_ca_list"><code>federation_custom_ca_list</code></a></h3>
<p>List of custom certificate authorities for federation traffic.</p>
<p>This setting should only normally be used within a private network of
homeservers.</p>
<p>Note that this list will replace those that are provided by your
operating environment. Certificates must be in PEM format.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_custom_ca_list:
  - myCA1.pem
  - myCA2.pem
  - myCA3.pem
</code></pre>
<hr />
<h2 id="federation"><a class="header" href="#federation">Federation</a></h2>
<p>Options related to federation.</p>
<hr />
<h3 id="federation_domain_whitelist"><a class="header" href="#federation_domain_whitelist"><code>federation_domain_whitelist</code></a></h3>
<p>Restrict federation to the given whitelist of domains.
N.B. we recommend also firewalling your federation listener to limit
inbound federation traffic as early as possible, rather than relying
purely on this application-layer restriction.  If not specified, the
default is to whitelist everything.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_domain_whitelist:
  - lon.example.com
  - nyc.example.com
  - syd.example.com
</code></pre>
<hr />
<h3 id="federation_metrics_domains"><a class="header" href="#federation_metrics_domains"><code>federation_metrics_domains</code></a></h3>
<p>Report prometheus metrics on the age of PDUs being sent to and received from
the given domains. This can be used to give an idea of &quot;delay&quot; on inbound
and outbound federation, though be aware that any delay can be due to problems
at either end or with the intermediate network.</p>
<p>By default, no domains are monitored in this way.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_metrics_domains:
  - matrix.org
  - example.com
</code></pre>
<hr />
<h3 id="allow_profile_lookup_over_federation"><a class="header" href="#allow_profile_lookup_over_federation"><code>allow_profile_lookup_over_federation</code></a></h3>
<p>Set to false to disable profile lookup over federation. By default, the
Federation API allows other homeservers to obtain profile data of any user
on this homeserver.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allow_profile_lookup_over_federation: false
</code></pre>
<hr />
<h3 id="allow_device_name_lookup_over_federation"><a class="header" href="#allow_device_name_lookup_over_federation"><code>allow_device_name_lookup_over_federation</code></a></h3>
<p>Set this option to true to allow device display name lookup over federation. By default, the
Federation API prevents other homeservers from obtaining the display names of any user devices
on this homeserver.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allow_device_name_lookup_over_federation: true
</code></pre>
<hr />
<h3 id="federation-1"><a class="header" href="#federation-1"><code>federation</code></a></h3>
<p>The federation section defines some sub-options related to federation.</p>
<p>The following options are related to configuring timeout and retry logic for one request,
independently of the others.
Short retry algorithm is used when something or someone will wait for the request to have an
answer, while long retry is used for requests that happen in the background,
like sending a federation transaction.</p>
<ul>
<li><code>client_timeout</code>: timeout for the federation requests. Default to 60s.</li>
<li><code>max_short_retry_delay</code>: maximum delay to be used for the short retry algo. Default to 2s.</li>
<li><code>max_long_retry_delay</code>: maximum delay to be used for the short retry algo. Default to 60s.</li>
<li><code>max_short_retries</code>: maximum number of retries for the short retry algo. Default to 3 attempts.</li>
<li><code>max_long_retries</code>: maximum number of retries for the long retry algo. Default to 10 attempts.</li>
</ul>
<p>The following options control the retry logic when communicating with a specific homeserver destination.
Unlike the previous configuration options, these values apply across all requests
for a given destination and the state of the backoff is stored in the database.</p>
<ul>
<li><code>destination_min_retry_interval</code>: the initial backoff, after the first request fails. Defaults to 10m.</li>
<li><code>destination_retry_multiplier</code>: how much we multiply the backoff by after each subsequent fail. Defaults to 2.</li>
<li><code>destination_max_retry_interval</code>: a cap on the backoff. Defaults to a week.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation:
  client_timeout: 180s
  max_short_retry_delay: 7s
  max_long_retry_delay: 100s
  max_short_retries: 5
  max_long_retries: 20
  destination_min_retry_interval: 30s
  destination_retry_multiplier: 5
  destination_max_retry_interval: 12h
</code></pre>
<hr />
<h2 id="caching"><a class="header" href="#caching">Caching</a></h2>
<p>Options related to caching.</p>
<hr />
<h3 id="event_cache_size"><a class="header" href="#event_cache_size"><code>event_cache_size</code></a></h3>
<p>The number of events to cache in memory. Defaults to 10K. Like other caches,
this is affected by <code>caches.global_factor</code> (see below).</p>
<p>Note that this option is not part of the <code>caches</code> section.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">event_cache_size: 15K
</code></pre>
<hr />
<h3 id="caches-and-associated-values"><a class="header" href="#caches-and-associated-values"><code>caches</code> and associated values</a></h3>
<p>A cache 'factor' is a multiplier that can be applied to each of
Synapse's caches in order to increase or decrease the maximum
number of entries that can be stored.</p>
<p><code>caches</code> can be configured through the following sub-options:</p>
<ul>
<li>
<p><code>global_factor</code>: Controls the global cache factor, which is the default cache factor
for all caches if a specific factor for that cache is not otherwise
set.</p>
<p>This can also be set by the <code>SYNAPSE_CACHE_FACTOR</code> environment
variable. Setting by environment variable takes priority over
setting through the config file.</p>
<p>Defaults to 0.5, which will halve the size of all caches.</p>
</li>
<li>
<p><code>per_cache_factors</code>: A dictionary of cache name to cache factor for that individual
cache. Overrides the global cache factor for a given cache.</p>
<p>These can also be set through environment variables comprised
of <code>SYNAPSE_CACHE_FACTOR_</code> + the name of the cache in capital
letters and underscores. Setting by environment variable
takes priority over setting through the config file.
Ex. <code>SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0</code></p>
<p>Some caches have '*' and other characters that are not
alphanumeric or underscores. These caches can be named with or
without the special characters stripped. For example, to specify
the cache factor for <code>*stateGroupCache*</code> via an environment
variable would be <code>SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0</code>.</p>
</li>
<li>
<p><code>expire_caches</code>: Controls whether cache entries are evicted after a specified time
period. Defaults to true. Set to false to disable this feature. Note that never expiring
caches may result in excessive memory usage.</p>
</li>
<li>
<p><code>cache_entry_ttl</code>: If <code>expire_caches</code> is enabled, this flag controls how long an entry can
be in a cache without having been accessed before being evicted.
Defaults to 30m.</p>
</li>
<li>
<p><code>sync_response_cache_duration</code>: Controls how long the results of a /sync request are
cached for after a successful response is returned. A higher duration can help clients
with intermittent connections, at the cost of higher memory usage.
A value of zero means that sync responses are not cached.
Defaults to 2m.</p>
<p><em>Changed in Synapse 1.62.0</em>: The default was changed from 0 to 2m.</p>
</li>
<li>
<p><code>cache_autotuning</code> and its sub-options <code>max_cache_memory_usage</code>, <code>target_cache_memory_usage</code>, and
<code>min_cache_ttl</code> work in conjunction with each other to maintain a balance between cache memory
usage and cache entry availability. You must be using <a href="usage/configuration/../administration/admin_faq.html#help-synapse-is-slow-and-eats-all-my-ramcpu">jemalloc</a>
to utilize this option, and all three of the options must be specified for this feature to work. This option
defaults to off, enable it by providing values for the sub-options listed below. Please note that the feature will not work
and may cause unstable behavior (such as excessive emptying of caches or exceptions) if all of the values are not provided.
Please see the <a href="usage/configuration/config_documentation.html#config-conventions">Config Conventions</a> for information on how to specify memory size and cache expiry
durations.</p>
<ul>
<li><code>max_cache_memory_usage</code> sets a ceiling on how much memory the cache can use before caches begin to be continuously evicted.
They will continue to be evicted until the memory usage drops below the <code>target_memory_usage</code>, set in
the setting below, or until the <code>min_cache_ttl</code> is hit. There is no default value for this option.</li>
<li><code>target_cache_memory_usage</code> sets a rough target for the desired memory usage of the caches. There is no default value
for this option.</li>
<li><code>min_cache_ttl</code> sets a limit under which newer cache entries are not evicted and is only applied when
caches are actively being evicted/<code>max_cache_memory_usage</code> has been exceeded. This is to protect hot caches
from being emptied while Synapse is evicting due to memory. There is no default value for this option.</li>
</ul>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">event_cache_size: 15K
caches:
  global_factor: 1.0
  per_cache_factors:
    get_users_who_share_room_with_user: 2.0
  sync_response_cache_duration: 2m
  cache_autotuning:
    max_cache_memory_usage: 1024M
    target_cache_memory_usage: 758M
    min_cache_ttl: 5m
</code></pre>
<h3 id="reloading-cache-factors"><a class="header" href="#reloading-cache-factors">Reloading cache factors</a></h3>
<p>The cache factors (i.e. <code>caches.global_factor</code> and <code>caches.per_cache_factors</code>)  may be reloaded at any time by sending a
<a href="https://en.wikipedia.org/wiki/SIGHUP"><code>SIGHUP</code></a> signal to Synapse using e.g.</p>
<pre><code class="language-commandline">kill -HUP [PID_OF_SYNAPSE_PROCESS]
</code></pre>
<p>If you are running multiple workers, you must individually update the worker
config file and send this signal to each worker process.</p>
<p>If you're using the <a href="https://github.com/matrix-org/synapse/blob/develop/contrib/systemd/matrix-synapse.service">example systemd service</a>
file in Synapse's <code>contrib</code> directory, you can send a <code>SIGHUP</code> signal by using
<code>systemctl reload matrix-synapse</code>.</p>
<hr />
<h2 id="database"><a class="header" href="#database">Database</a></h2>
<p>Config options related to database settings.</p>
<hr />
<h3 id="database-1"><a class="header" href="#database-1"><code>database</code></a></h3>
<p>The <code>database</code> setting defines the database that synapse uses to store all of
its data.</p>
<p>Associated sub-options:</p>
<ul>
<li>
<p><code>name</code>: this option specifies the database engine to use: either <code>sqlite3</code> (for SQLite)
or <code>psycopg2</code> (for PostgreSQL). If no name is specified Synapse will default to SQLite.</p>
</li>
<li>
<p><code>txn_limit</code> gives the maximum number of transactions to run per connection
before reconnecting. Defaults to 0, which means no limit.</p>
</li>
<li>
<p><code>allow_unsafe_locale</code> is an option specific to Postgres. Under the default behavior, Synapse will refuse to
start if the postgres db is set to a non-C locale. You can override this behavior (which is <em>not</em> recommended)
by setting <code>allow_unsafe_locale</code> to true. Note that doing so may corrupt your database. You can find more information
<a href="usage/configuration/../../postgres.html#fixing-incorrect-collate-or-ctype">here</a> and <a href="https://wiki.postgresql.org/wiki/Locale_data_changes">here</a>.</p>
</li>
<li>
<p><code>args</code> gives options which are passed through to the database engine,
except for options starting with <code>cp_</code>, which are used to configure the Twisted
connection pool. For a reference to valid arguments, see:</p>
<ul>
<li>for <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3.connect">sqlite</a></li>
<li>for <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">postgres</a></li>
<li>for <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__">the connection pool</a></li>
</ul>
</li>
</ul>
<p>For more information on using Synapse with Postgres,
see <a href="usage/configuration/../../postgres.html">here</a>.</p>
<p>Example SQLite configuration:</p>
<pre><code class="language-yaml">database:
  name: sqlite3
  args:
    database: /path/to/homeserver.db
</code></pre>
<p>Example Postgres configuration:</p>
<pre><code class="language-yaml">database:
  name: psycopg2
  txn_limit: 10000
  args:
    user: synapse_user
    password: secretpassword
    database: synapse
    host: localhost
    port: 5432
    cp_min: 5
    cp_max: 10
</code></pre>
<hr />
<h3 id="databases"><a class="header" href="#databases"><code>databases</code></a></h3>
<p>The <code>databases</code> option allows specifying a mapping between certain database tables and
database host details, spreading the load of a single Synapse instance across multiple
database backends. This is often referred to as &quot;database sharding&quot;. This option is only
supported for PostgreSQL database backends.</p>
<p><strong>Important note:</strong> This is a supported option, but is not currently used in production by the
Matrix.org Foundation. Proceed with caution and always make backups.</p>
<p><code>databases</code> is a dictionary of arbitrarily-named database entries. Each entry is equivalent
to the value of the <code>database</code> homeserver config option (see above), with the addition of
a <code>data_stores</code> key. <code>data_stores</code> is an array of strings that specifies the data store(s)
(a defined label for a set of tables) that should be stored on the associated database
backend entry.</p>
<p>The currently defined values for <code>data_stores</code> are:</p>
<ul>
<li>
<p><code>&quot;state&quot;</code>: Database that relates to state groups will be stored in this database.</p>
<p>Specifically, that means the following tables:</p>
<ul>
<li><code>state_groups</code></li>
<li><code>state_group_edges</code></li>
<li><code>state_groups_state</code></li>
</ul>
<p>And the following sequences:</p>
<ul>
<li><code>state_groups_seq_id</code></li>
</ul>
</li>
<li>
<p><code>&quot;main&quot;</code>: All other database tables and sequences.</p>
</li>
</ul>
<p>All databases will end up with additional tables used for tracking database schema migrations
and any pending background updates. Synapse will create these automatically on startup when checking for
and/or performing database schema migrations.</p>
<p>To migrate an existing database configuration (e.g. all tables on a single database) to a different
configuration (e.g. the &quot;main&quot; data store on one database, and &quot;state&quot; on another), do the following:</p>
<ol>
<li>
<p>Take a backup of your existing database. Things can and do go wrong and database corruption is no joke!</p>
</li>
<li>
<p>Ensure all pending database migrations have been applied and background updates have run. The simplest
way to do this is to use the <code>update_synapse_database</code> script supplied with your Synapse installation.</p>
<pre><code class="language-sh">update_synapse_database --database-config homeserver.yaml --run-background-updates
</code></pre>
</li>
<li>
<p>Copy over the necessary tables and sequences from one database to the other. Tables relating to database
migrations, schemas, schema versions and background updates should <strong>not</strong> be copied.</p>
<p>As an example, say that you'd like to split out the &quot;state&quot; data store from an existing database which
currently contains all data stores.</p>
<p>Simply copy the tables and sequences defined above for the &quot;state&quot; datastore from the existing database
to the secondary database. As noted above, additional tables will be created in the secondary database
when Synapse is started.</p>
</li>
<li>
<p>Modify/create the <code>databases</code> option in your <code>homeserver.yaml</code> to match the desired database configuration.</p>
</li>
<li>
<p>Start Synapse. Check that it starts up successfully and that things generally seem to be working.</p>
</li>
<li>
<p>Drop the old tables that were copied in step 3.</p>
</li>
</ol>
<p>Only one of the options <code>database</code> or <code>databases</code> may be specified in your config, but not both.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">databases:
  basement_box:
    name: psycopg2
    txn_limit: 10000
    data_stores: [&quot;main&quot;]
    args:
      user: synapse_user
      password: secretpassword
      database: synapse_main
      host: localhost
      port: 5432
      cp_min: 5
      cp_max: 10

  my_other_database:
    name: psycopg2
    txn_limit: 10000
    data_stores: [&quot;state&quot;]
    args:
      user: synapse_user
      password: secretpassword
      database: synapse_state
      host: localhost
      port: 5432
      cp_min: 5
      cp_max: 10
</code></pre>
<hr />
<h2 id="logging"><a class="header" href="#logging">Logging</a></h2>
<p>Config options related to logging.</p>
<hr />
<h3 id="log_config"><a class="header" href="#log_config"><code>log_config</code></a></h3>
<p>This option specifies a yaml python logging config file as described
<a href="https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema">here</a>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
</code></pre>
<hr />
<h2 id="ratelimiting"><a class="header" href="#ratelimiting">Ratelimiting</a></h2>
<p>Options related to ratelimiting in Synapse.</p>
<p>Each ratelimiting configuration is made of two parameters:</p>
<ul>
<li><code>per_second</code>: number of requests a client can send per second.</li>
<li><code>burst_count</code>: number of requests a client can send before being throttled.</li>
</ul>
<hr />
<h3 id="rc_message"><a class="header" href="#rc_message"><code>rc_message</code></a></h3>
<p>Ratelimiting settings for client messaging.</p>
<p>This is a ratelimiting option for messages that ratelimits sending based on the account the client
is using. It defaults to: <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_message:
  per_second: 0.5
  burst_count: 15
</code></pre>
<hr />
<h3 id="rc_registration"><a class="header" href="#rc_registration"><code>rc_registration</code></a></h3>
<p>This option ratelimits registration requests based on the client's IP address.
It defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_registration:
  per_second: 0.15
  burst_count: 2
</code></pre>
<hr />
<h3 id="rc_registration_token_validity"><a class="header" href="#rc_registration_token_validity"><code>rc_registration_token_validity</code></a></h3>
<p>This option checks the validity of registration tokens that ratelimits requests based on
the client's IP address.
Defaults to <code>per_second: 0.1</code>, <code>burst_count: 5</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_registration_token_validity:
  per_second: 0.3
  burst_count: 6
</code></pre>
<hr />
<h3 id="rc_login"><a class="header" href="#rc_login"><code>rc_login</code></a></h3>
<p>This option specifies several limits for login:</p>
<ul>
<li>
<p><code>address</code> ratelimits login requests based on the client's IP
address. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
</li>
<li>
<p><code>account</code> ratelimits login requests based on the account the
client is attempting to log into. Defaults to <code>per_second: 0.003</code>,
<code>burst_count: 5</code>.</p>
</li>
<li>
<p><code>failed_attempts</code> ratelimits login requests based on the account the
client is attempting to log into, based on the amount of failed login
attempts for this account. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_login:
  address:
    per_second: 0.15
    burst_count: 5
  account:
    per_second: 0.18
    burst_count: 4
  failed_attempts:
    per_second: 0.19
    burst_count: 7
</code></pre>
<hr />
<h3 id="rc_admin_redaction"><a class="header" href="#rc_admin_redaction"><code>rc_admin_redaction</code></a></h3>
<p>This option sets ratelimiting redactions by room admins. If this is not explicitly
set then it uses the same ratelimiting as per <code>rc_message</code>. This is useful
to allow room admins to deal with abuse quickly.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_admin_redaction:
  per_second: 1
  burst_count: 50
</code></pre>
<hr />
<h3 id="rc_joins"><a class="header" href="#rc_joins"><code>rc_joins</code></a></h3>
<p>This option allows for ratelimiting number of rooms a user can join. This setting has the following sub-options:</p>
<ul>
<li>
<p><code>local</code>: ratelimits when users are joining rooms the server is already in.
Defaults to <code>per_second: 0.1</code>, <code>burst_count: 10</code>.</p>
</li>
<li>
<p><code>remote</code>: ratelimits when users are trying to join rooms not on the server (which
can be more computationally expensive than restricting locally). Defaults to
<code>per_second: 0.01</code>, <code>burst_count: 10</code></p>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_joins:
  local:
    per_second: 0.2
    burst_count: 15
  remote:
    per_second: 0.03
    burst_count: 12
</code></pre>
<hr />
<h3 id="rc_joins_per_room"><a class="header" href="#rc_joins_per_room"><code>rc_joins_per_room</code></a></h3>
<p>This option allows admins to ratelimit joins to a room based on the number of recent
joins (local or remote) to that room. It is intended to mitigate mass-join spam
waves which target multiple homeservers.</p>
<p>By default, one join is permitted to a room every second, with an accumulating
buffer of up to ten instantaneous joins.</p>
<p>Example configuration (default values):</p>
<pre><code class="language-yaml">rc_joins_per_room:
  per_second: 1
  burst_count: 10
</code></pre>
<p><em>Added in Synapse 1.64.0.</em></p>
<hr />
<h3 id="rc_3pid_validation"><a class="header" href="#rc_3pid_validation"><code>rc_3pid_validation</code></a></h3>
<p>This option ratelimits how often a user or IP can attempt to validate a 3PID.
Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_3pid_validation:
  per_second: 0.003
  burst_count: 5
</code></pre>
<hr />
<h3 id="rc_invites"><a class="header" href="#rc_invites"><code>rc_invites</code></a></h3>
<p>This option sets ratelimiting how often invites can be sent in a room or to a
specific user. <code>per_room</code> defaults to <code>per_second: 0.3</code>, <code>burst_count: 10</code> and
<code>per_user</code> defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
<p>Client requests that invite user(s) when <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3createroom">creating a
room</a>
will count against the <code>rc_invites.per_room</code> limit, whereas
client requests to <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite">invite a single user to a
room</a>
will count against both the <code>rc_invites.per_user</code> and <code>rc_invites.per_room</code> limits.</p>
<p>Federation requests to invite a user will count against the <code>rc_invites.per_user</code>
limit only, as Synapse presumes ratelimiting by room will be done by the sending server.</p>
<p>The <code>rc_invites.per_user</code> limit applies to the <em>receiver</em> of the invite, rather than the
sender, meaning that a <code>rc_invite.per_user.burst_count</code> of 5 mandates that a single user
cannot <em>receive</em> more than a burst of 5 invites at a time.</p>
<p>In contrast, the <code>rc_invites.per_issuer</code> limit applies to the <em>issuer</em> of the invite, meaning that a <code>rc_invite.per_issuer.burst_count</code> of 5 mandates that single user cannot <em>send</em> more than a burst of 5 invites at a time.</p>
<p><em>Changed in version 1.63:</em> added the <code>per_issuer</code> limit.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_invites:
  per_room:
    per_second: 0.5
    burst_count: 5
  per_user:
    per_second: 0.004
    burst_count: 3
  per_issuer:
    per_second: 0.5
    burst_count: 5
</code></pre>
<hr />
<h3 id="rc_third_party_invite"><a class="header" href="#rc_third_party_invite"><code>rc_third_party_invite</code></a></h3>
<p>This option ratelimits 3PID invites (i.e. invites sent to a third-party ID
such as an email address or a phone number) based on the account that's
sending the invite. Defaults to <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_third_party_invite:
  per_second: 0.2
  burst_count: 10
</code></pre>
<hr />
<h3 id="rc_federation"><a class="header" href="#rc_federation"><code>rc_federation</code></a></h3>
<p>Defines limits on federation requests.</p>
<p>The <code>rc_federation</code> configuration has the following sub-options:</p>
<ul>
<li><code>window_size</code>: window size in milliseconds. Defaults to 1000.</li>
<li><code>sleep_limit</code>: number of federation requests from a single server in
a window before the server will delay processing the request. Defaults to 10.</li>
<li><code>sleep_delay</code>: duration in milliseconds to delay processing events
from remote servers by if they go over the sleep limit. Defaults to 500.</li>
<li><code>reject_limit</code>: maximum number of concurrent federation requests
allowed from a single server. Defaults to 50.</li>
<li><code>concurrent</code>: number of federation requests to concurrently process
from a single server. Defaults to 3.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">rc_federation:
  window_size: 750
  sleep_limit: 15
  sleep_delay: 400
  reject_limit: 40
  concurrent: 5
</code></pre>
<hr />
<h3 id="federation_rr_transactions_per_room_per_second"><a class="header" href="#federation_rr_transactions_per_room_per_second"><code>federation_rr_transactions_per_room_per_second</code></a></h3>
<p>Sets outgoing federation transaction frequency for sending read-receipts,
per-room.</p>
<p>If we end up trying to send out more read-receipts, they will get buffered up
into fewer transactions. Defaults to 50.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">federation_rr_transactions_per_room_per_second: 40
</code></pre>
<hr />
<h2 id="media-store"><a class="header" href="#media-store">Media Store</a></h2>
<p>Config options related to Synapse's media store.</p>
<hr />
<h3 id="enable_media_repo"><a class="header" href="#enable_media_repo"><code>enable_media_repo</code></a></h3>
<p>Enable the media store service in the Synapse master. Defaults to true.
Set to false if you are using a separate media store worker.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_media_repo: false
</code></pre>
<hr />
<h3 id="media_store_path"><a class="header" href="#media_store_path"><code>media_store_path</code></a></h3>
<p>Directory where uploaded images and attachments are stored.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">media_store_path: &quot;DATADIR/media_store&quot;
</code></pre>
<hr />
<h3 id="media_storage_providers"><a class="header" href="#media_storage_providers"><code>media_storage_providers</code></a></h3>
<p>Media storage providers allow media to be stored in different
locations. Defaults to none. Associated sub-options are:</p>
<ul>
<li><code>module</code>: type of resource, e.g. <code>file_system</code>.</li>
<li><code>store_local</code>: whether to store newly uploaded local files</li>
<li><code>store_remote</code>: whether to store newly downloaded local files</li>
<li><code>store_synchronous</code>: whether to wait for successful storage for local uploads</li>
<li><code>config</code>: sets a path to the resource through the <code>directory</code> option</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">media_storage_providers:
  - module: file_system
    store_local: false
    store_remote: false
    store_synchronous: false
    config:
       directory: /mnt/some/other/directory
</code></pre>
<hr />
<h3 id="max_upload_size"><a class="header" href="#max_upload_size"><code>max_upload_size</code></a></h3>
<p>The largest allowed upload size in bytes.</p>
<p>If you are using a reverse proxy you may also need to set this value in
your reverse proxy's config. Defaults to 50M. Notably Nginx has a small max body size by default.
See <a href="usage/configuration/../../reverse_proxy.html">here</a> for more on using a reverse proxy with Synapse.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">max_upload_size: 60M
</code></pre>
<hr />
<h3 id="max_image_pixels"><a class="header" href="#max_image_pixels"><code>max_image_pixels</code></a></h3>
<p>Maximum number of pixels that will be thumbnailed. Defaults to 32M.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">max_image_pixels: 35M
</code></pre>
<hr />
<h3 id="prevent_media_downloads_from"><a class="header" href="#prevent_media_downloads_from"><code>prevent_media_downloads_from</code></a></h3>
<p>A list of domains to never download media from. Media from these
domains that is already downloaded will not be deleted, but will be
inaccessible to users. This option does not affect admin APIs trying
to download/operate on media.</p>
<p>This will not prevent the listed domains from accessing media themselves.
It simply prevents users on this server from downloading media originating
from the listed servers.</p>
<p>This will have no effect on media originating from the local server.
This only affects media downloaded from other Matrix servers, to
block domains from URL previews see <a href="usage/configuration/config_documentation.html#url_preview_url_blacklist"><code>url_preview_url_blacklist</code></a>.</p>
<p>Defaults to an empty list (nothing blocked).</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">prevent_media_downloads_from:
  - evil.example.org
  - evil2.example.org
</code></pre>
<hr />
<h3 id="dynamic_thumbnails"><a class="header" href="#dynamic_thumbnails"><code>dynamic_thumbnails</code></a></h3>
<p>Whether to generate new thumbnails on the fly to precisely match
the resolution requested by the client. If true then whenever
a new resolution is requested by the client the server will
generate a new thumbnail. If false the server will pick a thumbnail
from a precalculated list. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">dynamic_thumbnails: true
</code></pre>
<hr />
<h3 id="thumbnail_sizes"><a class="header" href="#thumbnail_sizes"><code>thumbnail_sizes</code></a></h3>
<p>List of thumbnails to precalculate when an image is uploaded. Associated sub-options are:</p>
<ul>
<li><code>width</code></li>
<li><code>height</code></li>
<li><code>method</code>: i.e. <code>crop</code>, <code>scale</code>, etc.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">thumbnail_sizes:
  - width: 32
    height: 32
    method: crop
  - width: 96
    height: 96
    method: crop
  - width: 320
    height: 240
    method: scale
  - width: 640
    height: 480
    method: scale
  - width: 800
    height: 600
    method: scale
</code></pre>
<hr />
<h3 id="media_retention"><a class="header" href="#media_retention"><code>media_retention</code></a></h3>
<p>Controls whether local media and entries in the remote media cache
(media that is downloaded from other homeservers) should be removed
under certain conditions, typically for the purpose of saving space.</p>
<p>Purging media files will be the carried out by the media worker
(that is, the worker that has the <code>enable_media_repo</code> homeserver config
option set to 'true'). This may be the main process.</p>
<p>The <code>media_retention.local_media_lifetime</code> and
<code>media_retention.remote_media_lifetime</code> config options control whether
media will be purged if it has not been accessed in a given amount of
time. Note that media is 'accessed' when loaded in a room in a client, or
otherwise downloaded by a local or remote user. If the media has never
been accessed, the media's creation time is used instead. Both thumbnails
and the original media will be removed. If either of these options are unset,
then media of that type will not be purged.</p>
<p>Local or cached remote media that has been
<a href="usage/configuration/../../admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantined</a>
will not be deleted. Similarly, local media that has been marked as
<a href="usage/configuration/../../admin_api/media_admin_api.html#protecting-media-from-being-quarantined">protected from quarantine</a>
will not be deleted.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">media_retention:
    local_media_lifetime: 90d
    remote_media_lifetime: 14d
</code></pre>
<hr />
<h3 id="url_preview_enabled"><a class="header" href="#url_preview_enabled"><code>url_preview_enabled</code></a></h3>
<p>This setting determines whether the preview URL API is enabled.
It is disabled by default. Set to true to enable. If enabled you must specify a
<code>url_preview_ip_range_blacklist</code> blacklist.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">url_preview_enabled: true
</code></pre>
<hr />
<h3 id="url_preview_ip_range_blacklist"><a class="header" href="#url_preview_ip_range_blacklist"><code>url_preview_ip_range_blacklist</code></a></h3>
<p>List of IP address CIDR ranges that the URL preview spider is denied
from accessing.  There are no defaults: you must explicitly
specify a list for URL previewing to work.  You should specify any
internal services in your network that you do not want synapse to try
to connect to, otherwise anyone in any Matrix room could cause your
synapse to issue arbitrary GET requests to your internal services,
causing serious security issues.</p>
<p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
listed here, since they correspond to unroutable addresses.)</p>
<p>This must be specified if <code>url_preview_enabled</code> is set. It is recommended that
you use the following example list as a starting point.</p>
<p>Note: The value is ignored when an HTTP proxy is in use.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">url_preview_ip_range_blacklist:
  - '127.0.0.0/8'
  - '10.0.0.0/8'
  - '172.16.0.0/12'
  - '192.168.0.0/16'
  - '100.64.0.0/10'
  - '192.0.0.0/24'
  - '169.254.0.0/16'
  - '192.88.99.0/24'
  - '198.18.0.0/15'
  - '192.0.2.0/24'
  - '198.51.100.0/24'
  - '203.0.113.0/24'
  - '224.0.0.0/4'
  - '::1/128'
  - 'fe80::/10'
  - 'fc00::/7'
  - '2001:db8::/32'
  - 'ff00::/8'
  - 'fec0::/10'
</code></pre>
<hr />
<h3 id="url_preview_ip_range_whitelist"><a class="header" href="#url_preview_ip_range_whitelist"><code>url_preview_ip_range_whitelist</code></a></h3>
<p>This option sets a list of IP address CIDR ranges that the URL preview spider is allowed
to access even if they are specified in <code>url_preview_ip_range_blacklist</code>.
This is useful for specifying exceptions to wide-ranging blacklisted
target IP ranges - e.g. for enabling URL previews for a specific private
website only visible in your network. Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">url_preview_ip_range_whitelist:
   - '192.168.1.1'
</code></pre>
<hr />
<h3 id="url_preview_url_blacklist"><a class="header" href="#url_preview_url_blacklist"><code>url_preview_url_blacklist</code></a></h3>
<p>Optional list of URL matches that the URL preview spider is
denied from accessing.  You should use <code>url_preview_ip_range_blacklist</code>
in preference to this, otherwise someone could define a public DNS
entry that points to a private IP address and circumvent the blacklist.
This is more useful if you know there is an entire shape of URL that
you know that will never want synapse to try to spider.</p>
<p>Each list entry is a dictionary of url component attributes as returned
by urlparse.urlsplit as applied to the absolute form of the URL.  See
<a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit">here</a> for more
information. Some examples are:</p>
<ul>
<li><code>username</code></li>
<li><code>netloc</code></li>
<li><code>scheme</code></li>
<li><code>path</code></li>
</ul>
<p>The values of the dictionary are treated as a filename match pattern
applied to that component of URLs, unless they start with a ^ in which
case they are treated as a regular expression match.  If all the
specified component matches for a given list item succeed, the URL is
blacklisted.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">url_preview_url_blacklist:
  # blacklist any URL with a username in its URI
  - username: '*'

  # blacklist all *.google.com URLs
  - netloc: 'google.com'
  - netloc: '*.google.com'

  # blacklist all plain HTTP URLs
  - scheme: 'http'

  # blacklist http(s)://www.acme.com/foo
  - netloc: 'www.acme.com'
    path: '/foo'

  # blacklist any URL with a literal IPv4 address
  - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
</code></pre>
<hr />
<h3 id="max_spider_size"><a class="header" href="#max_spider_size"><code>max_spider_size</code></a></h3>
<p>The largest allowed URL preview spidering size in bytes. Defaults to 10M.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">max_spider_size: 8M
</code></pre>
<hr />
<h3 id="url_preview_accept_language"><a class="header" href="#url_preview_accept_language"><code>url_preview_accept_language</code></a></h3>
<p>A list of values for the Accept-Language HTTP header used when
downloading webpages during URL preview generation. This allows
Synapse to specify the preferred languages that URL previews should
be in when communicating with remote servers.</p>
<p>Each value is a IETF language tag; a 2-3 letter identifier for a
language, optionally followed by subtags separated by '-', specifying
a country or region variant.</p>
<p>Multiple values can be provided, and a weight can be added to each by
using quality value syntax (;q=). '*' translates to any language.</p>
<p>Defaults to &quot;en&quot;.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml"> url_preview_accept_language:
   - 'en-UK'
   - 'en-US;q=0.9'
   - 'fr;q=0.8'
   - '*;q=0.7'
</code></pre>
<hr />
<h3 id="oembed"><a class="header" href="#oembed"><code>oembed</code></a></h3>
<p>oEmbed allows for easier embedding content from a website. It can be
used for generating URLs previews of services which support it. A default list of oEmbed providers
is included with Synapse. Set <code>disable_default_providers</code> to true to disable using
these default oEmbed URLs. Use <code>additional_providers</code> to specify additional files with oEmbed configuration (each
should be in the form of providers.json). By default this list is empty.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">oembed:
  disable_default_providers: true
  additional_providers:
    - oembed/my_providers.json
</code></pre>
<hr />
<h2 id="captcha"><a class="header" href="#captcha">Captcha</a></h2>
<p>See <a href="usage/configuration/../../CAPTCHA_SETUP.html">here</a> for full details on setting up captcha.</p>
<hr />
<h3 id="recaptcha_public_key"><a class="header" href="#recaptcha_public_key"><code>recaptcha_public_key</code></a></h3>
<p>This homeserver's ReCAPTCHA public key. Must be specified if
<a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is enabled.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
</code></pre>
<hr />
<h3 id="recaptcha_private_key"><a class="header" href="#recaptcha_private_key"><code>recaptcha_private_key</code></a></h3>
<p>This homeserver's ReCAPTCHA private key. Must be specified if
<a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is
enabled.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">recaptcha_private_key: &quot;YOUR_PRIVATE_KEY&quot;
</code></pre>
<hr />
<h3 id="enable_registration_captcha"><a class="header" href="#enable_registration_captcha"><code>enable_registration_captcha</code></a></h3>
<p>Set to <code>true</code> to require users to complete a CAPTCHA test when registering an account.
Requires a valid ReCaptcha public/private key.
Defaults to <code>false</code>.</p>
<p>Note that <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> must also be set to allow account registration.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_registration_captcha: true
</code></pre>
<hr />
<h3 id="recaptcha_siteverify_api"><a class="header" href="#recaptcha_siteverify_api"><code>recaptcha_siteverify_api</code></a></h3>
<p>The API endpoint to use for verifying <code>m.login.recaptcha</code> responses.
Defaults to <code>https://www.recaptcha.net/recaptcha/api/siteverify</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">recaptcha_siteverify_api: &quot;https://my.recaptcha.site&quot;
</code></pre>
<hr />
<h2 id="turn"><a class="header" href="#turn">TURN</a></h2>
<p>Options related to adding a TURN server to Synapse.</p>
<hr />
<h3 id="turn_uris"><a class="header" href="#turn_uris"><code>turn_uris</code></a></h3>
<p>The public URIs of the TURN server to give to clients.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">turn_uris: [turn:example.org]
</code></pre>
<hr />
<h3 id="turn_shared_secret"><a class="header" href="#turn_shared_secret"><code>turn_shared_secret</code></a></h3>
<p>The shared secret used to compute passwords for the TURN server.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">turn_shared_secret: &quot;YOUR_SHARED_SECRET&quot;
</code></pre>
<hr />
<h3 id="turn_username-and-turn_password"><a class="header" href="#turn_username-and-turn_password"><code>turn_username</code> and <code>turn_password</code></a></h3>
<p>The Username and password if the TURN server needs them and does not use a token.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">turn_username: &quot;TURNSERVER_USERNAME&quot;
turn_password: &quot;TURNSERVER_PASSWORD&quot;
</code></pre>
<hr />
<h3 id="turn_user_lifetime"><a class="header" href="#turn_user_lifetime"><code>turn_user_lifetime</code></a></h3>
<p>How long generated TURN credentials last. Defaults to 1h.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">turn_user_lifetime: 2h
</code></pre>
<hr />
<h3 id="turn_allow_guests"><a class="header" href="#turn_allow_guests"><code>turn_allow_guests</code></a></h3>
<p>Whether guests should be allowed to use the TURN server. This defaults to true, otherwise
VoIP will be unreliable for guests. However, it does introduce a slight security risk as
it allows users to connect to arbitrary endpoints without having first signed up for a valid account (e.g. by passing a CAPTCHA).</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">turn_allow_guests: false
</code></pre>
<hr />
<h2 id="registration"><a class="header" href="#registration">Registration</a></h2>
<p>Registration can be rate-limited using the parameters in the <a href="usage/configuration/config_documentation.html#ratelimiting">Ratelimiting</a> section of this manual.</p>
<hr />
<h3 id="enable_registration"><a class="header" href="#enable_registration"><code>enable_registration</code></a></h3>
<p>Enable registration for new users. Defaults to <code>false</code>.</p>
<p>It is highly recommended that if you enable registration, you set one or more
or the following options, to avoid abuse of your server by &quot;bots&quot;:</p>
<ul>
<li><a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a></li>
<li><a href="usage/configuration/config_documentation.html#registrations_require_3pid"><code>registrations_require_3pid</code></a></li>
<li><a href="usage/configuration/config_documentation.html#registration_requires_token"><code>registration_requires_token</code></a></li>
</ul>
<p>(In order to enable registration without any verification, you must also set
<a href="usage/configuration/config_documentation.html#enable_registration_without_verification"><code>enable_registration_without_verification</code></a>.)</p>
<p>Note that even if this setting is disabled, new accounts can still be created
via the admin API if
<a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a> is set.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_registration: true
</code></pre>
<hr />
<h3 id="enable_registration_without_verification"><a class="header" href="#enable_registration_without_verification"><code>enable_registration_without_verification</code></a></h3>
<p>Enable registration without email or captcha verification. Note: this option is <em>not</em> recommended,
as registration without verification is a known vector for spam and abuse. Defaults to <code>false</code>. Has no effect
unless <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is also enabled.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_registration_without_verification: true
</code></pre>
<hr />
<h3 id="registrations_require_3pid"><a class="header" href="#registrations_require_3pid"><code>registrations_require_3pid</code></a></h3>
<p>If this is set, users must provide all of the specified types of 3PID when registering an account.</p>
<p>Note that <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> must also be set to allow account registration.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">registrations_require_3pid:
  - email
  - msisdn
</code></pre>
<hr />
<h3 id="disable_msisdn_registration"><a class="header" href="#disable_msisdn_registration"><code>disable_msisdn_registration</code></a></h3>
<p>Explicitly disable asking for MSISDNs from the registration
flow (overrides <code>registrations_require_3pid</code> if MSISDNs are set as required).</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">disable_msisdn_registration: true
</code></pre>
<hr />
<h3 id="allowed_local_3pids"><a class="header" href="#allowed_local_3pids"><code>allowed_local_3pids</code></a></h3>
<p>Mandate that users are only allowed to associate certain formats of
3PIDs with accounts on this server, as specified by the <code>medium</code> and <code>pattern</code> sub-options.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allowed_local_3pids:
  - medium: email
    pattern: '^[^@]+@matrix\.org$'
  - medium: email
    pattern: '^[^@]+@vector\.im$'
  - medium: msisdn
    pattern: '\+44'
</code></pre>
<hr />
<h3 id="enable_3pid_lookup"><a class="header" href="#enable_3pid_lookup"><code>enable_3pid_lookup</code></a></h3>
<p>Enable 3PIDs lookup requests to identity servers from this server. Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_3pid_lookup: false
</code></pre>
<hr />
<h3 id="registration_requires_token"><a class="header" href="#registration_requires_token"><code>registration_requires_token</code></a></h3>
<p>Require users to submit a token during registration.
Tokens can be managed using the admin <a href="usage/configuration/../administration/admin_api/registration_tokens.html">API</a>.
Disabling this option will not delete any tokens previously generated.
Defaults to <code>false</code>. Set to <code>true</code> to enable.</p>
<p>Note that <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> must also be set to allow account registration.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">registration_requires_token: true
</code></pre>
<hr />
<h3 id="registration_shared_secret"><a class="header" href="#registration_shared_secret"><code>registration_shared_secret</code></a></h3>
<p>If set, allows registration of standard or admin accounts by anyone who has the
shared secret, even if <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is not
set.</p>
<p>This is primarily intended for use with the <code>register_new_matrix_user</code> script
(see <a href="usage/configuration/../../setup/installation.html#registering-a-user">Registering a user</a>);
however, the interface is <a href="usage/configuration/../../admin_api/register_api.html">documented</a>.</p>
<p>See also <a href="usage/configuration/config_documentation.html#registration_shared_secret_path"><code>registration_shared_secret_path</code></a>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">registration_shared_secret: &lt;PRIVATE STRING&gt;
</code></pre>
<hr />
<h3 id="registration_shared_secret_path"><a class="header" href="#registration_shared_secret_path"><code>registration_shared_secret_path</code></a></h3>
<p>An alternative to <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>:
allows the shared secret to be specified in an external file.</p>
<p>The file should be a plain text file, containing only the shared secret.</p>
<p>If this file does not exist, Synapse will create a new shared
secret on startup and store it in this file.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">registration_shared_secret_path: /path/to/secrets/file
</code></pre>
<p><em>Added in Synapse 1.67.0.</em></p>
<hr />
<h3 id="bcrypt_rounds"><a class="header" href="#bcrypt_rounds"><code>bcrypt_rounds</code></a></h3>
<p>Set the number of bcrypt rounds used to generate password hash.
Larger numbers increase the work factor needed to generate the hash.
The default number is 12 (which equates to 2^12 rounds).
N.B. that increasing this will exponentially increase the time required
to register or login - e.g. 24 =&gt; 2^24 rounds which will take &gt;20 mins.
Example configuration:</p>
<pre><code class="language-yaml">bcrypt_rounds: 14
</code></pre>
<hr />
<h3 id="allow_guest_access"><a class="header" href="#allow_guest_access"><code>allow_guest_access</code></a></h3>
<p>Allows users to register as guests without a password/email/etc, and
participate in rooms hosted on this server which have been made
accessible to anonymous users. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">allow_guest_access: true
</code></pre>
<hr />
<h3 id="default_identity_server"><a class="header" href="#default_identity_server"><code>default_identity_server</code></a></h3>
<p>The identity server which we suggest that clients should use when users log
in on this server.</p>
<p>(By default, no suggestion is made, so it is left up to the client.
This setting is ignored unless <code>public_baseurl</code> is also explicitly set.)</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">default_identity_server: https://matrix.org
</code></pre>
<hr />
<h3 id="account_threepid_delegates"><a class="header" href="#account_threepid_delegates"><code>account_threepid_delegates</code></a></h3>
<p>Delegate verification of phone numbers to an identity server.</p>
<p>When a user wishes to add a phone number to their account, we need to verify that they
actually own that phone number, which requires sending them a text message (SMS).
Currently Synapse does not support sending those texts itself and instead delegates the
task to an identity server. The base URI for the identity server to be used is
specified by the <code>account_threepid_delegates.msisdn</code> option.</p>
<p>If this is left unspecified, Synapse will not allow users to add phone numbers to
their account.</p>
<p>(Servers handling the these requests must answer the <code>/requestToken</code> endpoints defined
by the Matrix Identity Service API
<a href="https://matrix.org/docs/spec/identity_service/latest">specification</a>.)</p>
<p><em>Deprecated in Synapse 1.64.0</em>: The <code>email</code> option is deprecated.</p>
<p><em>Removed in Synapse 1.66.0</em>: The <code>email</code> option has been removed.
If present, Synapse will report a configuration error on startup.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">account_threepid_delegates:
    msisdn: http://localhost:8090  # Delegate SMS sending to this local process
</code></pre>
<hr />
<h3 id="enable_set_displayname"><a class="header" href="#enable_set_displayname"><code>enable_set_displayname</code></a></h3>
<p>Whether users are allowed to change their displayname after it has
been initially set. Useful when provisioning users based on the
contents of a third-party directory.</p>
<p>Does not apply to server administrators. Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_set_displayname: false
</code></pre>
<hr />
<h3 id="enable_set_avatar_url"><a class="header" href="#enable_set_avatar_url"><code>enable_set_avatar_url</code></a></h3>
<p>Whether users are allowed to change their avatar after it has been
initially set. Useful when provisioning users based on the contents
of a third-party directory.</p>
<p>Does not apply to server administrators. Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_set_avatar_url: false
</code></pre>
<hr />
<h3 id="enable_3pid_changes"><a class="header" href="#enable_3pid_changes"><code>enable_3pid_changes</code></a></h3>
<p>Whether users can change the third-party IDs associated with their accounts
(email address and msisdn).</p>
<p>Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_3pid_changes: false
</code></pre>
<hr />
<h3 id="auto_join_rooms"><a class="header" href="#auto_join_rooms"><code>auto_join_rooms</code></a></h3>
<p>Users who register on this homeserver will automatically be joined
to the rooms listed under this option.</p>
<p>By default, any room aliases included in this list will be created
as a publicly joinable room when the first user registers for the
homeserver. If the room already exists, make certain it is a publicly joinable
room, i.e. the join rule of the room must be set to 'public'. You can find more options
relating to auto-joining rooms below.</p>
<p>As Spaces are just rooms under the hood, Space aliases may also be
used.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">auto_join_rooms:
  - &quot;#exampleroom:example.com&quot;
  - &quot;#anotherexampleroom:example.com&quot;
</code></pre>
<hr />
<h3 id="autocreate_auto_join_rooms"><a class="header" href="#autocreate_auto_join_rooms"><code>autocreate_auto_join_rooms</code></a></h3>
<p>Where <code>auto_join_rooms</code> are specified, setting this flag ensures that
the rooms exist by creating them when the first user on the
homeserver registers. This option will not create Spaces.</p>
<p>By default the auto-created rooms are publicly joinable from any federated
server. Use the <code>autocreate_auto_join_rooms_federated</code> and
<code>autocreate_auto_join_room_preset</code> settings to customise this behaviour.</p>
<p>Setting to false means that if the rooms are not manually created,
users cannot be auto-joined since they do not exist.</p>
<p>Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">autocreate_auto_join_rooms: false
</code></pre>
<hr />
<h3 id="autocreate_auto_join_rooms_federated"><a class="header" href="#autocreate_auto_join_rooms_federated"><code>autocreate_auto_join_rooms_federated</code></a></h3>
<p>Whether the rooms listed in <code>auto_join_rooms</code> that are auto-created are available
via federation. Only has an effect if <code>autocreate_auto_join_rooms</code> is true.</p>
<p>Note that whether a room is federated cannot be modified after
creation.</p>
<p>Defaults to true: the room will be joinable from other servers.
Set to false to prevent users from other homeservers from
joining these rooms.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">autocreate_auto_join_rooms_federated: false
</code></pre>
<hr />
<h3 id="autocreate_auto_join_room_preset"><a class="header" href="#autocreate_auto_join_room_preset"><code>autocreate_auto_join_room_preset</code></a></h3>
<p>The room preset to use when auto-creating one of <code>auto_join_rooms</code>. Only has an
effect if <code>autocreate_auto_join_rooms</code> is true.</p>
<p>Possible values for this option are:</p>
<ul>
<li>&quot;public_chat&quot;: the room is joinable by anyone, including
federated servers if <code>autocreate_auto_join_rooms_federated</code> is true (the default).</li>
<li>&quot;private_chat&quot;: an invitation is required to join these rooms.</li>
<li>&quot;trusted_private_chat&quot;: an invitation is required to join this room and the invitee is
assigned a power level of 100 upon joining the room.</li>
</ul>
<p>If a value of &quot;private_chat&quot; or &quot;trusted_private_chat&quot; is used then
<code>auto_join_mxid_localpart</code> must also be configured.</p>
<p>Defaults to &quot;public_chat&quot;.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">autocreate_auto_join_room_preset: private_chat
</code></pre>
<hr />
<h3 id="auto_join_mxid_localpart"><a class="header" href="#auto_join_mxid_localpart"><code>auto_join_mxid_localpart</code></a></h3>
<p>The local part of the user id which is used to create <code>auto_join_rooms</code> if
<code>autocreate_auto_join_rooms</code> is true. If this is not provided then the
initial user account that registers will be used to create the rooms.</p>
<p>The user id is also used to invite new users to any auto-join rooms which
are set to invite-only.</p>
<p>It <em>must</em> be configured if <code>autocreate_auto_join_room_preset</code> is set to
&quot;private_chat&quot; or &quot;trusted_private_chat&quot;.</p>
<p>Note that this must be specified in order for new users to be correctly
invited to any auto-join rooms which have been set to invite-only (either
at the time of creation or subsequently).</p>
<p>Note that, if the room already exists, this user must be joined and
have the appropriate permissions to invite new members.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">auto_join_mxid_localpart: system
</code></pre>
<hr />
<h3 id="auto_join_rooms_for_guests"><a class="header" href="#auto_join_rooms_for_guests"><code>auto_join_rooms_for_guests</code></a></h3>
<p>When <code>auto_join_rooms</code> is specified, setting this flag to false prevents
guest accounts from being automatically joined to the rooms.</p>
<p>Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">auto_join_rooms_for_guests: false
</code></pre>
<hr />
<h3 id="inhibit_user_in_use_error"><a class="header" href="#inhibit_user_in_use_error"><code>inhibit_user_in_use_error</code></a></h3>
<p>Whether to inhibit errors raised when registering a new account if the user ID
already exists. If turned on, requests to <code>/register/available</code> will always
show a user ID as available, and Synapse won't raise an error when starting
a registration with a user ID that already exists. However, Synapse will still
raise an error if the registration completes and the username conflicts.</p>
<p>Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">inhibit_user_in_use_error: true
</code></pre>
<hr />
<h2 id="user-session-management"><a class="header" href="#user-session-management">User session management</a></h2>
<hr />
<h3 id="session_lifetime"><a class="header" href="#session_lifetime"><code>session_lifetime</code></a></h3>
<p>Time that a user's session remains valid for, after they log in.</p>
<p>Note that this is not currently compatible with guest logins.</p>
<p>Note also that this is calculated at login time: changes are not applied retrospectively to users who have already
logged in.</p>
<p>By default, this is infinite.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">session_lifetime: 24h
</code></pre>
<hr />
<h3 id="refresh_access_token_lifetime"><a class="header" href="#refresh_access_token_lifetime"><code>refresh_access_token_lifetime</code></a></h3>
<p>Time that an access token remains valid for, if the session is using refresh tokens.</p>
<p>For more information about refresh tokens, please see the <a href="usage/configuration/user_authentication/refresh_tokens.html">manual</a>.</p>
<p>Note that this only applies to clients which advertise support for refresh tokens.</p>
<p>Note also that this is calculated at login time and refresh time: changes are not applied to
existing sessions until they are refreshed.</p>
<p>By default, this is 5 minutes.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">refreshable_access_token_lifetime: 10m
</code></pre>
<hr />
<h3 id="refresh_token_lifetime-24h"><a class="header" href="#refresh_token_lifetime-24h"><code>refresh_token_lifetime: 24h</code></a></h3>
<p>Time that a refresh token remains valid for (provided that it is not
exchanged for another one first).
This option can be used to automatically log-out inactive sessions.
Please see the manual for more information.</p>
<p>Note also that this is calculated at login time and refresh time:
changes are not applied to existing sessions until they are refreshed.</p>
<p>By default, this is infinite.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">refresh_token_lifetime: 24h
</code></pre>
<hr />
<h3 id="nonrefreshable_access_token_lifetime"><a class="header" href="#nonrefreshable_access_token_lifetime"><code>nonrefreshable_access_token_lifetime</code></a></h3>
<p>Time that an access token remains valid for, if the session is NOT
using refresh tokens.</p>
<p>Please note that not all clients support refresh tokens, so setting
this to a short value may be inconvenient for some users who will
then be logged out frequently.</p>
<p>Note also that this is calculated at login time: changes are not applied
retrospectively to existing sessions for users that have already logged in.</p>
<p>By default, this is infinite.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">nonrefreshable_access_token_lifetime: 24h
</code></pre>
<hr />
<h3 id="ui_auth"><a class="header" href="#ui_auth"><code>ui_auth</code></a></h3>
<p>The amount of time to allow a user-interactive authentication session to be active.</p>
<p>This defaults to 0, meaning the user is queried for their credentials
before every action, but this can be overridden to allow a single
validation to be re-used.  This weakens the protections afforded by
the user-interactive authentication process, by allowing for multiple
(and potentially different) operations to use the same validation session.</p>
<p>This is ignored for potentially &quot;dangerous&quot; operations (including
deactivating an account, modifying an account password, adding a 3PID,
and minting additional login tokens).</p>
<p>Use the <code>session_timeout</code> sub-option here to change the time allowed for credential validation.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">ui_auth:
    session_timeout: &quot;15s&quot;
</code></pre>
<hr />
<h3 id="login_via_existing_session"><a class="header" href="#login_via_existing_session"><code>login_via_existing_session</code></a></h3>
<p>Matrix supports the ability of an existing session to mint a login token for
another client.</p>
<p>Synapse disables this by default as it has security ramifications -- a malicious
client could use the mechanism to spawn more than one session.</p>
<p>The duration of time the generated token is valid for can be configured with the
<code>token_timeout</code> sub-option.</p>
<p>User-interactive authentication is required when this is enabled unless the
<code>require_ui_auth</code> sub-option is set to <code>False</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">login_via_existing_session:
    enabled: true
    require_ui_auth: false
    token_timeout: &quot;5m&quot;
</code></pre>
<hr />
<h2 id="metrics"><a class="header" href="#metrics">Metrics</a></h2>
<p>Config options related to metrics.</p>
<hr />
<h3 id="enable_metrics"><a class="header" href="#enable_metrics"><code>enable_metrics</code></a></h3>
<p>Set to true to enable collection and rendering of performance metrics.
Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_metrics: true
</code></pre>
<hr />
<h3 id="sentry"><a class="header" href="#sentry"><code>sentry</code></a></h3>
<p>Use this option to enable sentry integration. Provide the DSN assigned to you by sentry
with the <code>dsn</code> setting.</p>
<p>NOTE: While attempts are made to ensure that the logs don't contain
any sensitive information, this cannot be guaranteed. By enabling
this option the sentry server may therefore receive sensitive
information, and it in turn may then disseminate sensitive information
through insecure notification channels if so configured.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">sentry:
    dsn: &quot;...&quot;
</code></pre>
<hr />
<h3 id="metrics_flags"><a class="header" href="#metrics_flags"><code>metrics_flags</code></a></h3>
<p>Flags to enable Prometheus metrics which are not suitable to be
enabled by default, either for performance reasons or limited use.
Currently the only option is <code>known_servers</code>, which publishes
<code>synapse_federation_known_servers</code>, a gauge of the number of
servers this homeserver knows about, including itself. May cause
performance problems on large homeservers.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">metrics_flags:
    known_servers: true
</code></pre>
<hr />
<h3 id="report_stats"><a class="header" href="#report_stats"><code>report_stats</code></a></h3>
<p>Whether or not to report homeserver usage statistics. This is originally
set when generating the config. Set this option to true or false to change the current
behavior. See
<a href="usage/configuration/../administration/monitoring/reporting_homeserver_usage_statistics.html">Reporting Homeserver Usage Statistics</a>
for information on what data is reported.</p>
<p>Statistics will be reported 5 minutes after Synapse starts, and then every 3 hours
after that.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">report_stats: true
</code></pre>
<hr />
<h3 id="report_stats_endpoint"><a class="header" href="#report_stats_endpoint"><code>report_stats_endpoint</code></a></h3>
<p>The endpoint to report homeserver usage statistics to.
Defaults to https://matrix.org/report-usage-stats/push</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">report_stats_endpoint: https://example.com/report-usage-stats/push
</code></pre>
<hr />
<h2 id="api-configuration"><a class="header" href="#api-configuration">API Configuration</a></h2>
<p>Config settings related to the client/server API</p>
<hr />
<h3 id="room_prejoin_state"><a class="header" href="#room_prejoin_state"><code>room_prejoin_state</code></a></h3>
<p>This setting controls the state that is shared with users upon receiving an
invite to a room, or in reply to a knock on a room. By default, the following
state events are shared with users:</p>
<ul>
<li><code>m.room.join_rules</code></li>
<li><code>m.room.canonical_alias</code></li>
<li><code>m.room.avatar</code></li>
<li><code>m.room.encryption</code></li>
<li><code>m.room.name</code></li>
<li><code>m.room.create</code></li>
<li><code>m.room.topic</code></li>
</ul>
<p>To change the default behavior, use the following sub-options:</p>
<ul>
<li>
<p><code>disable_default_event_types</code>: boolean. Set to <code>true</code> to disable the above
defaults. If this is enabled, only the event types listed in
<code>additional_event_types</code> are shared. Defaults to <code>false</code>.</p>
</li>
<li>
<p><code>additional_event_types</code>: A list of additional state events to include in the
events to be shared. By default, this list is empty (so only the default event
types are shared).</p>
<p>Each entry in this list should be either a single string or a list of two
strings.</p>
<ul>
<li>A standalone string <code>t</code> represents all events with type <code>t</code> (i.e.
with no restrictions on state keys).</li>
<li>A pair of strings <code>[t, s]</code> represents a single event with type <code>t</code> and
state key <code>s</code>. The same type can appear in two entries with different state
keys: in this situation, both state keys are included in prejoin state.</li>
</ul>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">room_prejoin_state:
   disable_default_event_types: false
   additional_event_types:
     # Share all events of type `org.example.custom.event.typeA`
     - org.example.custom.event.typeA
     # Share only events of type `org.example.custom.event.typeB` whose
     # state_key is &quot;foo&quot;
     - [&quot;org.example.custom.event.typeB&quot;, &quot;foo&quot;]
     # Share only events of type `org.example.custom.event.typeC` whose
     # state_key is &quot;bar&quot; or &quot;baz&quot;
     - [&quot;org.example.custom.event.typeC&quot;, &quot;bar&quot;]
     - [&quot;org.example.custom.event.typeC&quot;, &quot;baz&quot;]
</code></pre>
<p><em>Changed in Synapse 1.74:</em> admins can filter the events in prejoin state based
on their state key.</p>
<hr />
<h3 id="track_puppeted_user_ips"><a class="header" href="#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a></h3>
<p>We record the IP address of clients used to access the API for various
reasons, including displaying it to the user in the &quot;Where you're signed in&quot;
dialog.</p>
<p>By default, when puppeting another user via the admin API, the client IP
address is recorded against the user who created the access token (ie, the
admin user), and <em>not</em> the puppeted user.</p>
<p>Set this option to true to also record the IP address against the puppeted
user. (This also means that the puppeted user will count as an &quot;active&quot; user
for the purpose of monthly active user tracking - see <code>limit_usage_by_mau</code> etc
above.)</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">track_puppeted_user_ips: true
</code></pre>
<hr />
<h3 id="app_service_config_files"><a class="header" href="#app_service_config_files"><code>app_service_config_files</code></a></h3>
<p>A list of application service config files to use.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">app_service_config_files:
  - app_service_1.yaml
  - app_service_2.yaml
</code></pre>
<hr />
<h3 id="track_appservice_user_ips"><a class="header" href="#track_appservice_user_ips"><code>track_appservice_user_ips</code></a></h3>
<p>Defaults to false. Set to true to enable tracking of application service IP addresses.
Implicitly enables MAU tracking for application service users.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">track_appservice_user_ips: true
</code></pre>
<hr />
<h3 id="use_appservice_legacy_authorization"><a class="header" href="#use_appservice_legacy_authorization"><code>use_appservice_legacy_authorization</code></a></h3>
<p>Whether to send the application service access tokens via the <code>access_token</code> query parameter
per older versions of the Matrix specification. Defaults to false. Set to true to enable sending
access tokens via a query parameter.</p>
<p>**Enabling this option is considered insecure and is not recommended. **</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">use_appservice_legacy_authorization: true 
</code></pre>
<hr />
<h3 id="macaroon_secret_key"><a class="header" href="#macaroon_secret_key"><code>macaroon_secret_key</code></a></h3>
<p>A secret which is used to sign</p>
<ul>
<li>access token for guest users,</li>
<li>short-term login token used during SSO logins (OIDC or SAML2) and</li>
<li>token used for unsubscribing from email notifications.</li>
</ul>
<p>If none is specified, the <code>registration_shared_secret</code> is used, if one is given;
otherwise, a secret key is derived from the signing key.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">macaroon_secret_key: &lt;PRIVATE STRING&gt;
</code></pre>
<hr />
<h3 id="form_secret"><a class="header" href="#form_secret"><code>form_secret</code></a></h3>
<p>A secret which is used to calculate HMACs for form values, to stop
falsification of values. Must be specified for the User Consent
forms to work.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">form_secret: &lt;PRIVATE STRING&gt;
</code></pre>
<hr />
<h2 id="signing-keys"><a class="header" href="#signing-keys">Signing Keys</a></h2>
<p>Config options relating to signing keys</p>
<hr />
<h3 id="signing_key_path"><a class="header" href="#signing_key_path"><code>signing_key_path</code></a></h3>
<p>Path to the signing key to sign events and federation requests with.</p>
<p><em>New in Synapse 1.67</em>: If this file does not exist, Synapse will create a new signing
key on startup and store it in this file.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
</code></pre>
<hr />
<h3 id="old_signing_keys"><a class="header" href="#old_signing_keys"><code>old_signing_keys</code></a></h3>
<p>The keys that the server used to sign messages with but won't use
to sign new messages. For each key, <code>key</code> should be the base64-encoded public key, and
<code>expired_ts</code>should be the time (in milliseconds since the unix epoch) that
it was last used.</p>
<p>It is possible to build an entry from an old <code>signing.key</code> file using the
<code>export_signing_key</code> script which is provided with synapse.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">old_signing_keys:
  &quot;ed25519:id&quot;: { key: &quot;base64string&quot;, expired_ts: 123456789123 }
</code></pre>
<hr />
<h3 id="key_refresh_interval"><a class="header" href="#key_refresh_interval"><code>key_refresh_interval</code></a></h3>
<p>How long key response published by this server is valid for.
Used to set the <code>valid_until_ts</code> in <code>/key/v2</code> APIs.
Determines how quickly servers will query to check which keys
are still valid. Defaults to 1d.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">key_refresh_interval: 2d
</code></pre>
<hr />
<h3 id="trusted_key_servers"><a class="header" href="#trusted_key_servers"><code>trusted_key_servers</code></a></h3>
<p>The trusted servers to download signing keys from.</p>
<p>When we need to fetch a signing key, each server is tried in parallel.</p>
<p>Normally, the connection to the key server is validated via TLS certificates.
Additional security can be provided by configuring a <code>verify key</code>, which
will make synapse check that the response is signed by that key.</p>
<p>This setting supercedes an older setting named <code>perspectives</code>. The old format
is still supported for backwards-compatibility, but it is deprecated.</p>
<p><code>trusted_key_servers</code> defaults to matrix.org, but using it will generate a
warning on start-up. To suppress this warning, set
<code>suppress_key_server_warning</code> to true.</p>
<p>If the use of a trusted key server has to be deactivated, e.g. in a private
federation or for privacy reasons, this can be realised by setting
an empty array (<code>trusted_key_servers: []</code>). Then Synapse will request the keys
directly from the server that owns the keys. If Synapse does not get keys directly
from the server, the events of this server will be rejected.</p>
<p>Options for each entry in the list include:</p>
<ul>
<li><code>server_name</code>: the name of the server. Required.</li>
<li><code>verify_keys</code>: an optional map from key id to base64-encoded public key.
If specified, we will check that the response is signed by at least
one of the given keys.</li>
<li><code>accept_keys_insecurely</code>: a boolean. Normally, if <code>verify_keys</code> is unset,
and <code>federation_verify_certificates</code> is not <code>true</code>, synapse will refuse
to start, because this would allow anyone who can spoof DNS responses
to masquerade as the trusted key server. If you know what you are doing
and are sure that your network environment provides a secure connection
to the key server, you can set this to <code>true</code> to override this behaviour.</li>
</ul>
<p>Example configuration #1:</p>
<pre><code class="language-yaml">trusted_key_servers:
  - server_name: &quot;my_trusted_server.example.com&quot;
    verify_keys:
      &quot;ed25519:auto&quot;: &quot;abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr&quot;
  - server_name: &quot;my_other_trusted_server.example.com&quot;
</code></pre>
<p>Example configuration #2:</p>
<pre><code class="language-yaml">trusted_key_servers:
  - server_name: &quot;matrix.org&quot;
</code></pre>
<hr />
<h3 id="suppress_key_server_warning"><a class="header" href="#suppress_key_server_warning"><code>suppress_key_server_warning</code></a></h3>
<p>Set the following to true to disable the warning that is emitted when the
<code>trusted_key_servers</code> include 'matrix.org'. See above.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">suppress_key_server_warning: true
</code></pre>
<hr />
<h3 id="key_server_signing_keys_path"><a class="header" href="#key_server_signing_keys_path"><code>key_server_signing_keys_path</code></a></h3>
<p>The signing keys to use when acting as a trusted key server. If not specified
defaults to the server signing key.</p>
<p>Can contain multiple keys, one per line.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">key_server_signing_keys_path: &quot;key_server_signing_keys.key&quot;
</code></pre>
<hr />
<h2 id="single-sign-on-integration"><a class="header" href="#single-sign-on-integration">Single sign-on integration</a></h2>
<p>The following settings can be used to make Synapse use a single sign-on
provider for authentication, instead of its internal password database.</p>
<p>You will probably also want to set the following options to <code>false</code> to
disable the regular login/registration flows:</p>
<ul>
<li><a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a></li>
<li><a href="usage/configuration/config_documentation.html#password_config"><code>password_config.enabled</code></a></li>
</ul>
<hr />
<h3 id="saml2_config"><a class="header" href="#saml2_config"><code>saml2_config</code></a></h3>
<p>Enable SAML2 for registration and login. Uses pysaml2. To learn more about pysaml and
to find a full list options for configuring pysaml, read the docs <a href="https://pysaml2.readthedocs.io/en/latest/">here</a>.</p>
<p>At least one of <code>sp_config</code> or <code>config_path</code> must be set in this section to
enable SAML login. You can either put your entire pysaml config inline using the <code>sp_config</code>
option, or you can specify a path to a psyaml config file with the sub-option <code>config_path</code>.
This setting has the following sub-options:</p>
<ul>
<li><code>idp_name</code>: A user-facing name for this identity provider, which is used to
offer the user a choice of login mechanisms.</li>
<li><code>idp_icon</code>: An optional icon for this identity provider, which is presented
by clients and Synapse's own IdP picker page. If given, must be an
MXC URI of the format <code>mxc://&lt;server-name&gt;/&lt;media-id&gt;</code>. (An easy way to
obtain such an MXC URI is to upload an image to an (unencrypted) room
and then copy the &quot;url&quot; from the source of the event.)</li>
<li><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
to style the login flow according to the identity provider in question.
See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</li>
<li><code>sp_config</code>: the configuration for the pysaml2 Service Provider. See pysaml2 docs for format of config.
Default values will be used for the <code>entityid</code> and <code>service</code> settings,
so it is not normally necessary to specify them unless you need to
override them. Here are a few useful sub-options for configuring pysaml:
<ul>
<li><code>metadata</code>: Point this to the IdP's metadata. You must provide either a local
file via the <code>local</code> attribute or (preferably) a URL via the
<code>remote</code> attribute.</li>
<li><code>accepted_time_diff: 3</code>: Allowed clock difference in seconds between the homeserver and IdP.
Defaults to 0.</li>
<li><code>service</code>: By default, the user has to go to our login page first. If you'd like
to allow IdP-initiated login, set <code>allow_unsolicited</code> to true under <code>sp</code> in the <code>service</code>
section.</li>
</ul>
</li>
<li><code>config_path</code>: specify a separate pysaml2 configuration file thusly:
<code>config_path: &quot;CONFDIR/sp_conf.py&quot;</code></li>
<li><code>saml_session_lifetime</code>: The lifetime of a SAML session. This defines how long a user has to
complete the authentication process, if <code>allow_unsolicited</code> is unset. The default is 15 minutes.</li>
<li><code>user_mapping_provider</code>: Using this option, an external module can be provided as a
custom solution to mapping attributes returned from a saml provider onto a matrix user. The
<code>user_mapping_provider</code> has the following attributes:
<ul>
<li><code>module</code>: The custom module's class.</li>
<li><code>config</code>: Custom configuration values for the module. Use the values provided in the
example if you are using the built-in user_mapping_provider, or provide your own
config values for a custom class if you are using one. This section will be passed as a Python
dictionary to the module's <code>parse_config</code> method. The built-in provider takes the following two
options:
<ul>
<li><code>mxid_source_attribute</code>: The SAML attribute (after mapping via the attribute maps) to use
to derive the Matrix ID from. It is 'uid' by default. Note: This used to be configured by the
<code>saml2_config.mxid_source_attribute option</code>. If that is still defined, its value will be used instead.</li>
<li><code>mxid_mapping</code>: The mapping system to use for mapping the saml attribute onto a
matrix ID. Options include: <code>hexencode</code> (which maps unpermitted characters to '=xx')
and <code>dotreplace</code> (which replaces unpermitted characters with '.').
The default is <code>hexencode</code>. Note: This used to be configured by the
<code>saml2_config.mxid_mapping option</code>. If that is still defined, its value will be used instead.</li>
</ul>
</li>
</ul>
</li>
<li><code>grandfathered_mxid_source_attribute</code>: In previous versions of synapse, the mapping from SAML attribute to
MXID was always calculated dynamically rather than stored in a table. For backwards- compatibility, we will look for <code>user_ids</code>
matching such a pattern before creating a new account. This setting controls the SAML attribute which will be used for this
backwards-compatibility lookup. Typically it should be 'uid', but if the attribute maps are changed, it may be necessary to change it.
The default is 'uid'.</li>
<li><code>attribute_requirements</code>: It is possible to configure Synapse to only allow logins if SAML attributes
match particular values. The requirements can be listed under
<code>attribute_requirements</code> as shown in the example. All of the listed attributes must
match for the login to be permitted.</li>
<li><code>idp_entityid</code>: If the metadata XML contains multiple IdP entities then the <code>idp_entityid</code>
option must be set to the entity to redirect users to.
Most deployments only have a single IdP entity and so should omit this option.</li>
</ul>
<p>Once SAML support is enabled, a metadata file will be exposed at
<code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/metadata.xml</code>, which you may be able to
use to configure your SAML IdP with. Alternatively, you can manually configure
the IdP to use an ACS location of
<code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/authn_response</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">saml2_config:
  sp_config:
    metadata:
      local: [&quot;saml2/idp.xml&quot;]
      remote:
        - url: https://our_idp/metadata.xml
    accepted_time_diff: 3

    service:
      sp:
        allow_unsolicited: true

    # The examples below are just used to generate our metadata xml, and you
    # may well not need them, depending on your setup. Alternatively you
    # may need a whole lot more detail - see the pysaml2 docs!
    description: [&quot;My awesome SP&quot;, &quot;en&quot;]
    name: [&quot;Test SP&quot;, &quot;en&quot;]

    ui_info:
      display_name:
        - lang: en
          text: &quot;Display Name is the descriptive name of your service.&quot;
      description:
        - lang: en
          text: &quot;Description should be a short paragraph explaining the purpose of the service.&quot;
      information_url:
        - lang: en
          text: &quot;https://example.com/terms-of-service&quot;
      privacy_statement_url:
        - lang: en
          text: &quot;https://example.com/privacy-policy&quot;
      keywords:
        - lang: en
          text: [&quot;Matrix&quot;, &quot;Element&quot;]
      logo:
        - lang: en
          text: &quot;https://example.com/logo.svg&quot;
          width: &quot;200&quot;
          height: &quot;80&quot;

    organization:
      name: Example com
      display_name:
        - [&quot;Example co&quot;, &quot;en&quot;]
      url: &quot;http://example.com&quot;

    contact_person:
      - given_name: Bob
        sur_name: &quot;the Sysadmin&quot;
        email_address&quot;: [&quot;admin@example.com&quot;]
        contact_type&quot;: technical

  saml_session_lifetime: 5m

  user_mapping_provider:
    # Below options are intended for the built-in provider, they should be
    # changed if using a custom module.
    config:
      mxid_source_attribute: displayName
      mxid_mapping: dotreplace

  grandfathered_mxid_source_attribute: upn

  attribute_requirements:
    - attribute: userGroup
      value: &quot;staff&quot;
    - attribute: department
      value: &quot;sales&quot;

  idp_entityid: 'https://our_idp/entityid'
</code></pre>
<hr />
<h3 id="oidc_providers"><a class="header" href="#oidc_providers"><code>oidc_providers</code></a></h3>
<p>List of OpenID Connect (OIDC) / OAuth 2.0 identity providers, for registration
and login. See <a href="usage/configuration/../../openid.html">here</a>
for information on how to configure these options.</p>
<p>For backwards compatibility, it is also possible to configure a single OIDC
provider via an <code>oidc_config</code> setting. This is now deprecated and admins are
advised to migrate to the <code>oidc_providers</code> format. (When doing that migration,
use <code>oidc</code> for the <code>idp_id</code> to ensure that existing users continue to be
recognised.)</p>
<p>Options for each entry include:</p>
<ul>
<li>
<p><code>idp_id</code>: a unique identifier for this identity provider. Used internally
by Synapse; should be a single word such as 'github'.
Note that, if this is changed, users authenticating via that provider
will no longer be recognised as the same user!
(Use &quot;oidc&quot; here if you are migrating from an old <code>oidc_config</code> configuration.)</p>
</li>
<li>
<p><code>idp_name</code>: A user-facing name for this identity provider, which is used to
offer the user a choice of login mechanisms.</p>
</li>
<li>
<p><code>idp_icon</code>: An optional icon for this identity provider, which is presented
by clients and Synapse's own IdP picker page. If given, must be an
MXC URI of the format <code>mxc://&lt;server-name&gt;/&lt;media-id&gt;</code>. (An easy way to
obtain such an MXC URI is to upload an image to an (unencrypted) room
and then copy the &quot;url&quot; from the source of the event.)</p>
</li>
<li>
<p><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
to style the login flow according to the identity provider in question.
See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</p>
</li>
<li>
<p><code>discover</code>: set to false to disable the use of the OIDC discovery mechanism
to discover endpoints. Defaults to true.</p>
</li>
<li>
<p><code>issuer</code>: Required. The OIDC issuer. Used to validate tokens and (if discovery
is enabled) to discover the provider's endpoints.</p>
</li>
<li>
<p><code>client_id</code>: Required. oauth2 client id to use.</p>
</li>
<li>
<p><code>client_secret</code>: oauth2 client secret to use. May be omitted if
<code>client_secret_jwt_key</code> is given, or if <code>client_auth_method</code> is 'none'.
Must be omitted if <code>client_secret_path</code> is specified.</p>
</li>
<li>
<p><code>client_secret_path</code>: path to the oauth2 client secret to use. With that
it's not necessary to leak secrets into the config file itself.
Mutually exclusive with <code>client_secret</code>. Can be omitted if
<code>client_secret_jwt_key</code> is specified.</p>
<p><em>Added in Synapse 1.91.0.</em></p>
</li>
<li>
<p><code>client_secret_jwt_key</code>: Alternative to client_secret: details of a key used
to create a JSON Web Token to be used as an OAuth2 client secret. If
given, must be a dictionary with the following properties:</p>
<ul>
<li>
<p><code>key</code>: a pem-encoded signing key. Must be a suitable key for the
algorithm specified. Required unless <code>key_file</code> is given.</p>
</li>
<li>
<p><code>key_file</code>: the path to file containing a pem-encoded signing key file.
Required unless <code>key</code> is given.</p>
</li>
<li>
<p><code>jwt_header</code>: a dictionary giving properties to include in the JWT
header. Must include the key <code>alg</code>, giving the algorithm used to
sign the JWT, such as &quot;ES256&quot;, using the JWA identifiers in
RFC7518.</p>
</li>
<li>
<p><code>jwt_payload</code>: an optional dictionary giving properties to include in
the JWT payload. Normally this should include an <code>iss</code> key.</p>
</li>
</ul>
</li>
<li>
<p><code>client_auth_method</code>: auth method to use when exchanging the token. Valid
values are <code>client_secret_basic</code> (default), <code>client_secret_post</code> and
<code>none</code>.</p>
</li>
<li>
<p><code>pkce_method</code>: Whether to use proof key for code exchange when requesting
and exchanging the token. Valid values are: <code>auto</code>, <code>always</code>, or <code>never</code>. Defaults
to <code>auto</code>, which uses PKCE if supported during metadata discovery. Set to <code>always</code>
to force enable PKCE or <code>never</code> to force disable PKCE.</p>
</li>
<li>
<p><code>scopes</code>: list of scopes to request. This should normally include the &quot;openid&quot;
scope. Defaults to <code>[&quot;openid&quot;]</code>.</p>
</li>
<li>
<p><code>authorization_endpoint</code>: the oauth2 authorization endpoint. Required if
provider discovery is disabled.</p>
</li>
<li>
<p><code>token_endpoint</code>: the oauth2 token endpoint. Required if provider discovery is
disabled.</p>
</li>
<li>
<p><code>userinfo_endpoint</code>: the OIDC userinfo endpoint. Required if discovery is
disabled and the 'openid' scope is not requested.</p>
</li>
<li>
<p><code>jwks_uri</code>: URI where to fetch the JWKS. Required if discovery is disabled and
the 'openid' scope is used.</p>
</li>
<li>
<p><code>skip_verification</code>: set to 'true' to skip metadata verification. Use this if
you are connecting to a provider that is not OpenID Connect compliant.
Defaults to false. Avoid this in production.</p>
</li>
<li>
<p><code>user_profile_method</code>: Whether to fetch the user profile from the userinfo
endpoint, or to rely on the data returned in the id_token from the <code>token_endpoint</code>.
Valid values are: <code>auto</code> or <code>userinfo_endpoint</code>.
Defaults to <code>auto</code>, which uses the userinfo endpoint if <code>openid</code> is
not included in <code>scopes</code>. Set to <code>userinfo_endpoint</code> to always use the
userinfo endpoint.</p>
</li>
<li>
<p><code>allow_existing_users</code>: set to true to allow a user logging in via OIDC to
match a pre-existing account instead of failing. This could be used if
switching from password logins to OIDC. Defaults to false.</p>
</li>
<li>
<p><code>enable_registration</code>: set to 'false' to disable automatic registration of new
users. This allows the OIDC SSO flow to be limited to sign in only, rather than
automatically registering users that have a valid SSO login but do not have
a pre-registered account. Defaults to true.</p>
</li>
<li>
<p><code>user_mapping_provider</code>: Configuration for how attributes returned from a OIDC
provider are mapped onto a matrix user. This setting has the following
sub-properties:</p>
<ul>
<li>
<p><code>module</code>: The class name of a custom mapping module. Default is
<code>synapse.handlers.oidc.JinjaOidcMappingProvider</code>.
See <a href="usage/configuration/../../sso_mapping_providers.html#openid-mapping-providers">OpenID Mapping Providers</a>
for information on implementing a custom mapping provider.</p>
</li>
<li>
<p><code>config</code>: Configuration for the mapping provider module. This section will
be passed as a Python dictionary to the user mapping provider
module's <code>parse_config</code> method.</p>
<p>For the default provider, the following settings are available:</p>
<ul>
<li>
<p><code>subject_template</code>: Jinja2 template for a unique identifier for the user.
Defaults to <code>{{ user.sub }}</code>, which OpenID Connect compliant providers should provide.</p>
<p>This replaces and overrides <code>subject_claim</code>.</p>
</li>
<li>
<p><code>subject_claim</code>: name of the claim containing a unique identifier
for the user. Defaults to 'sub', which OpenID Connect
compliant providers should provide.</p>
<p><em>Deprecated in Synapse v1.75.0.</em></p>
</li>
<li>
<p><code>picture_template</code>: Jinja2 template for an url for the user's profile picture.
Defaults to <code>{{ user.picture }}</code>, which OpenID Connect compliant providers should
provide and has to refer to a direct image file such as PNG, JPEG, or GIF image file.</p>
<p>This replaces and overrides <code>picture_claim</code>.</p>
<p>Currently only supported in monolithic (single-process) server configurations
where the media repository runs within the Synapse process.</p>
</li>
<li>
<p><code>picture_claim</code>: name of the claim containing an url for the user's profile picture.
Defaults to 'picture', which OpenID Connect compliant providers should provide
and has to refer to a direct image file such as PNG, JPEG, or GIF image file.</p>
<p>Currently only supported in monolithic (single-process) server configurations
where the media repository runs within the Synapse process.</p>
<p><em>Deprecated in Synapse v1.75.0.</em></p>
</li>
<li>
<p><code>localpart_template</code>: Jinja2 template for the localpart of the MXID.
If this is not set, the user will be prompted to choose their
own username (see the documentation for the <code>sso_auth_account_details.html</code>
template). This template can use the <code>localpart_from_email</code> filter.</p>
</li>
<li>
<p><code>confirm_localpart</code>: Whether to prompt the user to validate (or
change) the generated localpart (see the documentation for the
'sso_auth_account_details.html' template), instead of
registering the account right away.</p>
</li>
<li>
<p><code>display_name_template</code>: Jinja2 template for the display name to set
on first login. If unset, no displayname will be set.</p>
</li>
<li>
<p><code>email_template</code>: Jinja2 template for the email address of the user.
If unset, no email address will be added to the account.</p>
</li>
<li>
<p><code>extra_attributes</code>: a map of Jinja2 templates for extra attributes
to send back to the client during login. Note that these are non-standard and clients will ignore them
without modifications.</p>
</li>
</ul>
</li>
</ul>
<p>When rendering, the Jinja2 templates are given a 'user' variable,
which is set to the claims returned by the UserInfo Endpoint and/or
in the ID Token.</p>
</li>
<li>
<p><code>backchannel_logout_enabled</code>: set to <code>true</code> to process OIDC Back-Channel Logout notifications.
Those notifications are expected to be received on <code>/_synapse/client/oidc/backchannel_logout</code>.
Defaults to <code>false</code>.</p>
</li>
<li>
<p><code>backchannel_logout_ignore_sub</code>: by default, the OIDC Back-Channel Logout feature checks that the
<code>sub</code> claim matches the subject claim received during login. This check can be disabled by setting
this to <code>true</code>. Defaults to <code>false</code>.</p>
<p>You might want to disable this if the <code>subject_claim</code> returned by the mapping provider is not <code>sub</code>.</p>
</li>
</ul>
<p>It is possible to configure Synapse to only allow logins if certain attributes
match particular values in the OIDC userinfo. The requirements can be listed under
<code>attribute_requirements</code> as shown here:</p>
<pre><code class="language-yaml">attribute_requirements:
     - attribute: family_name
       value: &quot;Stephensson&quot;
     - attribute: groups
       value: &quot;admin&quot;
</code></pre>
<p>All of the listed attributes must match for the login to be permitted. Additional attributes can be added to
userinfo by expanding the <code>scopes</code> section of the OIDC config to retrieve
additional information from the OIDC provider.</p>
<p>If the OIDC claim is a list, then the attribute must match any value in the list.
Otherwise, it must exactly match the value of the claim. Using the example
above, the <code>family_name</code> claim MUST be &quot;Stephensson&quot;, but the <code>groups</code>
claim MUST contain &quot;admin&quot;.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">oidc_providers:
  # Generic example
  #
  - idp_id: my_idp
    idp_name: &quot;My OpenID provider&quot;
    idp_icon: &quot;mxc://example.com/mediaid&quot;
    discover: false
    issuer: &quot;https://accounts.example.com/&quot;
    client_id: &quot;provided-by-your-issuer&quot;
    client_secret: &quot;provided-by-your-issuer&quot;
    client_auth_method: client_secret_post
    scopes: [&quot;openid&quot;, &quot;profile&quot;]
    authorization_endpoint: &quot;https://accounts.example.com/oauth2/auth&quot;
    token_endpoint: &quot;https://accounts.example.com/oauth2/token&quot;
    userinfo_endpoint: &quot;https://accounts.example.com/userinfo&quot;
    jwks_uri: &quot;https://accounts.example.com/.well-known/jwks.json&quot;
    skip_verification: true
    enable_registration: true
    user_mapping_provider:
      config:
        subject_claim: &quot;id&quot;
        localpart_template: &quot;{{ user.login }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
        email_template: &quot;{{ user.email }}&quot;
    attribute_requirements:
      - attribute: userGroup
        value: &quot;synapseUsers&quot;
</code></pre>
<hr />
<h3 id="cas_config"><a class="header" href="#cas_config"><code>cas_config</code></a></h3>
<p>Enable Central Authentication Service (CAS) for registration and login.
Has the following sub-options:</p>
<ul>
<li><code>enabled</code>: Set this to true to enable authorization against a CAS server.
Defaults to false.</li>
<li><code>idp_name</code>: A user-facing name for this identity provider, which is used to
offer the user a choice of login mechanisms.</li>
<li><code>idp_icon</code>: An optional icon for this identity provider, which is presented
by clients and Synapse's own IdP picker page. If given, must be an
MXC URI of the format <code>mxc://&lt;server-name&gt;/&lt;media-id&gt;</code>. (An easy way to
obtain such an MXC URI is to upload an image to an (unencrypted) room
and then copy the &quot;url&quot; from the source of the event.)</li>
<li><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
to style the login flow according to the identity provider in question.
See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</li>
<li><code>server_url</code>: The URL of the CAS authorization endpoint.</li>
<li><code>protocol_version</code>: The CAS protocol version, defaults to none (version 3 is required if you want to use &quot;required_attributes&quot;).</li>
<li><code>displayname_attribute</code>: The attribute of the CAS response to use as the display name.
If no name is given here, no displayname will be set.</li>
<li><code>required_attributes</code>:  It is possible to configure Synapse to only allow logins if CAS attributes
match particular values. All of the keys given below must exist
and the values must match the given value. Alternately if the given value
is <code>None</code> then any value is allowed (the attribute just must exist).
All of the listed attributes must match for the login to be permitted.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">cas_config:
  enabled: true
  server_url: &quot;https://cas-server.com&quot;
  protocol_version: 3
  displayname_attribute: name
  required_attributes:
    userGroup: &quot;staff&quot;
    department: None
</code></pre>
<hr />
<h3 id="sso"><a class="header" href="#sso"><code>sso</code></a></h3>
<p>Additional settings to use with single-sign on systems such as OpenID Connect,
SAML2 and CAS.</p>
<p>Server admins can configure custom templates for pages related to SSO. See
<a href="usage/configuration/../../templates.html">here</a> for more information.</p>
<p>Options include:</p>
<ul>
<li><code>client_whitelist</code>: A list of client URLs which are whitelisted so that the user does not
have to confirm giving access to their account to the URL. Any client
whose URL starts with an entry in the following list will not be subject
to an additional confirmation step after the SSO login is completed.
WARNING: An entry such as &quot;https://my.client&quot; is insecure, because it
will also match &quot;https://my.client.evil.site&quot;, exposing your users to
phishing attacks from evil.site. To avoid this, include a slash after the
hostname: &quot;https://my.client/&quot;.
The login fallback page (used by clients that don't natively support the
required login flows) is whitelisted in addition to any URLs in this list.
By default, this list contains only the login fallback page.</li>
<li><code>update_profile_information</code>: Use this setting to keep a user's profile fields in sync with information from
the identity provider. Currently only syncing the displayname is supported. Fields
are checked on every SSO login, and are updated if necessary.
Note that enabling this option will override user profile information,
regardless of whether users have opted-out of syncing that
information when first signing in. Defaults to false.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">sso:
    client_whitelist:
      - https://riot.im/develop
      - https://my.custom.client/
    update_profile_information: true
</code></pre>
<hr />
<h3 id="jwt_config"><a class="header" href="#jwt_config"><code>jwt_config</code></a></h3>
<p>JSON web token integration. The following settings can be used to make
Synapse JSON web tokens for authentication, instead of its internal
password database.</p>
<p>Each JSON Web Token needs to contain a &quot;sub&quot; (subject) claim, which is
used as the localpart of the mxid.</p>
<p>Additionally, the expiration time (&quot;exp&quot;), not before time (&quot;nbf&quot;),
and issued at (&quot;iat&quot;) claims are validated if present.</p>
<p>Note that this is a non-standard login type and client support is
expected to be non-existent.</p>
<p>See <a href="usage/configuration/../../jwt.html">here</a> for more.</p>
<p>Additional sub-options for this setting include:</p>
<ul>
<li><code>enabled</code>: Set to true to enable authorization using JSON web
tokens. Defaults to false.</li>
<li><code>secret</code>: This is either the private shared secret or the public key used to
decode the contents of the JSON web token. Required if <code>enabled</code> is set to true.</li>
<li><code>algorithm</code>: The algorithm used to sign (or HMAC) the JSON web token.
Supported algorithms are listed
<a href="https://docs.authlib.org/en/latest/specs/rfc7518.html">here (section JWS)</a>.
Required if <code>enabled</code> is set to true.</li>
<li><code>subject_claim</code>: Name of the claim containing a unique identifier for the user.
Optional, defaults to <code>sub</code>.</li>
<li><code>issuer</code>: The issuer to validate the &quot;iss&quot; claim against. Optional. If provided the
&quot;iss&quot; claim will be required and validated for all JSON web tokens.</li>
<li><code>audiences</code>: A list of audiences to validate the &quot;aud&quot; claim against. Optional.
If provided the &quot;aud&quot; claim will be required and validated for all JSON web tokens.
Note that if the &quot;aud&quot; claim is included in a JSON web token then
validation will fail without configuring audiences.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">jwt_config:
    enabled: true
    secret: &quot;provided-by-your-issuer&quot;
    algorithm: &quot;provided-by-your-issuer&quot;
    subject_claim: &quot;name_of_claim&quot;
    issuer: &quot;provided-by-your-issuer&quot;
    audiences:
        - &quot;provided-by-your-issuer&quot;
</code></pre>
<hr />
<h3 id="password_config"><a class="header" href="#password_config"><code>password_config</code></a></h3>
<p>Use this setting to enable password-based logins.</p>
<p>This setting has the following sub-options:</p>
<ul>
<li><code>enabled</code>: Defaults to true.
Set to false to disable password authentication.
Set to <code>only_for_reauth</code> to allow users with existing passwords to use them
to log in and reauthenticate, whilst preventing new users from setting passwords.</li>
<li><code>localdb_enabled</code>: Set to false to disable authentication against the local password
database. This is ignored if <code>enabled</code> is false, and is only useful
if you have other <code>password_providers</code>. Defaults to true.</li>
<li><code>pepper</code>: Set the value here to a secret random string for extra security.
DO NOT CHANGE THIS AFTER INITIAL SETUP!</li>
<li><code>policy</code>: Define and enforce a password policy, such as minimum lengths for passwords, etc.
Each parameter is optional. This is an implementation of MSC2000. Parameters are as follows:
<ul>
<li><code>enabled</code>: Defaults to false. Set to true to enable.</li>
<li><code>minimum_length</code>: Minimum accepted length for a password. Defaults to 0.</li>
<li><code>require_digit</code>: Whether a password must contain at least one digit.
Defaults to false.</li>
<li><code>require_symbol</code>: Whether a password must contain at least one symbol.
A symbol is any character that's not a number or a letter. Defaults to false.</li>
<li><code>require_lowercase</code>: Whether a password must contain at least one lowercase letter.
Defaults to false.</li>
<li><code>require_uppercase</code>: Whether a password must contain at least one uppercase letter.
Defaults to false.</li>
</ul>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">password_config:
   enabled: false
   localdb_enabled: false
   pepper: &quot;EVEN_MORE_SECRET&quot;

   policy:
      enabled: true
      minimum_length: 15
      require_digit: true
      require_symbol: true
      require_lowercase: true
      require_uppercase: true
</code></pre>
<hr />
<h2 id="push"><a class="header" href="#push">Push</a></h2>
<p>Configuration settings related to push notifications</p>
<hr />
<h3 id="push-1"><a class="header" href="#push-1"><code>push</code></a></h3>
<p>This setting defines options for push notifications.</p>
<p>This option has a number of sub-options. They are as follows:</p>
<ul>
<li><code>enabled</code>: Enables or disables push notification calculation. Note, disabling this will also
stop unread counts being calculated for rooms. This mode of operation is intended
for homeservers which may only have bots or appservice users connected, or are otherwise
not interested in push/unread counters. This is enabled by default.</li>
<li><code>include_content</code>: Clients requesting push notifications can either have the body of
the message sent in the notification poke along with other details
like the sender, or just the event ID and room ID (<code>event_id_only</code>).
If clients choose the to have the body sent, this option controls whether the
notification request includes the content of the event (other details
like the sender are still included). If <code>event_id_only</code> is enabled, it
has no effect.
For modern android devices the notification content will still appear
because it is loaded by the app. iPhone, however will send a
notification saying only that a message arrived and who it came from.
Defaults to true. Set to false to only include the event ID and room ID in push notification payloads.</li>
<li><code>group_unread_count_by_room: false</code>: When a push notification is received, an unread count is also sent.
This number can either be calculated as the number of unread messages  for the user, or the number of <em>rooms</em> the
user has unread messages in. Defaults to true, meaning push clients will see the number of
rooms with unread messages in them. Set to false to instead send the number
of unread messages.</li>
<li><code>jitter_delay</code>: Delays push notifications by a random amount up to the given
duration. Useful for mitigating timing attacks. Optional, defaults to no
delay. <em>Added in Synapse 1.84.0.</em></li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">push:
  enabled: true
  include_content: false
  group_unread_count_by_room: false
  jitter_delay: &quot;10s&quot;
</code></pre>
<hr />
<h2 id="rooms"><a class="header" href="#rooms">Rooms</a></h2>
<p>Config options relating to rooms.</p>
<hr />
<h3 id="encryption_enabled_by_default_for_room_type"><a class="header" href="#encryption_enabled_by_default_for_room_type"><code>encryption_enabled_by_default_for_room_type</code></a></h3>
<p>Controls whether locally-created rooms should be end-to-end encrypted by
default.</p>
<p>Possible options are &quot;all&quot;, &quot;invite&quot;, and &quot;off&quot;. They are defined as:</p>
<ul>
<li>&quot;all&quot;: any locally-created room</li>
<li>&quot;invite&quot;: any room created with the <code>private_chat</code> or <code>trusted_private_chat</code>
room creation presets</li>
<li>&quot;off&quot;: this option will take no effect</li>
</ul>
<p>The default value is &quot;off&quot;.</p>
<p>Note that this option will only affect rooms created after it is set. It
will also not affect rooms created by other servers.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">encryption_enabled_by_default_for_room_type: invite
</code></pre>
<hr />
<h3 id="user_directory"><a class="header" href="#user_directory"><code>user_directory</code></a></h3>
<p>This setting defines options related to the user directory.</p>
<p>This option has the following sub-options:</p>
<ul>
<li>
<p><code>enabled</code>:  Defines whether users can search the user directory. If false then
empty responses are returned to all queries. Defaults to true.</p>
</li>
<li>
<p><code>search_all_users</code>: Defines whether to search all users visible to your HS at the time the search is performed. If set to true, will return all users who share a room with the user from the homeserver.
If false, search results will only contain users
visible in public rooms and users sharing a room with the requester.
Defaults to false.</p>
<p>NB. If you set this to true, and the last time the user_directory search
indexes were (re)built was before Synapse 1.44, you'll have to
rebuild the indexes in order to search through all known users.</p>
<p>These indexes are built the first time Synapse starts; admins can
manually trigger a rebuild via the API following the instructions
<a href="usage/configuration/../administration/admin_api/background_updates.html#run">for running background updates</a>,
set to true to return search results containing all known users, even if that
user does not share a room with the requester.</p>
</li>
<li>
<p><code>prefer_local_users</code>: Defines whether to prefer local users in search query results.
If set to true, local users are more likely to appear above remote users when searching the
user directory. Defaults to false.</p>
</li>
<li>
<p><code>show_locked_users</code>: Defines whether to show locked users in search query results. Defaults to false.</p>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">user_directory:
    enabled: false
    search_all_users: true
    prefer_local_users: true
    show_locked_users: true
</code></pre>
<hr />
<h3 id="user_consent"><a class="header" href="#user_consent"><code>user_consent</code></a></h3>
<p>For detailed instructions on user consent configuration, see <a href="usage/configuration/../../consent_tracking.html">here</a>.</p>
<p>Parts of this section are required if enabling the <code>consent</code> resource under
<a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code></a>, in particular <code>template_dir</code> and <code>version</code>.</p>
<ul>
<li>
<p><code>template_dir</code>: gives the location of the templates for the HTML forms.
This directory should contain one subdirectory per language (eg, <code>en</code>, <code>fr</code>),
and each language directory should contain the policy document (named as
<version>.html) and a success page (success.html).</p>
</li>
<li>
<p><code>version</code>: specifies the 'current' version of the policy document. It defines
the version to be served by the consent resource if there is no 'v'
parameter.</p>
</li>
<li>
<p><code>server_notice_content</code>: if enabled, will send a user a &quot;Server Notice&quot;
asking them to consent to the privacy policy. The <a href="usage/configuration/config_documentation.html#server_notices"><code>server_notices</code> section</a>
must also be configured for this to work. Notices will <em>not</em> be sent to
guest users unless <code>send_server_notice_to_guests</code> is set to true.</p>
</li>
<li>
<p><code>block_events_error</code>, if set, will block any attempts to send events
until the user consents to the privacy policy. The value of the setting is
used as the text of the error.</p>
</li>
<li>
<p><code>require_at_registration</code>, if enabled, will add a step to the registration
process, similar to how captcha works. Users will be required to accept the
policy before their account is created.</p>
</li>
<li>
<p><code>policy_name</code> is the display name of the policy users will see when registering
for an account. Has no effect unless <code>require_at_registration</code> is enabled.
Defaults to &quot;Privacy Policy&quot;.</p>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">user_consent:
  template_dir: res/templates/privacy
  version: 1.0
  server_notice_content:
    msgtype: m.text
    body: &gt;-
      To continue using this homeserver you must review and agree to the
      terms and conditions at %(consent_uri)s
  send_server_notice_to_guests: true
  block_events_error: &gt;-
    To continue using this homeserver you must review and agree to the
    terms and conditions at %(consent_uri)s
  require_at_registration: false
  policy_name: Privacy Policy
</code></pre>
<hr />
<h3 id="stats"><a class="header" href="#stats"><code>stats</code></a></h3>
<p>Settings for local room and user statistics collection. See <a href="usage/configuration/../../room_and_user_statistics.html">here</a>
for more.</p>
<ul>
<li><code>enabled</code>: Set to false to disable room and user statistics. Note that doing
so may cause certain features (such as the room directory) not to work
correctly. Defaults to true.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">stats:
  enabled: false
</code></pre>
<hr />
<h3 id="server_notices"><a class="header" href="#server_notices"><code>server_notices</code></a></h3>
<p>Use this setting to enable a room which can be used to send notices
from the server to users. It is a special room which users cannot leave; notices
in the room come from a special &quot;notices&quot; user id.</p>
<p>If you use this setting, you <em>must</em> define the <code>system_mxid_localpart</code>
sub-setting, which defines the id of the user which will be used to send the
notices.</p>
<p>Sub-options for this setting include:</p>
<ul>
<li><code>system_mxid_display_name</code>: set the display name of the &quot;notices&quot; user</li>
<li><code>system_mxid_avatar_url</code>: set the avatar for the &quot;notices&quot; user</li>
<li><code>room_name</code>: set the room name of the server notices room</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">server_notices:
  system_mxid_localpart: notices
  system_mxid_display_name: &quot;Server Notices&quot;
  system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  room_name: &quot;Server Notices&quot;
</code></pre>
<hr />
<h3 id="enable_room_list_search"><a class="header" href="#enable_room_list_search"><code>enable_room_list_search</code></a></h3>
<p>Set to false to disable searching the public room list. When disabled
blocks searching local and remote room lists for local and remote
users by always returning an empty list for all queries. Defaults to true.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">enable_room_list_search: false
</code></pre>
<hr />
<h3 id="alias_creation_rules"><a class="header" href="#alias_creation_rules"><code>alias_creation_rules</code></a></h3>
<p>The <code>alias_creation_rules</code> option controls who is allowed to create aliases
on this server.</p>
<p>The format of this option is a list of rules that contain globs that
match against user_id, room_id and the new alias (fully qualified with
server name). The action in the first rule that matches is taken,
which can currently either be &quot;allow&quot; or &quot;deny&quot;.</p>
<p>Missing user_id/room_id/alias fields default to &quot;*&quot;.</p>
<p>If no rules match the request is denied. An empty list means no one
can create aliases.</p>
<p>Options for the rules include:</p>
<ul>
<li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
<li><code>alias</code>: Matches against the alias being created. Defaults to &quot;*&quot;.</li>
<li><code>room_id</code>: Matches against the room ID the alias is being pointed at. Defaults to &quot;*&quot;</li>
<li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">alias_creation_rules:
  - user_id: &quot;bad_user&quot;
    alias: &quot;spammy_alias&quot;
    room_id: &quot;*&quot;
    action: deny
</code></pre>
<hr />
<h3 id="room_list_publication_rules"><a class="header" href="#room_list_publication_rules"><code>room_list_publication_rules</code></a></h3>
<p>The <code>room_list_publication_rules</code> option controls who can publish and
which rooms can be published in the public room list.</p>
<p>The format of this option is the same as that for
<code>alias_creation_rules</code>.</p>
<p>If the room has one or more aliases associated with it, only one of
the aliases needs to match the alias rule. If there are no aliases
then only rules with <code>alias: *</code> match.</p>
<p>If no rules match the request is denied. An empty list means no one
can publish rooms.</p>
<p>Options for the rules include:</p>
<ul>
<li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
<li><code>alias</code>: Matches against any current local or canonical aliases associated with the room. Defaults to &quot;*&quot;.</li>
<li><code>room_id</code>: Matches against the room ID being published. Defaults to &quot;*&quot;.</li>
<li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">room_list_publication_rules:
  - user_id: &quot;*&quot;
    alias: &quot;*&quot;
    room_id: &quot;*&quot;
    action: allow
</code></pre>
<hr />
<h3 id="default_power_level_content_override"><a class="header" href="#default_power_level_content_override"><code>default_power_level_content_override</code></a></h3>
<p>The <code>default_power_level_content_override</code> option controls the default power
levels for rooms.</p>
<p>Useful if you know that your users need special permissions in rooms
that they create (e.g. to send particular types of state events without
needing an elevated power level).  This takes the same shape as the
<code>power_level_content_override</code> parameter in the /createRoom API, but
is applied before that parameter.</p>
<p>Note that each key provided inside a preset (for example <code>events</code> in the example
below) will overwrite all existing defaults inside that key. So in the example
below, newly-created private_chat rooms will have no rules for any event types
except <code>com.example.foo</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">default_power_level_content_override:
   private_chat: { &quot;events&quot;: { &quot;com.example.foo&quot; : 0 } }
   trusted_private_chat: null
   public_chat: null
</code></pre>
<hr />
<h3 id="forget_rooms_on_leave"><a class="header" href="#forget_rooms_on_leave"><code>forget_rooms_on_leave</code></a></h3>
<p>Set to true to automatically forget rooms for users when they leave them, either
normally or via a kick or ban. Defaults to false.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">forget_rooms_on_leave: false
</code></pre>
<hr />
<h3 id="exclude_rooms_from_sync"><a class="header" href="#exclude_rooms_from_sync"><code>exclude_rooms_from_sync</code></a></h3>
<p>A list of rooms to exclude from sync responses. This is useful for server
administrators wishing to group users into a room without these users being able
to see it from their client.</p>
<p>By default, no room is excluded.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">exclude_rooms_from_sync:
    - !foo:example.com
</code></pre>
<hr />
<h2 id="opentracing"><a class="header" href="#opentracing">Opentracing</a></h2>
<p>Configuration options related to Opentracing support.</p>
<hr />
<h3 id="opentracing-1"><a class="header" href="#opentracing-1"><code>opentracing</code></a></h3>
<p>These settings enable and configure opentracing, which implements distributed tracing.
This allows you to observe the causal chains of events across servers
including requests, key lookups etc., across any server running
synapse or any other services which support opentracing
(specifically those implemented with Jaeger).</p>
<p>Sub-options include:</p>
<ul>
<li><code>enabled</code>: whether tracing is enabled. Set to true to enable. Disabled by default.</li>
<li><code>homeserver_whitelist</code>: The list of homeservers we wish to send and receive span contexts and span baggage.
See <a href="usage/configuration/../../opentracing.html">here</a> for more.
This is a list of regexes which are matched against the <code>server_name</code> of the homeserver.
By default, it is empty, so no servers are matched.</li>
<li><code>force_tracing_for_users</code>: # A list of the matrix IDs of users whose requests will always be traced,
even if the tracing system would otherwise drop the traces due to probabilistic sampling.
By default, the list is empty.</li>
<li><code>jaeger_config</code>: Jaeger can be configured to sample traces at different rates.
All configuration options provided by Jaeger can be set here. Jaeger's configuration is
mostly related to trace sampling which is documented <a href="https://www.jaegertracing.io/docs/latest/sampling/">here</a>.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">opentracing:
    enabled: true
    homeserver_whitelist:
      - &quot;.*&quot;
    force_tracing_for_users:
      - &quot;@user1:server_name&quot;
      - &quot;@user2:server_name&quot;

    jaeger_config:
      sampler:
        type: const
        param: 1
      logging:
        false
</code></pre>
<hr />
<h2 id="coordinating-workers"><a class="header" href="#coordinating-workers">Coordinating workers</a></h2>
<p>Configuration options related to workers which belong in the main config file
(usually called <code>homeserver.yaml</code>).
A Synapse deployment can scale horizontally by running multiple Synapse processes
called <em>workers</em>. Incoming requests are distributed between workers to handle higher
loads. Some workers are privileged and can accept requests from other workers.</p>
<p>As a result, the worker configuration is divided into two parts.</p>
<ol>
<li>The first part (in this section of the manual) defines which shardable tasks
are delegated to privileged workers. This allows unprivileged workers to make
requests to a privileged worker to act on their behalf.</li>
<li><a href="usage/configuration/config_documentation.html#individual-worker-configuration">The second part</a>
controls the behaviour of individual workers in isolation.</li>
</ol>
<p>For guidance on setting up workers, see the <a href="usage/configuration/../../workers.html">worker documentation</a>.</p>
<hr />
<h3 id="worker_replication_secret"><a class="header" href="#worker_replication_secret"><code>worker_replication_secret</code></a></h3>
<p>A shared secret used by the replication APIs on the main process to authenticate
HTTP requests from workers.</p>
<p>The default, this value is omitted (equivalently <code>null</code>), which means that
traffic between the workers and the main process is not authenticated.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_replication_secret: &quot;secret_secret&quot;
</code></pre>
<hr />
<h3 id="start_pushers"><a class="header" href="#start_pushers"><code>start_pushers</code></a></h3>
<p>Unnecessary to set if using <a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a> with <a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>generic_workers</code></a>.</p>
<p>Controls sending of push notifications on the main process. Set to <code>false</code>
if using a <a href="usage/configuration/../../workers.html#synapseapppusher">pusher worker</a>. Defaults to <code>true</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">start_pushers: false
</code></pre>
<hr />
<h3 id="pusher_instances"><a class="header" href="#pusher_instances"><code>pusher_instances</code></a></h3>
<p>It is possible to scale the processes that handle sending push notifications to <a href="https://github.com/matrix-org/sygnal">sygnal</a>
and email by running a <a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>generic_worker</code></a> and adding it's <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a> to
a <code>pusher_instances</code> map. Doing so will remove handling of this function from the main
process. Multiple workers can be added to this map, in which case the work is balanced
across them. Ensure the main process and all pusher workers are restarted after changing
this option.</p>
<p>Example configuration for a single worker:</p>
<pre><code class="language-yaml">pusher_instances:
  - pusher_worker1
</code></pre>
<p>And for multiple workers:</p>
<pre><code class="language-yaml">pusher_instances:
  - pusher_worker1
  - pusher_worker2
</code></pre>
<hr />
<h3 id="send_federation"><a class="header" href="#send_federation"><code>send_federation</code></a></h3>
<p>Unnecessary to set if using <a href="usage/configuration/config_documentation.html#federation_sender_instances"><code>federation_sender_instances</code></a> with <a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>generic_workers</code></a>.</p>
<p>Controls sending of outbound federation transactions on the main process.
Set to <code>false</code> if using a <a href="usage/configuration/../../workers.html#synapseappfederation_sender">federation sender worker</a>.
Defaults to <code>true</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">send_federation: false
</code></pre>
<hr />
<h3 id="federation_sender_instances"><a class="header" href="#federation_sender_instances"><code>federation_sender_instances</code></a></h3>
<p>It is possible to scale the processes that handle sending outbound federation requests
by running a <a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>generic_worker</code></a> and adding it's <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a> to
a <code>federation_sender_instances</code> map. Doing so will remove handling of this function from
the main process. Multiple workers can be added to this map, in which case the work is
balanced across them.</p>
<p>This configuration setting must be shared between all workers handling federation
sending, and if changed all federation sender workers must be stopped at the same time
and then started, to ensure that all instances are running with the same config (otherwise
events may be dropped).</p>
<p>Example configuration for a single worker:</p>
<pre><code class="language-yaml">federation_sender_instances:
  - federation_sender1
</code></pre>
<p>And for multiple workers:</p>
<pre><code class="language-yaml">federation_sender_instances:
  - federation_sender1
  - federation_sender2
</code></pre>
<hr />
<h3 id="instance_map"><a class="header" href="#instance_map"><code>instance_map</code></a></h3>
<p>When using workers this should be a map from <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a> to the HTTP
replication listener of the worker, if configured, and to the main process. Each worker
declared under <a href="usage/configuration/../../workers.html#stream-writers"><code>stream_writers</code></a> and
<a href="usage/configuration/config_documentation.html#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a> needs a HTTP
replication listener, and that listener should be included in the <code>instance_map</code>. The
main process also needs an entry on the <code>instance_map</code>, and it should be listed under
<code>main</code> <strong>if even one other worker exists</strong>. Ensure the port matches with what is
declared inside the <code>listener</code> block for a <code>replication</code> listener.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">instance_map:
  main:
    host: localhost
    port: 8030
  worker1:
    host: localhost
    port: 8034
</code></pre>
<p>Example configuration(#2, for UNIX sockets):</p>
<pre><code class="language-yaml">instance_map:
  main:
    path: /var/run/synapse/main_replication.sock
  worker1:
    path: /var/run/synapse/worker1_replication.sock
</code></pre>
<hr />
<h3 id="stream_writers"><a class="header" href="#stream_writers"><code>stream_writers</code></a></h3>
<p>Experimental: When using workers you can define which workers should
handle writing to streams such as event persistence and typing notifications.
Any worker specified here must also be in the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>.</p>
<p>See the list of available streams in the
<a href="usage/configuration/../../workers.html#stream-writers">worker documentation</a>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">stream_writers:
  events: worker1
  typing: worker1
</code></pre>
<hr />
<h3 id="outbound_federation_restricted_to"><a class="header" href="#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a></h3>
<p>When using workers, you can restrict outbound federation traffic to only go through a
specific subset of workers. Any worker specified here must also be in the
<a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>.
<a href="usage/configuration/config_documentation.html#worker_replication_secret"><code>worker_replication_secret</code></a> must also be configured to
authorize inter-worker communication.</p>
<pre><code class="language-yaml">outbound_federation_restricted_to:
  - federation_sender1
  - federation_sender2
</code></pre>
<h2>Also see the <a href="usage/configuration/../../workers.html#restrict-outbound-federation-traffic-to-a-specific-set-of-workers">worker
documentation</a>
for more info.</h2>
<h3 id="run_background_tasks_on"><a class="header" href="#run_background_tasks_on"><code>run_background_tasks_on</code></a></h3>
<p>The <a href="usage/configuration/../../workers.html#background-tasks">worker</a> that is used to run
background tasks (e.g. cleaning up expired data). If not provided this
defaults to the main process.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">run_background_tasks_on: worker1
</code></pre>
<hr />
<h3 id="update_user_directory_from_worker"><a class="header" href="#update_user_directory_from_worker"><code>update_user_directory_from_worker</code></a></h3>
<p>The <a href="usage/configuration/../../workers.html#updating-the-user-directory">worker</a> that is used to
update the user directory. If not provided this defaults to the main process.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">update_user_directory_from_worker: worker1
</code></pre>
<p><em>Added in Synapse 1.59.0.</em></p>
<hr />
<h3 id="notify_appservices_from_worker"><a class="header" href="#notify_appservices_from_worker"><code>notify_appservices_from_worker</code></a></h3>
<p>The <a href="usage/configuration/../../workers.html#notifying-application-services">worker</a> that is used to
send output traffic to Application Services. If not provided this defaults
to the main process.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">notify_appservices_from_worker: worker1
</code></pre>
<p><em>Added in Synapse 1.59.0.</em></p>
<hr />
<h3 id="media_instance_running_background_jobs"><a class="header" href="#media_instance_running_background_jobs"><code>media_instance_running_background_jobs</code></a></h3>
<p>The <a href="usage/configuration/../../workers.html#synapseappmedia_repository">worker</a> that is used to run
background tasks for media repository. If running multiple media repositories
you must configure a single instance to run the background tasks. If not provided
this defaults to the main process or your single <code>media_repository</code> worker.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">media_instance_running_background_jobs: worker1
</code></pre>
<p><em>Added in Synapse 1.16.0.</em></p>
<hr />
<h3 id="redis"><a class="header" href="#redis"><code>redis</code></a></h3>
<p>Configuration for Redis when using workers. This <em>must</em> be enabled when using workers.
This setting has the following sub-options:</p>
<ul>
<li>
<p><code>enabled</code>: whether to use Redis support. Defaults to false.</p>
</li>
<li>
<p><code>host</code> and <code>port</code>: Optional host and port to use to connect to redis. Defaults to
localhost and 6379</p>
</li>
<li>
<p><code>path</code>: The full path to a local Unix socket file. <strong>If this is used, <code>host</code> and
<code>port</code> are ignored.</strong> Defaults to `/tmp/redis.sock'</p>
</li>
<li>
<p><code>password</code>: Optional password if configured on the Redis instance.</p>
</li>
<li>
<p><code>dbid</code>: Optional redis dbid if needs to connect to specific redis logical db.</p>
</li>
<li>
<p><code>use_tls</code>: Whether to use tls connection. Defaults to false.</p>
</li>
<li>
<p><code>certificate_file</code>: Optional path to the certificate file</p>
</li>
<li>
<p><code>private_key_file</code>: Optional path to the private key file</p>
</li>
<li>
<p><code>ca_file</code>: Optional path to the CA certificate file. Use this one or:</p>
</li>
<li>
<p><code>ca_path</code>: Optional path to the folder containing the CA certificate file</p>
<p><em>Added in Synapse 1.78.0.</em></p>
<p><em>Changed in Synapse 1.84.0: Added use_tls, certificate_file, private_key_file, ca_file and ca_path attributes</em></p>
<p><em>Changed in Synapse 1.85.0: Added path option to use a local Unix socket</em></p>
</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">redis:
  enabled: true
  host: localhost
  port: 6379
  password: &lt;secret_password&gt;
  dbid: &lt;dbid&gt;
  #use_tls: True
  #certificate_file: &lt;path_to_the_certificate_file&gt;
  #private_key_file: &lt;path_to_the_private_key_file&gt;
  #ca_file: &lt;path_to_the_ca_certificate_file&gt;
</code></pre>
<hr />
<h2 id="individual-worker-configuration"><a class="header" href="#individual-worker-configuration">Individual worker configuration</a></h2>
<p>These options configure an individual worker, in its worker configuration file.
They should be not be provided when configuring the main process.</p>
<p>Note also the configuration above for
<a href="usage/configuration/config_documentation.html#coordinating-workers">coordinating a cluster of workers</a>.</p>
<p>For guidance on setting up workers, see the <a href="usage/configuration/../../workers.html">worker documentation</a>.</p>
<hr />
<h3 id="worker_app"><a class="header" href="#worker_app"><code>worker_app</code></a></h3>
<p>The type of worker. The currently available worker applications are listed
in <a href="usage/configuration/../../workers.html#available-worker-applications">worker documentation</a>.</p>
<p>The most common worker is the
<a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
</code></pre>
<hr />
<h3 id="worker_name"><a class="header" href="#worker_name"><code>worker_name</code></a></h3>
<p>A unique name for the worker. The worker needs a name to be addressed in
further parameters and identification in log files. We strongly recommend
giving each worker a unique <code>worker_name</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_name: generic_worker1
</code></pre>
<hr />
<h3 id="worker_listeners"><a class="header" href="#worker_listeners"><code>worker_listeners</code></a></h3>
<p>A worker can handle HTTP requests. To do so, a <code>worker_listeners</code> option
must be declared, in the same way as the <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code> option</a>
in the shared config.</p>
<p>Workers declared in <a href="usage/configuration/config_documentation.html#stream_writers"><code>stream_writers</code></a> and <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>
will need to include a <code>replication</code> listener here, in order to accept internal HTTP 
requests from other workers.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_listeners:
  - type: http
    port: 8083
    resources:
      - names: [client, federation]
</code></pre>
<p>Example configuration(#2, using UNIX sockets with a <code>replication</code> listener):</p>
<pre><code class="language-yaml">worker_listeners:
  - type: http
    path: /var/run/synapse/worker_public.sock
    resources:
      - names: [client, federation]
  - type: http
    path: /var/run/synapse/worker_replication.sock
    resources:
      - names: [replication]
</code></pre>
<hr />
<h3 id="worker_manhole"><a class="header" href="#worker_manhole"><code>worker_manhole</code></a></h3>
<p>A worker may have a listener for <a href="usage/configuration/../../manhole.html"><code>manhole</code></a>.
It allows server administrators to access a Python shell on the worker.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_manhole: 9000
</code></pre>
<p>This is a short form for:</p>
<pre><code class="language-yaml">worker_listeners:
  - port: 9000
    bind_addresses: ['127.0.0.1']
    type: manhole
</code></pre>
<p>It needs also an additional <a href="usage/configuration/config_documentation.html#manhole_settings"><code>manhole_settings</code></a> configuration.</p>
<hr />
<h3 id="worker_daemonize"><a class="header" href="#worker_daemonize"><code>worker_daemonize</code></a></h3>
<p>Specifies whether the worker should be started as a daemon process.
If Synapse is being managed by <a href="usage/configuration/../../systemd-with-workers/">systemd</a>, this option
must be omitted or set to <code>false</code>.</p>
<p>Defaults to <code>false</code>.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_daemonize: true
</code></pre>
<hr />
<h3 id="worker_pid_file"><a class="header" href="#worker_pid_file"><code>worker_pid_file</code></a></h3>
<p>When running a worker as a daemon, we need a place to store the
<a href="https://en.wikipedia.org/wiki/Process_identifier">PID</a> of the worker.
This option defines the location of that &quot;pid file&quot;.</p>
<p>This option is required if <code>worker_daemonize</code> is <code>true</code> and ignored
otherwise. It has no default.</p>
<p>See also the <a href="usage/configuration/config_documentation.html#pid_file"><code>pid_file</code> option</a> option for the main Synapse process.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_pid_file: DATADIR/generic_worker1.pid
</code></pre>
<hr />
<h3 id="worker_log_config"><a class="header" href="#worker_log_config"><code>worker_log_config</code></a></h3>
<p>This option specifies a yaml python logging config file as described
<a href="https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema">here</a>.
See also the <a href="usage/configuration/config_documentation.html#log_config"><code>log_config</code> option</a> option for the main Synapse process.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
</code></pre>
<hr />
<h2 id="background-updates"><a class="header" href="#background-updates">Background Updates</a></h2>
<p>Configuration settings related to background updates.</p>
<hr />
<h3 id="background_updates"><a class="header" href="#background_updates"><code>background_updates</code></a></h3>
<p>Background updates are database updates that are run in the background in batches.
The duration, minimum batch size, default batch size, whether to sleep between batches and if so, how long to
sleep can all be configured. This is helpful to speed up or slow down the updates.
This setting has the following sub-options:</p>
<ul>
<li><code>background_update_duration_ms</code>: How long in milliseconds to run a batch of background updates for. Defaults to 100.
Set a different time to change the default.</li>
<li><code>sleep_enabled</code>: Whether to sleep between updates. Defaults to true. Set to false to change the default.</li>
<li><code>sleep_duration_ms</code>: If sleeping between updates, how long in milliseconds to sleep for. Defaults to 1000.
Set a duration to change the default.</li>
<li><code>min_batch_size</code>: Minimum size a batch of background updates can be. Must be greater than 0. Defaults to 1.
Set a size to change the default.</li>
<li><code>default_batch_size</code>: The batch size to use for the first iteration of a new background update. The default is 100.
Set a size to change the default.</li>
</ul>
<p>Example configuration:</p>
<pre><code class="language-yaml">background_updates:
    background_update_duration_ms: 500
    sleep_enabled: false
    sleep_duration_ms: 300
    min_batch_size: 10
    default_batch_size: 50
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="homeserver-sample-configuration-file"><a class="header" href="#homeserver-sample-configuration-file">Homeserver Sample Configuration File</a></h1>
<p>Below is a sample homeserver configuration file. The homeserver configuration file 
can be tweaked to change the behaviour of your homeserver. A restart of the server is 
generally required to apply any changes made to this file.</p>
<p>Note that the contents below are <em>not</em> intended to be copied and used as the basis for
a real homeserver.yaml. Instead, if you are starting from scratch, please generate
a fresh config using Synapse by following the instructions in
<a href="usage/configuration/../../setup/installation.html">Installation</a>.</p>
<p>Documentation for all configuration options can be found in the
<a href="usage/configuration/./config_documentation.html">Configuration Manual</a>.</p>
<pre><code class="language-yaml"># This file is maintained as an up-to-date snapshot of the default
# homeserver.yaml configuration generated by Synapse. You can find a
# complete accounting of possible configuration options at
# https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
#
# It is *not* intended to be copied and used as the basis for a real
# homeserver.yaml. Instead, if you are starting from scratch, please generate
# a fresh config using Synapse by following the instructions in
# https://matrix-org.github.io/synapse/latest/setup/installation.html.
#
################################################################################

# Configuration file for Synapse.
#
# This is a YAML file: see [1] for a quick introduction. Note in particular
# that *indentation is important*: all the elements of a list or dictionary
# should have the same indentation.
#
# [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
#
# For more information on how to configure Synapse, including a complete accounting of
# each option, go to docs/usage/configuration/config_documentation.md or
# https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
server_name: &quot;SERVERNAME&quot;
pid_file: DATADIR/homeserver.pid
listeners:
  - port: 8008
    tls: false
    type: http
    x_forwarded: true
    bind_addresses: ['::1', '127.0.0.1']
    resources:
      - names: [client, federation]
        compress: false
database:
  name: sqlite3
  args:
    database: DATADIR/homeserver.db
log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
media_store_path: DATADIR/media_store
signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
trusted_key_servers:
  - server_name: &quot;matrix.org&quot;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="logging-sample-configuration-file"><a class="header" href="#logging-sample-configuration-file">Logging Sample Configuration File</a></h1>
<p>Below is a sample logging configuration file. This file can be tweaked to control how your
homeserver will output logs. The value of the <code>log_config</code> option in your homeserver config
should be the path to this file.</p>
<p>To apply changes made to this file, send Synapse a SIGHUP signal (or, if using <code>systemd</code>, run
<code>systemctl reload</code> on the Synapse service).</p>
<p>Note that a default logging configuration (shown below) is created automatically alongside
the homeserver config when following the <a href="usage/configuration/../../setup/installation.html">installation instructions</a>.
It should be named <code>&lt;SERVERNAME&gt;.log.config</code> by default.</p>
<pre><code class="language-yaml"># Log configuration for Synapse.
#
# This is a YAML file containing a standard Python logging configuration
# dictionary. See [1] for details on the valid settings.
#
# Synapse also supports structured logging for machine readable logs which can
# be ingested by ELK stacks. See [2] for details.
#
# [1]: https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema
# [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html

version: 1

formatters:
    precise:
        format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'

handlers:
    file:
        class: logging.handlers.TimedRotatingFileHandler
        formatter: precise
        filename: /var/log/matrix-synapse/homeserver.log
        when: midnight
        backupCount: 3  # Does not include the current log file.
        encoding: utf8

    # Default to buffering writes to log file for efficiency.
    # WARNING/ERROR logs will still be flushed immediately, but there will be a
    # delay (of up to `period` seconds, or until the buffer is full with
    # `capacity` messages) before INFO/DEBUG logs get written.
    buffer:
        class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
        target: file

        # The capacity is the maximum number of log lines that are buffered
        # before being written to disk. Increasing this will lead to better
        # performance, at the expensive of it taking longer for log lines to
        # be written to disk.
        # This parameter is required.
        capacity: 10

        # Logs with a level at or above the flush level will cause the buffer to
        # be flushed immediately.
        # Default value: 40 (ERROR)
        # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
        flushLevel: 30  # Flush immediately for WARNING logs and higher

        # The period of time, in seconds, between forced flushes.
        # Messages will not be delayed for longer than this time.
        # Default value: 5 seconds
        period: 5

    # A handler that writes logs to stderr. Unused by default, but can be used
    # instead of &quot;buffer&quot; and &quot;file&quot; in the logger handlers.
    console:
        class: logging.StreamHandler
        formatter: precise

loggers:
    synapse.storage.SQL:
        # beware: increasing this to DEBUG will make synapse log sensitive
        # information such as access tokens.
        level: INFO

root:
    level: INFO

    # Write logs to the `buffer` handler, which will buffer them together in memory,
    # then write them to a file.
    #
    # Replace &quot;buffer&quot; with &quot;console&quot; to log to stderr instead.
    #
    handlers: [buffer]

disable_existing_loggers: false
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="structured-logging"><a class="header" href="#structured-logging">Structured Logging</a></h1>
<p>A structured logging system can be useful when your logs are destined for a
machine to parse and process. By maintaining its machine-readable characteristics,
it enables more efficient searching and aggregations when consumed by software
such as the <a href="https://opensource.com/article/18/9/open-source-log-aggregation-tools">ELK stack</a>.</p>
<p>Synapse's structured logging system is configured via the file that Synapse's
<code>log_config</code> config option points to. The file should include a formatter which
uses the <code>synapse.logging.TerseJsonFormatter</code> class included with Synapse and a
handler which uses the above formatter.</p>
<p>There is also a <code>synapse.logging.JsonFormatter</code> option which does not include
a timestamp in the resulting JSON. This is useful if the log ingester adds its
own timestamp.</p>
<p>A structured logging configuration looks similar to the following:</p>
<pre><code class="language-yaml">version: 1

formatters:
    structured:
        class: synapse.logging.TerseJsonFormatter

handlers:
    file:
        class: logging.handlers.TimedRotatingFileHandler
        formatter: structured
        filename: /path/to/my/logs/homeserver.log
        when: midnight
        backupCount: 3  # Does not include the current log file.
        encoding: utf8

loggers:
    synapse:
        level: INFO
        handlers: [remote]
    synapse.storage.SQL:
        level: WARNING
</code></pre>
<p>The above logging config will set Synapse as 'INFO' logging level by default,
with the SQL layer at 'WARNING', and will log to a file, stored as JSON.</p>
<p>It is also possible to configure Synapse to log to a remote endpoint by using the
<code>synapse.logging.RemoteHandler</code> class included with Synapse. It takes the
following arguments:</p>
<ul>
<li><code>host</code>: Hostname or IP address of the log aggregator.</li>
<li><code>port</code>: Numerical port to contact on the host.</li>
<li><code>maximum_buffer</code>: (Optional, defaults to 1000) The maximum buffer size to allow.</li>
</ul>
<p>A remote structured logging configuration looks similar to the following:</p>
<pre><code class="language-yaml">version: 1

formatters:
    structured:
        class: synapse.logging.TerseJsonFormatter

handlers:
    remote:
        class: synapse.logging.RemoteHandler
        formatter: structured
        host: 10.1.2.3
        port: 9999

loggers:
    synapse:
        level: INFO
        handlers: [remote]
    synapse.storage.SQL:
        level: WARNING
</code></pre>
<p>The above logging config will set Synapse as 'INFO' logging level by default,
with the SQL layer at 'WARNING', and will log JSON formatted messages to a
remote endpoint at 10.1.2.3:9999.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="templates"><a class="header" href="#templates">Templates</a></h1>
<p>Synapse uses parametrised templates to generate the content of emails it sends and
webpages it shows to users.</p>
<p>By default, Synapse will use the templates listed <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">here</a>.
Server admins can configure an additional directory for Synapse to look for templates
in, allowing them to specify custom templates:</p>
<pre><code class="language-yaml">templates:
  custom_template_directory: /path/to/custom/templates/
</code></pre>
<p>If this setting is not set, or the files named below are not found within the directory,
default templates from within the Synapse package will be used.</p>
<p>Templates that are given variables when being rendered are rendered using <a href="https://jinja.palletsprojects.com/en/2.11.x/">Jinja 2</a>.
Templates rendered by Jinja 2 can also access two functions on top of the functions
already available as part of Jinja 2:</p>
<pre><code class="language-python">format_ts(value: int, format: str) -&gt; str
</code></pre>
<p>Formats a timestamp in milliseconds.</p>
<p>Example: <code>reason.last_sent_ts|format_ts(&quot;%c&quot;)</code></p>
<pre><code class="language-python">mxc_to_http(value: str, width: int, height: int, resize_method: str = &quot;crop&quot;) -&gt; str
</code></pre>
<p>Turns a <code>mxc://</code> URL for media content into an HTTP(S) one using the homeserver's
<code>public_baseurl</code> configuration setting as the URL's base.</p>
<p>Example: <code>message.sender_avatar_url|mxc_to_http(32,32)</code></p>
<pre><code class="language-python">localpart_from_email(address: str) -&gt; str
</code></pre>
<p>Returns the local part of an email address (e.g. <code>alice</code> in <code>alice@example.com</code>).</p>
<p>Example: <code>user.email_address|localpart_from_email</code></p>
<h2 id="email-templates"><a class="header" href="#email-templates">Email templates</a></h2>
<p>Below are the templates Synapse will look for when generating the content of an email:</p>
<ul>
<li><code>notif_mail.html</code> and <code>notif_mail.txt</code>: The contents of email notifications of missed
events.
When rendering, this template is given the following variables:
<ul>
<li><code>user_display_name</code>: the display name for the user receiving the notification</li>
<li><code>unsubscribe_link</code>: the link users can click to unsubscribe from email notifications</li>
<li><code>summary_text</code>: a summary of the notification(s). The text used can be customised
by configuring the various settings in the <code>email.subjects</code> section of the
configuration file.</li>
<li><code>rooms</code>: a list of rooms containing events to include in the email. Each element is
an object with the following attributes:
<ul>
<li><code>title</code>: a human-readable name for the room</li>
<li><code>hash</code>: a hash of the ID of the room</li>
<li><code>invite</code>: a boolean, which is <code>True</code> if the room is an invite the user hasn't
accepted yet, <code>False</code> otherwise</li>
<li><code>notifs</code>: a list of events, or an empty list if <code>invite</code> is <code>True</code>. Each element
is an object with the following attributes:
<ul>
<li><code>link</code>: a <code>matrix.to</code> link to the event</li>
<li><code>ts</code>: the time in milliseconds at which the event was received</li>
<li><code>messages</code>: a list of messages containing one message before the event, the
message in the event, and one message after the event. Each element is an
object with the following attributes:
<ul>
<li><code>event_type</code>: the type of the event</li>
<li><code>is_historical</code>: a boolean, which is <code>False</code> if the message is the one
that triggered the notification, <code>True</code> otherwise</li>
<li><code>id</code>: the ID of the event</li>
<li><code>ts</code>: the time in milliseconds at which the event was sent</li>
<li><code>sender_name</code>: the display name for the event's sender</li>
<li><code>sender_avatar_url</code>: the avatar URL (as a <code>mxc://</code> URL) for the event's
sender</li>
<li><code>sender_hash</code>: a hash of the user ID of the sender</li>
<li><code>msgtype</code>: the type of the message</li>
<li><code>body_text_html</code>: html representation of the message</li>
<li><code>body_text_plain</code>: plaintext representation of the message</li>
<li><code>image_url</code>: mxc url of an image, when &quot;msgtype&quot; is &quot;m.image&quot;</li>
</ul>
</li>
</ul>
</li>
<li><code>link</code>: a <code>matrix.to</code> link to the room</li>
<li><code>avator_url</code>: url to the room's avator</li>
</ul>
</li>
<li><code>reason</code>: information on the event that triggered the email to be sent. It's an
object with the following attributes:
<ul>
<li><code>room_id</code>: the ID of the room the event was sent in</li>
<li><code>room_name</code>: a human-readable name for the room the event was sent in</li>
<li><code>now</code>: the current time in milliseconds</li>
<li><code>received_at</code>: the time in milliseconds at which the event was received</li>
<li><code>delay_before_mail_ms</code>: the amount of time in milliseconds Synapse always waits
before ever emailing about a notification (to give the user a chance to respond
to other push or notice the window)</li>
<li><code>last_sent_ts</code>: the time in milliseconds at which a notification was last sent
for an event in this room</li>
<li><code>throttle_ms</code>: the minimum amount of time in milliseconds between two
notifications can be sent for this room</li>
</ul>
</li>
</ul>
</li>
<li><code>password_reset.html</code> and <code>password_reset.txt</code>: The contents of password reset emails
sent by the homeserver.
When rendering, these templates are given a <code>link</code> variable which contains the link the
user must click in order to reset their password.</li>
<li><code>registration.html</code> and <code>registration.txt</code>: The contents of address verification emails
sent during registration.
When rendering, these templates are given a <code>link</code> variable which contains the link the
user must click in order to validate their email address.</li>
<li><code>add_threepid.html</code> and <code>add_threepid.txt</code>: The contents of address verification emails
sent when an address is added to a Matrix account.
When rendering, these templates are given a <code>link</code> variable which contains the link the
user must click in order to validate their email address.</li>
</ul>
<h2 id="html-page-templates-for-registration-and-password-reset"><a class="header" href="#html-page-templates-for-registration-and-password-reset">HTML page templates for registration and password reset</a></h2>
<p>Below are the templates Synapse will look for when generating pages related to
registration and password reset:</p>
<ul>
<li><code>password_reset_confirmation.html</code>: An HTML page that a user will see when they follow
the link in the password reset email. The user will be asked to confirm the action
before their password is reset.
When rendering, this template is given the following variables:
<ul>
<li><code>sid</code>: the session ID for the password reset</li>
<li><code>token</code>: the token for the password reset</li>
<li><code>client_secret</code>: the client secret for the password reset</li>
</ul>
</li>
<li><code>password_reset_success.html</code> and <code>password_reset_failure.html</code>: HTML pages for success
and failure that a user will see when they confirm the password reset flow using the
page above.
When rendering, <code>password_reset_success.html</code> is given no variable, and
<code>password_reset_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
for the password reset failure. </li>
<li><code>registration_success.html</code> and <code>registration_failure.html</code>: HTML pages for success and
failure that a user will see when they follow the link in an address verification email
sent during registration.
When rendering, <code>registration_success.html</code> is given no variable, and
<code>registration_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
for the registration failure.</li>
<li><code>add_threepid_success.html</code> and <code>add_threepid_failure.html</code>: HTML pages for success and
failure that a user will see when they follow the link in an address verification email
sent when an address is added to a Matrix account.
When rendering, <code>add_threepid_success.html</code> is given no variable, and
<code>add_threepid_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
for the registration failure.</li>
</ul>
<h2 id="html-page-templates-for-single-sign-on-sso"><a class="header" href="#html-page-templates-for-single-sign-on-sso">HTML page templates for Single Sign-On (SSO)</a></h2>
<p>Below are the templates Synapse will look for when generating pages related to SSO:</p>
<ul>
<li><code>sso_login_idp_picker.html</code>: HTML page to prompt the user to choose an
Identity Provider during login.
This is only used if multiple SSO Identity Providers are configured.
When rendering, this template is given the following variables:
<ul>
<li><code>redirect_url</code>: the URL that the user will be redirected to after
login.</li>
<li><code>server_name</code>: the homeserver's name.</li>
<li><code>providers</code>: a list of available Identity Providers. Each element is
an object with the following attributes:
<ul>
<li><code>idp_id</code>: unique identifier for the IdP</li>
<li><code>idp_name</code>: user-facing name for the IdP</li>
<li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
for the IdP</li>
<li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
for the brand of the IdP
The rendered HTML page should contain a form which submits its results
back as a GET request, with the following query parameters:</li>
</ul>
</li>
<li><code>redirectUrl</code>: the client redirect URI (ie, the <code>redirect_url</code> passed
to the template)</li>
<li><code>idp</code>: the 'idp_id' of the chosen IDP.</li>
</ul>
</li>
<li><code>sso_auth_account_details.html</code>: HTML page to prompt new users to enter a
userid and confirm other details. This is only shown if the
SSO implementation (with any <code>user_mapping_provider</code>) does not return
a localpart.
When rendering, this template is given the following variables:
<ul>
<li><code>server_name</code>: the homeserver's name.</li>
<li><code>idp</code>: details of the SSO Identity Provider that the user logged in
with: an object with the following attributes:
<ul>
<li><code>idp_id</code>: unique identifier for the IdP</li>
<li><code>idp_name</code>: user-facing name for the IdP</li>
<li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
for the IdP</li>
<li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
for the brand of the IdP</li>
</ul>
</li>
<li><code>user_attributes</code>: an object containing details about the user that
we received from the IdP. May have the following attributes:
<ul>
<li><code>display_name</code>: the user's display name</li>
<li><code>emails</code>: a list of email addresses</li>
<li><code>localpart</code>: the local part of the Matrix user ID to register,
if <code>localpart_template</code> is set in the mapping provider configuration (empty
string if not)
The template should render a form which submits the following fields:</li>
</ul>
</li>
<li><code>username</code>: the localpart of the user's chosen user id</li>
</ul>
</li>
<li><code>sso_new_user_consent.html</code>: HTML page allowing the user to consent to the
server's terms and conditions. This is only shown for new users, and only if
<code>user_consent.require_at_registration</code> is set.
When rendering, this template is given the following variables:
<ul>
<li><code>server_name</code>: the homeserver's name.</li>
<li><code>user_id</code>: the user's matrix proposed ID.</li>
<li><code>user_profile.display_name</code>: the user's proposed display name, if any.</li>
<li>consent_version: the version of the terms that the user will be
shown</li>
<li><code>terms_url</code>: a link to the page showing the terms.
The template should render a form which submits the following fields:</li>
<li><code>accepted_version</code>: the version of the terms accepted by the user
(ie, 'consent_version' from the input variables).</li>
</ul>
</li>
<li><code>sso_redirect_confirm.html</code>: HTML page for a confirmation step before redirecting back
to the client with the login token.
When rendering, this template is given the following variables:
<ul>
<li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
<li><code>display_url</code>: the same as <code>redirect_url</code>, but with the query
parameters stripped. The intention is to have a
human-readable URL to show to users, not to use it as
the final address to redirect to.</li>
<li><code>server_name</code>: the homeserver's name.</li>
<li><code>new_user</code>: a boolean indicating whether this is the user's first time
logging in.</li>
<li><code>user_id</code>: the user's matrix ID.</li>
<li><code>user_profile.avatar_url</code>: an MXC URI for the user's avatar, if any.
<code>None</code> if the user has not set an avatar.</li>
<li><code>user_profile.display_name</code>: the user's display name. <code>None</code> if the user
has not set a display name.</li>
</ul>
</li>
<li><code>sso_auth_confirm.html</code>: HTML page which notifies the user that they are authenticating
to confirm an operation on their account during the user interactive authentication
process.
When rendering, this template is given the following variables:
<ul>
<li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
<li><code>description</code>: the operation which the user is being asked to confirm</li>
<li><code>idp</code>: details of the Identity Provider that we will use to confirm
the user's identity: an object with the following attributes:
<ul>
<li><code>idp_id</code>: unique identifier for the IdP</li>
<li><code>idp_name</code>: user-facing name for the IdP</li>
<li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
for the IdP</li>
<li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
for the brand of the IdP</li>
</ul>
</li>
</ul>
</li>
<li><code>sso_auth_success.html</code>: HTML page shown after a successful user interactive
authentication session.
Note that this page must include the JavaScript which notifies of a successful
authentication (see https://matrix.org/docs/spec/client_server/r0.6.0#fallback).
This template has no additional variables.</li>
<li><code>sso_auth_bad_user.html</code>: HTML page shown after a user-interactive authentication
session which does not map correctly onto the expected user.
When rendering, this template is given the following variables:
<ul>
<li><code>server_name</code>: the homeserver's name.</li>
<li><code>user_id_to_verify</code>: the MXID of the user that we are trying to
validate.</li>
</ul>
</li>
<li><code>sso_account_deactivated.html</code>: HTML page shown during single sign-on if a deactivated
user (according to Synapse's database) attempts to login.
This template has no additional variables.</li>
<li><code>sso_error.html</code>: HTML page to display to users if something goes wrong during the
OpenID Connect authentication process.
When rendering, this template is given two variables:
<ul>
<li><code>error</code>: the technical name of the error</li>
<li><code>error_description</code>: a human-readable message for the error</li>
</ul>
</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="user-authentication"><a class="header" href="#user-authentication">User Authentication</a></h1>
<p>Synapse supports multiple methods of authenticating users, either out-of-the-box or through custom pluggable
authentication modules.</p>
<p>Included in Synapse is support for authenticating users via:</p>
<ul>
<li>A username and password.</li>
<li>An email address and password.</li>
<li>Single Sign-On through the SAML, Open ID Connect or CAS protocols.</li>
<li>JSON Web Tokens.</li>
<li>An administrator's shared secret.</li>
</ul>
<p>Synapse can additionally be extended to support custom authentication schemes through optional &quot;password auth provider&quot;
modules.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="single-sign-on"><a class="header" href="#single-sign-on">Single Sign-On</a></h1>
<p>Synapse supports single sign-on through the SAML, Open ID Connect or CAS protocols. 
LDAP and other login methods are supported through first and third-party password
auth provider modules.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="configuring-synapse-to-authenticate-against-an-openid-connect-provider"><a class="header" href="#configuring-synapse-to-authenticate-against-an-openid-connect-provider">Configuring Synapse to authenticate against an OpenID Connect provider</a></h1>
<p>Synapse can be configured to use an OpenID Connect Provider (OP) for
authentication, instead of its own local password database.</p>
<p>Any OP should work with Synapse, as long as it supports the authorization code
flow. There are a few options for that:</p>
<ul>
<li>
<p>start a local OP. Synapse has been tested with <a href="https://www.ory.sh/docs/hydra/">Hydra</a> and
<a href="https://github.com/dexidp/dex">Dex</a>.  Note that for an OP to work, it should be served under a
secure (HTTPS) origin.  A certificate signed with a self-signed, locally
trusted CA should work. In that case, start Synapse with a <code>SSL_CERT_FILE</code>
environment variable set to the path of the CA.</p>
</li>
<li>
<p>set up a SaaS OP, like <a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a>, <a href="https://auth0.com/">Auth0</a> or
<a href="https://www.okta.com/">Okta</a>. Synapse has been tested with Auth0 and Google.</p>
</li>
</ul>
<p>It may also be possible to use other OAuth2 providers which provide the
<a href="https://tools.ietf.org/html/rfc6749#section-4.1">authorization code grant type</a>,
such as <a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">Github</a>.</p>
<h2 id="preparing-synapse"><a class="header" href="#preparing-synapse">Preparing Synapse</a></h2>
<p>The OpenID integration in Synapse uses the
<a href="https://pypi.org/project/Authlib/"><code>authlib</code></a> library, which must be installed
as follows:</p>
<ul>
<li>
<p>The relevant libraries are included in the Docker images and Debian packages
provided by <code>matrix.org</code> so no further action is needed.</p>
</li>
<li>
<p>If you installed Synapse into a virtualenv, run <code>/path/to/env/bin/pip install matrix-synapse[oidc]</code> to install the necessary dependencies.</p>
</li>
<li>
<p>For other installation mechanisms, see the documentation provided by the
maintainer.</p>
</li>
</ul>
<p>To enable the OpenID integration, you should then add a section to the <code>oidc_providers</code>
setting in your configuration file.
See the <a href="usage/configuration/config_documentation.html#oidc_providers">configuration manual</a> for some sample settings, as well as
the text below for example configurations for specific providers.</p>
<h2 id="oidc-back-channel-logout"><a class="header" href="#oidc-back-channel-logout">OIDC Back-Channel Logout</a></h2>
<p>Synapse supports receiving <a href="https://openid.net/specs/openid-connect-backchannel-1_0.html">OpenID Connect Back-Channel Logout</a> notifications.</p>
<p>This lets the OpenID Connect Provider notify Synapse when a user logs out, so that Synapse can end that user session.
This feature can be enabled by setting the <code>backchannel_logout_enabled</code> property to <code>true</code> in the provider configuration, and setting the following URL as destination for Back-Channel Logout notifications in your OpenID Connect Provider: <code>[synapse public baseurl]/_synapse/client/oidc/backchannel_logout</code></p>
<h2 id="sample-configs"><a class="header" href="#sample-configs">Sample configs</a></h2>
<p>Here are a few configs for providers that should work with Synapse.</p>
<h3 id="microsoft-azure-active-directory"><a class="header" href="#microsoft-azure-active-directory">Microsoft Azure Active Directory</a></h3>
<p>Azure AD can act as an OpenID Connect Provider. Register a new application under
<em>App registrations</em> in the Azure AD management console. The RedirectURI for your
application should point to your matrix server:
<code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
<p>Go to <em>Certificates &amp; secrets</em> and register a new client secret. Make note of your
Directory (tenant) ID as it will be used in the Azure links.
Edit your Synapse config file and change the <code>oidc_config</code> section:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: microsoft
    idp_name: Microsoft
    issuer: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/v2.0&quot;
    client_id: &quot;&lt;client id&gt;&quot;
    client_secret: &quot;&lt;client secret&gt;&quot;
    scopes: [&quot;openid&quot;, &quot;profile&quot;]
    authorization_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/authorize&quot;
    token_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/token&quot;
    userinfo_endpoint: &quot;https://graph.microsoft.com/oidc/userinfo&quot;

    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username.split('@')[0] }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
</code></pre>
<h3 id="apple"><a class="header" href="#apple">Apple</a></h3>
<p>Configuring &quot;Sign in with Apple&quot; (SiWA) requires an Apple Developer account.</p>
<p>You will need to create a new &quot;Services ID&quot; for SiWA, and create and download a
private key with &quot;SiWA&quot; enabled.</p>
<p>As well as the private key file, you will need:</p>
<ul>
<li>Client ID: the &quot;identifier&quot; you gave the &quot;Services ID&quot;</li>
<li>Team ID: a 10-character ID associated with your developer account.</li>
<li>Key ID: the 10-character identifier for the key.</li>
</ul>
<p><a href="https://help.apple.com/developer-account/?lang=en#/dev77c875b7e">Apple's developer documentation</a>
has more information on setting up SiWA.</p>
<p>The synapse config will look like this:</p>
<pre><code class="language-yaml">  - idp_id: apple
    idp_name: Apple
    issuer: &quot;https://appleid.apple.com&quot;
    client_id: &quot;your-client-id&quot; # Set to the &quot;identifier&quot; for your &quot;ServicesID&quot;
    client_auth_method: &quot;client_secret_post&quot;
    client_secret_jwt_key:
      key_file: &quot;/path/to/AuthKey_KEYIDCODE.p8&quot;  # point to your key file
      jwt_header:
        alg: ES256
        kid: &quot;KEYIDCODE&quot;   # Set to the 10-char Key ID
      jwt_payload:
        iss: TEAMIDCODE    # Set to the 10-char Team ID
    scopes: [&quot;name&quot;, &quot;email&quot;, &quot;openid&quot;]
    authorization_endpoint: https://appleid.apple.com/auth/authorize?response_mode=form_post
    user_mapping_provider:
      config:
        email_template: &quot;{{ user.email }}&quot;
</code></pre>
<h3 id="auth0"><a class="header" href="#auth0">Auth0</a></h3>
<p><a href="https://auth0.com/">Auth0</a> is a hosted SaaS IdP solution.</p>
<ol>
<li>
<p>Create a regular web application for Synapse</p>
</li>
<li>
<p>Set the Allowed Callback URLs to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
</li>
<li>
<p>Add a rule with any name to add the <code>preferred_username</code> claim. 
(See https://auth0.com/docs/customize/rules/create-rules for more information on how to create rules.)</p>
<details>
 <summary>Code sample</summary>
<pre><code class="language-js">function addPersistenceAttribute(user, context, callback) {
  user.user_metadata = user.user_metadata || {};
  user.user_metadata.preferred_username = user.user_metadata.preferred_username || user.user_id;
  context.idToken.preferred_username = user.user_metadata.preferred_username;

  auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
    .then(function(){
        callback(null, user, context);
    })
    .catch(function(err){
        callback(err);
    });
}
</code></pre>
</li>
</ol>
</details>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: auth0
    idp_name: Auth0
    issuer: &quot;https://your-tier.eu.auth0.com/&quot; # TO BE FILLED
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    scopes: [&quot;openid&quot;, &quot;profile&quot;]
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
</code></pre>
<h3 id="authentik"><a class="header" href="#authentik">Authentik</a></h3>
<p><a href="https://goauthentik.io/">Authentik</a> is an open-source IdP solution.</p>
<ol>
<li>Create a provider in Authentik, with type OAuth2/OpenID.</li>
<li>The parameters are:</li>
</ol>
<ul>
<li>Client Type: Confidential</li>
<li>JWT Algorithm: RS256</li>
<li>Scopes: OpenID, Email and Profile</li>
<li>RSA Key: Select any available key</li>
<li>Redirect URIs: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
</ul>
<ol start="3">
<li>Create an application for synapse in Authentik and link it to the provider.</li>
<li>Note the slug of your application, Client ID and Client Secret.</li>
</ol>
<p>Note: RSA keys must be used for signing for Authentik, ECC keys do not work.</p>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: authentik
    idp_name: authentik
    discover: true
    issuer: &quot;https://your.authentik.example.org/application/o/your-app-slug/&quot; # TO BE FILLED: domain and slug
    client_id: &quot;your client id&quot; # TO BE FILLED
    client_secret: &quot;your client secret&quot; # TO BE FILLED
    scopes:
      - &quot;openid&quot;
      - &quot;profile&quot;
      - &quot;email&quot;
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username }}&quot;
        display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot; # TO BE FILLED: If your users have names in Authentik and you want those in Synapse, this should be replaced with user.name|capitalize.
</code></pre>
<h3 id="dex"><a class="header" href="#dex">Dex</a></h3>
<p><a href="https://github.com/dexidp/dex">Dex</a> is a simple, open-source OpenID Connect Provider.
Although it is designed to help building a full-blown provider with an
external database, it can be configured with static passwords in a config file.</p>
<p>Follow the <a href="https://dexidp.io/docs/getting-started/">Getting Started guide</a>
to install Dex.</p>
<p>Edit <code>examples/config-dev.yaml</code> config file from the Dex repo to add a client:</p>
<pre><code class="language-yaml">staticClients:
- id: synapse
  secret: secret
  redirectURIs:
  - '[synapse public baseurl]/_synapse/client/oidc/callback'
  name: 'Synapse'
</code></pre>
<p>Run with <code>dex serve examples/config-dev.yaml</code>.</p>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: dex
    idp_name: &quot;My Dex server&quot;
    skip_verification: true # This is needed as Dex is served on an insecure endpoint
    issuer: &quot;http://127.0.0.1:5556/dex&quot;
    client_id: &quot;synapse&quot;
    client_secret: &quot;secret&quot;
    scopes: [&quot;openid&quot;, &quot;profile&quot;]
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.name }}&quot;
        display_name_template: &quot;{{ user.name|capitalize }}&quot;
</code></pre>
<h3 id="django-oauth-toolkit"><a class="header" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h3>
<p><a href="https://github.com/jazzband/django-oauth-toolkit">django-oauth-toolkit</a> is a
Django application providing out of the box all the endpoints, data and logic
needed to add OAuth2 capabilities to your Django projects. It supports
<a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html">OpenID Connect too</a>.</p>
<p>Configuration on Django's side:</p>
<ol>
<li>Add an application: <code>https://example.com/admin/oauth2_provider/application/add/</code> and choose parameters like this:</li>
</ol>
<ul>
<li><code>Redirect uris</code>: <code>https://synapse.example.com/_synapse/client/oidc/callback</code></li>
<li><code>Client type</code>: <code>Confidential</code></li>
<li><code>Authorization grant type</code>: <code>Authorization code</code></li>
<li><code>Algorithm</code>: <code>HMAC with SHA-2 256</code></li>
</ul>
<ol start="2">
<li>
<p>You can <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html#customizing-the-oidc-responses">customize the claims</a> Django gives to synapse (optional):</p>
<details>
 <summary>Code sample</summary>
<pre><code class="language-python">class CustomOAuth2Validator(OAuth2Validator):

    def get_additional_claims(self, request):
        return {
            &quot;sub&quot;: request.user.email,
            &quot;email&quot;: request.user.email,
            &quot;first_name&quot;: request.user.first_name,
            &quot;last_name&quot;: request.user.last_name,
        }
</code></pre>
</details>
</li>
</ol>
<p>Your synapse config is then:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: django_example
    idp_name: &quot;Django Example&quot;
    issuer: &quot;https://example.com/o/&quot;
    client_id: &quot;your-client-id&quot;  # CHANGE ME
    client_secret: &quot;your-client-secret&quot;  # CHANGE ME
    scopes: [&quot;openid&quot;]
    user_profile_method: &quot;userinfo_endpoint&quot;  # needed because oauth-toolkit does not include user information in the authorization response
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.email.split('@')[0] }}&quot;
        display_name_template: &quot;{{ user.first_name }} {{ user.last_name }}&quot;
        email_template: &quot;{{ user.email }}&quot;
</code></pre>
<h3 id="facebook"><a class="header" href="#facebook">Facebook</a></h3>
<ol start="0">
<li>You will need a Facebook developer account. You can register for one
<a href="https://developers.facebook.com/async/registration/">here</a>.</li>
<li>On the <a href="https://developers.facebook.com/apps/">apps</a> page of the developer
console, &quot;Create App&quot;, and choose &quot;Build Connected Experiences&quot;.</li>
<li>Once the app is created, add &quot;Facebook Login&quot; and choose &quot;Web&quot;. You don't
need to go through the whole form here.</li>
<li>In the left-hand menu, open &quot;Products&quot;/&quot;Facebook Login&quot;/&quot;Settings&quot;.
<ul>
<li>Add <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> as an OAuth Redirect
URL.</li>
</ul>
</li>
<li>In the left-hand menu, open &quot;Settings/Basic&quot;. Here you can copy the &quot;App ID&quot;
and &quot;App Secret&quot; for use below.</li>
</ol>
<p>Synapse config:</p>
<pre><code class="language-yaml">  - idp_id: facebook
    idp_name: Facebook
    idp_brand: &quot;facebook&quot;  # optional: styling hint for clients
    discover: false
    issuer: &quot;https://www.facebook.com&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    scopes: [&quot;openid&quot;, &quot;email&quot;]
    authorization_endpoint: &quot;https://facebook.com/dialog/oauth&quot;
    token_endpoint: &quot;https://graph.facebook.com/v9.0/oauth/access_token&quot;
    jwks_uri: &quot;https://www.facebook.com/.well-known/oauth/openid/jwks/&quot;
    user_mapping_provider:
      config:
        display_name_template: &quot;{{ user.name }}&quot;
        email_template: &quot;{{ user.email }}&quot;
</code></pre>
<p>Relevant documents:</p>
<ul>
<li><a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow">Manually Build a Login Flow</a></li>
<li><a href="https://developers.facebook.com/docs/graph-api/using-graph-api/">Using Facebook's Graph API</a></li>
<li><a href="https://developers.facebook.com/docs/graph-api/reference/user">Reference to the User endpoint</a></li>
</ul>
<p>Facebook do have an <a href="https://www.facebook.com/.well-known/openid-configuration">OIDC discovery endpoint</a>,
but it has a <code>response_types_supported</code> which excludes &quot;code&quot; (which we rely on, and
is even mentioned in their <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login">documentation</a>),
so we have to disable discovery and configure the URIs manually.</p>
<h3 id="github"><a class="header" href="#github">GitHub</a></h3>
<p><a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">GitHub</a> is a bit special as it is not an OpenID Connect compliant provider, but
just a regular OAuth2 provider.</p>
<p>The <a href="https://developer.github.com/v3/users/#get-the-authenticated-user"><code>/user</code> API endpoint</a>
can be used to retrieve information on the authenticated user. As the Synapse
login mechanism needs an attribute to uniquely identify users, and that endpoint
does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
<ol>
<li>Create a new OAuth application: <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a>.</li>
<li>Set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
</ol>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: github
    idp_name: Github
    idp_brand: &quot;github&quot;  # optional: styling hint for clients
    discover: false
    issuer: &quot;https://github.com/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    authorization_endpoint: &quot;https://github.com/login/oauth/authorize&quot;
    token_endpoint: &quot;https://github.com/login/oauth/access_token&quot;
    userinfo_endpoint: &quot;https://api.github.com/user&quot;
    scopes: [&quot;read:user&quot;]
    user_mapping_provider:
      config:
        subject_claim: &quot;id&quot;
        localpart_template: &quot;{{ user.login }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
</code></pre>
<h3 id="gitlab"><a class="header" href="#gitlab">GitLab</a></h3>
<ol>
<li>Create a <a href="https://gitlab.com/profile/applications">new application</a>.</li>
<li>Add the <code>read_user</code> and <code>openid</code> scopes.</li>
<li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
</ol>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: gitlab
    idp_name: Gitlab
    idp_brand: &quot;gitlab&quot;  # optional: styling hint for clients
    issuer: &quot;https://gitlab.com/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    client_auth_method: &quot;client_secret_post&quot;
    scopes: [&quot;openid&quot;, &quot;read_user&quot;]
    user_profile_method: &quot;userinfo_endpoint&quot;
    user_mapping_provider:
      config:
        localpart_template: '{{ user.nickname }}'
        display_name_template: '{{ user.name }}'
</code></pre>
<h3 id="gitea"><a class="header" href="#gitea">Gitea</a></h3>
<p>Gitea is, like Github, not an OpenID provider, but just an OAuth2 provider.</p>
<p>The <a href="https://try.gitea.io/api/swagger#/user/userGetCurrent"><code>/user</code> API endpoint</a>
can be used to retrieve information on the authenticated user. As the Synapse
login mechanism needs an attribute to uniquely identify users, and that endpoint
does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
<ol>
<li>Create a new application.</li>
<li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
</ol>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: gitea
    idp_name: Gitea
    discover: false
    issuer: &quot;https://your-gitea.com/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    client_auth_method: client_secret_post
    scopes: [] # Gitea doesn't support Scopes
    authorization_endpoint: &quot;https://your-gitea.com/login/oauth/authorize&quot;
    token_endpoint: &quot;https://your-gitea.com/login/oauth/access_token&quot;
    userinfo_endpoint: &quot;https://your-gitea.com/api/v1/user&quot;
    user_mapping_provider:
      config:
        subject_claim: &quot;id&quot;
        localpart_template: &quot;{{ user.login }}&quot;
        display_name_template: &quot;{{ user.full_name }}&quot;
</code></pre>
<h3 id="google"><a class="header" href="#google">Google</a></h3>
<p><a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a> is an OpenID certified authentication and authorisation provider.</p>
<ol>
<li>Set up a project in the Google API Console (see 
<a href="https://developers.google.com/identity/protocols/oauth2/openid-connect#appsetup">documentation</a>).</li>
<li>Add an &quot;OAuth Client ID&quot; for a Web Application under &quot;Credentials&quot;.</li>
<li>Copy the Client ID and Client Secret, and add the following to your synapse config:
<pre><code class="language-yaml">oidc_providers:
  - idp_id: google
    idp_name: Google
    idp_brand: &quot;google&quot;  # optional: styling hint for clients
    issuer: &quot;https://accounts.google.com/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;] # email is optional, read below
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.given_name|lower }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
        email_template: &quot;{{ user.email }}&quot; # needs &quot;email&quot; in scopes above
</code></pre>
</li>
<li>Back in the Google console, add this Authorized redirect URI: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
</ol>
<h3 id="keycloak"><a class="header" href="#keycloak">Keycloak</a></h3>
<p><a href="https://www.keycloak.org/docs/latest/server_admin/#sso-protocols">Keycloak</a> is an opensource IdP maintained by Red Hat.</p>
<p>Keycloak supports OIDC Back-Channel Logout, which sends logout notification to Synapse, so that Synapse users get logged out when they log out from Keycloak.
This can be optionally enabled by setting <code>backchannel_logout_enabled</code> to <code>true</code> in the Synapse configuration, and by setting the &quot;Backchannel Logout URL&quot; in Keycloak.</p>
<p>Follow the <a href="https://www.keycloak.org/guides">Getting Started Guide</a> to install Keycloak and set up a realm.</p>
<ol>
<li>
<p>Click <code>Clients</code> in the sidebar and click <code>Create</code></p>
</li>
<li>
<p>Fill in the fields as below:</p>
</li>
</ol>
<table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
<tr><td>Client ID</td><td><code>synapse</code></td></tr>
<tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
</tbody></table>
<ol start="3">
<li>Click <code>Save</code></li>
<li>Fill in the fields as below:</li>
</ol>
<table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
<tr><td>Client ID</td><td><code>synapse</code></td></tr>
<tr><td>Enabled</td><td><code>On</code></td></tr>
<tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
<tr><td>Access Type</td><td><code>confidential</code></td></tr>
<tr><td>Valid Redirect URIs</td><td><code>[synapse public baseurl]/_synapse/client/oidc/callback</code></td></tr>
<tr><td>Backchannel Logout URL (optional)</td><td> <code>[synapse public baseurl]/_synapse/client/oidc/backchannel_logout</code></td></tr>
<tr><td>Backchannel Logout Session Required (optional)</td><td> <code>On</code></td></tr>
</tbody></table>
<ol start="5">
<li>Click <code>Save</code></li>
<li>On the Credentials tab, update the fields:</li>
</ol>
<table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
<tr><td>Client Authenticator</td><td><code>Client ID and Secret</code></td></tr>
</tbody></table>
<ol start="7">
<li>Click <code>Regenerate Secret</code></li>
<li>Copy Secret</li>
</ol>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: keycloak
    idp_name: &quot;My KeyCloak server&quot;
    issuer: &quot;https://127.0.0.1:8443/realms/{realm_name}&quot;
    client_id: &quot;synapse&quot;
    client_secret: &quot;copy secret generated from above&quot;
    scopes: [&quot;openid&quot;, &quot;profile&quot;]
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
    backchannel_logout_enabled: true # Optional
</code></pre>
<h3 id="lemonldap"><a class="header" href="#lemonldap">LemonLDAP</a></h3>
<p><a href="https://lemonldap-ng.org/">LemonLDAP::NG</a> is an open-source IdP solution.</p>
<ol>
<li>Create an OpenID Connect Relying Parties in LemonLDAP::NG</li>
<li>The parameters are:</li>
</ol>
<ul>
<li>Client ID under the basic menu of the new Relying Parties (<code>Options &gt; Basic &gt; Client ID</code>)</li>
<li>Client secret (<code>Options &gt; Basic &gt; Client secret</code>)</li>
<li>JWT Algorithm: RS256 within the security menu of the new Relying Parties
(<code>Options &gt; Security &gt; ID Token signature algorithm</code> and <code>Options &gt; Security &gt; Access Token signature algorithm</code>)</li>
<li>Scopes: OpenID, Email and Profile</li>
<li>Allowed redirection addresses for login (<code>Options &gt; Basic &gt; Allowed redirection addresses for login</code> ) :
<code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
</ul>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: lemonldap
    idp_name: lemonldap
    discover: true
    issuer: &quot;https://auth.example.org/&quot; # TO BE FILLED: replace with your domain
    client_id: &quot;your client id&quot; # TO BE FILLED
    client_secret: &quot;your client secret&quot; # TO BE FILLED
    scopes:
      - &quot;openid&quot;
      - &quot;profile&quot;
      - &quot;email&quot;
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username }}}&quot;
        # TO BE FILLED: If your users have names in LemonLDAP::NG and you want those in Synapse, this should be replaced with user.name|capitalize or any valid filter.
        display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot;
</code></pre>
<h3 id="mastodon"><a class="header" href="#mastodon">Mastodon</a></h3>
<p><a href="https://docs.joinmastodon.org/">Mastodon</a> instances provide an <a href="https://docs.joinmastodon.org/spec/oauth/">OAuth API</a>, allowing those instances to be used as a single sign-on provider for Synapse.</p>
<p>The first step is to register Synapse as an application with your Mastodon instance, using the <a href="https://docs.joinmastodon.org/methods/apps/#create">Create an application API</a> (see also <a href="https://docs.joinmastodon.org/client/token/">here</a>). There are several ways to do this, but in the example below we are using CURL.</p>
<p>This example assumes that:</p>
<ul>
<li>the Mastodon instance website URL is <code>https://your.mastodon.instance.url</code>, and</li>
<li>Synapse will be registered as an app named <code>my_synapse_app</code>.</li>
</ul>
<p>Send the following request, substituting the value of <code>synapse_public_baseurl</code> from your Synapse installation.</p>
<pre><code class="language-sh">curl -d &quot;client_name=my_synapse_app&amp;redirect_uris=https://[synapse_public_baseurl]/_synapse/client/oidc/callback&quot; -X POST https://your.mastodon.instance.url/api/v1/apps
</code></pre>
<p>You should receive a response similar to the following. Make sure to save it.</p>
<pre><code class="language-json">{&quot;client_id&quot;:&quot;someclientid_123&quot;,&quot;client_secret&quot;:&quot;someclientsecret_123&quot;,&quot;id&quot;:&quot;12345&quot;,&quot;name&quot;:&quot;my_synapse_app&quot;,&quot;redirect_uri&quot;:&quot;https://[synapse_public_baseurl]/_synapse/client/oidc/callback&quot;,&quot;website&quot;:null,&quot;vapid_key&quot;:&quot;somerandomvapidkey_123&quot;}
</code></pre>
<p>As the Synapse login mechanism needs an attribute to uniquely identify users, and Mastodon's endpoint does not return a <code>sub</code> property, an alternative <code>subject_template</code> has to be set. Your Synapse configuration should include the following:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: my_mastodon
    idp_name: &quot;Mastodon Instance Example&quot;
    discover: false
    issuer: &quot;https://your.mastodon.instance.url/@admin&quot;
    client_id: &quot;someclientid_123&quot;    
    client_secret: &quot;someclientsecret_123&quot;
    authorization_endpoint: &quot;https://your.mastodon.instance.url/oauth/authorize&quot;
    token_endpoint: &quot;https://your.mastodon.instance.url/oauth/token&quot;
    userinfo_endpoint: &quot;https://your.mastodon.instance.url/api/v1/accounts/verify_credentials&quot;
    scopes: [&quot;read&quot;]
    user_mapping_provider:
      config:
        subject_template: &quot;{{ user.id }}&quot;
        localpart_template: &quot;{{ user.username }}&quot;
        display_name_template: &quot;{{ user.display_name }}&quot;
</code></pre>
<p>Note that the fields <code>client_id</code> and <code>client_secret</code> are taken from the CURL response above.</p>
<h3 id="shibboleth-with-oidc-plugin"><a class="header" href="#shibboleth-with-oidc-plugin">Shibboleth with OIDC Plugin</a></h3>
<p><a href="https://www.shibboleth.net/">Shibboleth</a> is an open Standard IdP solution widely used by Universities.</p>
<ol>
<li>Shibboleth needs the <a href="https://shibboleth.atlassian.net/wiki/spaces/IDPPLUGINS/pages/1376878976/OIDC+OP">OIDC Plugin</a> installed and working correctly.</li>
<li>Create a new config on the IdP Side, ensure that the <code>client_id</code> and <code>client_secret</code>
are randomly generated data.</li>
</ol>
<pre><code class="language-json">{
    &quot;client_id&quot;: &quot;SOME-CLIENT-ID&quot;,
    &quot;client_secret&quot;: &quot;SOME-SUPER-SECRET-SECRET&quot;,
    &quot;response_types&quot;: [&quot;code&quot;],
    &quot;grant_types&quot;: [&quot;authorization_code&quot;],
    &quot;scope&quot;: &quot;openid profile email&quot;,
    &quot;redirect_uris&quot;: [&quot;https://[synapse public baseurl]/_synapse/client/oidc/callback&quot;]
}
</code></pre>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  # Shibboleth IDP
  #
  - idp_id: shibboleth
    idp_name: &quot;Shibboleth Login&quot;
    discover: true
    issuer: &quot;https://YOUR-IDP-URL.TLD&quot;
    client_id: &quot;YOUR_CLIENT_ID&quot;
    client_secret: &quot;YOUR-CLIENT-SECRECT-FROM-YOUR-IDP&quot;
    scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;]
    allow_existing_users: true
    user_profile_method: &quot;userinfo_endpoint&quot;
    user_mapping_provider:
      config:
        subject_claim: &quot;sub&quot;
        localpart_template: &quot;{{ user.sub.split('@')[0] }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
        email_template: &quot;{{ user.email }}&quot;
</code></pre>
<h3 id="twitch"><a class="header" href="#twitch">Twitch</a></h3>
<ol>
<li>Setup a developer account on <a href="https://dev.twitch.tv/">Twitch</a></li>
<li>Obtain the OAuth 2.0 credentials by <a href="https://dev.twitch.tv/console/apps/">creating an app</a></li>
<li>Add this OAuth Redirect URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
</ol>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: twitch
    idp_name: Twitch
    issuer: &quot;https://id.twitch.tv/oauth2/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    client_auth_method: &quot;client_secret_post&quot;
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
</code></pre>
<h3 id="twitter"><a class="header" href="#twitter">Twitter</a></h3>
<p><em>Using Twitter as an identity provider requires using Synapse 1.75.0 or later.</em></p>
<ol>
<li>Setup a developer account on <a href="https://developer.twitter.com/en/portal/dashboard">Twitter</a></li>
<li>Create a project &amp; app.</li>
<li>Enable user authentication and under &quot;Type of App&quot; choose &quot;Web App, Automated App or Bot&quot;.</li>
<li>Under &quot;App info&quot; set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
<li>Obtain the OAuth 2.0 credentials under the &quot;Keys and tokens&quot; tab, copy the &quot;OAuth 2.0 Client ID and Client Secret&quot;</li>
</ol>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: twitter
    idp_name: Twitter
    idp_brand: &quot;twitter&quot;  # optional: styling hint for clients
    discover: false  # Twitter is not OpenID compliant.
    issuer: &quot;https://twitter.com/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_secret: &quot;your-client-secret&quot; # TO BE FILLED
    pkce_method: &quot;always&quot;
    # offline.access providers refresh tokens, tweet.read and users.read needed for userinfo request.
    scopes: [&quot;offline.access&quot;, &quot;tweet.read&quot;, &quot;users.read&quot;]
    authorization_endpoint: https://twitter.com/i/oauth2/authorize
    token_endpoint: https://api.twitter.com/2/oauth2/token
    userinfo_endpoint: https://api.twitter.com/2/users/me?user.fields=profile_image_url
    user_mapping_provider:
      config:
        subject_template: &quot;{{ user.data.id }}&quot;
        localpart_template: &quot;{{ user.data.username }}&quot;
        display_name_template: &quot;{{ user.data.name }}&quot;
        picture_template: &quot;{{ user.data.profile_image_url }}&quot;
</code></pre>
<h3 id="xwiki"><a class="header" href="#xwiki">XWiki</a></h3>
<p>Install <a href="https://extensions.xwiki.org/xwiki/bin/view/Extension/OpenID%20Connect/OpenID%20Connect%20Provider/">OpenID Connect Provider</a> extension in your <a href="https://www.xwiki.org">XWiki</a> instance.</p>
<p>Synapse config:</p>
<pre><code class="language-yaml">oidc_providers:
  - idp_id: xwiki
    idp_name: &quot;XWiki&quot;
    issuer: &quot;https://myxwikihost/xwiki/oidc/&quot;
    client_id: &quot;your-client-id&quot; # TO BE FILLED
    client_auth_method: none
    scopes: [&quot;openid&quot;, &quot;profile&quot;]
    user_profile_method: &quot;userinfo_endpoint&quot;
    user_mapping_provider:
      config:
        localpart_template: &quot;{{ user.preferred_username }}&quot;
        display_name_template: &quot;{{ user.name }}&quot;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="saml"><a class="header" href="#saml">SAML</a></h1>
<p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion
Markup Language</a>
(SAML) protocol natively.</p>
<p>Please see the <code>saml2_config</code> and <code>sso</code> sections of the <a href="usage/configuration/user_authentication/single_sign_on/../../../configuration/homeserver_sample_config.html">Synapse configuration
file</a> for more details.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="cas"><a class="header" href="#cas">CAS</a></h1>
<p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Central_Authentication_Service">Central Authentication
Service protocol</a>
(CAS) natively.</p>
<p>Please see the <a href="usage/configuration/user_authentication/single_sign_on/../../../configuration/config_documentation.html#cas_config">cas_config</a> and <a href="usage/configuration/user_authentication/single_sign_on/../../../configuration/config_documentation.html#sso">sso</a>
sections of the configuration manual for more details.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="sso-mapping-providers"><a class="header" href="#sso-mapping-providers">SSO Mapping Providers</a></h1>
<p>A mapping provider is a Python class (loaded via a Python module) that
works out how to map attributes of a SSO response to Matrix-specific
user attributes. Details such as user ID localpart, displayname, and even avatar
URLs are all things that can be mapped from talking to a SSO service.</p>
<p>As an example, a SSO service may return the email address
&quot;john.smith@example.com&quot; for a user, whereas Synapse will need to figure out how
to turn that into a displayname when creating a Matrix user for this individual.
It may choose <code>John Smith</code>, or <code>Smith, John [Example.com]</code> or any number of
variations. As each Synapse configuration may want something different, this is
where SAML mapping providers come into play.</p>
<p>SSO mapping providers are currently supported for OpenID and SAML SSO
configurations. Please see the details below for how to implement your own.</p>
<p>It is up to the mapping provider whether the user should be assigned a predefined
Matrix ID based on the SSO attributes, or if the user should be allowed to
choose their own username.</p>
<p>In the first case - where users are automatically allocated a Matrix ID - it is
the responsibility of the mapping provider to normalise the SSO attributes and
map them to a valid Matrix ID. The <a href="https://spec.matrix.org/latest/appendices/#user-identifiers">specification for Matrix
IDs</a> has some
information about what is considered valid.</p>
<p>If the mapping provider does not assign a Matrix ID, then Synapse will
automatically serve an HTML page allowing the user to pick their own username.</p>
<p>External mapping providers are provided to Synapse in the form of an external
Python module. You can retrieve this module from <a href="https://pypi.org">PyPI</a> or elsewhere,
but it must be importable via Synapse (e.g. it must be in the same virtualenv
as Synapse). The Synapse config is then modified to point to the mapping provider
(and optionally provide additional configuration for it).</p>
<h2 id="openid-mapping-providers"><a class="header" href="#openid-mapping-providers">OpenID Mapping Providers</a></h2>
<p>The OpenID mapping provider can be customized by editing the
<a href="usage/configuration/config_documentation.html#oidc_providers"><code>oidc_providers.user_mapping_provider.module</code></a>
config option.</p>
<p><code>oidc_providers.user_mapping_provider.config</code> allows you to provide custom
configuration options to the module. Check with the module's documentation for
what options it provides (if any). The options listed by default are for the
user mapping provider built in to Synapse. If using a custom module, you should
comment these options out and use those specified by the module instead.</p>
<h3 id="building-a-custom-openid-mapping-provider"><a class="header" href="#building-a-custom-openid-mapping-provider">Building a Custom OpenID Mapping Provider</a></h3>
<p>A custom mapping provider must specify the following methods:</p>
<ul>
<li><code>def __init__(self, parsed_config)</code>
<ul>
<li>Arguments:
<ul>
<li><code>parsed_config</code> - A configuration object that is the return value of the
<code>parse_config</code> method. You should set any configuration options needed by
the module here.</li>
</ul>
</li>
</ul>
</li>
<li><code>def parse_config(config)</code>
<ul>
<li>This method should have the <code>@staticmethod</code> decoration.</li>
<li>Arguments:
<ul>
<li><code>config</code> - A <code>dict</code> representing the parsed content of the
<code>oidc_providers.user_mapping_provider.config</code> homeserver config option.
Runs on homeserver startup. Providers should extract and validate
any option values they need here.</li>
</ul>
</li>
<li>Whatever is returned will be passed back to the user mapping provider module's
<code>__init__</code> method during construction.</li>
</ul>
</li>
<li><code>def get_remote_user_id(self, userinfo)</code>
<ul>
<li>Arguments:
<ul>
<li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
information from.</li>
</ul>
</li>
<li>This method must return a string, which is the unique, immutable identifier
for the user. Commonly the <code>sub</code> claim of the response.</li>
</ul>
</li>
<li><code>async def map_user_attributes(self, userinfo, token, failures)</code>
<ul>
<li>This method must be async.</li>
<li>Arguments:
<ul>
<li><code>userinfo</code> - An <a href="https://docs.authlib.org/en/latest/specs/oidc.html#authlib.oidc.core.UserInfo"><code>authlib.oidc.core.claims.UserInfo</code></a>
object to extract user information from.</li>
<li><code>token</code> - A dictionary which includes information necessary to make
further requests to the OpenID provider.</li>
<li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
mxid localpart mapping has failed.  This should be used
to create a deduplicated mxid localpart which should be
returned instead. For example, if this method returns
<code>john.doe</code> as the value of <code>localpart</code> in the returned
dict, and that is already taken on the homeserver, this
method will be called again with the same parameters but
with failures=1. The method should then return a different
<code>localpart</code> value, such as <code>john.doe1</code>.</li>
</ul>
</li>
<li>Returns a dictionary with two keys:
<ul>
<li><code>localpart</code>: A string, used to generate the Matrix ID. If this is
<code>None</code>, the user is prompted to pick their own username. This is only used
during a user's first login. Once a localpart has been associated with a
remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
<li><code>confirm_localpart</code>: A boolean. If set to <code>True</code>, when a <code>localpart</code>
string is returned from this method, Synapse will prompt the user to
either accept this localpart or pick their own username. Otherwise this
option has no effect. If omitted, defaults to <code>False</code>.</li>
<li><code>display_name</code>: An optional string, the display name for the user.</li>
<li><code>emails</code>: A list of strings, the email address(es) to associate with
this user. If omitted, defaults to an empty list.</li>
</ul>
</li>
</ul>
</li>
<li><code>async def get_extra_attributes(self, userinfo, token)</code>
<ul>
<li>
<p>This method must be async.</p>
</li>
<li>
<p>Arguments:</p>
<ul>
<li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
information from.</li>
<li><code>token</code> - A dictionary which includes information necessary to make
further requests to the OpenID provider.</li>
</ul>
</li>
<li>
<p>Returns a dictionary that is suitable to be serialized to JSON. This
will be returned as part of the response during a successful login.</p>
<p>Note that care should be taken to not overwrite any of the parameters
usually returned as part of the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3login">login response</a>.</p>
</li>
</ul>
</li>
</ul>
<h3 id="default-openid-mapping-provider"><a class="header" href="#default-openid-mapping-provider">Default OpenID Mapping Provider</a></h3>
<p>Synapse has a built-in OpenID mapping provider if a custom provider isn't
specified in the config. It is located at
<a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/oidc.py"><code>synapse.handlers.oidc.JinjaOidcMappingProvider</code></a>.</p>
<h2 id="saml-mapping-providers"><a class="header" href="#saml-mapping-providers">SAML Mapping Providers</a></h2>
<p>The SAML mapping provider can be customized by editing the
<a href="usage/configuration/config_documentation.html#saml2_config"><code>saml2_config.user_mapping_provider.module</code></a>
config option.</p>
<p><code>saml2_config.user_mapping_provider.config</code> allows you to provide custom
configuration options to the module. Check with the module's documentation for
what options it provides (if any). The options listed by default are for the
user mapping provider built in to Synapse. If using a custom module, you should
comment these options out and use those specified by the module instead.</p>
<h3 id="building-a-custom-saml-mapping-provider"><a class="header" href="#building-a-custom-saml-mapping-provider">Building a Custom SAML Mapping Provider</a></h3>
<p>A custom mapping provider must specify the following methods:</p>
<ul>
<li><code>def __init__(self, parsed_config, module_api)</code>
<ul>
<li>Arguments:
<ul>
<li><code>parsed_config</code> - A configuration object that is the return value of the
<code>parse_config</code> method. You should set any configuration options needed by
the module here.</li>
<li><code>module_api</code> - a <code>synapse.module_api.ModuleApi</code> object which provides the
stable API available for extension modules.</li>
</ul>
</li>
</ul>
</li>
<li><code>def parse_config(config)</code>
<ul>
<li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
<li>Arguments:
<ul>
<li><code>config</code> - A <code>dict</code> representing the parsed content of the
<code>saml_config.user_mapping_provider.config</code> homeserver config option.
Runs on homeserver startup. Providers should extract and validate
any option values they need here.</li>
</ul>
</li>
<li>Whatever is returned will be passed back to the user mapping provider module's
<code>__init__</code> method during construction.</li>
</ul>
</li>
<li><code>def get_saml_attributes(config)</code>
<ul>
<li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
<li>Arguments:
<ul>
<li><code>config</code> - A object resulting from a call to <code>parse_config</code>.</li>
</ul>
</li>
<li>Returns a tuple of two sets. The first set equates to the SAML auth
response attributes that are required for the module to function, whereas
the second set consists of those attributes which can be used if available,
but are not necessary.</li>
</ul>
</li>
<li><code>def get_remote_user_id(self, saml_response, client_redirect_url)</code>
<ul>
<li>Arguments:
<ul>
<li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
information from.</li>
<li><code>client_redirect_url</code> - A string, the URL that the client will be
redirected to.</li>
</ul>
</li>
<li>This method must return a string, which is the unique, immutable identifier
for the user. Commonly the <code>uid</code> claim of the response.</li>
</ul>
</li>
<li><code>def saml_response_to_user_attributes(self, saml_response, failures, client_redirect_url)</code>
<ul>
<li>
<p>Arguments:</p>
<ul>
<li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
information from.</li>
<li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
mxid localpart mapping has failed.  This should be used
to create a deduplicated mxid localpart which should be
returned instead. For example, if this method returns
<code>john.doe</code> as the value of <code>mxid_localpart</code> in the returned
dict, and that is already taken on the homeserver, this
method will be called again with the same parameters but
with failures=1. The method should then return a different
<code>mxid_localpart</code> value, such as <code>john.doe1</code>.</li>
<li><code>client_redirect_url</code> - A string, the URL that the client will be
redirected to.</li>
</ul>
</li>
<li>
<p>This method must return a dictionary, which will then be used by Synapse
to build a new user. The following keys are allowed:</p>
<ul>
<li><code>mxid_localpart</code> - A string, the mxid localpart of the new user. If this is
<code>None</code>, the user is prompted to pick their own username. This is only used
during a user's first login. Once a localpart has been associated with a
remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
<li><code>displayname</code> - The displayname of the new user. If not provided, will default to
the value of <code>mxid_localpart</code>.</li>
<li><code>emails</code> - A list of emails for the new user. If not provided, will
default to an empty list.</li>
</ul>
<p>Alternatively it can raise a <code>synapse.api.errors.RedirectException</code> to
redirect the user to another page. This is useful to prompt the user for
additional information, e.g. if you want them to provide their own username.
It is the responsibility of the mapping provider to either redirect back
to <code>client_redirect_url</code> (including any additional information) or to
complete registration using methods from the <code>ModuleApi</code>.</p>
</li>
</ul>
</li>
</ul>
<h3 id="default-saml-mapping-provider"><a class="header" href="#default-saml-mapping-provider">Default SAML Mapping Provider</a></h3>
<p>Synapse has a built-in SAML mapping provider if a custom provider isn't
specified in the config. It is located at
<a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/saml.py"><code>synapse.handlers.saml.DefaultSamlMappingProvider</code></a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h2 style="color:red">
This page of the Synapse documentation is now deprecated. For up to date
documentation on setting up or writing a password auth provider module, please see
<a href="modules/index.html">this page</a>.
</h2>
<h1 id="password-auth-provider-modules"><a class="header" href="#password-auth-provider-modules">Password auth provider modules</a></h1>
<p>Password auth providers offer a way for server administrators to
integrate their Synapse installation with an existing authentication
system.</p>
<p>A password auth provider is a Python class which is dynamically loaded
into Synapse, and provides a number of methods by which it can integrate
with the authentication system.</p>
<p>This document serves as a reference for those looking to implement their
own password auth providers. Additionally, here is a list of known
password auth provider module implementations:</p>
<ul>
<li><a href="https://github.com/matrix-org/matrix-synapse-ldap3/">matrix-synapse-ldap3</a></li>
<li><a href="https://github.com/devture/matrix-synapse-shared-secret-auth">matrix-synapse-shared-secret-auth</a></li>
<li><a href="https://github.com/ma1uta/matrix-synapse-rest-password-provider">matrix-synapse-rest-password-provider</a></li>
</ul>
<h2 id="required-methods"><a class="header" href="#required-methods">Required methods</a></h2>
<p>Password auth provider classes must provide the following methods:</p>
<ul>
<li>
<p><code>parse_config(config)</code>
This method is passed the <code>config</code> object for this module from the
homeserver configuration file.</p>
<p>It should perform any appropriate sanity checks on the provided
configuration, and return an object which is then passed into
<code>__init__</code>.</p>
<p>This method should have the <code>@staticmethod</code> decoration.</p>
</li>
<li>
<p><code>__init__(self, config, account_handler)</code></p>
<p>The constructor is passed the config object returned by
<code>parse_config</code>, and a <code>synapse.module_api.ModuleApi</code> object which
allows the password provider to check if accounts exist and/or create
new ones.</p>
</li>
</ul>
<h2 id="optional-methods"><a class="header" href="#optional-methods">Optional methods</a></h2>
<p>Password auth provider classes may optionally provide the following methods:</p>
<ul>
<li>
<p><code>get_db_schema_files(self)</code></p>
<p>This method, if implemented, should return an Iterable of
<code>(name, stream)</code> pairs of database schema files. Each file is applied
in turn at initialisation, and a record is then made in the database
so that it is not re-applied on the next start.</p>
</li>
<li>
<p><code>get_supported_login_types(self)</code></p>
<p>This method, if implemented, should return a <code>dict</code> mapping from a
login type identifier (such as <code>m.login.password</code>) to an iterable
giving the fields which must be provided by the user in the submission
to <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">the <code>/login</code> API</a>.
These fields are passed in the <code>login_dict</code> dictionary to <code>check_auth</code>.</p>
<p>For example, if a password auth provider wants to implement a custom
login type of <code>com.example.custom_login</code>, where the client is expected
to pass the fields <code>secret1</code> and <code>secret2</code>, the provider should
implement this method and return the following dict:</p>
<pre><code class="language-python">{&quot;com.example.custom_login&quot;: (&quot;secret1&quot;, &quot;secret2&quot;)}
</code></pre>
</li>
<li>
<p><code>check_auth(self, username, login_type, login_dict)</code></p>
<p>This method does the real work. If implemented, it
will be called for each login attempt where the login type matches one
of the keys returned by <code>get_supported_login_types</code>.</p>
<p>It is passed the (possibly unqualified) <code>user</code> field provided by the client,
the login type, and a dictionary of login secrets passed by the
client.</p>
<p>The method should return an <code>Awaitable</code> object, which resolves
to the canonical <code>@localpart:domain</code> user ID if authentication is
successful, and <code>None</code> if not.</p>
<p>Alternatively, the <code>Awaitable</code> can resolve to a <code>(str, func)</code> tuple, in
which case the second field is a callback which will be called with
the result from the <code>/login</code> call (including <code>access_token</code>,
<code>device_id</code>, etc.)</p>
</li>
<li>
<p><code>check_3pid_auth(self, medium, address, password)</code></p>
<p>This method, if implemented, is called when a user attempts to
register or log in with a third party identifier, such as email. It is
passed the medium (ex. &quot;email&quot;), an address (ex.
&quot;<a href="mailto:jdoe@example.com">jdoe@example.com</a>&quot;) and the user's password.</p>
<p>The method should return an <code>Awaitable</code> object, which resolves
to a <code>str</code> containing the user's (canonical) User id if
authentication was successful, and <code>None</code> if not.</p>
<p>As with <code>check_auth</code>, the <code>Awaitable</code> may alternatively resolve to a
<code>(user_id, callback)</code> tuple.</p>
</li>
<li>
<p><code>check_password(self, user_id, password)</code></p>
<p>This method provides a simpler interface than
<code>get_supported_login_types</code> and <code>check_auth</code> for password auth
providers that just want to provide a mechanism for validating
<code>m.login.password</code> logins.</p>
<p>If implemented, it will be called to check logins with an
<code>m.login.password</code> login type. It is passed a qualified
<code>@localpart:domain</code> user id, and the password provided by the user.</p>
<p>The method should return an <code>Awaitable</code> object, which resolves
to <code>True</code> if authentication is successful, and <code>False</code> if not.</p>
</li>
<li>
<p><code>on_logged_out(self, user_id, device_id, access_token)</code></p>
<p>This method, if implemented, is called when a user logs out. It is
passed the qualified user ID, the ID of the deactivated device (if
any: access tokens are occasionally created without an associated
device ID), and the (now deactivated) access token.</p>
<p>It may return an <code>Awaitable</code> object; the logout request will
wait for the <code>Awaitable</code> to complete, but the result is ignored.</p>
</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="jwt-login-type"><a class="header" href="#jwt-login-type">JWT Login Type</a></h1>
<p>Synapse comes with a non-standard login type to support
<a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JSON Web Tokens</a>. In general the
documentation for
<a href="https://matrix.org/docs/spec/client_server/r0.6.1#login">the login endpoint</a>
is still valid (and the mechanism works similarly to the
<a href="https://matrix.org/docs/spec/client_server/r0.6.1#token-based">token based login</a>).</p>
<p>To log in using a JSON Web Token, clients should submit a <code>/login</code> request as
follows:</p>
<pre><code class="language-json">{
  &quot;type&quot;: &quot;org.matrix.login.jwt&quot;,
  &quot;token&quot;: &quot;&lt;jwt&gt;&quot;
}
</code></pre>
<p>The <code>token</code> field should include the JSON web token with the following claims:</p>
<ul>
<li>A claim that encodes the local part of the user ID is required. By default,
the <code>sub</code> (subject) claim is used, or a custom claim can be set in the
configuration file.</li>
<li>The expiration time (<code>exp</code>), not before time (<code>nbf</code>), and issued at (<code>iat</code>)
claims are optional, but validated if present.</li>
<li>The issuer (<code>iss</code>) claim is optional, but required and validated if configured.</li>
<li>The audience (<code>aud</code>) claim is optional, but required and validated if configured.
Providing the audience claim when not configured will cause validation to fail.</li>
</ul>
<p>In the case that the token is not valid, the homeserver must respond with
<code>403 Forbidden</code> and an error code of <code>M_FORBIDDEN</code>.</p>
<p>As with other login types, there are additional fields (e.g. <code>device_id</code> and
<code>initial_device_display_name</code>) which can be included in the above request.</p>
<h2 id="preparing-synapse-1"><a class="header" href="#preparing-synapse-1">Preparing Synapse</a></h2>
<p>The JSON Web Token integration in Synapse uses the
<a href="https://docs.authlib.org/en/latest/index.html"><code>Authlib</code></a> library, which must be installed
as follows:</p>
<ul>
<li>
<p>The relevant libraries are included in the Docker images and Debian packages
provided by <code>matrix.org</code> so no further action is needed.</p>
</li>
<li>
<p>If you installed Synapse into a virtualenv, run <code>/path/to/env/bin/pip install synapse[jwt]</code> to install the necessary dependencies.</p>
</li>
<li>
<p>For other installation mechanisms, see the documentation provided by the
maintainer.</p>
</li>
</ul>
<p>To enable the JSON web token integration, you should then add a <code>jwt_config</code> option
to your configuration file. See the <a href="usage/configuration/config_documentation.html#jwt_config">configuration manual</a> for some
sample settings.</p>
<h2 id="how-to-test-jwt-as-a-developer"><a class="header" href="#how-to-test-jwt-as-a-developer">How to test JWT as a developer</a></h2>
<p>Although JSON Web Tokens are typically generated from an external server, the
example below uses a locally generated JWT.</p>
<ol>
<li>
<p>Configure Synapse with JWT logins, note that this example uses a pre-shared
secret and an algorithm of HS256:</p>
<pre><code class="language-yaml">jwt_config:
    enabled: true
    secret: &quot;my-secret-token&quot;
    algorithm: &quot;HS256&quot;
</code></pre>
</li>
<li>
<p>Generate a JSON web token:</p>
<p>You can use the following short Python snippet to generate a JWT
protected by an HMAC.
Take care that the <code>secret</code> and the algorithm given in the <code>header</code> match
the entries from <code>jwt_config</code> above.</p>
<pre><code class="language-python">from authlib.jose import jwt

header = {&quot;alg&quot;: &quot;HS256&quot;}
payload = {&quot;sub&quot;: &quot;user1&quot;, &quot;aud&quot;: [&quot;audience&quot;]}
secret = &quot;my-secret-token&quot;
result = jwt.encode(header, payload, secret)
print(result.decode(&quot;ascii&quot;))
</code></pre>
</li>
<li>
<p>Query for the login types and ensure <code>org.matrix.login.jwt</code> is there:</p>
<pre><code class="language-bash">curl http://localhost:8080/_matrix/client/r0/login
</code></pre>
</li>
<li>
<p>Login used the generated JSON web token from above:</p>
<pre><code class="language-bash">$ curl http://localhost:8082/_matrix/client/r0/login -X POST \
    --data '{&quot;type&quot;:&quot;org.matrix.login.jwt&quot;,&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc&quot;}'
{
    &quot;access_token&quot;: &quot;&lt;access token&gt;&quot;,
    &quot;device_id&quot;: &quot;ACBDEFGHI&quot;,
    &quot;home_server&quot;: &quot;localhost:8080&quot;,
    &quot;user_id&quot;: &quot;@test-user:localhost:8480&quot;
}
</code></pre>
</li>
</ol>
<p>You should now be able to use the returned access token to query the client API.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="refresh-tokens"><a class="header" href="#refresh-tokens">Refresh Tokens</a></h1>
<p>Synapse supports refresh tokens since version 1.49 (some earlier versions had support for an earlier, experimental draft of <a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/2918-refreshtokens.md#msc2918-refresh-tokens">MSC2918</a> which is not compatible).</p>
<h2 id="background-and-motivation"><a class="header" href="#background-and-motivation">Background and motivation</a></h2>
<p>Synapse users' sessions are identified by <strong>access tokens</strong>; access tokens are
issued to users on login. Each session gets a unique access token which identifies
it; the access token must be kept secret as it grants access to the user's account.</p>
<p>Traditionally, these access tokens were eternally valid (at least until the user
explicitly chose to log out).</p>
<p>In some cases, it may be desirable for these access tokens to expire so that the
potential damage caused by leaking an access token is reduced.
On the other hand, forcing a user to re-authenticate (log in again) often might
be too much of an inconvenience.</p>
<p><strong>Refresh tokens</strong> are a mechanism to avoid some of this inconvenience whilst
still getting most of the benefits of short access token lifetimes.
Refresh tokens are also a concept present in OAuth 2 — further reading is available
<a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5">here</a>.</p>
<p>When refresh tokens are in use, both an access token and a refresh token will be
issued to users on login. The access token will expire after a predetermined amount
of time, but otherwise works in the same way as before. When the access token is
close to expiring (or has expired), the user's client should present the homeserver
(Synapse) with the refresh token.</p>
<p>The homeserver will then generate a new access token and refresh token for the user
and return them. The old refresh token is invalidated and can not be used again*.</p>
<p>Finally, refresh tokens also make it possible for sessions to be logged out if they
are inactive for too long, before the session naturally ends; see the configuration
guide below.</p>
<p>*To prevent issues if clients lose connection half-way through refreshing a token,
the refresh token is only invalidated once the new access token has been used at
least once. For all intents and purposes, the above simplification is sufficient.</p>
<h2 id="caveats"><a class="header" href="#caveats">Caveats</a></h2>
<p>There are some caveats:</p>
<ul>
<li>If a third party gets both your access token and refresh token, they will be able to
continue to enjoy access to your session.
<ul>
<li>This is still an improvement because you (the user) will notice when <em>your</em>
session expires and you're not able to use your refresh token.
That would be a giveaway that someone else has compromised your session.
You would be able to log in again and terminate that session.
Previously (with long-lived access tokens), a third party that has your access
token could go undetected for a very long time.</li>
</ul>
</li>
<li>Clients need to implement support for refresh tokens in order for them to be a
useful mechanism.
<ul>
<li>It is up to homeserver administrators if they want to issue long-lived access
tokens to clients not implementing refresh tokens.
<ul>
<li>For compatibility, it is likely that they should, at least until client support
is widespread.
<ul>
<li>Users with clients that support refresh tokens will still benefit from the
added security; it's not possible to downgrade a session to using long-lived
access tokens so this effectively gives users the choice.</li>
</ul>
</li>
<li>In a closed environment where all users use known clients, this may not be
an issue as the homeserver administrator can know if the clients have refresh
token support. In that case, the non-refreshable access token lifetime
may be set to a short duration so that a similar level of security is provided.</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="configuration-guide"><a class="header" href="#configuration-guide">Configuration Guide</a></h2>
<p>The following configuration options, in the <code>registration</code> section, are related:</p>
<ul>
<li><code>session_lifetime</code>: maximum length of a session, even if it's refreshed.
In other words, the client must log in again after this time period.
In most cases, this can be unset (infinite) or set to a long time (years or months).</li>
<li><code>refreshable_access_token_lifetime</code>: lifetime of access tokens that are created
by clients supporting refresh tokens.
This should be short; a good value might be 5 minutes (<code>5m</code>).</li>
<li><code>nonrefreshable_access_token_lifetime</code>: lifetime of access tokens that are created
by clients which don't support refresh tokens.
Make this short if you want to effectively force use of refresh tokens.
Make this long if you don't want to inconvenience users of clients which don't
support refresh tokens (by forcing them to frequently re-authenticate using
login credentials).</li>
<li><code>refresh_token_lifetime</code>: lifetime of refresh tokens.
In other words, the client must refresh within this time period to maintain its session.
Unless you want to log inactive sessions out, it is often fine to use a long
value here or even leave it unset (infinite).
Beware that making it too short will inconvenience clients that do not connect
very often, including mobile clients and clients of infrequent users (by making
it more difficult for them to refresh in time, which may force them to need to
re-authenticate using login credentials).</li>
</ul>
<p><strong>Note:</strong> All four options above only apply when tokens are created (by logging in or refreshing).
Changes to these settings do not apply retroactively.</p>
<h3 id="using-refresh-token-expiry-to-log-out-inactive-sessions"><a class="header" href="#using-refresh-token-expiry-to-log-out-inactive-sessions">Using refresh token expiry to log out inactive sessions</a></h3>
<p>If you'd like to force sessions to be logged out upon inactivity, you can enable
refreshable access token expiry and refresh token expiry.</p>
<p>This works because a client must refresh at least once within a period of
<code>refresh_token_lifetime</code> in order to maintain valid credentials to access the
account.</p>
<p>(It's suggested that <code>refresh_token_lifetime</code> should be longer than
<code>refreshable_access_token_lifetime</code> and this section assumes that to be the case
for simplicity.)</p>
<p>Note: this will only affect sessions using refresh tokens. You may wish to
set a short <code>nonrefreshable_access_token_lifetime</code> to prevent this being bypassed
by clients that do not support refresh tokens.</p>
<h4 id="choosing-values-that-guarantee-permitting-some-inactivity"><a class="header" href="#choosing-values-that-guarantee-permitting-some-inactivity">Choosing values that guarantee permitting some inactivity</a></h4>
<p>It may be desirable to permit some short periods of inactivity, for example to
accommodate brief outages in client connectivity.</p>
<p>The following model aims to provide guidance for choosing <code>refresh_token_lifetime</code>
and <code>refreshable_access_token_lifetime</code> to satisfy requirements of the form:</p>
<ol>
<li>inactivity longer than <code>L</code> <strong>MUST</strong> cause the session to be logged out; and</li>
<li>inactivity shorter than <code>S</code> <strong>MUST NOT</strong> cause the session to be logged out.</li>
</ol>
<p>This model makes the weakest assumption that all active clients will refresh as
needed to maintain an active access token, but no sooner.
<em>In reality, clients may refresh more often than this model assumes, but the
above requirements will still hold.</em></p>
<p>To satisfy the above model,</p>
<ul>
<li><code>refresh_token_lifetime</code> should be set to <code>L</code>; and</li>
<li><code>refreshable_access_token_lifetime</code> should be set to <code>L - S</code>.</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="overview-2"><a class="header" href="#overview-2">Overview</a></h1>
<p>A captcha can be enabled on your homeserver to help prevent bots from registering
accounts. Synapse currently uses Google's reCAPTCHA service which requires API keys
from Google.</p>
<h2 id="getting-api-keys"><a class="header" href="#getting-api-keys">Getting API keys</a></h2>
<ol>
<li>Create a new site at <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></li>
<li>Set the label to anything you want</li>
<li>Set the type to reCAPTCHA v2 using the &quot;I'm not a robot&quot; Checkbox option.
This is the only type of captcha that works with Synapse.</li>
<li>Add the public hostname for your server, as set in <code>public_baseurl</code>
in <code>homeserver.yaml</code>, to the list of authorized domains. If you have not set
<code>public_baseurl</code>, use <code>server_name</code>.</li>
<li>Agree to the terms of service and submit.</li>
<li>Copy your site key and secret key and add them to your <code>homeserver.yaml</code>
configuration file
<pre><code class="language-yaml">recaptcha_public_key: YOUR_SITE_KEY
recaptcha_private_key: YOUR_SECRET_KEY
</code></pre>
</li>
<li>Enable the CAPTCHA for new registrations
<pre><code class="language-yaml">enable_registration_captcha: true
</code></pre>
</li>
<li>Go to the settings page for the CAPTCHA you just created</li>
<li>Uncheck the &quot;Verify the origin of reCAPTCHA solutions&quot; checkbox so that the
captcha can be displayed in any client. If you do not disable this option then you
must specify the domains of every client that is allowed to display the CAPTCHA.</li>
</ol>
<h2 id="configuring-ip-used-for-auth"><a class="header" href="#configuring-ip-used-for-auth">Configuring IP used for auth</a></h2>
<p>The reCAPTCHA API requires that the IP address of the user who solved the
CAPTCHA is sent. If the client is connecting through a proxy or load balancer,
it may be required to use the <code>X-Forwarded-For</code> (XFF) header instead of the origin
IP address. This can be configured using the <code>x_forwarded</code> directive in the
listeners section of the <code>homeserver.yaml</code> configuration file.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="registering-an-application-service"><a class="header" href="#registering-an-application-service">Registering an Application Service</a></h1>
<p>The registration of new application services depends on the homeserver used. 
In synapse, you need to create a new configuration file for your AS and add it
to the list specified under the <code>app_service_config_files</code> config
option in your synapse config.</p>
<p>For example:</p>
<pre><code class="language-yaml">app_service_config_files:
- /home/matrix/.synapse/&lt;your-AS&gt;.yaml
</code></pre>
<p>The format of the AS configuration file is as follows:</p>
<pre><code class="language-yaml">id: &lt;your-AS-id&gt;
url: &lt;base url of AS&gt;
as_token: &lt;token AS will add to requests to HS&gt;
hs_token: &lt;token HS will add to requests to AS&gt;
sender_localpart: &lt;localpart of AS user&gt;
namespaces:
  users:  # List of users we're interested in
    - exclusive: &lt;bool&gt;
      regex: &lt;regex&gt;
      group_id: &lt;group&gt;
    - ...
  aliases: []  # List of aliases we're interested in
  rooms: [] # List of room ids we're interested in
</code></pre>
<p><code>exclusive</code>: If enabled, only this application service is allowed to register users in its namespace(s).
<code>group_id</code>: All users of this application service are dynamically joined to this group. This is useful for e.g user organisation or flairs.</p>
<p>See the <a href="https://matrix.org/docs/spec/application_service/unstable.html">spec</a> for further details on how application services work.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices"><a class="header" href="#server-notices">Server Notices</a></h1>
<p>'Server Notices' are a new feature introduced in Synapse 0.30. They provide a
channel whereby server administrators can send messages to users on the server.</p>
<p>They are used as part of communication of the server polices (see
<a href="consent_tracking.html">Consent Tracking</a>), however the intention is that
they may also find a use for features such as &quot;Message of the day&quot;.</p>
<p>This is a feature specific to Synapse, but it uses standard Matrix
communication mechanisms, so should work with any Matrix client.</p>
<h2 id="user-experience"><a class="header" href="#user-experience">User experience</a></h2>
<p>When the user is first sent a server notice, they will get an invitation to a
room (typically called 'Server Notices', though this is configurable in
<code>homeserver.yaml</code>). They will be <strong>unable to reject</strong> this invitation -
attempts to do so will receive an error.</p>
<p>Once they accept the invitation, they will see the notice message in the room
history; it will appear to have come from the 'server notices user' (see
below).</p>
<p>The user is prevented from sending any messages in this room by the power
levels.</p>
<p>Having joined the room, the user can leave the room if they want. Subsequent
server notices will then cause a new room to be created.</p>
<h2 id="synapse-configuration"><a class="header" href="#synapse-configuration">Synapse configuration</a></h2>
<p>Server notices come from a specific user id on the server. Server
administrators are free to choose the user id - something like <code>server</code> is
suggested, meaning the notices will come from
<code>@server:&lt;your_server_name&gt;</code>. Once the Server Notices user is configured, that
user id becomes a special, privileged user, so administrators should ensure
that <strong>it is not already allocated</strong>.</p>
<p>In order to support server notices, it is necessary to add some configuration
to the <code>homeserver.yaml</code> file. In particular, you should add a <code>server_notices</code>
section, which should look like this:</p>
<pre><code class="language-yaml">server_notices:
   system_mxid_localpart: server
   system_mxid_display_name: &quot;Server Notices&quot;
   system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
   room_name: &quot;Server Notices&quot;
</code></pre>
<p>The only compulsory setting is <code>system_mxid_localpart</code>, which defines the user
id of the Server Notices user, as above. <code>room_name</code> defines the name of the
room which will be created.</p>
<p><code>system_mxid_display_name</code> and <code>system_mxid_avatar_url</code> can be used to set the
displayname and avatar of the Server Notices user.</p>
<h2 id="sending-notices"><a class="header" href="#sending-notices">Sending notices</a></h2>
<p>To send server notices to users you can use the
<a href="admin_api/server_notices.html">admin_api</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="support-in-synapse-for-tracking-agreement-to-server-terms-and-conditions"><a class="header" href="#support-in-synapse-for-tracking-agreement-to-server-terms-and-conditions">Support in Synapse for tracking agreement to server terms and conditions</a></h1>
<p>Synapse 0.30 introduces support for tracking whether users have agreed to the
terms and conditions set by the administrator of a server - and blocking access
to the server until they have.</p>
<p>There are several parts to this functionality; each requires some specific
configuration in <code>homeserver.yaml</code> to be enabled.</p>
<p>Note that various parts of the configuation and this document refer to the
&quot;privacy policy&quot;: agreement with a privacy policy is one particular use of this
feature, but of course adminstrators can specify other terms and conditions
unrelated to &quot;privacy&quot; per se.</p>
<h2 id="collecting-policy-agreement-from-a-user"><a class="header" href="#collecting-policy-agreement-from-a-user">Collecting policy agreement from a user</a></h2>
<p>Synapse can be configured to serve the user a simple policy form with an
&quot;accept&quot; button. Clicking &quot;Accept&quot; records the user's acceptance in the
database and shows a success page.</p>
<p>To enable this, first create templates for the policy and success pages.
These should be stored on the local filesystem.</p>
<p>These templates use the <a href="http://jinja.pocoo.org">Jinja2</a> templating language,
and <a href="https://github.com/matrix-org/synapse/tree/develop/docs/privacy_policy_templates/">docs/privacy_policy_templates</a>
gives examples of the sort of thing that can be done.</p>
<p>Note that the templates must be stored under a name giving the language of the
template - currently this must always be <code>en</code> (for &quot;English&quot;);
internationalisation support is intended for the future.</p>
<p>The template for the policy itself should be versioned and named according to
the version: for example <code>1.0.html</code>. The version of the policy which the user
has agreed to is stored in the database.</p>
<p>Once the templates are in place, make the following changes to <code>homeserver.yaml</code>:</p>
<ol>
<li>
<p>Add a <code>user_consent</code> section, which should look like:</p>
<pre><code class="language-yaml">user_consent:
  template_dir: privacy_policy_templates
  version: 1.0
</code></pre>
<p><code>template_dir</code> points to the directory containing the policy
templates. <code>version</code> defines the version of the policy which will be served
to the user. In the example above, Synapse will serve
<code>privacy_policy_templates/en/1.0.html</code>.</p>
</li>
<li>
<p>Add a <code>form_secret</code> setting at the top level:</p>
<pre><code class="language-yaml">form_secret: &quot;&lt;unique secret&gt;&quot;
</code></pre>
<p>This should be set to an arbitrary secret string (try <code>pwgen -y 30</code> to
generate suitable secrets).</p>
<p>More on what this is used for below.</p>
</li>
<li>
<p>Add <code>consent</code> wherever the <code>client</code> resource is currently enabled in the
<code>listeners</code> configuration. For example:</p>
<pre><code class="language-yaml">listeners:
  - port: 8008
    resources:
      - names:
        - client
        - consent
</code></pre>
</li>
</ol>
<p>Finally, ensure that <code>jinja2</code> is installed. If you are using a virtualenv, this
should be a matter of <code>pip install Jinja2</code>. On debian, try <code>apt-get install python-jinja2</code>.</p>
<p>Once this is complete, and the server has been restarted, try visiting
<code>https://&lt;server&gt;/_matrix/consent</code>. If correctly configured, this should give
an error &quot;Missing string query parameter 'u'&quot;. It is now possible to manually
construct URIs where users can give their consent.</p>
<h3 id="enabling-consent-tracking-at-registration"><a class="header" href="#enabling-consent-tracking-at-registration">Enabling consent tracking at registration</a></h3>
<ol>
<li>
<p>Add the following to your configuration:</p>
<pre><code class="language-yaml">user_consent:
  require_at_registration: true
  policy_name: &quot;Privacy Policy&quot; # or whatever you'd like to call the policy
</code></pre>
</li>
<li>
<p>In your consent templates, make use of the <code>public_version</code> variable to
see if an unauthenticated user is viewing the page. This is typically
wrapped around the form that would be used to actually agree to the document:</p>
<pre><code class="language-html">{% if not public_version %}
  &lt;!-- The variables used here are only provided when the 'u' param is given to the homeserver --&gt;
  &lt;form method=&quot;post&quot; action=&quot;consent&quot;&gt;
    &lt;input type=&quot;hidden&quot; name=&quot;v&quot; value=&quot;{{version}}&quot;/&gt;
    &lt;input type=&quot;hidden&quot; name=&quot;u&quot; value=&quot;{{user}}&quot;/&gt;
    &lt;input type=&quot;hidden&quot; name=&quot;h&quot; value=&quot;{{userhmac}}&quot;/&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Sure thing!&quot;/&gt;
  &lt;/form&gt;
{% endif %}
</code></pre>
</li>
<li>
<p>Restart Synapse to apply the changes.</p>
</li>
</ol>
<p>Visiting <code>https://&lt;server&gt;/_matrix/consent</code> should now give you a view of the privacy
document. This is what users will be able to see when registering for accounts.</p>
<h3 id="constructing-the-consent-uri"><a class="header" href="#constructing-the-consent-uri">Constructing the consent URI</a></h3>
<p>It may be useful to manually construct the &quot;consent URI&quot; for a given user - for
instance, in order to send them an email asking them to consent. To do this,
take the base <code>https://&lt;server&gt;/_matrix/consent</code> URL and add the following
query parameters:</p>
<ul>
<li>
<p><code>u</code>: the user id of the user. This can either be a full MXID
(<code>@user:server.com</code>) or just the localpart (<code>user</code>).</p>
</li>
<li>
<p><code>h</code>: hex-encoded HMAC-SHA256 of <code>u</code> using the <code>form_secret</code> as a key. It is
possible to calculate this on the commandline with something like:</p>
<pre><code class="language-bash">echo -n '&lt;user&gt;' | openssl sha256 -hmac '&lt;form_secret&gt;'
</code></pre>
<p>This should result in a URI which looks something like:
<code>https://&lt;server&gt;/_matrix/consent?u=&lt;user&gt;&amp;h=68a152465a4d...</code>.</p>
</li>
</ul>
<p>Note that not providing a <code>u</code> parameter will be interpreted as wanting to view
the document from an unauthenticated perspective, such as prior to registration.
Therefore, the <code>h</code> parameter is not required in this scenario. To enable this
behaviour, set <code>require_at_registration</code> to <code>true</code> in your <code>user_consent</code> config.</p>
<h2 id="sending-users-a-server-notice-asking-them-to-agree-to-the-policy"><a class="header" href="#sending-users-a-server-notice-asking-them-to-agree-to-the-policy">Sending users a server notice asking them to agree to the policy</a></h2>
<p>It is possible to configure Synapse to send a <a href="server_notices.html">server
notice</a> to anybody who has not yet agreed to the current
version of the policy. To do so:</p>
<ul>
<li>
<p>ensure that the consent resource is configured, as in the previous section</p>
</li>
<li>
<p>ensure that server notices are configured, as in <a href="server_notices.html">the server notice documentation</a>.</p>
</li>
<li>
<p>Add <code>server_notice_content</code> under <code>user_consent</code> in <code>homeserver.yaml</code>. For
example:</p>
<pre><code class="language-yaml">user_consent:
  server_notice_content:
    msgtype: m.text
    body: &gt;-
      Please give your consent to the privacy policy at %(consent_uri)s.
</code></pre>
<p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
consent uri for that user.</p>
</li>
<li>
<p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
URI that clients use to connect to the server. (It is used to construct
<code>consent_uri</code> in the server notice.)</p>
</li>
</ul>
<h2 id="blocking-users-from-using-the-server-until-they-agree-to-the-policy"><a class="header" href="#blocking-users-from-using-the-server-until-they-agree-to-the-policy">Blocking users from using the server until they agree to the policy</a></h2>
<p>Synapse can be configured to block any attempts to join rooms or send messages
until the user has given their agreement to the policy. (Joining the server
notices room is exempted from this).</p>
<p>To enable this, add <code>block_events_error</code> under <code>user_consent</code>. For example:</p>
<pre><code class="language-yaml">user_consent:
  block_events_error: &gt;-
    You can't send any messages until you consent to the privacy policy at
    %(consent_uri)s.
</code></pre>
<p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
consent uri for that user.</p>
<p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
URI that clients use to connect to the server. (It is used to construct
<code>consent_uri</code> in the error.)</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="user-directory-api-implementation"><a class="header" href="#user-directory-api-implementation">User Directory API Implementation</a></h1>
<p>The user directory is currently maintained based on the 'visible' users
on this particular server - i.e. ones which your account shares a room with, or
who are present in a publicly viewable room present on the server.</p>
<p>The directory info is stored in various tables, which can (typically after
DB corruption) get stale or out of sync. If this happens, for now the
solution to fix it is to use the <a href="usage/administration/admin_api/background_updates.html#run">admin API</a>
and execute the job <code>regenerate_directory</code>. This should then start a background task to
flush the current tables and regenerate the directory.</p>
<h2 id="data-model"><a class="header" href="#data-model">Data model</a></h2>
<p>There are five relevant tables that collectively form the &quot;user directory&quot;.
Three of them track a master list of all the users we could search for.
The last two (collectively called the &quot;search tables&quot;) track who can
see who.</p>
<p>From all of these tables we exclude three types of local user:</p>
<ul>
<li>support users</li>
<li>appservice users</li>
<li>deactivated users</li>
</ul>
<ul>
<li>
<p><code>user_directory</code>. This contains the user_id, display name and avatar we'll
return when you search the directory.</p>
<ul>
<li>Because there's only one directory entry per user, it's important that we only
ever put publicly visible names here. Otherwise we might leak a private
nickname or avatar used in a private room.</li>
<li>Indexed on rooms. Indexed on users.</li>
</ul>
</li>
<li>
<p><code>user_directory_search</code>. To be joined to <code>user_directory</code>. It contains an extra
column that enables full text search based on user ids and display names.
Different schemas for SQLite and Postgres with different code paths to match.</p>
<ul>
<li>Indexed on the full text search data. Indexed on users.</li>
</ul>
</li>
<li>
<p><code>user_directory_stream_pos</code>. When the initial background update to populate
the directory is complete, we record a stream position here. This indicates
that synapse should now listen for room changes and incrementally update
the directory where necessary.</p>
</li>
<li>
<p><code>users_in_public_rooms</code>. Contains associations between users and the public rooms they're in.
Used to determine which users are in public rooms and should be publicly visible in the directory.</p>
</li>
<li>
<p><code>users_who_share_private_rooms</code>. Rows are triples <code>(L, M, room id)</code> where <code>L</code>
is a local user and <code>M</code> is a local or remote user. <code>L</code> and <code>M</code> should be
different, but this isn't enforced by a constraint.</p>
</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="message-retention-policies"><a class="header" href="#message-retention-policies">Message retention policies</a></h1>
<p>Synapse admins can enable support for message retention policies on
their homeserver. Message retention policies exist at a room level,
follow the semantics described in
<a href="https://github.com/matrix-org/matrix-doc/blob/matthew/msc1763/proposals/1763-configurable-retention-periods.md">MSC1763</a>,
and allow server and room admins to configure how long messages should
be kept in a homeserver's database before being purged from it.
<strong>Please note that, as this feature isn't part of the Matrix
specification yet, this implementation is to be considered as
experimental. There are known bugs which may cause database corruption.
Proceed with caution.</strong> </p>
<p>A message retention policy is mainly defined by its <code>max_lifetime</code>
parameter, which defines how long a message can be kept around after
it was sent to the room. If a room doesn't have a message retention
policy, and there's no default one for a given server, then no message
sent in that room is ever purged on that server.</p>
<p>MSC1763 also specifies semantics for a <code>min_lifetime</code> parameter which
defines the amount of time after which an event <em>can</em> get purged (after
it was sent to the room), but Synapse doesn't currently support it
beyond registering it.</p>
<p>Both <code>max_lifetime</code> and <code>min_lifetime</code> are optional parameters.</p>
<p>Note that message retention policies don't apply to state events.</p>
<p>Once an event reaches its expiry date (defined as the time it was sent
plus the value for <code>max_lifetime</code> in the room), two things happen:</p>
<ul>
<li>Synapse stops serving the event to clients via any endpoint.</li>
<li>The message gets picked up by the next purge job (see the &quot;Purge jobs&quot;
section) and is removed from Synapse's database.</li>
</ul>
<p>Since purge jobs don't run continuously, this means that an event might
stay in a server's database for longer than the value for <code>max_lifetime</code>
in the room would allow, though hidden from clients.</p>
<p>Similarly, if a server (with support for message retention policies
enabled) receives from another server an event that should have been
purged according to its room's policy, then the receiving server will
process and store that event until it's picked up by the next purge job,
though it will always hide it from clients.</p>
<p>Synapse requires at least one message in each room, so it will never
delete the last message in a room. It will, however, hide it from
clients.</p>
<h2 id="server-configuration"><a class="header" href="#server-configuration">Server configuration</a></h2>
<p>Support for this feature can be enabled and configured by adding a the
<code>retention</code> in the Synapse configuration file (see
<a href="usage/configuration/config_documentation.html#retention">configuration manual</a>).</p>
<p>To enable support for message retention policies, set the setting
<code>enabled</code> in this section to <code>true</code>.</p>
<h3 id="default-policy"><a class="header" href="#default-policy">Default policy</a></h3>
<p>A default message retention policy is a policy defined in Synapse's
configuration that is used by Synapse for every room that doesn't have a
message retention policy configured in its state. This allows server
admins to ensure that messages are never kept indefinitely in a server's
database. </p>
<p>A default policy can be defined as such, by adding the <code>retention</code> option in
the configuration file and adding these sub-options:</p>
<pre><code class="language-yaml">default_policy:
  min_lifetime: 1d
  max_lifetime: 1y
</code></pre>
<p>Here, <code>min_lifetime</code> and <code>max_lifetime</code> have the same meaning and level
of support as previously described. They can be expressed either as a
duration (using the units <code>s</code> (seconds), <code>m</code> (minutes), <code>h</code> (hours),
<code>d</code> (days), <code>w</code> (weeks) and <code>y</code> (years)) or as a number of milliseconds.</p>
<h3 id="purge-jobs"><a class="header" href="#purge-jobs">Purge jobs</a></h3>
<p>Purge jobs are the jobs that Synapse runs in the background to purge
expired events from the database. They are only run if support for
message retention policies is enabled in the server's configuration. If
no configuration for purge jobs is configured by the server admin,
Synapse will use a default configuration, which is described here in the
<a href="usage/configuration/config_documentation.html#retention">configuration manual</a>.</p>
<p>Some server admins might want a finer control on when events are removed
depending on an event's room's policy. This can be done by setting the
<code>purge_jobs</code> sub-section in the <code>retention</code> section of the configuration
file. An example of such configuration could be:</p>
<pre><code class="language-yaml">purge_jobs:
  - longest_max_lifetime: 3d
    interval: 12h
  - shortest_max_lifetime: 3d
    longest_max_lifetime: 1w
    interval: 1d
  - shortest_max_lifetime: 1w
    interval: 2d
</code></pre>
<p>In this example, we define three jobs:</p>
<ul>
<li>one that runs twice a day (every 12 hours) and purges events in rooms
which policy's <code>max_lifetime</code> is lower or equal to 3 days.</li>
<li>one that runs once a day and purges events in rooms which policy's
<code>max_lifetime</code> is between 3 days and a week.</li>
<li>one that runs once every 2 days and purges events in rooms which
policy's <code>max_lifetime</code> is greater than a week.</li>
</ul>
<p>Note that this example is tailored to show different configurations and
features slightly more jobs than it's probably necessary (in practice, a
server admin would probably consider it better to replace the two last
jobs with one that runs once a day and handles rooms which
policy's <code>max_lifetime</code> is greater than 3 days).</p>
<p>Keep in mind, when configuring these jobs, that a purge job can become
quite heavy on the server if it targets many rooms, therefore prefer
having jobs with a low interval that target a limited set of rooms. Also
make sure to include a job with no minimum and one with no maximum to
make sure your configuration handles every policy.</p>
<p>As previously mentioned in this documentation, while a purge job that
runs e.g. every day means that an expired event might stay in the
database for up to a day after its expiry, Synapse hides expired events
from clients as soon as they expire, so the event is not visible to
local users between its expiry date and the moment it gets purged from
the server's database.</p>
<h3 id="lifetime-limits"><a class="header" href="#lifetime-limits">Lifetime limits</a></h3>
<p>Server admins can set limits on the values of <code>max_lifetime</code> to use when
purging old events in a room. These limits can be defined under the
<code>retention</code> option in the configuration file:</p>
<pre><code class="language-yaml">allowed_lifetime_min: 1d
allowed_lifetime_max: 1y
</code></pre>
<p>The limits are considered when running purge jobs. If necessary, the
effective value of <code>max_lifetime</code> will be brought between
<code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> (inclusive).
This means that, if the value of <code>max_lifetime</code> defined in the room's state
is lower than <code>allowed_lifetime_min</code>, the value of <code>allowed_lifetime_min</code>
will be used instead. Likewise, if the value of <code>max_lifetime</code> is higher
than <code>allowed_lifetime_max</code>, the value of <code>allowed_lifetime_max</code> will be
used instead.</p>
<p>In the example above, we ensure Synapse never deletes events that are less
than one day old, and that it always deletes events that are over a year
old.</p>
<p>If a default policy is set, and its <code>max_lifetime</code> value is lower than
<code>allowed_lifetime_min</code> or higher than <code>allowed_lifetime_max</code>, the same
process applies.</p>
<p>Both parameters are optional; if one is omitted Synapse won't use it to
adjust the effective value of <code>max_lifetime</code>.</p>
<p>Like other settings in this section, these parameters can be expressed
either as a duration or as a number of milliseconds.</p>
<h2 id="room-configuration"><a class="header" href="#room-configuration">Room configuration</a></h2>
<p>To configure a room's message retention policy, a room's admin or
moderator needs to send a state event in that room with the type
<code>m.room.retention</code> and the following content:</p>
<pre><code class="language-json">{
    &quot;max_lifetime&quot;: ...
}
</code></pre>
<p>In this event's content, the <code>max_lifetime</code> parameter has the same
meaning as previously described, and needs to be expressed in
milliseconds. The event's content can also include a <code>min_lifetime</code>
parameter, which has the same meaning and limited support as previously
described.</p>
<p>Note that over every server in the room, only the ones with support for
message retention policies will actually remove expired events. This
support is currently not enabled by default in Synapse.</p>
<h2 id="note-on-reclaiming-disk-space"><a class="header" href="#note-on-reclaiming-disk-space">Note on reclaiming disk space</a></h2>
<p>While purge jobs actually delete data from the database, the disk space
used by the database might not decrease immediately on the database's
host. However, even though the database engine won't free up the disk
space, it will start writing new data into where the purged data was.</p>
<p>If you want to reclaim the freed disk space anyway and return it to the
operating system, the server admin needs to run <code>VACUUM FULL;</code> (or
<code>VACUUM;</code> for SQLite databases) on Synapse's database (see the related
<a href="https://www.postgresql.org/docs/current/sql-vacuum.html">PostgreSQL documentation</a>).</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="modules-2"><a class="header" href="#modules-2">Modules</a></h1>
<p>Synapse supports extending its functionality by configuring external modules.</p>
<p><strong>Note</strong>: When using third-party modules, you effectively allow someone else to run
custom code on your Synapse homeserver. Server admins are encouraged to verify the
provenance of the modules they use on their homeserver and make sure the modules aren't
running malicious code on their instance.</p>
<h2 id="using-modules"><a class="header" href="#using-modules">Using modules</a></h2>
<p>To use a module on Synapse, add it to the <code>modules</code> section of the configuration file:</p>
<pre><code class="language-yaml">modules:
  - module: my_super_module.MySuperClass
    config:
      do_thing: true
  - module: my_other_super_module.SomeClass
    config: {}
</code></pre>
<p>Each module is defined by a path to a Python class as well as a configuration. This
information for a given module should be available in the module's own documentation.</p>
<h2 id="using-multiple-modules"><a class="header" href="#using-multiple-modules">Using multiple modules</a></h2>
<p>The order in which modules are listed in this section is important. When processing an
action that can be handled by several modules, Synapse will always prioritise the module
that appears first (i.e. is the highest in the list). This means:</p>
<ul>
<li>If several modules register the same callback, the callback registered by the module
that appears first is used.</li>
<li>If several modules try to register a handler for the same HTTP path, only the handler
registered by the module that appears first is used. Handlers registered by the other
module(s) are ignored and Synapse will log a warning message about them.</li>
</ul>
<p>Note that Synapse doesn't allow multiple modules implementing authentication checkers via
the password auth provider feature for the same login type with different fields. If this
happens, Synapse will refuse to start.</p>
<h2 id="current-status"><a class="header" href="#current-status">Current status</a></h2>
<p>We are currently in the process of migrating module interfaces to this system. While some
interfaces might be compatible with it, others still require configuring modules in
another part of Synapse's configuration file.</p>
<p>Currently, only the following pre-existing interfaces are compatible with this new system:</p>
<ul>
<li>spam checker</li>
<li>third-party rules</li>
<li>presence router</li>
<li>password auth providers</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="writing-a-module"><a class="header" href="#writing-a-module">Writing a module</a></h1>
<p>A module is a Python class that uses Synapse's module API to interact with the
homeserver. It can register callbacks that Synapse will call on specific operations, as
well as web resources to attach to Synapse's web server.</p>
<p>When instantiated, a module is given its parsed configuration as well as an instance of
the <code>synapse.module_api.ModuleApi</code> class. The configuration is a dictionary, and is
either the output of the module's <code>parse_config</code> static method (see below), or the
configuration associated with the module in Synapse's configuration file.</p>
<p>See the documentation for the <code>ModuleApi</code> class
<a href="https://github.com/matrix-org/synapse/blob/master/synapse/module_api/__init__.py">here</a>.</p>
<h2 id="when-synapse-runs-with-several-modules-configured"><a class="header" href="#when-synapse-runs-with-several-modules-configured">When Synapse runs with several modules configured</a></h2>
<p>If Synapse is running with other modules configured, the order each module appears in
within the <code>modules</code> section of the Synapse configuration file might restrict what it can
or cannot register. See <a href="modules/index.html#using-multiple-modules">this section</a> for more
information.</p>
<p>On top of the rules listed in the link above, if a callback returns a value that should
cause the current operation to fail (e.g. if a callback checking an event returns with a
value that should cause the event to be denied), Synapse will fail the operation and
ignore any subsequent callbacks that should have been run after this one.</p>
<p>The documentation for each callback mentions how Synapse behaves when
multiple modules implement it.</p>
<h2 id="handling-the-modules-configuration"><a class="header" href="#handling-the-modules-configuration">Handling the module's configuration</a></h2>
<p>A module can implement the following static method:</p>
<pre><code class="language-python">@staticmethod
def parse_config(config: dict) -&gt; Any
</code></pre>
<p>This method is given a dictionary resulting from parsing the YAML configuration for the
module. It may modify it (for example by parsing durations expressed as strings (e.g.
&quot;5d&quot;) into milliseconds, etc.), and return the modified dictionary. It may also verify
that the configuration is correct, and raise an instance of
<code>synapse.module_api.errors.ConfigError</code> if not.</p>
<h2 id="registering-a-web-resource"><a class="header" href="#registering-a-web-resource">Registering a web resource</a></h2>
<p>Modules can register web resources onto Synapse's web server using the following module
API method:</p>
<pre><code class="language-python">def ModuleApi.register_web_resource(path: str, resource: IResource) -&gt; None
</code></pre>
<p>The path is the full absolute path to register the resource at. For example, if you
register a resource for the path <code>/_synapse/client/my_super_module/say_hello</code>, Synapse
will serve it at <code>http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello</code>. Note
that Synapse does not allow registering resources for several sub-paths in the <code>/_matrix</code>
namespace (such as anything under <code>/_matrix/client</code> for example). It is strongly
recommended that modules register their web resources under the <code>/_synapse/client</code>
namespace.</p>
<p>The provided resource is a Python class that implements Twisted's <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.web.resource.IResource.html">IResource</a>
interface (such as <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.web.resource.Resource.html">Resource</a>).</p>
<p>Only one resource can be registered for a given path. If several modules attempt to
register a resource for the same path, the module that appears first in Synapse's
configuration file takes priority.</p>
<p>Modules <strong>must</strong> register their web resources in their <code>__init__</code> method.</p>
<h2 id="registering-a-callback"><a class="header" href="#registering-a-callback">Registering a callback</a></h2>
<p>Modules can use Synapse's module API to register callbacks. Callbacks are functions that
Synapse will call when performing specific actions. Callbacks must be asynchronous (unless
specified otherwise), and are split in categories. A single module may implement callbacks
from multiple categories, and is under no obligation to implement all callbacks from the
categories it registers callbacks for.</p>
<p>Modules can register callbacks using one of the module API's <code>register_[...]_callbacks</code>
methods. The callback functions are passed to these methods as keyword arguments, with
the callback name as the argument name and the function as its value. A
<code>register_[...]_callbacks</code> method exists for each category.</p>
<p>Callbacks for each category can be found on their respective page of the
<a href="https://matrix-org.github.io/synapse">Synapse documentation website</a>.</p>
<h2 id="caching-1"><a class="header" href="#caching-1">Caching</a></h2>
<p><em>Added in Synapse 1.74.0.</em></p>
<p>Modules can leverage Synapse's caching tools to manage their own cached functions. This
can be helpful for modules that need to repeatedly request the same data from the database
or a remote service.</p>
<p>Functions that need to be wrapped with a cache need to be decorated with a <code>@cached()</code>
decorator (which can be imported from <code>synapse.module_api</code>) and registered with the
<a href="https://github.com/matrix-org/synapse/blob/release-v1.77/synapse/module_api/__init__.py#L888"><code>ModuleApi.register_cached_function</code></a>
API when initialising the module. If the module needs to invalidate an entry in a cache,
it needs to use the <a href="https://github.com/matrix-org/synapse/blob/release-v1.77/synapse/module_api/__init__.py#L904"><code>ModuleApi.invalidate_cache</code></a>
API, with the function to invalidate the cache of and the key(s) of the entry to
invalidate.</p>
<p>Below is an example of a simple module using a cached function:</p>
<pre><code class="language-python">from typing import Any
from synapse.module_api import cached, ModuleApi

class MyModule:
    def __init__(self, config: Any, api: ModuleApi):
        self.api = api
        
        # Register the cached function so Synapse knows how to correctly invalidate
        # entries for it.
        self.api.register_cached_function(self.get_user_from_id)

    @cached()
    async def get_department_for_user(self, user_id: str) -&gt; str:
        &quot;&quot;&quot;A function with a cache.&quot;&quot;&quot;
        # Request a department from an external service.
        return await self.http_client.get_json(
            &quot;https://int.example.com/users&quot;, {&quot;user_id&quot;: user_id)
        )[&quot;department&quot;]

    async def do_something_with_users(self) -&gt; None:
        &quot;&quot;&quot;Calls the cached function and then invalidates an entry in its cache.&quot;&quot;&quot;
        
        user_id = &quot;@alice:example.com&quot;
        
        # Get the user. Since get_department_for_user is wrapped with a cache,
        # the return value for this user_id will be cached.
        department = await self.get_department_for_user(user_id)
        
        # Do something with `department`...
        
        # Let's say something has changed with our user, and the entry we have for
        # them in the cache is out of date, so we want to invalidate it.
        await self.api.invalidate_cache(self.get_department_for_user, (user_id,))
</code></pre>
<p>See the <a href="https://github.com/matrix-org/synapse/blob/release-v1.77/synapse/module_api/__init__.py#L190"><code>cached</code> docstring</a> for more details.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="spam-checker-callbacks"><a class="header" href="#spam-checker-callbacks">Spam checker callbacks</a></h1>
<p>Spam checker callbacks allow module developers to implement spam mitigation actions for
Synapse instances. Spam checker callbacks can be registered using the module API's
<code>register_spam_checker_callbacks</code> method.</p>
<h2 id="callbacks"><a class="header" href="#callbacks">Callbacks</a></h2>
<p>The available spam checker callbacks are:</p>
<h3 id="check_event_for_spam"><a class="header" href="#check_event_for_spam"><code>check_event_for_spam</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.60.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean or a string is now deprecated.</em> </p>
<pre><code class="language-python">async def check_event_for_spam(event: &quot;synapse.module_api.EventBase&quot;) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, str, bool]
</code></pre>
<p>Called when receiving an event from a client or via federation. The callback must return one of:</p>
<ul>
<li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</li>
<li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
<li>(deprecated) a non-<code>Codes</code> <code>str</code> to reject the operation and specify an error message. Note that clients
typically will not localize the error message to the user's preferred locale.</li>
<li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
<li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="user_may_join_room"><a class="header" href="#user_may_join_room"><code>user_may_join_room</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.61.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def user_may_join_room(user: str, room: str, is_invited: bool) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when a user is trying to join a room. The user is represented by their Matrix user ID (e.g.
<code>@alice:example.com</code>) and the room is represented by its Matrix ID (e.g.
<code>!room:example.com</code>). The module is also given a boolean to indicate whether the user
currently has a pending invite in the room.</p>
<p>This callback isn't called if the join is performed by a server administrator, or in the
context of a room creation.</p>
<p>The callback must return one of:</p>
<ul>
<li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</li>
<li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
<li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
<li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="user_may_invite"><a class="header" href="#user_may_invite"><code>user_may_invite</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.62.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def user_may_invite(inviter: str, invitee: str, room_id: str) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when processing an invitation. Both inviter and invitee are
represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
<p>The callback must return one of:</p>
<ul>
<li>
<p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</p>
</li>
<li>
<p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
</li>
<li>
<p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
</li>
<li>
<p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="user_may_send_3pid_invite"><a class="header" href="#user_may_send_3pid_invite"><code>user_may_send_3pid_invite</code></a></h3>
<p><em>First introduced in Synapse v1.45.0</em></p>
<p><em>Changed in Synapse v1.62.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def user_may_send_3pid_invite(
    inviter: str,
    medium: str,
    address: str,
    room_id: str,
) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when processing an invitation using a third-party identifier (also called a 3PID,
e.g. an email address or a phone number). </p>
<p>The inviter is represented by their Matrix user ID (e.g. <code>@alice:example.com</code>), and the
invitee is represented by its medium (e.g. &quot;email&quot;) and its address
(e.g. <code>alice@example.com</code>). See <a href="https://matrix.org/docs/spec/appendices#pid-types">the Matrix specification</a>
for more information regarding third-party identifiers.</p>
<p>For example, a call to this callback to send an invitation to the email address
<code>alice@example.com</code> would look like this:</p>
<pre><code class="language-python">await user_may_send_3pid_invite(
    &quot;@bob:example.com&quot;,  # The inviter's user ID
    &quot;email&quot;,  # The medium of the 3PID to invite
    &quot;alice@example.com&quot;,  # The address of the 3PID to invite
    &quot;!some_room:example.com&quot;,  # The ID of the room to send the invite into
)
</code></pre>
<p><strong>Note</strong>: If the third-party identifier is already associated with a matrix user ID,
<a href="modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a> will be used instead.</p>
<p>The callback must return one of:</p>
<ul>
<li>
<p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</p>
</li>
<li>
<p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
</li>
<li>
<p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
</li>
<li>
<p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="user_may_create_room"><a class="header" href="#user_may_create_room"><code>user_may_create_room</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.62.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def user_may_create_room(user_id: str) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when processing a room creation request.</p>
<p>The callback must return one of:</p>
<ul>
<li>
<p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</p>
</li>
<li>
<p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
</li>
<li>
<p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
</li>
<li>
<p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="user_may_create_room_alias"><a class="header" href="#user_may_create_room_alias"><code>user_may_create_room_alias</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.62.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def user_may_create_room_alias(user_id: str, room_alias: &quot;synapse.module_api.RoomAlias&quot;) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when trying to associate an alias with an existing room.</p>
<p>The callback must return one of:</p>
<ul>
<li>
<p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</p>
</li>
<li>
<p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
</li>
<li>
<p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
</li>
<li>
<p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="user_may_publish_room"><a class="header" href="#user_may_publish_room"><code>user_may_publish_room</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.62.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def user_may_publish_room(user_id: str, room_id: str) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when trying to publish a room to the homeserver's public rooms directory.</p>
<p>The callback must return one of:</p>
<ul>
<li>
<p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</p>
</li>
<li>
<p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
</li>
<li>
<p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
</li>
<li>
<p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="check_username_for_spam"><a class="header" href="#check_username_for_spam"><code>check_username_for_spam</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<pre><code class="language-python">async def check_username_for_spam(user_profile: synapse.module_api.UserProfile) -&gt; bool
</code></pre>
<p>Called when computing search results in the user directory. The module must return a
<code>bool</code> indicating whether the given user should be excluded from user directory 
searches. Return <code>True</code> to indicate that the user is spammy and exclude them from 
search results; otherwise return <code>False</code>.</p>
<p>The profile is represented as a dictionary with the following keys:</p>
<ul>
<li><code>user_id: str</code>. The Matrix ID for this user.</li>
<li><code>display_name: Optional[str]</code>. The user's display name, or <code>None</code> if this user
has not set a display name.</li>
<li><code>avatar_url: Optional[str]</code>. The <code>mxc://</code> URL to the user's avatar, or <code>None</code>
if this user has not set an avatar.</li>
</ul>
<p>The module is given a copy of the original dictionary, so modifying it from within the
module cannot modify a user's profile when included in user directory search results.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="check_registration_for_spam"><a class="header" href="#check_registration_for_spam"><code>check_registration_for_spam</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<pre><code class="language-python">async def check_registration_for_spam(
    email_threepid: Optional[dict],
    username: Optional[str],
    request_info: Collection[Tuple[str, str]],
    auth_provider_id: Optional[str] = None,
) -&gt; &quot;synapse.spam_checker_api.RegistrationBehaviour&quot;
</code></pre>
<p>Called when registering a new user. The module must return a <code>RegistrationBehaviour</code>
indicating whether the registration can go through or must be denied, or whether the user
may be allowed to register but will be shadow banned.</p>
<p>The arguments passed to this callback are:</p>
<ul>
<li><code>email_threepid</code>: The email address used for registering, if any.</li>
<li><code>username</code>: The username the user would like to register. Can be <code>None</code>, meaning that
Synapse will generate one later.</li>
<li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
second item is an IP address. These user agents and IP addresses are the ones that were
used during the registration process.</li>
<li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>RegistrationBehaviour.ALLOW</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>RegistrationBehaviour.ALLOW</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="check_media_file_for_spam"><a class="header" href="#check_media_file_for_spam"><code>check_media_file_for_spam</code></a></h3>
<p><em>First introduced in Synapse v1.37.0</em></p>
<p><em>Changed in Synapse v1.62.0: <code>synapse.module_api.NOT_SPAM</code> and <code>synapse.module_api.errors.Codes</code> can be returned by this callback. Returning a boolean is now deprecated.</em> </p>
<pre><code class="language-python">async def check_media_file_for_spam(
    file_wrapper: &quot;synapse.media.media_storage.ReadableFileWrapper&quot;,
    file_info: &quot;synapse.media._base.FileInfo&quot;,
) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
</code></pre>
<p>Called when storing a local or remote file.</p>
<p>The callback must return one of:</p>
<ul>
<li>
<p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still 
decide to reject it.</p>
</li>
<li>
<p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
</li>
<li>
<p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
</li>
<li>
<p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<h3 id="should_drop_federated_event"><a class="header" href="#should_drop_federated_event"><code>should_drop_federated_event</code></a></h3>
<p><em>First introduced in Synapse v1.60.0</em></p>
<pre><code class="language-python">async def should_drop_federated_event(event: &quot;synapse.events.EventBase&quot;) -&gt; bool
</code></pre>
<p>Called when checking whether a remote server can federate an event with us. <strong>Returning
<code>True</code> from this function will silently drop a federated event and split-brain our view
of a room's DAG, and thus you shouldn't use this callback unless you know what you are
doing.</strong></p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="check_login_for_spam"><a class="header" href="#check_login_for_spam"><code>check_login_for_spam</code></a></h3>
<p><em>First introduced in Synapse v1.87.0</em></p>
<pre><code class="language-python">async def check_login_for_spam(
    user_id: str,
    device_id: Optional[str],
    initial_display_name: Optional[str],
    request_info: Collection[Tuple[Optional[str], str]],
    auth_provider_id: Optional[str] = None,
) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;]
</code></pre>
<p>Called when a user logs in.</p>
<p>The arguments passed to this callback are:</p>
<ul>
<li><code>user_id</code>: The user ID the user is logging in with</li>
<li><code>device_id</code>: The device ID the user is re-logging into.</li>
<li><code>initial_display_name</code>: The device display name, if any.</li>
<li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
second item is an IP address. These user agents and IP addresses are the ones that were
used during the login process.</li>
<li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
</ul>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
be used. If this happens, Synapse will not call any of the subsequent implementations of
this callback.</p>
<p><em>Note:</em> This will not be called when a user registers.</p>
<h2 id="example"><a class="header" href="#example">Example</a></h2>
<p>The example below is a module that implements the spam checker callback
<code>check_event_for_spam</code> to deny any message sent by users whose Matrix user IDs are
mentioned in a configured list, and registers a web resource to the path
<code>/_synapse/client/list_spam_checker/is_evil</code> that returns a JSON object indicating
whether the provided user appears in that list.</p>
<pre><code class="language-python">import json
from typing import Union

from twisted.web.resource import Resource
from twisted.web.server import Request

from synapse.module_api import ModuleApi


class IsUserEvilResource(Resource):
    def __init__(self, config):
        super(IsUserEvilResource, self).__init__()
        self.evil_users = config.get(&quot;evil_users&quot;) or []

    def render_GET(self, request: Request):
        user = request.args.get(b&quot;user&quot;)[0].decode()
        request.setHeader(b&quot;Content-Type&quot;, b&quot;application/json&quot;)
        return json.dumps({&quot;evil&quot;: user in self.evil_users}).encode()


class ListSpamChecker:
    def __init__(self, config: dict, api: ModuleApi):
        self.api = api
        self.evil_users = config.get(&quot;evil_users&quot;) or []

        self.api.register_spam_checker_callbacks(
            check_event_for_spam=self.check_event_for_spam,
        )

        self.api.register_web_resource(
            path=&quot;/_synapse/client/list_spam_checker/is_evil&quot;,
            resource=IsUserEvilResource(config),
        )

    async def check_event_for_spam(self, event: &quot;synapse.events.EventBase&quot;) -&gt; Union[Literal[&quot;NOT_SPAM&quot;], Codes]:
        if event.sender in self.evil_users:
          return Codes.FORBIDDEN
        else:
          return synapse.module_api.NOT_SPAM
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="third-party-rules-callbacks"><a class="header" href="#third-party-rules-callbacks">Third party rules callbacks</a></h1>
<p>Third party rules callbacks allow module developers to add extra checks to verify the
validity of incoming events. Third party event rules callbacks can be registered using
the module API's <code>register_third_party_rules_callbacks</code> method.</p>
<h2 id="callbacks-1"><a class="header" href="#callbacks-1">Callbacks</a></h2>
<p>The available third party rules callbacks are:</p>
<h3 id="check_event_allowed"><a class="header" href="#check_event_allowed"><code>check_event_allowed</code></a></h3>
<p><em>First introduced in Synapse v1.39.0</em></p>
<pre><code class="language-python">async def check_event_allowed(
    event: &quot;synapse.events.EventBase&quot;,
    state_events: &quot;synapse.types.StateMap&quot;,
) -&gt; Tuple[bool, Optional[dict]]
</code></pre>
<p><strong><span style="color:red">
This callback is very experimental and can and will break without notice. Module developers
are encouraged to implement <code>check_event_for_spam</code> from the spam checker category instead.
</span></strong></p>
<p>Called when processing any incoming event, with the event and a <code>StateMap</code>
representing the current state of the room the event is being sent into. A <code>StateMap</code> is
a dictionary that maps tuples containing an event type and a state key to the
corresponding state event. For example retrieving the room's <code>m.room.create</code> event from
the <code>state_events</code> argument would look like this: <code>state_events.get((&quot;m.room.create&quot;, &quot;&quot;))</code>.
The module must return a boolean indicating whether the event can be allowed.</p>
<p>Note that this callback function processes incoming events coming via federation
traffic (on top of client traffic). This means denying an event might cause the local
copy of the room's history to diverge from that of remote servers. This may cause
federation issues in the room. It is strongly recommended to only deny events using this
callback function if the sender is a local user, or in a private federation in which all
servers are using the same module, with the same configuration.</p>
<p>If the boolean returned by the module is <code>True</code>, it may also tell Synapse to replace the
event with new data by returning the new event's data as a dictionary. In order to do
that, it is recommended the module calls <code>event.get_dict()</code> to get the current event as a
dictionary, and modify the returned dictionary accordingly.</p>
<p>If <code>check_event_allowed</code> raises an exception, the module is assumed to have failed.
The event will not be accepted but is not treated as explicitly rejected, either.
An HTTP request causing the module check will likely result in a 500 Internal
Server Error.</p>
<p>When the boolean returned by the module is <code>False</code>, the event is rejected.
(Module developers should not use exceptions for rejection.)</p>
<p>Note that replacing the event only works for events sent by local users, not for events
received over federation.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="on_create_room"><a class="header" href="#on_create_room"><code>on_create_room</code></a></h3>
<p><em>First introduced in Synapse v1.39.0</em></p>
<pre><code class="language-python">async def on_create_room(
    requester: &quot;synapse.types.Requester&quot;,
    request_content: dict,
    is_requester_admin: bool,
) -&gt; None
</code></pre>
<p>Called when processing a room creation request, with the <code>Requester</code> object for the user
performing the request, a dictionary representing the room creation request's JSON body
(see <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom">the spec</a>
for a list of possible parameters), and a boolean indicating whether the user performing
the request is a server admin.</p>
<p>Modules can modify the <code>request_content</code> (by e.g. adding events to its <code>initial_state</code>),
or deny the room's creation by raising a <code>module_api.errors.SynapseError</code>.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns without raising an exception, Synapse falls through to the next one. The
room creation will be forbidden as soon as one of the callbacks raises an exception. If
this happens, Synapse will not call any of the subsequent implementations of this
callback.</p>
<h3 id="check_threepid_can_be_invited"><a class="header" href="#check_threepid_can_be_invited"><code>check_threepid_can_be_invited</code></a></h3>
<p><em>First introduced in Synapse v1.39.0</em></p>
<pre><code class="language-python">async def check_threepid_can_be_invited(
    medium: str,
    address: str,
    state_events: &quot;synapse.types.StateMap&quot;,
) -&gt; bool:
</code></pre>
<p>Called when processing an invite via a third-party identifier (i.e. email or phone number).
The module must return a boolean indicating whether the invite can go through.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="check_visibility_can_be_modified"><a class="header" href="#check_visibility_can_be_modified"><code>check_visibility_can_be_modified</code></a></h3>
<p><em>First introduced in Synapse v1.39.0</em></p>
<pre><code class="language-python">async def check_visibility_can_be_modified(
    room_id: str,
    state_events: &quot;synapse.types.StateMap&quot;,
    new_visibility: str,
) -&gt; bool:
</code></pre>
<p>Called when changing the visibility of a room in the local public room directory. The
visibility is a string that's either &quot;public&quot; or &quot;private&quot;. The module must return a
boolean indicating whether the change can go through.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="on_new_event"><a class="header" href="#on_new_event"><code>on_new_event</code></a></h3>
<p><em>First introduced in Synapse v1.47.0</em></p>
<pre><code class="language-python">async def on_new_event(
    event: &quot;synapse.events.EventBase&quot;,
    state_events: &quot;synapse.types.StateMap&quot;,
) -&gt; None:
</code></pre>
<p>Called after sending an event into a room. The module is passed the event, as well
as the state of the room <em>after</em> the event. This means that if the event is a state event,
it will be included in this state.</p>
<p>Note that this callback is called when the event has already been processed and stored
into the room, which means this callback cannot be used to deny persisting the event. To
deny an incoming event, see <a href="modules/spam_checker_callbacks.html#check_event_for_spam"><code>check_event_for_spam</code></a> instead.</p>
<p>For any given event, this callback will be called on every worker process, even if that worker will not end up
acting on that event. This callback will not be called for events that are marked as rejected.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h3 id="check_can_shutdown_room"><a class="header" href="#check_can_shutdown_room"><code>check_can_shutdown_room</code></a></h3>
<p><em>First introduced in Synapse v1.55.0</em></p>
<pre><code class="language-python">async def check_can_shutdown_room(
    user_id: str, room_id: str,
) -&gt; bool:
</code></pre>
<p>Called when an admin user requests the shutdown of a room. The module must return a
boolean indicating whether the shutdown can go through. If the callback returns <code>False</code>,
the shutdown will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="check_can_deactivate_user"><a class="header" href="#check_can_deactivate_user"><code>check_can_deactivate_user</code></a></h3>
<p><em>First introduced in Synapse v1.55.0</em></p>
<pre><code class="language-python">async def check_can_deactivate_user(
    user_id: str, by_admin: bool,
) -&gt; bool:
</code></pre>
<p>Called when the deactivation of a user is requested. User deactivation can be
performed by an admin or the user themselves, so developers are encouraged to check the
requester when implementing this callback. The module must return a
boolean indicating whether the deactivation can go through. If the callback returns <code>False</code>,
the deactivation will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
<p>The module is passed two parameters, <code>user_id</code> which is the ID of the user being deactivated, and <code>by_admin</code> which is <code>True</code> if the request is made by a serve admin, and <code>False</code> otherwise.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="on_profile_update"><a class="header" href="#on_profile_update"><code>on_profile_update</code></a></h3>
<p><em>First introduced in Synapse v1.54.0</em></p>
<pre><code class="language-python">async def on_profile_update(
    user_id: str,
    new_profile: &quot;synapse.module_api.ProfileInfo&quot;,
    by_admin: bool,
    deactivation: bool,
) -&gt; None:
</code></pre>
<p>Called after updating a local user's profile. The update can be triggered either by the
user themselves or a server admin. The update can also be triggered by a user being
deactivated (in which case their display name is set to an empty string (<code>&quot;&quot;</code>) and the
avatar URL is set to <code>None</code>). The module is passed the Matrix ID of the user whose profile
has been updated, their new profile, as well as a <code>by_admin</code> boolean that is <code>True</code> if the
update was triggered by a server admin (and <code>False</code> otherwise), and a <code>deactivated</code>
boolean that is <code>True</code> if the update is a result of the user being deactivated.</p>
<p>Note that the <code>by_admin</code> boolean is also <code>True</code> if the profile change happens as a result
of the user logging in through Single Sign-On, or if a server admin updates their own
profile.</p>
<p>Per-room profile changes do not trigger this callback to be called. Synapse administrators
wishing this callback to be called on every profile change are encouraged to disable
per-room profiles globally using the <code>allow_per_room_profiles</code> configuration setting in
Synapse's configuration file.
This callback is not called when registering a user, even when setting it through the
<a href="https://matrix-org.github.io/synapse/latest/modules/password_auth_provider_callbacks.html#get_displayname_for_registration"><code>get_displayname_for_registration</code></a>
module callback.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h3 id="on_user_deactivation_status_changed"><a class="header" href="#on_user_deactivation_status_changed"><code>on_user_deactivation_status_changed</code></a></h3>
<p><em>First introduced in Synapse v1.54.0</em></p>
<pre><code class="language-python">async def on_user_deactivation_status_changed(
    user_id: str, deactivated: bool, by_admin: bool
) -&gt; None:
</code></pre>
<p>Called after deactivating a local user, or reactivating them through the admin API. The
deactivation can be triggered either by the user themselves or a server admin. The module
is passed the Matrix ID of the user whose status is changed, as well as a <code>deactivated</code>
boolean that is <code>True</code> if the user is being deactivated and <code>False</code> if they're being
reactivated, and a <code>by_admin</code> boolean that is <code>True</code> if the deactivation was triggered by
a server admin (and <code>False</code> otherwise). This latter <code>by_admin</code> boolean is always <code>True</code>
if the user is being reactivated, as this operation can only be performed through the
admin API.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h3 id="on_threepid_bind"><a class="header" href="#on_threepid_bind"><code>on_threepid_bind</code></a></h3>
<p><em>First introduced in Synapse v1.56.0</em></p>
<p><strong><span style="color:red">
This callback is deprecated in favour of the <code>on_add_user_third_party_identifier</code> callback, which
features the same functionality. The only difference is in name.
</span></strong></p>
<pre><code class="language-python">async def on_threepid_bind(user_id: str, medium: str, address: str) -&gt; None:
</code></pre>
<p>Called after creating an association between a local user and a third-party identifier
(email address, phone number). The module is given the Matrix ID of the user the
association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
third-party identifier.</p>
<p>Note that this callback is <em>not</em> called after a successful association on an <em>identity
server</em>.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h3 id="on_add_user_third_party_identifier"><a class="header" href="#on_add_user_third_party_identifier"><code>on_add_user_third_party_identifier</code></a></h3>
<p><em>First introduced in Synapse v1.79.0</em></p>
<pre><code class="language-python">async def on_add_user_third_party_identifier(user_id: str, medium: str, address: str) -&gt; None:
</code></pre>
<p>Called after successfully creating an association between a user and a third-party identifier
(email address, phone number). The module is given the Matrix ID of the user the
association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
third-party identifier (i.e. an email address).</p>
<p>Note that this callback is <em>not</em> called if a user attempts to bind their third-party identifier
to an identity server (via a call to <a href="https://spec.matrix.org/v1.5/client-server-api/#post_matrixclientv3account3pidbind"><code>POST /_matrix/client/v3/account/3pid/bind</code></a>).</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h3 id="on_remove_user_third_party_identifier"><a class="header" href="#on_remove_user_third_party_identifier"><code>on_remove_user_third_party_identifier</code></a></h3>
<p><em>First introduced in Synapse v1.79.0</em></p>
<pre><code class="language-python">async def on_remove_user_third_party_identifier(user_id: str, medium: str, address: str) -&gt; None:
</code></pre>
<p>Called after successfully removing an association between a user and a third-party identifier
(email address, phone number). The module is given the Matrix ID of the user the
association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
third-party identifier (i.e. an email address).</p>
<p>Note that this callback is <em>not</em> called if a user attempts to unbind their third-party
identifier from an identity server (via a call to <a href="https://spec.matrix.org/v1.5/client-server-api/#post_matrixclientv3account3pidunbind"><code>POST /_matrix/client/v3/account/3pid/unbind</code></a>).</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h2 id="example-1"><a class="header" href="#example-1">Example</a></h2>
<p>The example below is a module that implements the third-party rules callback
<code>check_event_allowed</code> to censor incoming messages as dictated by a third-party service.</p>
<pre><code class="language-python">from typing import Optional, Tuple

from synapse.module_api import ModuleApi

_DEFAULT_CENSOR_ENDPOINT = &quot;https://my-internal-service.local/censor-event&quot;

class EventCensorer:
    def __init__(self, config: dict, api: ModuleApi):
        self.api = api
        self._endpoint = config.get(&quot;endpoint&quot;, _DEFAULT_CENSOR_ENDPOINT)

        self.api.register_third_party_rules_callbacks(
            check_event_allowed=self.check_event_allowed,
        )

    async def check_event_allowed(
        self,
        event: &quot;synapse.events.EventBase&quot;,
        state_events: &quot;synapse.types.StateMap&quot;,
    ) -&gt; Tuple[bool, Optional[dict]]:
        event_dict = event.get_dict()
        new_event_content = await self.api.http_client.post_json_get_json(
            uri=self._endpoint, post_json=event_dict,
        )
        event_dict[&quot;content&quot;] = new_event_content
        return event_dict
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="presence-router-callbacks"><a class="header" href="#presence-router-callbacks">Presence router callbacks</a></h1>
<p>Presence router callbacks allow module developers to specify additional users (local or remote)
to receive certain presence updates from local users. Presence router callbacks can be 
registered using the module API's <code>register_presence_router_callbacks</code> method.</p>
<h2 id="callbacks-2"><a class="header" href="#callbacks-2">Callbacks</a></h2>
<p>The available presence router callbacks are:</p>
<h3 id="get_users_for_states"><a class="header" href="#get_users_for_states"><code>get_users_for_states</code></a></h3>
<p><em>First introduced in Synapse v1.42.0</em></p>
<pre><code class="language-python">async def get_users_for_states(
    state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]
</code></pre>
<p><strong>Requires</strong> <code>get_interested_users</code> to also be registered</p>
<p>Called when processing updates to the presence state of one or more users. This callback can
be used to instruct the server to forward that presence state to specific users. The module
must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the
<code>UserPresenceState</code> changes that they should be forwarded.</p>
<p>Synapse will then attempt to send the specified presence updates to each user when possible.</p>
<p>If multiple modules implement this callback, Synapse merges all the dictionaries returned
by the callbacks. If multiple callbacks return a dictionary containing the same key,
Synapse concatenates the sets associated with this key from each dictionary. </p>
<h3 id="get_interested_users"><a class="header" href="#get_interested_users"><code>get_interested_users</code></a></h3>
<p><em>First introduced in Synapse v1.42.0</em></p>
<pre><code class="language-python">async def get_interested_users(
    user_id: str
) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]
</code></pre>
<p><strong>Requires</strong> <code>get_users_for_states</code> to also be registered</p>
<p>Called when determining which users someone should be able to see the presence state of. This
callback should return complementary results to <code>get_users_for_state</code> or the presence information 
may not be properly forwarded.</p>
<p>The callback is given the Matrix user ID for a local user that is requesting presence data and
should return the Matrix user IDs of the users whose presence state they are allowed to
query. The returned users can be local or remote. </p>
<p>Alternatively the callback can return <code>synapse.module_api.PRESENCE_ALL_USERS</code>
to indicate that the user should receive updates from all known users.</p>
<p>If multiple modules implement this callback, they will be considered in order. Synapse
calls each callback one by one, and use a concatenation of all the <code>set</code>s returned by the
callbacks. If one callback returns <code>synapse.module_api.PRESENCE_ALL_USERS</code>, Synapse uses
this value instead. If this happens, Synapse does not call any of the subsequent
implementations of this callback.</p>
<h2 id="example-2"><a class="header" href="#example-2">Example</a></h2>
<p>The example below is a module that implements both presence router callbacks, and ensures
that <code>@alice:example.org</code> receives all presence updates from <code>@bob:example.com</code> and
<code>@charlie:somewhere.org</code>, regardless of whether Alice shares a room with any of them.</p>
<pre><code class="language-python">from typing import Dict, Iterable, Set, Union

from synapse.module_api import ModuleApi


class CustomPresenceRouter:
    def __init__(self, config: dict, api: ModuleApi):
        self.api = api

        self.api.register_presence_router_callbacks(
            get_users_for_states=self.get_users_for_states,
            get_interested_users=self.get_interested_users,
        )

    async def get_users_for_states(
        self,
        state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
    ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]:
        res = {}
        for update in state_updates:
            if (
                update.user_id == &quot;@bob:example.com&quot;
                or update.user_id == &quot;@charlie:somewhere.org&quot;
            ):
                res.setdefault(&quot;@alice:example.com&quot;, set()).add(update)

        return res

    async def get_interested_users(
        self,
        user_id: str,
    ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]:
        if user_id == &quot;@alice:example.com&quot;:
            return {&quot;@bob:example.com&quot;, &quot;@charlie:somewhere.org&quot;}

        return set()
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="account-validity-callbacks"><a class="header" href="#account-validity-callbacks">Account validity callbacks</a></h1>
<p>Account validity callbacks allow module developers to add extra steps to verify the
validity on an account, i.e. see if a user can be granted access to their account on the
Synapse instance. Account validity callbacks can be registered using the module API's
<code>register_account_validity_callbacks</code> method.</p>
<p>The available account validity callbacks are:</p>
<h3 id="is_user_expired"><a class="header" href="#is_user_expired"><code>is_user_expired</code></a></h3>
<p><em>First introduced in Synapse v1.39.0</em></p>
<pre><code class="language-python">async def is_user_expired(user: str) -&gt; Optional[bool]
</code></pre>
<p>Called when processing any authenticated request (except for logout requests). The module
can return a <code>bool</code> to indicate whether the user has expired and should be locked out of
their account, or <code>None</code> if the module wasn't able to figure it out. The user is
represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
<p>If the module returns <code>True</code>, the current request will be denied with the error code
<code>ORG_MATRIX_EXPIRED_ACCOUNT</code> and the HTTP status code 403. Note that this doesn't
invalidate the user's access token.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h3 id="on_user_registration"><a class="header" href="#on_user_registration"><code>on_user_registration</code></a></h3>
<p><em>First introduced in Synapse v1.39.0</em></p>
<pre><code class="language-python">async def on_user_registration(user: str) -&gt; None
</code></pre>
<p>Called after successfully registering a user, in case the module needs to perform extra
operations to keep track of them. (e.g. add them to a database table). The user is
represented by their Matrix user ID.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="password-auth-provider-callbacks"><a class="header" href="#password-auth-provider-callbacks">Password auth provider callbacks</a></h1>
<p>Password auth providers offer a way for server administrators to integrate
their Synapse installation with an external authentication system. The callbacks can be
registered by using the Module API's <code>register_password_auth_provider_callbacks</code> method.</p>
<h2 id="callbacks-3"><a class="header" href="#callbacks-3">Callbacks</a></h2>
<h3 id="auth_checkers"><a class="header" href="#auth_checkers"><code>auth_checkers</code></a></h3>
<p><em>First introduced in Synapse v1.46.0</em></p>
<pre><code class="language-python">auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
</code></pre>
<p>A dict mapping from tuples of a login type identifier (such as <code>m.login.password</code>) and a
tuple of field names (such as <code>(&quot;password&quot;, &quot;secret_thing&quot;)</code>) to authentication checking
callbacks, which should be of the following form:</p>
<pre><code class="language-python">async def check_auth(
    user: str,
    login_type: str,
    login_dict: &quot;synapse.module_api.JsonDict&quot;,
) -&gt; Optional[
    Tuple[
        str, 
        Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
    ]
]
</code></pre>
<p>The login type and field names should be provided by the user in the
request to the <code>/login</code> API. <a href="https://matrix.org/docs/spec/client_server/latest#authentication-types">The Matrix specification</a>
defines some types, however user defined ones are also allowed.</p>
<p>The callback is passed the <code>user</code> field provided by the client (which might not be in
<code>@username:server</code> form), the login type, and a dictionary of login secrets passed by
the client.</p>
<p>If the authentication is successful, the module must return the user's Matrix ID (e.g. 
<code>@alice:example.com</code>) and optionally a callback to be called with the response to the
<code>/login</code> request. If the module doesn't wish to return a callback, it must return <code>None</code>
instead.</p>
<p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
<p>Note that the user is not automatically registered, the <code>register_user(..)</code> method of
the <a href="modules/writing_a_module.html">module API</a> can be used to lazily create users.</p>
<p>If multiple modules register an auth checker for the same login type but with different
fields, Synapse will refuse to start.</p>
<p>If multiple modules register an auth checker for the same login type with the same fields,
then the callbacks will be executed in order, until one returns a Matrix User ID (and
optionally a callback). In that case, the return value of that callback will be accepted
and subsequent callbacks will not be fired. If every callback returns <code>None</code>, then the
authentication fails.</p>
<h3 id="check_3pid_auth"><a class="header" href="#check_3pid_auth"><code>check_3pid_auth</code></a></h3>
<p><em>First introduced in Synapse v1.46.0</em></p>
<pre><code class="language-python">async def check_3pid_auth(
    medium: str, 
    address: str,
    password: str,
) -&gt; Optional[
    Tuple[
        str, 
        Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
    ]
]
</code></pre>
<p>Called when a user attempts to register or log in with a third party identifier,
such as email. It is passed the medium (eg. <code>email</code>), an address (eg. <code>jdoe@example.com</code>)
and the user's password.</p>
<p>If the authentication is successful, the module must return the user's Matrix ID (e.g. 
<code>@alice:example.com</code>) and optionally a callback to be called with the response to the <code>/login</code> request.
If the module doesn't wish to return a callback, it must return None instead.</p>
<p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
the authentication is denied.</p>
<h3 id="on_logged_out"><a class="header" href="#on_logged_out"><code>on_logged_out</code></a></h3>
<p><em>First introduced in Synapse v1.46.0</em></p>
<pre><code class="language-python">async def on_logged_out(
    user_id: str,
    device_id: Optional[str],
    access_token: str
) -&gt; None
</code></pre>
<p>Called during a logout request for a user. It is passed the qualified user ID, the ID of the
deactivated device (if any: access tokens are occasionally created without an associated
device ID), and the (now deactivated) access token.</p>
<p>Deleting the related pushers is done after calling <code>on_logged_out</code>, so you can rely on them
to still be present.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h3 id="get_username_for_registration"><a class="header" href="#get_username_for_registration"><code>get_username_for_registration</code></a></h3>
<p><em>First introduced in Synapse v1.52.0</em></p>
<pre><code class="language-python">async def get_username_for_registration(
    uia_results: Dict[str, Any],
    params: Dict[str, Any],
) -&gt; Optional[str]
</code></pre>
<p>Called when registering a new user. The module can return a username to set for the user
being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
username for this user. If a username is returned, it will be used as the local part of a
user's full Matrix ID (e.g. it's <code>alice</code> in <code>@alice:example.com</code>).</p>
<p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
has been completed by the user. It is not called when registering a user via SSO. It is
passed two dictionaries, which include the information that the user has provided during
the registration process.</p>
<p>The first dictionary contains the results of the <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
flow followed by the user. Its keys are the identifiers of every step involved in the flow,
associated with either a boolean value indicating whether the step was correctly completed,
or additional information (e.g. email address, phone number...). A list of most existing
identifiers can be found in the <a href="https://spec.matrix.org/v1.1/client-server-api/#authentication-types">Matrix specification</a>.
Here's an example featuring all currently supported keys:</p>
<pre><code class="language-python">{
    &quot;m.login.dummy&quot;: True,  # Dummy authentication
    &quot;m.login.terms&quot;: True,  # User has accepted the terms of service for the homeserver
    &quot;m.login.recaptcha&quot;: True,  # User has completed the recaptcha challenge
    &quot;m.login.email.identity&quot;: {  # User has provided and verified an email address
        &quot;medium&quot;: &quot;email&quot;,
        &quot;address&quot;: &quot;alice@example.com&quot;,
        &quot;validated_at&quot;: 1642701357084,
    },
    &quot;m.login.msisdn&quot;: {  # User has provided and verified a phone number
        &quot;medium&quot;: &quot;msisdn&quot;,
        &quot;address&quot;: &quot;33123456789&quot;,
        &quot;validated_at&quot;: 1642701357084,
    },
    &quot;m.login.registration_token&quot;: &quot;sometoken&quot;,  # User has registered through a registration token
}
</code></pre>
<p>The second dictionary contains the parameters provided by the user's client in the request
to <code>/_matrix/client/v3/register</code>. See the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register">Matrix specification</a>
for a complete list of these parameters.</p>
<p>If the module cannot, or does not wish to, generate a username for this user, it must
return <code>None</code>.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
the username provided by the user is used, if any (otherwise one is automatically
generated).</p>
<h3 id="get_displayname_for_registration"><a class="header" href="#get_displayname_for_registration"><code>get_displayname_for_registration</code></a></h3>
<p><em>First introduced in Synapse v1.54.0</em></p>
<pre><code class="language-python">async def get_displayname_for_registration(
    uia_results: Dict[str, Any],
    params: Dict[str, Any],
) -&gt; Optional[str]
</code></pre>
<p>Called when registering a new user. The module can return a display name to set for the
user being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
display name for this user.</p>
<p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
has been completed by the user. It is not called when registering a user via SSO. It is
passed two dictionaries, which include the information that the user has provided during
the registration process. These dictionaries are identical to the ones passed to
<a href="modules/password_auth_provider_callbacks.html#get_username_for_registration"><code>get_username_for_registration</code></a>, so refer to the
documentation of this callback for more information about them.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
the username will be used (e.g. <code>alice</code> if the user being registered is <code>@alice:example.com</code>).</p>
<h2 id="is_3pid_allowed"><a class="header" href="#is_3pid_allowed"><code>is_3pid_allowed</code></a></h2>
<p><em>First introduced in Synapse v1.53.0</em></p>
<pre><code class="language-python">async def is_3pid_allowed(self, medium: str, address: str, registration: bool) -&gt; bool
</code></pre>
<p>Called when attempting to bind a third-party identifier (i.e. an email address or a phone
number). The module is given the medium of the third-party identifier (which is <code>email</code> if
the identifier is an email address, or <code>msisdn</code> if the identifier is a phone number) and
its address, as well as a boolean indicating whether the attempt to bind is happening as
part of registering a new user. The module must return a boolean indicating whether the
identifier can be allowed to be bound to an account on the local homeserver.</p>
<p>If multiple modules implement this callback, they will be considered in order. If a
callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
any of the subsequent implementations of this callback.</p>
<h2 id="example-3"><a class="header" href="#example-3">Example</a></h2>
<p>The example module below implements authentication checkers for two different login types: </p>
<ul>
<li><code>my.login.type</code> 
<ul>
<li>Expects a <code>my_field</code> field to be sent to <code>/login</code></li>
<li>Is checked by the method: <code>self.check_my_login</code></li>
</ul>
</li>
<li><code>m.login.password</code> (defined in <a href="https://matrix.org/docs/spec/client_server/latest#password-based">the spec</a>)
<ul>
<li>Expects a <code>password</code> field to be sent to <code>/login</code></li>
<li>Is checked by the method: <code>self.check_pass</code></li>
</ul>
</li>
</ul>
<pre><code class="language-python">from typing import Awaitable, Callable, Optional, Tuple

import synapse
from synapse import module_api


class MyAuthProvider:
    def __init__(self, config: dict, api: module_api):

        self.api = api

        self.credentials = {
            &quot;bob&quot;: &quot;building&quot;,
            &quot;@scoop:matrix.org&quot;: &quot;digging&quot;,
        }

        api.register_password_auth_provider_callbacks(
            auth_checkers={
                (&quot;my.login_type&quot;, (&quot;my_field&quot;,)): self.check_my_login,
                (&quot;m.login.password&quot;, (&quot;password&quot;,)): self.check_pass,
            },
        )

    async def check_my_login(
        self,
        username: str,
        login_type: str,
        login_dict: &quot;synapse.module_api.JsonDict&quot;,
    ) -&gt; Optional[
        Tuple[
            str,
            Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
        ]
    ]:
        if login_type != &quot;my.login_type&quot;:
            return None

        if self.credentials.get(username) == login_dict.get(&quot;my_field&quot;):
            return (self.api.get_qualified_user_id(username), None)

    async def check_pass(
        self,
        username: str,
        login_type: str,
        login_dict: &quot;synapse.module_api.JsonDict&quot;,
    ) -&gt; Optional[
        Tuple[
            str,
            Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
        ]
    ]:
        if login_type != &quot;m.login.password&quot;:
            return None

        if self.credentials.get(username) == login_dict.get(&quot;password&quot;):
            return (self.api.get_qualified_user_id(username), None)
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="background-update-controller-callbacks"><a class="header" href="#background-update-controller-callbacks">Background update controller callbacks</a></h1>
<p>Background update controller callbacks allow module developers to control (e.g. rate-limit)
how database background updates are run. A database background update is an operation
Synapse runs on its database in the background after it starts. It's usually used to run
database operations that would take too long if they were run at the same time as schema
updates (which are run on startup) and delay Synapse's startup too much: populating a
table with a big amount of data, adding an index on a big table, deleting superfluous data,
etc.</p>
<p>Background update controller callbacks can be registered using the module API's
<code>register_background_update_controller_callbacks</code> method. Only the first module (in order
of appearance in Synapse's configuration file) calling this method can register background
update controller callbacks, subsequent calls are ignored.</p>
<p>The available background update controller callbacks are:</p>
<h3 id="on_update"><a class="header" href="#on_update"><code>on_update</code></a></h3>
<p><em>First introduced in Synapse v1.49.0</em></p>
<pre><code class="language-python">def on_update(update_name: str, database_name: str, one_shot: bool) -&gt; AsyncContextManager[int]
</code></pre>
<p>Called when about to do an iteration of a background update. The module is given the name
of the update, the name of the database, and a flag to indicate whether the background
update will happen in one go and may take a long time (e.g. creating indices). If this last
argument is set to <code>False</code>, the update will be run in batches.</p>
<p>The module must return an async context manager. It will be entered before Synapse runs a 
background update; this should return the desired duration of the iteration, in
milliseconds.</p>
<p>The context manager will be exited when the iteration completes. Note that the duration
returned by the context manager is a target, and an iteration may take substantially longer
or shorter. If the <code>one_shot</code> flag is set to <code>True</code>, the duration returned is ignored.</p>
<p><strong>Note</strong>: Unlike most module callbacks in Synapse, this one is <em>synchronous</em>. This is
because asynchronous operations are expected to be run by the async context manager.</p>
<p>This callback is required when registering any other background update controller callback.</p>
<h3 id="default_batch_size"><a class="header" href="#default_batch_size"><code>default_batch_size</code></a></h3>
<p><em>First introduced in Synapse v1.49.0</em></p>
<pre><code class="language-python">async def default_batch_size(update_name: str, database_name: str) -&gt; int
</code></pre>
<p>Called before the first iteration of a background update, with the name of the update and
of the database. The module must return the number of elements to process in this first
iteration.</p>
<p>If this callback is not defined, Synapse will use a default value of 100.</p>
<h3 id="min_batch_size"><a class="header" href="#min_batch_size"><code>min_batch_size</code></a></h3>
<p><em>First introduced in Synapse v1.49.0</em></p>
<pre><code class="language-python">async def min_batch_size(update_name: str, database_name: str) -&gt; int
</code></pre>
<p>Called before running a new batch for a background update, with the name of the update and
of the database. The module must return an integer representing the minimum number of
elements to process in this iteration. This number must be at least 1, and is used to
ensure that progress is always made.</p>
<p>If this callback is not defined, Synapse will use a default value of 100.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="account-data-callbacks"><a class="header" href="#account-data-callbacks">Account data callbacks</a></h1>
<p>Account data callbacks allow module developers to react to changes of the account data
of local users. Account data callbacks can be registered using the module API's
<code>register_account_data_callbacks</code> method.</p>
<h2 id="callbacks-4"><a class="header" href="#callbacks-4">Callbacks</a></h2>
<p>The available account data callbacks are:</p>
<h3 id="on_account_data_updated"><a class="header" href="#on_account_data_updated"><code>on_account_data_updated</code></a></h3>
<p><em>First introduced in Synapse v1.57.0</em></p>
<pre><code class="language-python">async def on_account_data_updated(
    user_id: str,
    room_id: Optional[str],
    account_data_type: str,
    content: &quot;synapse.module_api.JsonDict&quot;,
) -&gt; None:
</code></pre>
<p>Called after user's account data has been updated. The module is given the
Matrix ID of the user whose account data is changing, the room ID the data is associated
with, the type associated with the change, as well as the new content. If the account
data is not associated with a specific room, then the room ID is <code>None</code>.</p>
<p>This callback is triggered when new account data is added or when the data associated with
a given type (and optionally room) changes. This includes deletion, since in Matrix,
deleting account data consists of replacing the data associated with a given type
(and optionally room) with an empty dictionary (<code>{}</code>).</p>
<p>Note that this doesn't trigger when changing the tags associated with a room, as these are
processed separately by Synapse.</p>
<p>If multiple modules implement this callback, Synapse runs them all in order.</p>
<h2 id="example-4"><a class="header" href="#example-4">Example</a></h2>
<p>The example below is a module that implements the <code>on_account_data_updated</code> callback, and
sends an event to an audit room when a user changes their account data.</p>
<pre><code class="language-python">import json
import attr
from typing import Any, Dict, Optional

from synapse.module_api import JsonDict, ModuleApi
from synapse.module_api.errors import ConfigError


@attr.s(auto_attribs=True)
class CustomAccountDataConfig:
    audit_room: str
    sender: str


class CustomAccountDataModule:
    def __init__(self, config: CustomAccountDataConfig, api: ModuleApi):
        self.api = api
        self.config = config

        self.api.register_account_data_callbacks(
            on_account_data_updated=self.log_new_account_data,
        )

    @staticmethod
    def parse_config(config: Dict[str, Any]) -&gt; CustomAccountDataConfig:
        def check_in_config(param: str):
            if param not in config:
                raise ConfigError(f&quot;'{param}' is required&quot;)

        check_in_config(&quot;audit_room&quot;)
        check_in_config(&quot;sender&quot;)

        return CustomAccountDataConfig(
            audit_room=config[&quot;audit_room&quot;],
            sender=config[&quot;sender&quot;],
        )

    async def log_new_account_data(
        self,
        user_id: str,
        room_id: Optional[str],
        account_data_type: str,
        content: JsonDict,
    ) -&gt; None:
        content_raw = json.dumps(content)
        msg_content = f&quot;{user_id} has changed their account data for type {account_data_type} to: {content_raw}&quot;

        if room_id is not None:
            msg_content += f&quot; (in room {room_id})&quot;

        await self.api.create_and_send_event_into_room(
            {
                &quot;room_id&quot;: self.config.audit_room,
                &quot;sender&quot;: self.config.sender,
                &quot;type&quot;: &quot;m.room.message&quot;,
                &quot;content&quot;: {
                    &quot;msgtype&quot;: &quot;m.text&quot;,
                    &quot;body&quot;: msg_content
                }
            }
        )
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="porting-an-existing-module-that-uses-the-old-interface"><a class="header" href="#porting-an-existing-module-that-uses-the-old-interface">Porting an existing module that uses the old interface</a></h1>
<p>In order to port a module that uses Synapse's old module interface, its author needs to:</p>
<ul>
<li>ensure the module's callbacks are all asynchronous.</li>
<li>register their callbacks using one or more of the <code>register_[...]_callbacks</code> methods
from the <code>ModuleApi</code> class in the module's <code>__init__</code> method (see <a href="modules/writing_a_module.html#registering-a-callback">this section</a>
for more info).</li>
</ul>
<p>Additionally, if the module is packaged with an additional web resource, the module
should register this resource in its <code>__init__</code> method using the <code>register_web_resource</code>
method from the <code>ModuleApi</code> class (see <a href="modules/writing_a_module.html#registering-a-web-resource">this section</a> for
more info).</p>
<p>There is no longer a <code>get_db_schema_files</code> callback provided for password auth provider modules. Any
changes to the database should now be made by the module using the module API class.</p>
<p>The module's author should also update any example in the module's configuration to only
use the new <code>modules</code> section in Synapse's configuration file (see <a href="modules/index.html#using-modules">this section</a>
for more info).</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="scaling-synapse-via-workers"><a class="header" href="#scaling-synapse-via-workers">Scaling synapse via workers</a></h1>
<p>For small instances it is recommended to run Synapse in the default monolith mode.
For larger instances where performance is a concern it can be helpful to split
out functionality into multiple separate python processes. These processes are
called 'workers', and are (eventually) intended to scale horizontally
independently.</p>
<p>Synapse's worker support is under active development and subject to change as
we attempt to rapidly scale ever larger Synapse instances. However we are
documenting it here to help admins needing a highly scalable Synapse instance
similar to the one running <code>matrix.org</code>.</p>
<p>All processes continue to share the same database instance, and as such,
workers only work with PostgreSQL-based Synapse deployments. SQLite should only
be used for demo purposes and any admin considering workers should already be
running PostgreSQL.</p>
<p>See also <a href="https://matrix.org/blog/2020/11/03/how-we-fixed-synapses-scalability">Matrix.org blog post</a>
for a higher level overview.</p>
<h2 id="main-processworker-communication"><a class="header" href="#main-processworker-communication">Main process/worker communication</a></h2>
<p>The processes communicate with each other via a Synapse-specific protocol called
'replication' (analogous to MySQL- or Postgres-style database replication) which
feeds streams of newly written data between processes so they can be kept in
sync with the database state.</p>
<p>When configured to do so, Synapse uses a
<a href="https://redis.io/docs/manual/pubsub/">Redis pub/sub channel</a> to send the replication
stream between all configured Synapse processes. Additionally, processes may
make HTTP requests to each other, primarily for operations which need to wait
for a reply ─ such as sending an event.</p>
<p>All the workers and the main process connect to Redis, which relays replication
commands between processes.</p>
<p>If Redis support is enabled Synapse will use it as a shared cache, as well as a
pub/sub mechanism.</p>
<p>See the <a href="workers.html#architectural-diagram">Architectural diagram</a> section at the end for
a visualisation of what this looks like.</p>
<h2 id="setting-up-workers"><a class="header" href="#setting-up-workers">Setting up workers</a></h2>
<p>A Redis server is required to manage the communication between the processes.
The Redis server should be installed following the normal procedure for your
distribution (e.g. <code>apt install redis-server</code> on Debian). It is safe to use an
existing Redis deployment if you have one.</p>
<p>Once installed, check that Redis is running and accessible from the host running
Synapse, for example by executing <code>echo PING | nc -q1 localhost 6379</code> and seeing
a response of <code>+PONG</code>.</p>
<p>The appropriate dependencies must also be installed for Synapse. If using a
virtualenv, these can be installed with:</p>
<pre><code class="language-sh">pip install &quot;matrix-synapse[redis]&quot;
</code></pre>
<p>Note that these dependencies are included when synapse is installed with <code>pip install matrix-synapse[all]</code>. They are also included in the debian packages from
<code>matrix.org</code> and in the docker images at
https://hub.docker.com/r/matrixdotorg/synapse/.</p>
<p>To make effective use of the workers, you will need to configure an HTTP
reverse-proxy such as nginx or haproxy, which will direct incoming requests to
the correct worker, or to the main synapse instance. See
<a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a reverse
proxy.</p>
<p>When using workers, each worker process has its own configuration file which
contains settings specific to that worker, such as the HTTP listener that it
provides (if any), logging configuration, etc.</p>
<p>Normally, the worker processes are configured to read from a shared
configuration file as well as the worker-specific configuration files. This
makes it easier to keep common configuration settings synchronised across all
the processes.</p>
<p>The main process is somewhat special in this respect: it does not normally
need its own configuration file and can take all of its configuration from the
shared configuration file.</p>
<h3 id="shared-configuration"><a class="header" href="#shared-configuration">Shared configuration</a></h3>
<p>Normally, only a few changes are needed to make an existing configuration
file suitable for use with workers:</p>
<ul>
<li>First, you need to enable an
<a href="usage/configuration/config_documentation.html#listeners">&quot;HTTP replication listener&quot;</a>
for the main process</li>
<li>Secondly, you need to enable
<a href="usage/configuration/config_documentation.html#redis">redis-based replication</a></li>
<li>You will need to add an <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a> 
with the <code>main</code> process defined, as well as the relevant connection information from
it's HTTP <code>replication</code> listener (defined in step 1 above).
<ul>
<li>Note that the <code>host</code> defined is the address the worker needs to look for the <code>main</code>
process at, not necessarily the same address that is bound to.</li>
<li>If you are using Unix sockets for the <code>replication</code> resource, make sure to
use a <code>path</code> to the socket file instead of a <code>port</code>.</li>
</ul>
</li>
<li>Optionally, a <a href="usage/configuration/config_documentation.html#worker_replication_secret">shared secret</a>
can be used to authenticate HTTP traffic between workers. For example:</li>
</ul>
<pre><code class="language-yaml"># extend the existing `listeners` section. This defines the ports that the
# main process will listen on.
listeners:
  # The HTTP replication port
  - port: 9093
    bind_address: '127.0.0.1'
    type: http
    resources:
     - names: [replication]

# Add a random shared secret to authenticate traffic.
worker_replication_secret: &quot;&quot;

redis:
    enabled: true

instance_map:
    main:
        host: 'localhost'
        port: 9093
</code></pre>
<p>See the <a href="usage/configuration/config_documentation.html">configuration manual</a>
for the full documentation of each option.</p>
<p>Under <strong>no circumstances</strong> should the replication listener be exposed to the
public internet; replication traffic is:</p>
<ul>
<li>always unencrypted</li>
<li>unauthenticated, unless <a href="usage/configuration/config_documentation.html#worker_replication_secret"><code>worker_replication_secret</code></a>
is configured</li>
</ul>
<h3 id="worker-configuration"><a class="header" href="#worker-configuration">Worker configuration</a></h3>
<p>In the config file for each worker, you must specify:</p>
<ul>
<li>The type of worker (<a href="usage/configuration/config_documentation.html#worker_app"><code>worker_app</code></a>).
The currently available worker applications are listed <a href="workers.html#available-worker-applications">below</a>.</li>
<li>A unique name for the worker (<a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>).</li>
<li>If handling HTTP requests, a <a href="usage/configuration/config_documentation.html#worker_listeners"><code>worker_listeners</code></a> option
with an <code>http</code> listener.</li>
<li><strong>Synapse 1.72 and older:</strong> if handling the <code>^/_matrix/client/v3/keys/upload</code> endpoint, the HTTP URI for
the main process (<code>worker_main_http_uri</code>). This config option is no longer required and is ignored when running Synapse 1.73 and newer.</li>
</ul>
<p>For example:</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
worker_name: generic_worker1

worker_listeners:
  - type: http
    port: 8083
    x_forwarded: true
    resources:
      - names: [client, federation]

worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
</code></pre>
<p>...is a full configuration for a generic worker instance, which will expose a
plain HTTP endpoint on port 8083 separately serving various endpoints, e.g.
<code>/sync</code>, which are listed below.</p>
<p>Obviously you should configure your reverse-proxy to route the relevant
endpoints to the worker (<code>localhost:8083</code> in the above example).</p>
<h3 id="running-synapse-with-workers"><a class="header" href="#running-synapse-with-workers">Running Synapse with workers</a></h3>
<p>Finally, you need to start your worker processes. This can be done with either
<code>synctl</code> or your distribution's preferred service manager such as <code>systemd</code>. We
recommend the use of <code>systemd</code> where available: for information on setting up
<code>systemd</code> to start synapse workers, see
<a href="systemd-with-workers/">Systemd with Workers</a>. To use <code>synctl</code>, see
<a href="synctl_workers.html">Using synctl with Workers</a>.</p>
<h2 id="start-synapse-with-poetry"><a class="header" href="#start-synapse-with-poetry">Start Synapse with Poetry</a></h2>
<p>The following applies to Synapse installations that have been installed from source using <code>poetry</code>.</p>
<p>You can start the main Synapse process with Poetry by running the following command:</p>
<pre><code class="language-console">poetry run synapse_homeserver --config-file [your homeserver.yaml]
</code></pre>
<p>For worker setups, you can run the following command</p>
<pre><code class="language-console">poetry run synapse_worker --config-file [your homeserver.yaml] --config-file [your worker.yaml]
</code></pre>
<h2 id="available-worker-applications"><a class="header" href="#available-worker-applications">Available worker applications</a></h2>
<h3 id="synapseappgeneric_worker"><a class="header" href="#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a></h3>
<p>This worker can handle API requests matching the following regular expressions.
These endpoints can be routed to any worker. If a worker is set up to handle a
stream then, for maximum efficiency, additional endpoints should be routed to that
worker: refer to the <a href="workers.html#stream-writers">stream writers</a> section below for further
information.</p>
<pre><code># Sync requests
^/_matrix/client/(r0|v3)/sync$
^/_matrix/client/(api/v1|r0|v3)/events$
^/_matrix/client/(api/v1|r0|v3)/initialSync$
^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$

# Federation requests
^/_matrix/federation/v1/event/
^/_matrix/federation/v1/state/
^/_matrix/federation/v1/state_ids/
^/_matrix/federation/v1/backfill/
^/_matrix/federation/v1/get_missing_events/
^/_matrix/federation/v1/publicRooms
^/_matrix/federation/v1/query/
^/_matrix/federation/v1/make_join/
^/_matrix/federation/v1/make_leave/
^/_matrix/federation/(v1|v2)/send_join/
^/_matrix/federation/(v1|v2)/send_leave/
^/_matrix/federation/(v1|v2)/invite/
^/_matrix/federation/v1/event_auth/
^/_matrix/federation/v1/timestamp_to_event/
^/_matrix/federation/v1/exchange_third_party_invite/
^/_matrix/federation/v1/user/devices/
^/_matrix/key/v2/query
^/_matrix/federation/v1/hierarchy/

# Inbound federation transaction request
^/_matrix/federation/v1/send/

# Client API requests
^/_matrix/client/(api/v1|r0|v3|unstable)/createRoom$
^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$
^/_matrix/client/v1/rooms/.*/hierarchy$
^/_matrix/client/(v1|unstable)/rooms/.*/relations/
^/_matrix/client/v1/rooms/.*/threads$
^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary$
^/_matrix/client/(r0|v3|unstable)/account/3pid$
^/_matrix/client/(r0|v3|unstable)/account/whoami$
^/_matrix/client/(r0|v3|unstable)/devices$
^/_matrix/client/versions$
^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event/
^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms$
^/_matrix/client/v1/rooms/.*/timestamp_to_event$
^/_matrix/client/(api/v1|r0|v3|unstable/.*)/rooms/.*/aliases
^/_matrix/client/(api/v1|r0|v3|unstable)/search$
^/_matrix/client/(r0|v3|unstable)/user/.*/filter(/|$)
^/_matrix/client/(api/v1|r0|v3|unstable)/directory/room/.*$
^/_matrix/client/(r0|v3|unstable)/capabilities$

# Encryption requests
^/_matrix/client/(r0|v3|unstable)/keys/query$
^/_matrix/client/(r0|v3|unstable)/keys/changes$
^/_matrix/client/(r0|v3|unstable)/keys/claim$
^/_matrix/client/(r0|v3|unstable)/room_keys/
^/_matrix/client/(r0|v3|unstable)/keys/upload/

# Registration/login requests
^/_matrix/client/(api/v1|r0|v3|unstable)/login$
^/_matrix/client/(r0|v3|unstable)/register$
^/_matrix/client/(r0|v3|unstable)/register/available$
^/_matrix/client/v1/register/m.login.registration_token/validity$
^/_matrix/client/(r0|v3|unstable)/password_policy$

# Event sending requests
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state/
^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$
^/_matrix/client/(api/v1|r0|v3|unstable)/join/
^/_matrix/client/(api/v1|r0|v3|unstable)/knock/
^/_matrix/client/(api/v1|r0|v3|unstable)/profile/

# Account data requests
^/_matrix/client/(r0|v3|unstable)/.*/tags
^/_matrix/client/(r0|v3|unstable)/.*/account_data

# Receipts requests
^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers

# Presence requests
^/_matrix/client/(api/v1|r0|v3|unstable)/presence/

# User directory search requests
^/_matrix/client/(r0|v3|unstable)/user_directory/search$
</code></pre>
<p>Additionally, the following REST endpoints can be handled for GET requests:</p>
<pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/pushrules/
</code></pre>
<p>Pagination requests can also be handled, but all requests for a given
room must be routed to the same instance. Additionally, care must be taken to
ensure that the purge history admin API is not used while pagination requests
for the room are in flight:</p>
<pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$
</code></pre>
<p>Additionally, the following endpoints should be included if Synapse is configured
to use SSO (you only need to include the ones for whichever SSO provider you're
using):</p>
<pre><code># for all SSO providers
^/_matrix/client/(api/v1|r0|v3|unstable)/login/sso/redirect
^/_synapse/client/pick_idp$
^/_synapse/client/pick_username
^/_synapse/client/new_user_consent$
^/_synapse/client/sso_register$

# OpenID Connect requests.
^/_synapse/client/oidc/callback$

# SAML requests.
^/_synapse/client/saml2/authn_response$

# CAS requests.
^/_matrix/client/(api/v1|r0|v3|unstable)/login/cas/ticket$
</code></pre>
<p>Ensure that all SSO logins go to a single process.
For multiple workers not handling the SSO endpoints properly, see
<a href="https://github.com/matrix-org/synapse/issues/7530">#7530</a> and
<a href="https://github.com/matrix-org/synapse/issues/9427">#9427</a>.</p>
<p>Note that a <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a>
with <code>client</code> and <code>federation</code> <code>resources</code> must be configured in the
<a href="usage/configuration/config_documentation.html#worker_listeners"><code>worker_listeners</code></a>
option in the worker config.</p>
<h4 id="load-balancing"><a class="header" href="#load-balancing">Load balancing</a></h4>
<p>It is possible to run multiple instances of this worker app, with incoming requests
being load-balanced between them by the reverse-proxy. However, different endpoints
have different characteristics and so admins
may wish to run multiple groups of workers handling different endpoints so that
load balancing can be done in different ways.</p>
<p>For <code>/sync</code> and <code>/initialSync</code> requests it will be more efficient if all
requests from a particular user are routed to a single instance. This can
be done in reverse proxy by extracting username part from the users access token.</p>
<p>Admins may additionally wish to separate out <code>/sync</code>
requests that have a <code>since</code> query parameter from those that don't (and
<code>/initialSync</code>), as requests that don't are known as &quot;initial sync&quot; that happens
when a user logs in on a new device and can be <em>very</em> resource intensive, so
isolating these requests will stop them from interfering with other users ongoing
syncs.</p>
<p>Example <code>nginx</code> configuration snippet that handles the cases above. This is just an
example and probably requires some changes according to your particular setup:</p>
<pre><code class="language-nginx"># Choose sync worker based on the existence of &quot;since&quot; query parameter
map $arg_since $sync {
    default synapse_sync;
    '' synapse_initial_sync;
}

# Extract username from access token passed as URL parameter
map $arg_access_token $accesstoken_from_urlparam {
    # Defaults to just passing back the whole accesstoken
    default   $arg_access_token;
    # Try to extract username part from accesstoken URL parameter
    &quot;~syt_(?&lt;username&gt;.*?)_.*&quot;           $username;
}

# Extract username from access token passed as authorization header
map $http_authorization $mxid_localpart {
    # Defaults to just passing back the whole accesstoken
    default                              $http_authorization;
    # Try to extract username part from accesstoken header
    &quot;~Bearer syt_(?&lt;username&gt;.*?)_.*&quot;    $username;
    # if no authorization-header exist, try mapper for URL parameter &quot;access_token&quot;
    &quot;&quot;                                   $accesstoken_from_urlparam;
}

upstream synapse_initial_sync {
    # Use the username mapper result for hash key
    hash $mxid_localpart consistent;
    server 127.0.0.1:8016;
    server 127.0.0.1:8036;
}

upstream synapse_sync {
    # Use the username mapper result for hash key
    hash $mxid_localpart consistent;
    server 127.0.0.1:8013;
    server 127.0.0.1:8037;
    server 127.0.0.1:8038;
    server 127.0.0.1:8039;
}

# Sync initial/normal
location ~ ^/_matrix/client/(r0|v3)/sync$ {
	proxy_pass http://$sync;
}

# Normal sync
location ~ ^/_matrix/client/(api/v1|r0|v3)/events$ {
	proxy_pass http://synapse_sync;
}

# Initial_sync
location ~ ^/_matrix/client/(api/v1|r0|v3)/initialSync$ {
	proxy_pass http://synapse_initial_sync;
}
location ~ ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$ {
	proxy_pass http://synapse_initial_sync;
}
</code></pre>
<p>Federation and client requests can be balanced via simple round robin.</p>
<p>The inbound federation transaction request <code>^/_matrix/federation/v1/send/</code>
should be balanced by source IP so that transactions from the same remote server
go to the same process.</p>
<p>Registration/login requests can be handled separately purely to help ensure that
unexpected load doesn't affect new logins and sign ups.</p>
<p>Finally, event sending requests can be balanced by the room ID in the URI (or
the full URI, or even just round robin), the room ID is the path component after
<code>/rooms/</code>. If there is a large bridge connected that is sending or may send lots
of events, then a dedicated set of workers can be provisioned to limit the
effects of bursts of events from that bridge on events sent by normal users.</p>
<h4 id="stream-writers"><a class="header" href="#stream-writers">Stream writers</a></h4>
<p>Additionally, the writing of specific streams (such as events) can be moved off
of the main process to a particular worker.</p>
<p>To enable this, the worker must have:</p>
<ul>
<li>An <a href="usage/configuration/config_documentation.html#listeners">HTTP <code>replication</code> listener</a> configured,</li>
<li>Have a <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>
and be listed in the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>
config. </li>
<li>Have the main process declared on the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a> as well.</li>
</ul>
<p>Note: The same worker can handle multiple streams, but unless otherwise documented,
each stream can only have a single writer.</p>
<p>For example, to move event persistence off to a dedicated worker, the shared
configuration would include:</p>
<pre><code class="language-yaml">instance_map:
    main:
        host: localhost
        port: 8030
    event_persister1:
        host: localhost
        port: 8034

stream_writers:
    events: event_persister1
</code></pre>
<p>An example for a stream writer instance:</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
worker_name: event_persister1

worker_listeners:
  - type: http
    port: 8034
    resources:
      - names: [replication]

  # Enable listener if this stream writer handles endpoints for the `typing` or
  # `to_device` streams. Uses a different port to the `replication` listener to
  # avoid exposing the `replication` listener publicly.
  #
  #- type: http
  #  port: 8035
  #  x_forwarded: true
  #  resources:
  #    - names: [client]

worker_log_config: /etc/matrix-synapse/event-persister-log.yaml
</code></pre>
<p>Some of the streams have associated endpoints which, for maximum efficiency, should
be routed to the workers handling that stream. See below for the currently supported
streams and the endpoints associated with them:</p>
<h5 id="the-events-stream"><a class="header" href="#the-events-stream">The <code>events</code> stream</a></h5>
<p>The <code>events</code> stream experimentally supports having multiple writer workers, where load
is sharded between them by room ID. Each writer is called an <em>event persister</em>. They are
responsible for</p>
<ul>
<li>receiving new events,</li>
<li>linking them to those already in the room <a href="development/room-dag-concepts.html">DAG</a>,</li>
<li>persisting them to the DB, and finally</li>
<li>updating the events stream.</li>
</ul>
<p>Because load is sharded in this way, you <em>must</em> restart all worker instances when
adding or removing event persisters.</p>
<p>An <code>event_persister</code> should not be mistaken for an <code>event_creator</code>.
An <code>event_creator</code> listens for requests from clients to create new events and does
so. It will then pass those events over HTTP replication to any configured event
persisters (or the main process if none are configured).</p>
<p>Note that <code>event_creator</code>s and <code>event_persister</code>s are implemented using the same
<a href="workers.html#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a>.</p>
<p>An example <a href="usage/configuration/config_documentation.html#stream_writers"><code>stream_writers</code></a>
configuration with multiple writers:</p>
<pre><code class="language-yaml">stream_writers:
    events:
        - event_persister1
        - event_persister2
</code></pre>
<h5 id="the-typing-stream"><a class="header" href="#the-typing-stream">The <code>typing</code> stream</a></h5>
<p>The following endpoints should be routed directly to the worker configured as
the stream writer for the <code>typing</code> stream:</p>
<pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing
</code></pre>
<h5 id="the-to_device-stream"><a class="header" href="#the-to_device-stream">The <code>to_device</code> stream</a></h5>
<p>The following endpoints should be routed directly to the worker configured as
the stream writer for the <code>to_device</code> stream:</p>
<pre><code>^/_matrix/client/(r0|v3|unstable)/sendToDevice/
</code></pre>
<h5 id="the-account_data-stream"><a class="header" href="#the-account_data-stream">The <code>account_data</code> stream</a></h5>
<p>The following endpoints should be routed directly to the worker configured as
the stream writer for the <code>account_data</code> stream:</p>
<pre><code>^/_matrix/client/(r0|v3|unstable)/.*/tags
^/_matrix/client/(r0|v3|unstable)/.*/account_data
</code></pre>
<h5 id="the-receipts-stream"><a class="header" href="#the-receipts-stream">The <code>receipts</code> stream</a></h5>
<p>The following endpoints should be routed directly to the worker configured as
the stream writer for the <code>receipts</code> stream:</p>
<pre><code>^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
</code></pre>
<h5 id="the-presence-stream"><a class="header" href="#the-presence-stream">The <code>presence</code> stream</a></h5>
<p>The following endpoints should be routed directly to the worker configured as
the stream writer for the <code>presence</code> stream:</p>
<pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
</code></pre>
<h4 id="restrict-outbound-federation-traffic-to-a-specific-set-of-workers"><a class="header" href="#restrict-outbound-federation-traffic-to-a-specific-set-of-workers">Restrict outbound federation traffic to a specific set of workers</a></h4>
<p>The
<a href="usage/configuration/config_documentation.html#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a>
configuration is useful to make sure outbound federation traffic only goes through a
specified subset of workers. This allows you to set more strict access controls (like a
firewall) for all workers and only allow the <code>federation_sender</code>'s to contact the
outside world.</p>
<pre><code class="language-yaml">instance_map:
    main:
        host: localhost
        port: 8030
    federation_sender1:
        host: localhost
        port: 8034

outbound_federation_restricted_to:
  - federation_sender1

worker_replication_secret: &quot;secret_secret&quot;
</code></pre>
<h4 id="background-tasks"><a class="header" href="#background-tasks">Background tasks</a></h4>
<p>There is also support for moving background tasks to a separate
worker. Background tasks are run periodically or started via replication. Exactly
which tasks are configured to run depends on your Synapse configuration (e.g. if
stats is enabled). This worker doesn't handle any REST endpoints itself.</p>
<p>To enable this, the worker must have a unique
<a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>
and can be configured to run background tasks. For example, to move background tasks
to a dedicated worker, the shared configuration would include:</p>
<pre><code class="language-yaml">run_background_tasks_on: background_worker
</code></pre>
<p>You might also wish to investigate the
<a href="workers.html#updating-the-user-directory"><code>update_user_directory_from_worker</code></a> and
<a href="workers.html#synapseappmedia_repository"><code>media_instance_running_background_jobs</code></a> settings.</p>
<p>An example for a dedicated background worker instance:</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
worker_name: background_worker

worker_log_config: /etc/matrix-synapse/background-worker-log.yaml
</code></pre>
<h4 id="updating-the-user-directory"><a class="header" href="#updating-the-user-directory">Updating the User Directory</a></h4>
<p>You can designate one generic worker to update the user directory.</p>
<p>Specify its name in the <a href="usage/configuration/config_documentation.html#update_user_directory_from_worker">shared configuration</a>
as follows:</p>
<pre><code class="language-yaml">update_user_directory_from_worker: worker_name
</code></pre>
<p>This work cannot be load-balanced; please ensure the main process is restarted
after setting this option in the shared configuration!</p>
<p>User directory updates allow REST endpoints matching the following regular
expressions to work:</p>
<pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
</code></pre>
<p>The above endpoints can be routed to any worker, though you may choose to route
it to the chosen user directory worker.</p>
<p>This style of configuration supersedes the legacy <code>synapse.app.user_dir</code>
worker application type.</p>
<h4 id="notifying-application-services"><a class="header" href="#notifying-application-services">Notifying Application Services</a></h4>
<p>You can designate one generic worker to send output traffic to Application Services.
Doesn't handle any REST endpoints itself, but you should specify its name in the
<a href="usage/configuration/config_documentation.html#notify_appservices_from_worker">shared configuration</a>
as follows:</p>
<pre><code class="language-yaml">notify_appservices_from_worker: worker_name
</code></pre>
<p>This work cannot be load-balanced; please ensure the main process is restarted
after setting this option in the shared configuration!</p>
<p>This style of configuration supersedes the legacy <code>synapse.app.appservice</code>
worker application type.</p>
<h4 id="push-notifications"><a class="header" href="#push-notifications">Push Notifications</a></h4>
<p>You can designate generic worker to sending push notifications to
a <a href="https://spec.matrix.org/v1.5/push-gateway-api/">push gateway</a> such as
<a href="https://github.com/matrix-org/sygnal">sygnal</a> and email.</p>
<p>This will stop the main process sending push notifications.</p>
<p>The workers responsible for sending push notifications can be defined using the
<a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a>
option. For example:</p>
<pre><code class="language-yaml">pusher_instances:
  - pusher_worker1
  - pusher_worker2
</code></pre>
<p>Multiple workers can be added to this map, in which case the work is balanced
across them. Ensure the main process and all pusher workers are restarted after changing
this option.</p>
<p>These workers don't need to accept incoming HTTP requests to send push notifications,
so no additional reverse proxy configuration is required for pusher workers.</p>
<p>This style of configuration supersedes the legacy <code>synapse.app.pusher</code>
worker application type.</p>
<h3 id="synapseapppusher"><a class="header" href="#synapseapppusher"><code>synapse.app.pusher</code></a></h3>
<p>It is likely this option will be deprecated in the future and is not recommended for new
installations. Instead, <a href="workers.html#push-notifications">use <code>synapse.app.generic_worker</code> with the <code>pusher_instances</code></a>.</p>
<p>Handles sending push notifications to sygnal and email. Doesn't handle any
REST endpoints itself, but you should set
<a href="usage/configuration/config_documentation.html#start_pushers"><code>start_pushers: false</code></a> in the
shared configuration file to stop the main synapse sending push notifications.</p>
<p>To run multiple instances at once the
<a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a>
option should list all pusher instances by their
<a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>, e.g.:</p>
<pre><code class="language-yaml">start_pushers: false
pusher_instances:
    - pusher_worker1
    - pusher_worker2
</code></pre>
<p>An example for a pusher instance:</p>
<pre><code class="language-yaml">worker_app: synapse.app.pusher
worker_name: pusher_worker1

worker_log_config: /etc/matrix-synapse/pusher-worker-log.yaml
</code></pre>
<h3 id="synapseappappservice"><a class="header" href="#synapseappappservice"><code>synapse.app.appservice</code></a></h3>
<p><strong>Deprecated as of Synapse v1.59.</strong> <a href="workers.html#notifying-application-services">Use <code>synapse.app.generic_worker</code> with the
<code>notify_appservices_from_worker</code> option instead.</a></p>
<p>Handles sending output traffic to Application Services. Doesn't handle any
REST endpoints itself, but you should set <code>notify_appservices: False</code> in the
shared configuration file to stop the main synapse sending appservice notifications.</p>
<p>Note this worker cannot be load-balanced: only one instance should be active.</p>
<h3 id="synapseappfederation_sender"><a class="header" href="#synapseappfederation_sender"><code>synapse.app.federation_sender</code></a></h3>
<p>It is likely this option will be deprecated in the future and not recommended for
new installations. Instead, <a href="usage/configuration/config_documentation.html#federation_sender_instances">use <code>synapse.app.generic_worker</code> with the <code>federation_sender_instances</code></a>.</p>
<p>Handles sending federation traffic to other servers. Doesn't handle any
REST endpoints itself, but you should set
<a href="usage/configuration/config_documentation.html#send_federation"><code>send_federation: false</code></a>
in the shared configuration file to stop the main synapse sending this traffic.</p>
<p>If running multiple federation senders then you must list each
instance in the
<a href="usage/configuration/config_documentation.html#federation_sender_instances"><code>federation_sender_instances</code></a>
option by their
<a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>.
All instances must be stopped and started when adding or removing instances.
For example:</p>
<pre><code class="language-yaml">send_federation: false
federation_sender_instances:
    - federation_sender1
    - federation_sender2
</code></pre>
<p>An example for a federation sender instance:</p>
<pre><code class="language-yaml">worker_app: synapse.app.federation_sender
worker_name: federation_sender1

worker_log_config: /etc/matrix-synapse/federation-sender-log.yaml
</code></pre>
<h3 id="synapseappmedia_repository"><a class="header" href="#synapseappmedia_repository"><code>synapse.app.media_repository</code></a></h3>
<p>Handles the media repository. It can handle all endpoints starting with:</p>
<pre><code>/_matrix/media/
</code></pre>
<p>... and the following regular expressions matching media-specific administration APIs:</p>
<pre><code>^/_synapse/admin/v1/purge_media_cache$
^/_synapse/admin/v1/room/.*/media.*$
^/_synapse/admin/v1/user/.*/media.*$
^/_synapse/admin/v1/media/.*$
^/_synapse/admin/v1/quarantine_media/.*$
^/_synapse/admin/v1/users/.*/media$
</code></pre>
<p>You should also set
<a href="usage/configuration/config_documentation.html#enable_media_repo"><code>enable_media_repo: False</code></a>
in the shared configuration
file to stop the main synapse running background jobs related to managing the
media repository. Note that doing so will prevent the main process from being
able to handle the above endpoints.</p>
<p>In the <code>media_repository</code> worker configuration file, configure the
<a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a> to
expose the <code>media</code> resource. For example:</p>
<pre><code class="language-yaml">worker_app: synapse.app.media_repository
worker_name: media_worker

worker_listeners:
  - type: http
    port: 8085
    x_forwarded: true
    resources:
      - names: [media]

worker_log_config: /etc/matrix-synapse/media-worker-log.yaml
</code></pre>
<p>Note that if running multiple media repositories they must be on the same server
and you must specify a single instance to run the background tasks in the
<a href="usage/configuration/config_documentation.html#media_instance_running_background_jobs">shared configuration</a>,
e.g.:</p>
<pre><code class="language-yaml">media_instance_running_background_jobs: &quot;media-repository-1&quot;
</code></pre>
<p>Note that if a reverse proxy is used , then <code>/_matrix/media/</code> must be routed for both inbound client and federation requests (if they are handled separately).</p>
<h3 id="synapseappuser_dir"><a class="header" href="#synapseappuser_dir"><code>synapse.app.user_dir</code></a></h3>
<p><strong>Deprecated as of Synapse v1.59.</strong> <a href="workers.html#updating-the-user-directory">Use <code>synapse.app.generic_worker</code> with the
<code>update_user_directory_from_worker</code> option instead.</a></p>
<p>Handles searches in the user directory. It can handle REST endpoints matching
the following regular expressions:</p>
<pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
</code></pre>
<p>When using this worker you must also set <code>update_user_directory: false</code> in the
shared configuration file to stop the main synapse running background
jobs related to updating the user directory.</p>
<p>Above endpoint is not <em>required</em> to be routed to this worker. By default,
<code>update_user_directory</code> is set to <code>true</code>, which means the main process
will handle updates. All workers configured with <code>client</code> can handle the above
endpoint as long as either this worker or the main process are configured to
handle it, and are online.</p>
<p>If <code>update_user_directory</code> is set to <code>false</code>, and this worker is not running,
the above endpoint may give outdated results.</p>
<h3 id="historical-apps"><a class="header" href="#historical-apps">Historical apps</a></h3>
<p>The following used to be separate worker application types, but are now
equivalent to <code>synapse.app.generic_worker</code>:</p>
<ul>
<li><code>synapse.app.client_reader</code></li>
<li><code>synapse.app.event_creator</code></li>
<li><code>synapse.app.federation_reader</code></li>
<li><code>synapse.app.federation_sender</code></li>
<li><code>synapse.app.frontend_proxy</code></li>
<li><code>synapse.app.pusher</code></li>
<li><code>synapse.app.synchrotron</code></li>
</ul>
<h2 id="migration-from-old-config"><a class="header" href="#migration-from-old-config">Migration from old config</a></h2>
<p>A main change that has occurred is the merging of worker apps into
<code>synapse.app.generic_worker</code>. This change is backwards compatible and so no
changes to the config are required.</p>
<p>To migrate apps to use <code>synapse.app.generic_worker</code> simply update the
<code>worker_app</code> option in the worker configs, and where worker are started (e.g.
in systemd service files, but not required for synctl).</p>
<h2 id="architectural-diagram"><a class="header" href="#architectural-diagram">Architectural diagram</a></h2>
<p>The following shows an example setup using Redis and a reverse proxy:</p>
<pre><code>                     Clients &amp; Federation
                              |
                              v
                        +-----------+
                        |           |
                        |  Reverse  |
                        |  Proxy    |
                        |           |
                        +-----------+
                            | | |
                            | | | HTTP requests
        +-------------------+ | +-----------+
        |                 +---+             |
        |                 |                 |
        v                 v                 v
+--------------+  +--------------+  +--------------+  +--------------+
|   Main       |  |   Generic    |  |   Generic    |  |  Event       |
|   Process    |  |   Worker 1   |  |   Worker 2   |  |  Persister   |
+--------------+  +--------------+  +--------------+  +--------------+
      ^    ^          |   ^   |         |   ^   |         |   ^   ^
      |    |          |   |   |         |   |   |         |   |   |
      |    |          |   |   |  HTTP   |   |   |         |   |   |
      |    +----------+&lt;--|---|---------+&lt;--|---|---------+   |   |
      |                   |   +-------------|--&gt;+-------------+   |
      |                   |                 |                     |
      |                   |                 |                     |
      v                   v                 v                     v
======================================================================
                                                         Redis pub/sub channel
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h3 id="using-synctl-with-workers"><a class="header" href="#using-synctl-with-workers">Using synctl with workers</a></h3>
<p>If you want to use <code>synctl</code> to manage your synapse processes, you will need to
create an an additional configuration file for the main synapse process. That
configuration should look like this:</p>
<pre><code class="language-yaml">worker_app: synapse.app.homeserver
</code></pre>
<p>Additionally, each worker app must be configured with the name of a &quot;pid file&quot;,
to which it will write its process ID when it starts. For example, for a
synchrotron, you might write:</p>
<pre><code class="language-yaml">worker_pid_file: /home/matrix/synapse/worker1.pid
</code></pre>
<p>Finally, to actually run your worker-based synapse, you must pass synctl the <code>-a</code>
commandline option to tell it to operate on all the worker configurations found
in the given directory, e.g.:</p>
<pre><code class="language-sh">synctl -a $CONFIG/workers start
</code></pre>
<p>Currently one should always restart all workers when restarting or upgrading
synapse, unless you explicitly know it's safe not to.  For instance, restarting
synapse without restarting all the synchrotrons may result in broken typing
notifications.</p>
<p>To manipulate a specific worker, you pass the -w option to synctl:</p>
<pre><code class="language-sh">synctl -w $CONFIG/workers/worker1.yaml restart
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="setting-up-synapse-with-workers-and-systemd"><a class="header" href="#setting-up-synapse-with-workers-and-systemd">Setting up Synapse with Workers and Systemd</a></h1>
<p>This is a setup for managing synapse with systemd, including support for
managing workers. It provides a <code>matrix-synapse</code> service for the master, as
well as a <code>matrix-synapse-worker@</code> service template for any workers you
require. Additionally, to group the required services, it sets up a
<code>matrix-synapse.target</code>.</p>
<p>See the folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
for the systemd unit files.</p>
<p>The folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/workers/">workers</a>
contains an example configuration for the <code>generic_worker</code> worker.</p>
<h2 id="synapse-configuration-files"><a class="header" href="#synapse-configuration-files">Synapse configuration files</a></h2>
<p>See <a href="systemd-with-workers/../workers.html">the worker documentation</a> for information on how to set up the
configuration files and reverse-proxy correctly.
Below is a sample <code>generic_worker</code> worker configuration file.</p>
<pre><code class="language-yaml">worker_app: synapse.app.generic_worker
worker_name: generic_worker1

worker_listeners:
  - type: http
    port: 8083
    x_forwarded: true
    resources:
      - names: [client, federation]

worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
</code></pre>
<p>Systemd manages daemonization itself, so ensure that none of the configuration
files set either <code>daemonize</code> or <code>worker_daemonize</code>.</p>
<p>The config files of all workers are expected to be located in
<code>/etc/matrix-synapse/workers</code>. If you want to use a different location, edit
the provided <code>*.service</code> files accordingly.</p>
<p>There is no need for a separate configuration file for the master process.</p>
<h2 id="set-up"><a class="header" href="#set-up">Set up</a></h2>
<ol>
<li>Adjust synapse configuration files as above.</li>
<li>Copy the <code>*.service</code> and <code>*.target</code> files in <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
to <code>/etc/systemd/system</code>.</li>
<li>Run <code>systemctl daemon-reload</code> to tell systemd to load the new unit files.</li>
<li>Run <code>systemctl enable matrix-synapse.service</code>. This will configure the
synapse master process to be started as part of the <code>matrix-synapse.target</code>
target.</li>
<li>For each worker process to be enabled, run <code>systemctl enable matrix-synapse-worker@&lt;worker_name&gt;.service</code>. For each <code>&lt;worker_name&gt;</code>, there
should be a corresponding configuration file.
<code>/etc/matrix-synapse/workers/&lt;worker_name&gt;.yaml</code>.</li>
<li>Start all the synapse processes with <code>systemctl start matrix-synapse.target</code>.</li>
<li>Tell systemd to start synapse on boot with <code>systemctl enable matrix-synapse.target</code>.</li>
</ol>
<h2 id="usage"><a class="header" href="#usage">Usage</a></h2>
<p>Once the services are correctly set up, you can use the following commands
to manage your synapse installation:</p>
<pre><code class="language-sh"># Restart Synapse master and all workers
systemctl restart matrix-synapse.target

# Stop Synapse and all workers
systemctl stop matrix-synapse.target

# Restart the master alone
systemctl start matrix-synapse.service

# Restart a specific worker (eg. generic_worker); the master is
# unaffected by this.
systemctl restart matrix-synapse-worker@generic_worker.service

# Add a new worker (assuming all configs are set up already)
systemctl enable matrix-synapse-worker@federation_writer.service
systemctl restart matrix-synapse.target
</code></pre>
<h2 id="hardening"><a class="header" href="#hardening">Hardening</a></h2>
<p><strong>Optional:</strong> If further hardening is desired, the file
<code>override-hardened.conf</code> may be copied from
<a href="https://github.com/matrix-org/synapse/tree/develop/contrib/systemd/">contrib/systemd/override-hardened.conf</a>
in this repository to the location
<code>/etc/systemd/system/matrix-synapse.service.d/override-hardened.conf</code> (the
directory may have to be created). It enables certain sandboxing features in
systemd to further secure the synapse service. You may read the comments to
understand what the override file is doing. The same file will need to be copied to
<code>/etc/systemd/system/matrix-synapse-worker@.service.d/override-hardened-worker.conf</code>
(this directory may also have to be created) in order to apply the same
hardening options to any worker processes.</p>
<p>Once these files have been copied to their appropriate locations, simply reload
systemd's manager config files and restart all Synapse services to apply the hardening options. They will automatically
be applied at every restart as long as the override files are present at the
specified locations.</p>
<pre><code class="language-sh">systemctl daemon-reload

# Restart services
systemctl restart matrix-synapse.target
</code></pre>
<p>In order to see their effect, you may run <code>systemd-analyze security matrix-synapse.service</code> before and after applying the hardening options to see
the changes being applied at a glance.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="administration"><a class="header" href="#administration">Administration</a></h1>
<p>This section contains information on managing your Synapse homeserver. This includes:</p>
<ul>
<li>Managing users, rooms and media via the Admin API.</li>
<li>Setting up metrics and monitoring to give you insight into your homeserver's health.</li>
<li>Configuring structured logging.</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-admin-api"><a class="header" href="#the-admin-api">The Admin API</a></h1>
<h2 id="authenticate-as-a-server-admin"><a class="header" href="#authenticate-as-a-server-admin">Authenticate as a server admin</a></h2>
<p>Many of the API calls in the admin api will require an <code>access_token</code> for a
server admin. (Note that a server admin is distinct from a room admin.)</p>
<p>An existing user can be marked as a server admin by updating the database directly.</p>
<p>Check your <a href="usage/administration/admin_api/../../configuration/config_documentation.html#database">database settings</a> in the configuration file, connect to the correct database using either <code>psql [database name]</code> (if using PostgreSQL) or <code>sqlite3 path/to/your/database.db</code> (if using SQLite) and elevate the user <code>@foo:bar.com</code> to administrator.</p>
<pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
</code></pre>
<p>A new server admin user can also be created using the <code>register_new_matrix_user</code>
command. This is a script that is distributed as part of synapse. It is possibly
already on your <code>$PATH</code> depending on how Synapse was installed.</p>
<p>Finding your user's <code>access_token</code> is client-dependent, but will usually be shown in the client's settings.</p>
<h2 id="making-an-admin-api-request"><a class="header" href="#making-an-admin-api-request">Making an Admin API request</a></h2>
<p>For security reasons, we <a href="usage/administration/admin_api/../../../reverse_proxy.html#synapse-administration-endpoints">recommend</a>
that the Admin API (<code>/_synapse/admin/...</code>) should be hidden from public view using a
reverse proxy. This means you should typically query the Admin API from a terminal on
the machine which runs Synapse.</p>
<p>Once you have your <code>access_token</code>, you will need to authenticate each request to an Admin API endpoint by
providing the token as either a query parameter or a request header. To add it as a request header in cURL:</p>
<pre><code class="language-sh">curl --header &quot;Authorization: Bearer &lt;access_token&gt;&quot; &lt;the_rest_of_your_API_request&gt;
</code></pre>
<p>For example, suppose we want to
<a href="usage/administration/admin_api/../../../admin_api/user_admin_api.html#query-user-account">query the account</a> of the user
<code>@foo:bar.com</code>. We need an admin access token (e.g.
<code>syt_AjfVef2_L33JNpafeif_0feKJfeaf0CQpoZk</code>), and we need to know which port
Synapse's <a href="usage/administration/admin_api/../../configuration/config_documentation.html#listeners"><code>client</code> listener</a> is listening
on (e.g. <code>8008</code>). Then we can use the following command to request the account
information from the Admin API.</p>
<pre><code class="language-sh">curl --header &quot;Authorization: Bearer syt_AjfVef2_L33JNpafeif_0feKJfeaf0CQpoZk&quot; -X GET http://127.0.0.1:8008/_synapse/admin/v2/users/@foo:bar.com
</code></pre>
<p>For more details on access tokens in Matrix, please refer to the complete
<a href="https://matrix.org/docs/spec/client_server/r0.6.1#using-access-tokens">matrix spec documentation</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="account-validity-api"><a class="header" href="#account-validity-api">Account validity API</a></h1>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>This API allows a server administrator to manage the validity of an account. To
use it, you must enable the account validity feature (under
<code>account_validity</code>) in Synapse's configuration.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<h2 id="renew-account"><a class="header" href="#renew-account">Renew account</a></h2>
<p>This API extends the validity of an account by as much time as configured in the
<code>period</code> parameter from the <code>account_validity</code> configuration.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/account_validity/validity
</code></pre>
<p>with the following body:</p>
<pre><code class="language-json">{
    &quot;user_id&quot;: &quot;&lt;user ID for the account to renew&gt;&quot;,
    &quot;expiration_ts&quot;: 0,
    &quot;enable_renewal_emails&quot;: true
}
</code></pre>
<p><code>expiration_ts</code> is an optional parameter and overrides the expiration date,
which otherwise defaults to now + validity period.</p>
<p><code>enable_renewal_emails</code> is also an optional parameter and enables/disables
sending renewal emails to the user. Defaults to true.</p>
<p>The API returns with the new expiration date for this account, as a timestamp in
milliseconds since epoch:</p>
<pre><code class="language-json">{
    &quot;expiration_ts&quot;: 0
}
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="background-updates-api"><a class="header" href="#background-updates-api">Background Updates API</a></h1>
<p>This API allows a server administrator to manage the background updates being
run against the database.</p>
<h2 id="status"><a class="header" href="#status">Status</a></h2>
<p>This API gets the current status of the background updates.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/background_updates/status
</code></pre>
<p>Returning:</p>
<pre><code class="language-json">{
    &quot;enabled&quot;: true,
    &quot;current_updates&quot;: {
        &quot;&lt;db_name&gt;&quot;: {
            &quot;name&quot;: &quot;&lt;background_update_name&gt;&quot;,
            &quot;total_item_count&quot;: 50,
            &quot;total_duration_ms&quot;: 10000.0,
            &quot;average_items_per_ms&quot;: 2.2,
        },
    }
}
</code></pre>
<p><code>enabled</code> whether the background updates are enabled or disabled.</p>
<p><code>db_name</code> the database name (usually Synapse is configured with a single database named 'master').</p>
<p>For each update:</p>
<p><code>name</code> the name of the update.
<code>total_item_count</code> total number of &quot;items&quot; processed (the meaning of 'items' depends on the update in question).
<code>total_duration_ms</code> how long the background process has been running, not including time spent sleeping.
<code>average_items_per_ms</code> how many items are processed per millisecond based on an exponential average.</p>
<h2 id="enabled"><a class="header" href="#enabled">Enabled</a></h2>
<p>This API allow pausing background updates.</p>
<p>Background updates should <em>not</em> be paused for significant periods of time, as
this can affect the performance of Synapse.</p>
<p><em>Note</em>: This won't persist over restarts.</p>
<p><em>Note</em>: This won't cancel any update query that is currently running. This is
usually fine since most queries are short lived, except for <code>CREATE INDEX</code>
background updates which won't be cancelled once started.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/background_updates/enabled
</code></pre>
<p>with the following body:</p>
<pre><code class="language-json">{
    &quot;enabled&quot;: false
}
</code></pre>
<p><code>enabled</code> sets whether the background updates are enabled or disabled.</p>
<p>The API returns the <code>enabled</code> param.</p>
<pre><code class="language-json">{
    &quot;enabled&quot;: false
}
</code></pre>
<p>There is also a <code>GET</code> version which returns the <code>enabled</code> state.</p>
<h2 id="run"><a class="header" href="#run">Run</a></h2>
<p>This API schedules a specific background update to run. The job starts immediately after calling the API.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/background_updates/start_job
</code></pre>
<p>with the following body:</p>
<pre><code class="language-json">{
    &quot;job_name&quot;: &quot;populate_stats_process_rooms&quot;
}
</code></pre>
<p>The following JSON body parameters are available:</p>
<ul>
<li><code>job_name</code> - A string which job to run. Valid values are:
<ul>
<li><code>populate_stats_process_rooms</code> - Recalculate the stats for all rooms.</li>
<li><code>regenerate_directory</code> - Recalculate the <a href="usage/administration/admin_api/../../../user_directory.html">user directory</a> if it is stale or out of sync.</li>
</ul>
</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="show-reported-events"><a class="header" href="#show-reported-events">Show reported events</a></h1>
<p>This API returns information about reported events.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<p>The api is:</p>
<pre><code>GET /_synapse/admin/v1/event_reports?from=0&amp;limit=10
</code></pre>
<p>It returns a JSON body like the following:</p>
<pre><code class="language-json">{
    &quot;event_reports&quot;: [
        {
            &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
            &quot;id&quot;: 2,
            &quot;reason&quot;: &quot;foo&quot;,
            &quot;score&quot;: -100,
            &quot;received_ts&quot;: 1570897107409,
            &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
            &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
            &quot;name&quot;: &quot;Matrix HQ&quot;,
            &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
            &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
        },
        {
            &quot;event_id&quot;: &quot;$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I&quot;,
            &quot;id&quot;: 3,
            &quot;reason&quot;: &quot;bar&quot;,
            &quot;score&quot;: -100,
            &quot;received_ts&quot;: 1598889612059,
            &quot;canonical_alias&quot;: &quot;#alias2:matrix.org&quot;,
            &quot;room_id&quot;: &quot;!eGvUQuTCkHGVwNMOjv:matrix.org&quot;,
            &quot;name&quot;: &quot;Your room name here&quot;,
            &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
            &quot;user_id&quot;: &quot;@bar:matrix.org&quot;
        }
    ],
    &quot;next_token&quot;: 2,
    &quot;total&quot;: 4
}
</code></pre>
<p>To paginate, check for <code>next_token</code> and if present, call the endpoint again with <code>from</code>
set to the value of <code>next_token</code>. This will return a new page.</p>
<p>If the endpoint does not return a <code>next_token</code> then there are no more reports to
paginate through.</p>
<p><strong>URL parameters:</strong></p>
<ul>
<li><code>limit</code>: integer - Is optional but is used for pagination, denoting the maximum number
of items to return in this call. Defaults to <code>100</code>.</li>
<li><code>from</code>: integer - Is optional but used for pagination, denoting the offset in the
returned results. This should be treated as an opaque value and not explicitly set to
anything other than the return value of <code>next_token</code> from a previous call. Defaults to <code>0</code>.</li>
<li><code>dir</code>: string - Direction of event report order. Whether to fetch the most recent
first (<code>b</code>) or the oldest first (<code>f</code>). Defaults to <code>b</code>.</li>
<li><code>user_id</code>: string - Is optional and filters to only return users with user IDs that
contain this value. This is the user who reported the event and wrote the reason.</li>
<li><code>room_id</code>: string - Is optional and filters to only return rooms with room IDs that
contain this value.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>id</code>: integer - ID of event report.</li>
<li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
report was sent.</li>
<li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
<li><code>name</code>: string - The name of the room.</li>
<li><code>event_id</code>: string - The ID of the reported event.</li>
<li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
<li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank or <code>null</code>.</li>
<li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
&quot;most offensive&quot; and 0 is &quot;inoffensive&quot;. May be <code>null</code>.</li>
<li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
was reported.</li>
<li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
have a canonical alias set.</li>
<li><code>next_token</code>: integer - Indication for pagination. See above.</li>
<li><code>total</code>: integer - Total number of event reports related to the query
(<code>user_id</code> and <code>room_id</code>).</li>
</ul>
<h1 id="show-details-of-a-specific-event-report"><a class="header" href="#show-details-of-a-specific-event-report">Show details of a specific event report</a></h1>
<p>This API returns information about a specific event report.</p>
<p>The api is:</p>
<pre><code>GET /_synapse/admin/v1/event_reports/&lt;report_id&gt;
</code></pre>
<p>It returns a JSON body like the following:</p>
<pre><code class="language-json">{
    &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
    &quot;event_json&quot;: {
        &quot;auth_events&quot;: [
            &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;,
            &quot;$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws&quot;
        ],
        &quot;content&quot;: {
            &quot;body&quot;: &quot;matrix.org: This Week in Matrix&quot;,
            &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
            &quot;formatted_body&quot;: &quot;&lt;strong&gt;matrix.org&lt;/strong&gt;:&lt;br&gt;&lt;a href=\&quot;https://matrix.org/blog/\&quot;&gt;&lt;strong&gt;This Week in Matrix&lt;/strong&gt;&lt;/a&gt;&quot;,
            &quot;msgtype&quot;: &quot;m.notice&quot;
        },
        &quot;depth&quot;: 546,
        &quot;hashes&quot;: {
            &quot;sha256&quot;: &quot;xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw&quot;
        },
        &quot;origin&quot;: &quot;matrix.org&quot;,
        &quot;origin_server_ts&quot;: 1592291711430,
        &quot;prev_events&quot;: [
            &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;
        ],
        &quot;prev_state&quot;: [],
        &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
        &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
        &quot;signatures&quot;: {
            &quot;matrix.org&quot;: {
                &quot;ed25519:a_JaEG&quot;: &quot;cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg&quot;
            }
        },
        &quot;type&quot;: &quot;m.room.message&quot;,
        &quot;unsigned&quot;: {
            &quot;age_ts&quot;: 1592291711430
        }
    },
    &quot;id&quot;: &lt;report_id&gt;,
    &quot;reason&quot;: &quot;foo&quot;,
    &quot;score&quot;: -100,
    &quot;received_ts&quot;: 1570897107409,
    &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
    &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
    &quot;name&quot;: &quot;Matrix HQ&quot;,
    &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
    &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
}
</code></pre>
<p><strong>URL parameters:</strong></p>
<ul>
<li><code>report_id</code>: string - The ID of the event report.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>id</code>: integer - ID of event report.</li>
<li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
report was sent.</li>
<li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
<li><code>name</code>: string - The name of the room.</li>
<li><code>event_id</code>: string - The ID of the reported event.</li>
<li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
<li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank.</li>
<li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
&quot;most offensive&quot; and 0 is &quot;inoffensive&quot;.</li>
<li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
was reported.</li>
<li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
have a canonical alias set.</li>
<li><code>event_json</code>: object - Details of the original event that was reported.</li>
</ul>
<h1 id="delete-a-specific-event-report"><a class="header" href="#delete-a-specific-event-report">Delete a specific event report</a></h1>
<p>This API deletes a specific event report. If the request is successful, the response body
will be an empty JSON object.</p>
<p>The api is:</p>
<pre><code>DELETE /_synapse/admin/v1/event_reports/&lt;report_id&gt;
</code></pre>
<p><strong>URL parameters:</strong></p>
<ul>
<li><code>report_id</code>: string - The ID of the event report.</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="experimental-features-api"><a class="header" href="#experimental-features-api">Experimental Features API</a></h1>
<p>This API allows a server administrator to enable or disable some experimental features on a per-user
basis. The currently supported features are: </p>
<ul>
<li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3026">MSC3026</a>: busy 
presence state enabled</li>
<li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3881">MSC3881</a>: enable remotely toggling push notifications 
for another client </li>
<li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3967">MSC3967</a>: do not require
UIA when first uploading cross-signing keys. </li>
</ul>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<h2 id="enablingdisabling-features"><a class="header" href="#enablingdisabling-features">Enabling/Disabling Features</a></h2>
<p>This API allows a server administrator to enable experimental features for a given user. The request must 
provide a body containing the user id and listing the features to enable/disable in the following format:</p>
<pre><code class="language-json">{
   &quot;features&quot;: {
      &quot;msc3026&quot;:true,
      &quot;msc3881&quot;:true
   }
}
</code></pre>
<p>where true is  used to enable the feature, and false is used to disable the feature.</p>
<p>The API is:</p>
<pre><code>PUT /_synapse/admin/v1/experimental_features/&lt;user_id&gt;
</code></pre>
<h2 id="listing-enabled-features"><a class="header" href="#listing-enabled-features">Listing Enabled Features</a></h2>
<p>To list which features are enabled/disabled for a given user send a request to the following API:</p>
<pre><code>GET /_synapse/admin/v1/experimental_features/&lt;user_id&gt;
</code></pre>
<p>It will return a list of possible features and indicate whether they are enabled or disabled for the
user like so:</p>
<pre><code class="language-json">{
   &quot;features&quot;: {
      &quot;msc3026&quot;: true,
      &quot;msc3881&quot;: false,
      &quot;msc3967&quot;: false
   }
}
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="querying-media"><a class="header" href="#querying-media">Querying media</a></h1>
<p>These APIs allow extracting media information from the homeserver.</p>
<p>Details about the format of the <code>media_id</code> and storage of the media in the file system
are documented under <a href="admin_api/../media_repository.html">media repository</a>.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<h2 id="list-all-media-in-a-room"><a class="header" href="#list-all-media-in-a-room">List all media in a room</a></h2>
<p>This API gets a list of known media in a room.
However, it only shows media from unencrypted events or rooms.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/room/&lt;room_id&gt;/media
</code></pre>
<p>The API returns a JSON body like the following:</p>
<pre><code class="language-json">{
  &quot;local&quot;: [
    &quot;mxc://localhost/xwvutsrqponmlkjihgfedcba&quot;,
    &quot;mxc://localhost/abcdefghijklmnopqrstuvwx&quot;
  ],
  &quot;remote&quot;: [
    &quot;mxc://matrix.org/xwvutsrqponmlkjihgfedcba&quot;,
    &quot;mxc://matrix.org/abcdefghijklmnopqrstuvwx&quot;
  ]
}
</code></pre>
<h2 id="list-all-media-uploaded-by-a-user"><a class="header" href="#list-all-media-uploaded-by-a-user">List all media uploaded by a user</a></h2>
<p>Listing all media that has been uploaded by a local user can be achieved through
the use of the
<a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>
Admin API.</p>
<h1 id="quarantine-media"><a class="header" href="#quarantine-media">Quarantine media</a></h1>
<p>Quarantining media means that it is marked as inaccessible by users. It applies
to any local media, and any locally-cached copies of remote media.</p>
<p>The media file itself (and any thumbnails) is not deleted from the server.</p>
<h2 id="quarantining-media-by-id"><a class="header" href="#quarantining-media-by-id">Quarantining media by ID</a></h2>
<p>This API quarantines a single piece of local or remote media.</p>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/media/quarantine/&lt;server_name&gt;/&lt;media_id&gt;

{}
</code></pre>
<p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
form of <code>abcdefg12345...</code>.</p>
<p>Response:</p>
<pre><code class="language-json">{}
</code></pre>
<h2 id="remove-media-from-quarantine-by-id"><a class="header" href="#remove-media-from-quarantine-by-id">Remove media from quarantine by ID</a></h2>
<p>This API removes a single piece of local or remote media from quarantine.</p>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/media/unquarantine/&lt;server_name&gt;/&lt;media_id&gt;

{}
</code></pre>
<p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
form of <code>abcdefg12345...</code>.</p>
<p>Response:</p>
<pre><code class="language-json">{}
</code></pre>
<h2 id="quarantining-media-in-a-room"><a class="header" href="#quarantining-media-in-a-room">Quarantining media in a room</a></h2>
<p>This API quarantines all local and remote media in a room.</p>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/room/&lt;room_id&gt;/media/quarantine

{}
</code></pre>
<p>Where <code>room_id</code> is in the form of <code>!roomid12345:example.org</code>.</p>
<p>Response:</p>
<pre><code class="language-json">{
  &quot;num_quarantined&quot;: 10
}
</code></pre>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
</ul>
<p>Note that there is a legacy endpoint, <code>POST /_synapse/admin/v1/quarantine_media/&lt;room_id&gt;</code>, that operates the same.
However, it is deprecated and may be removed in a future release.</p>
<h2 id="quarantining-all-media-of-a-user"><a class="header" href="#quarantining-all-media-of-a-user">Quarantining all media of a user</a></h2>
<p>This API quarantines all <em>local</em> media that a <em>local</em> user has uploaded. That is to say, if
you would like to quarantine media uploaded by a user on a remote homeserver, you should
instead use one of the other APIs.</p>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/user/&lt;user_id&gt;/media/quarantine

{}
</code></pre>
<p>URL Parameters</p>
<ul>
<li><code>user_id</code>: string - User ID in the form of <code>@bob:example.org</code></li>
</ul>
<p>Response:</p>
<pre><code class="language-json">{
  &quot;num_quarantined&quot;: 10
}
</code></pre>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
</ul>
<h2 id="protecting-media-from-being-quarantined"><a class="header" href="#protecting-media-from-being-quarantined">Protecting media from being quarantined</a></h2>
<p>This API protects a single piece of local media from being quarantined using the
above APIs. This is useful for sticker packs and other shared media which you do
not want to get quarantined, especially when
<a href="admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantining media in a room</a>.</p>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/media/protect/&lt;media_id&gt;

{}
</code></pre>
<p>Where <code>media_id</code> is in the  form of <code>abcdefg12345...</code>.</p>
<p>Response:</p>
<pre><code class="language-json">{}
</code></pre>
<h2 id="unprotecting-media-from-being-quarantined"><a class="header" href="#unprotecting-media-from-being-quarantined">Unprotecting media from being quarantined</a></h2>
<p>This API reverts the protection of a media.</p>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/media/unprotect/&lt;media_id&gt;

{}
</code></pre>
<p>Where <code>media_id</code> is in the  form of <code>abcdefg12345...</code>.</p>
<p>Response:</p>
<pre><code class="language-json">{}
</code></pre>
<h1 id="delete-local-media"><a class="header" href="#delete-local-media">Delete local media</a></h1>
<p>This API deletes the <em>local</em> media from the disk of your own server.
This includes any local thumbnails and copies of media downloaded from
remote homeservers.
This API will not affect media that has been uploaded to external
media repositories (e.g https://github.com/turt2live/matrix-media-repo/).
See also <a href="admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a>.</p>
<h2 id="delete-a-specific-local-media"><a class="header" href="#delete-a-specific-local-media">Delete a specific local media</a></h2>
<p>Delete a specific <code>media_id</code>.</p>
<p>Request:</p>
<pre><code>DELETE /_synapse/admin/v1/media/&lt;server_name&gt;/&lt;media_id&gt;

{}
</code></pre>
<p>URL Parameters</p>
<ul>
<li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>)</li>
<li><code>media_id</code>: string - The ID of the media (e.g <code>abcdefghijklmnopqrstuvwx</code>)</li>
</ul>
<p>Response:</p>
<pre><code class="language-json">{
  &quot;deleted_media&quot;: [
    &quot;abcdefghijklmnopqrstuvwx&quot;
  ],
  &quot;total&quot;: 1
}
</code></pre>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
<li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
</ul>
<h2 id="delete-local-media-by-date-or-size"><a class="header" href="#delete-local-media-by-date-or-size">Delete local media by date or size</a></h2>
<p>Request:</p>
<pre><code>POST /_synapse/admin/v1/media/delete?before_ts=&lt;before_ts&gt;

{}
</code></pre>
<p><em>Deprecated in Synapse v1.78.0:</em> This API is available at the deprecated endpoint:</p>
<pre><code>POST /_synapse/admin/v1/media/&lt;server_name&gt;/delete?before_ts=&lt;before_ts&gt;

{}
</code></pre>
<p>URL Parameters</p>
<ul>
<li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>). <em>Deprecated in Synapse v1.78.0.</em></li>
<li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
Files that were last used before this timestamp will be deleted. It is the timestamp of
last access, not the timestamp when the file was created.</li>
<li><code>size_gt</code>: Optional - string representing a positive integer - Size of the media in bytes.
Files that are larger will be deleted. Defaults to <code>0</code>.</li>
<li><code>keep_profiles</code>: Optional - string representing a boolean - Switch to also delete files
that are still used in image data (e.g user profile, room avatar).
If <code>false</code> these files will be deleted. Defaults to <code>true</code>.</li>
</ul>
<p>Response:</p>
<pre><code class="language-json">{
  &quot;deleted_media&quot;: [
    &quot;abcdefghijklmnopqrstuvwx&quot;,
    &quot;abcdefghijklmnopqrstuvwz&quot;
  ],
  &quot;total&quot;: 2
}
</code></pre>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
<li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
</ul>
<h2 id="delete-media-uploaded-by-a-user"><a class="header" href="#delete-media-uploaded-by-a-user">Delete media uploaded by a user</a></h2>
<p>You can find details of how to delete multiple media uploaded by a user in
<a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">User Admin API</a>.</p>
<h1 id="purge-remote-media-api"><a class="header" href="#purge-remote-media-api">Purge Remote Media API</a></h1>
<p>The purge remote media API allows server admins to purge old cached remote media.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/purge_media_cache?before_ts=&lt;unix_timestamp_in_ms&gt;

{}
</code></pre>
<p>URL Parameters</p>
<ul>
<li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
All cached media that was last accessed before this timestamp will be removed.</li>
</ul>
<p>Response:</p>
<pre><code class="language-json">{
  &quot;deleted&quot;: 10
}
</code></pre>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>deleted</code>: integer - The number of media items successfully deleted</li>
</ul>
<p>If the user re-requests purged remote media, synapse will re-request the media
from the originating server.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="purge-history-api"><a class="header" href="#purge-history-api">Purge History API</a></h1>
<p>The purge history API allows server admins to purge historic events from their
database, reclaiming disk space.</p>
<p>Depending on the amount of history being purged a call to the API may take
several minutes or longer. During this period users will not be able to
paginate further back in the room from the point being purged from.</p>
<p>Note that Synapse requires at least one message in each room, so it will never
delete the last message in a room.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/purge_history/&lt;room_id&gt;[/&lt;event_id&gt;]
</code></pre>
<p>By default, events sent by local users are not deleted, as they may represent
the only copies of this content in existence. (Events sent by remote users are
deleted.)</p>
<p>Room state data (such as joins, leaves, topic) is always preserved.</p>
<p>To delete local message events as well, set <code>delete_local_events</code> in the body:</p>
<pre><code class="language-json">{
   &quot;delete_local_events&quot;: true
}
</code></pre>
<p>The caller must specify the point in the room to purge up to. This can be
specified by including an event_id in the URI, or by setting a
<code>purge_up_to_event_id</code> or <code>purge_up_to_ts</code> in the request body. If an event
id is given, that event (and others at the same graph depth) will be retained.
If <code>purge_up_to_ts</code> is given, it should be a timestamp since the unix epoch,
in milliseconds.</p>
<p>The API starts the purge running, and returns immediately with a JSON body with
a purge id:</p>
<pre><code class="language-json">{
    &quot;purge_id&quot;: &quot;&lt;opaque id&gt;&quot;
}
</code></pre>
<h2 id="purge-status-query"><a class="header" href="#purge-status-query">Purge status query</a></h2>
<p>It is possible to poll for updates on recent purges with a second API;</p>
<pre><code>GET /_synapse/admin/v1/purge_history_status/&lt;purge_id&gt;
</code></pre>
<p>This API returns a JSON body like the following:</p>
<pre><code class="language-json">{
    &quot;status&quot;: &quot;active&quot;
}
</code></pre>
<p>The status will be one of <code>active</code>, <code>complete</code>, or <code>failed</code>.</p>
<p>If <code>status</code> is <code>failed</code> there will be a string <code>error</code> with the error message.</p>
<h2 id="reclaim-disk-space-postgres"><a class="header" href="#reclaim-disk-space-postgres">Reclaim disk space (Postgres)</a></h2>
<p>To reclaim the disk space and return it to the operating system, you need to run
<code>VACUUM FULL;</code> on the database.</p>
<p><a href="https://www.postgresql.org/docs/current/sql-vacuum.html">https://www.postgresql.org/docs/current/sql-vacuum.html</a></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="shared-secret-registration"><a class="header" href="#shared-secret-registration">Shared-Secret Registration</a></h1>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>This API allows for the creation of users in an administrative and
non-interactive way. This is generally used for bootstrapping a Synapse
instance with administrator accounts.</p>
<p>To authenticate yourself to the server, you will need both the shared secret
(<a href="admin_api/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>
in the homeserver configuration), and a one-time nonce. If the registration
shared secret is not configured, this API is not enabled.</p>
<p>To fetch the nonce, you need to request one from the API:</p>
<pre><code>&gt; GET /_synapse/admin/v1/register

&lt; {&quot;nonce&quot;: &quot;thisisanonce&quot;}
</code></pre>
<p>Once you have the nonce, you can make a <code>POST</code> to the same URL with a JSON
body containing the nonce, username, password, whether they are an admin
(optional, False by default), and a HMAC digest of the content. Also you can
set the displayname (optional, <code>username</code> by default).</p>
<p>As an example:</p>
<pre><code>&gt; POST /_synapse/admin/v1/register
&gt; {
   &quot;nonce&quot;: &quot;thisisanonce&quot;,
   &quot;username&quot;: &quot;pepper_roni&quot;,
   &quot;displayname&quot;: &quot;Pepper Roni&quot;,
   &quot;password&quot;: &quot;pizza&quot;,
   &quot;admin&quot;: true,
   &quot;mac&quot;: &quot;mac_digest_here&quot;
  }

&lt; {
   &quot;access_token&quot;: &quot;token_here&quot;,
   &quot;user_id&quot;: &quot;@pepper_roni:localhost&quot;,
   &quot;home_server&quot;: &quot;test&quot;,
   &quot;device_id&quot;: &quot;device_id_here&quot;
  }
</code></pre>
<p>The MAC is the hex digest output of the HMAC-SHA1 algorithm, with the key being
the shared secret and the content being the nonce, user, password, either the
string &quot;admin&quot; or &quot;notadmin&quot;, and optionally the user_type
each separated by NULs.</p>
<p>Here is an easy way to generate the HMAC digest if you have Bash and OpenSSL:</p>
<pre><code class="language-bash"># Update these values and then paste this code block into a bash terminal
nonce='thisisanonce'
username='pepper_roni'
password='pizza'
admin='admin'
secret='shared_secret'

printf '%s\0%s\0%s\0%s' &quot;$nonce&quot; &quot;$username&quot; &quot;$password&quot; &quot;$admin&quot; |
  openssl sha1 -hmac &quot;$secret&quot; |
  awk '{print $2}'
</code></pre>
<p>For an example of generation in Python:</p>
<pre><code class="language-python">import hmac, hashlib

def generate_mac(nonce, user, password, admin=False, user_type=None):

    mac = hmac.new(
      key=shared_secret,
      digestmod=hashlib.sha1,
    )

    mac.update(nonce.encode('utf8'))
    mac.update(b&quot;\x00&quot;)
    mac.update(user.encode('utf8'))
    mac.update(b&quot;\x00&quot;)
    mac.update(password.encode('utf8'))
    mac.update(b&quot;\x00&quot;)
    mac.update(b&quot;admin&quot; if admin else b&quot;notadmin&quot;)
    if user_type:
        mac.update(b&quot;\x00&quot;)
        mac.update(user_type.encode('utf8'))

    return mac.hexdigest()
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="registration-tokens"><a class="header" href="#registration-tokens">Registration Tokens</a></h1>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>This API allows you to manage tokens which can be used to authenticate
registration requests, as proposed in
<a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md">MSC3231</a>
and stabilised in version 1.2 of the Matrix specification.
To use it, you will need to enable the <code>registration_requires_token</code> config
option, and authenticate by providing an <code>access_token</code> for a server admin:
see <a href="usage/administration/admin_api/../admin_api/">Admin API</a>.</p>
<h2 id="registration-token-objects"><a class="header" href="#registration-token-objects">Registration token objects</a></h2>
<p>Most endpoints make use of JSON objects that contain details about tokens.
These objects have the following fields:</p>
<ul>
<li><code>token</code>: The token which can be used to authenticate registration.</li>
<li><code>uses_allowed</code>: The number of times the token can be used to complete a
registration before it becomes invalid.</li>
<li><code>pending</code>: The number of pending uses the token has. When someone uses
the token to authenticate themselves, the pending counter is incremented
so that the token is not used more than the permitted number of times.
When the person completes registration the pending counter is decremented,
and the completed counter is incremented.</li>
<li><code>completed</code>: The number of times the token has been used to successfully
complete a registration.</li>
<li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
To convert this into a human-readable form you can remove the milliseconds
and use the <code>date</code> command. For example, <code>date -d '@1625394937'</code>.</li>
</ul>
<h2 id="list-all-tokens"><a class="header" href="#list-all-tokens">List all tokens</a></h2>
<p>Lists all tokens and details about them. If the request is successful, the top
level JSON object will have a <code>registration_tokens</code> key which is an array of
registration token objects.</p>
<pre><code>GET /_synapse/admin/v1/registration_tokens
</code></pre>
<p>Optional query parameters:</p>
<ul>
<li><code>valid</code>: <code>true</code> or <code>false</code>. If <code>true</code>, only valid tokens are returned.
If <code>false</code>, only tokens that have expired or have had all uses exhausted are
returned. If omitted, all tokens are returned regardless of validity.</li>
</ul>
<p>Example:</p>
<pre><code>GET /_synapse/admin/v1/registration_tokens
</code></pre>
<pre><code>200 OK

{
    &quot;registration_tokens&quot;: [
        {
            &quot;token&quot;: &quot;abcd&quot;,
            &quot;uses_allowed&quot;: 3,
            &quot;pending&quot;: 0,
            &quot;completed&quot;: 1,
            &quot;expiry_time&quot;: null
        },
        {
            &quot;token&quot;: &quot;pqrs&quot;,
            &quot;uses_allowed&quot;: 2,
            &quot;pending&quot;: 1,
            &quot;completed&quot;: 1,
            &quot;expiry_time&quot;: null
        },
        {
            &quot;token&quot;: &quot;wxyz&quot;,
            &quot;uses_allowed&quot;: null,
            &quot;pending&quot;: 0,
            &quot;completed&quot;: 9,
            &quot;expiry_time&quot;: 1625394937000    // 2021-07-04 10:35:37 UTC
        }
    ]
}
</code></pre>
<p>Example using the <code>valid</code> query parameter:</p>
<pre><code>GET /_synapse/admin/v1/registration_tokens?valid=false
</code></pre>
<pre><code>200 OK

{
    &quot;registration_tokens&quot;: [
        {
            &quot;token&quot;: &quot;pqrs&quot;,
            &quot;uses_allowed&quot;: 2,
            &quot;pending&quot;: 1,
            &quot;completed&quot;: 1,
            &quot;expiry_time&quot;: null
        },
        {
            &quot;token&quot;: &quot;wxyz&quot;,
            &quot;uses_allowed&quot;: null,
            &quot;pending&quot;: 0,
            &quot;completed&quot;: 9,
            &quot;expiry_time&quot;: 1625394937000    // 2021-07-04 10:35:37 UTC
        }
    ]
}
</code></pre>
<h2 id="get-one-token"><a class="header" href="#get-one-token">Get one token</a></h2>
<p>Get details about a single token. If the request is successful, the response
body will be a registration token object.</p>
<pre><code>GET /_synapse/admin/v1/registration_tokens/&lt;token&gt;
</code></pre>
<p>Path parameters:</p>
<ul>
<li><code>token</code>: The registration token to return details of.</li>
</ul>
<p>Example:</p>
<pre><code>GET /_synapse/admin/v1/registration_tokens/abcd
</code></pre>
<pre><code>200 OK

{
    &quot;token&quot;: &quot;abcd&quot;,
    &quot;uses_allowed&quot;: 3,
    &quot;pending&quot;: 0,
    &quot;completed&quot;: 1,
    &quot;expiry_time&quot;: null
}
</code></pre>
<h2 id="create-token"><a class="header" href="#create-token">Create token</a></h2>
<p>Create a new registration token. If the request is successful, the newly created
token will be returned as a registration token object in the response body.</p>
<pre><code>POST /_synapse/admin/v1/registration_tokens/new
</code></pre>
<p>The request body must be a JSON object and can contain the following fields:</p>
<ul>
<li><code>token</code>: The registration token. A string of no more than 64 characters that
consists only of characters matched by the regex <code>[A-Za-z0-9._~-]</code>.
Default: randomly generated.</li>
<li><code>uses_allowed</code>: The integer number of times the token can be used to complete
a registration before it becomes invalid.
Default: <code>null</code> (unlimited uses).</li>
<li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
You could use, for example, <code>date '+%s000' -d 'tomorrow'</code>.
Default: <code>null</code> (token does not expire).</li>
<li><code>length</code>: The length of the token randomly generated if <code>token</code> is not
specified. Must be between 1 and 64 inclusive. Default: <code>16</code>.</li>
</ul>
<p>If a field is omitted the default is used.</p>
<p>Example using defaults:</p>
<pre><code>POST /_synapse/admin/v1/registration_tokens/new

{}
</code></pre>
<pre><code>200 OK

{
    &quot;token&quot;: &quot;0M-9jbkf2t_Tgiw1&quot;,
    &quot;uses_allowed&quot;: null,
    &quot;pending&quot;: 0,
    &quot;completed&quot;: 0,
    &quot;expiry_time&quot;: null
}
</code></pre>
<p>Example specifying some fields:</p>
<pre><code>POST /_synapse/admin/v1/registration_tokens/new

{
    &quot;token&quot;: &quot;defg&quot;,
    &quot;uses_allowed&quot;: 1
}
</code></pre>
<pre><code>200 OK

{
    &quot;token&quot;: &quot;defg&quot;,
    &quot;uses_allowed&quot;: 1,
    &quot;pending&quot;: 0,
    &quot;completed&quot;: 0,
    &quot;expiry_time&quot;: null
}
</code></pre>
<h2 id="update-token"><a class="header" href="#update-token">Update token</a></h2>
<p>Update the number of allowed uses or expiry time of a token. If the request is
successful, the updated token will be returned as a registration token object
in the response body.</p>
<pre><code>PUT /_synapse/admin/v1/registration_tokens/&lt;token&gt;
</code></pre>
<p>Path parameters:</p>
<ul>
<li><code>token</code>: The registration token to update.</li>
</ul>
<p>The request body must be a JSON object and can contain the following fields:</p>
<ul>
<li><code>uses_allowed</code>: The integer number of times the token can be used to complete
a registration before it becomes invalid. By setting <code>uses_allowed</code> to <code>0</code>
the token can be easily made invalid without deleting it.
If <code>null</code> the token will have an unlimited number of uses.</li>
<li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
If <code>null</code> the token will not expire.</li>
</ul>
<p>If a field is omitted its value is not modified.</p>
<p>Example:</p>
<pre><code>PUT /_synapse/admin/v1/registration_tokens/defg

{
    &quot;expiry_time&quot;: 4781243146000    // 2121-07-06 11:05:46 UTC
}
</code></pre>
<pre><code>200 OK

{
    &quot;token&quot;: &quot;defg&quot;,
    &quot;uses_allowed&quot;: 1,
    &quot;pending&quot;: 0,
    &quot;completed&quot;: 0,
    &quot;expiry_time&quot;: 4781243146000
}
</code></pre>
<h2 id="delete-token"><a class="header" href="#delete-token">Delete token</a></h2>
<p>Delete a registration token. If the request is successful, the response body
will be an empty JSON object.</p>
<pre><code>DELETE /_synapse/admin/v1/registration_tokens/&lt;token&gt;
</code></pre>
<p>Path parameters:</p>
<ul>
<li><code>token</code>: The registration token to delete.</li>
</ul>
<p>Example:</p>
<pre><code>DELETE /_synapse/admin/v1/registration_tokens/wxyz
</code></pre>
<pre><code>200 OK

{}
</code></pre>
<h2 id="errors"><a class="header" href="#errors">Errors</a></h2>
<p>If a request fails a &quot;standard error response&quot; will be returned as defined in
the <a href="https://matrix.org/docs/spec/client_server/r0.6.1#api-standards">Matrix Client-Server API specification</a>.</p>
<p>For example, if the token specified in a path parameter does not exist a
<code>404 Not Found</code> error will be returned.</p>
<pre><code>GET /_synapse/admin/v1/registration_tokens/1234
</code></pre>
<pre><code>404 Not Found

{
    &quot;errcode&quot;: &quot;M_NOT_FOUND&quot;,
    &quot;error&quot;: &quot;No such registration token: 1234&quot;
}
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="edit-room-membership-api"><a class="header" href="#edit-room-membership-api">Edit Room Membership API</a></h1>
<p>This API allows an administrator to join an user account with a given <code>user_id</code>
to a room with a given <code>room_id_or_alias</code>. You can only modify the membership of
local users. The server administrator must be in the room and have permission to
invite users.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<h2 id="parameters"><a class="header" href="#parameters">Parameters</a></h2>
<p>The following parameters are available:</p>
<ul>
<li><code>user_id</code> - Fully qualified user: for example, <code>@user:server.com</code>.</li>
<li><code>room_id_or_alias</code> - The room identifier or alias to join: for example,
<code>!636q39766251:server.com</code>.</li>
</ul>
<h2 id="usage-1"><a class="header" href="#usage-1">Usage</a></h2>
<pre><code>POST /_synapse/admin/v1/join/&lt;room_id_or_alias&gt;

{
  &quot;user_id&quot;: &quot;@user:server.com&quot;
}
</code></pre>
<p>Response:</p>
<pre><code class="language-json">{
  &quot;room_id&quot;: &quot;!636q39766251:server.com&quot;
}
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="list-room-api"><a class="header" href="#list-room-api">List Room API</a></h1>
<p>The List Room admin API allows server admins to get a list of rooms on their
server. There are various parameters available that allow for filtering and
sorting the returned list. This API supports pagination.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<p><strong>Parameters</strong></p>
<p>The following query parameters are available:</p>
<ul>
<li>
<p><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</p>
</li>
<li>
<p><code>limit</code> - Maximum amount of rooms to return. Defaults to <code>100</code>.</p>
</li>
<li>
<p><code>order_by</code> - The method in which to sort the returned list of rooms. Valid values are:</p>
<ul>
<li><code>alphabetical</code> - Same as <code>name</code>. This is deprecated.</li>
<li><code>size</code> - Same as <code>joined_members</code>. This is deprecated.</li>
<li><code>name</code> - Rooms are ordered alphabetically by room name. This is the default.</li>
<li><code>canonical_alias</code> - Rooms are ordered alphabetically by main alias address of the room.</li>
<li><code>joined_members</code> - Rooms are ordered by the number of members. Largest to smallest.</li>
<li><code>joined_local_members</code> - Rooms are ordered by the number of local members. Largest to smallest.</li>
<li><code>version</code> - Rooms are ordered by room version. Largest to smallest.</li>
<li><code>creator</code> - Rooms are ordered alphabetically by creator of the room.</li>
<li><code>encryption</code> - Rooms are ordered alphabetically by the end-to-end encryption algorithm.</li>
<li><code>federatable</code> - Rooms are ordered by whether the room is federatable.</li>
<li><code>public</code> - Rooms are ordered by visibility in room list.</li>
<li><code>join_rules</code> - Rooms are ordered alphabetically by join rules of the room.</li>
<li><code>guest_access</code> - Rooms are ordered alphabetically by guest access option of the room.</li>
<li><code>history_visibility</code> - Rooms are ordered alphabetically by visibility of history of the room.</li>
<li><code>state_events</code> - Rooms are ordered by number of state events. Largest to smallest.</li>
</ul>
</li>
<li>
<p><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
</li>
<li>
<p><code>search_term</code> - Filter rooms by their room name, canonical alias and room id.
Specifically, rooms are selected if the search term is contained in</p>
<ul>
<li>the room's name,</li>
<li>the local part of the room's canonical alias, or</li>
<li>the complete (local and server part) room's id (case sensitive).</li>
</ul>
<p>Defaults to no filtering.</p>
</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are possible in the JSON response body:</p>
<ul>
<li><code>rooms</code> - An array of objects, each containing information about a room.
<ul>
<li>Room objects contain the following fields:
<ul>
<li><code>room_id</code> - The ID of the room.</li>
<li><code>name</code> - The name of the room.</li>
<li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
<li><code>joined_members</code> - How many users are currently in the room.</li>
<li><code>joined_local_members</code> - How many local users are currently in the room.</li>
<li><code>version</code> - The version of the room as a string.</li>
<li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
<li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
<li><code>federatable</code> - Whether users on other servers can join this room.</li>
<li><code>public</code> - Whether the room is visible in room directory.</li>
<li><code>join_rules</code> - The type of rules used for users wishing to join this room. One of: [&quot;public&quot;, &quot;knock&quot;, &quot;invite&quot;, &quot;private&quot;].</li>
<li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
<li><code>history_visibility</code> - Who can see the room history. One of: [&quot;invited&quot;, &quot;joined&quot;, &quot;shared&quot;, &quot;world_readable&quot;].</li>
<li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
<li><code>room_type</code> - The type of the room taken from the room's creation event; for example &quot;m.space&quot; if the room is a space. If the room does not define a type, the value will be <code>null</code>.</li>
</ul>
</li>
</ul>
</li>
<li><code>offset</code> - The current pagination offset in rooms. This parameter should be
used instead of <code>next_token</code> for room offset as <code>next_token</code> is
not intended to be parsed.</li>
<li><code>total_rooms</code> - The total number of rooms this query can return. Using this
and <code>offset</code>, you have enough information to know the current
progression through the list.</li>
<li><code>next_batch</code> - If this field is present, we know that there are potentially
more rooms on the server that did not all fit into this response.
We can use <code>next_batch</code> to get the &quot;next page&quot; of results. To do
so, simply repeat your request, setting the <code>from</code> parameter to
the value of <code>next_batch</code>.</li>
<li><code>prev_batch</code> - If this field is present, it is possible to paginate backwards.
Use <code>prev_batch</code> for the <code>from</code> value in the next request to
get the &quot;previous page&quot; of results.</li>
</ul>
<p>The API is:</p>
<p>A standard request with no filtering:</p>
<pre><code>GET /_synapse/admin/v1/rooms
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;rooms&quot;: [
    {
      &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
      &quot;name&quot;: &quot;Matrix HQ&quot;,
      &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
      &quot;joined_members&quot;: 8326,
      &quot;joined_local_members&quot;: 2,
      &quot;version&quot;: &quot;1&quot;,
      &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
      &quot;encryption&quot;: null,
      &quot;federatable&quot;: true,
      &quot;public&quot;: true,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 93534,
      &quot;room_type&quot;: &quot;m.space&quot;
    },
    ... (8 hidden items) ...
    {
      &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
      &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
      &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
      &quot;joined_members&quot;: 314,
      &quot;joined_local_members&quot;: 20,
      &quot;version&quot;: &quot;4&quot;,
      &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
      &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
      &quot;federatable&quot;: true,
      &quot;public&quot;: false,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 8345,
      &quot;room_type&quot;: null
    }
  ],
  &quot;offset&quot;: 0,
  &quot;total_rooms&quot;: 10
}
</code></pre>
<p>Filtering by room name:</p>
<pre><code>GET /_synapse/admin/v1/rooms?search_term=TWIM
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;rooms&quot;: [
    {
      &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
      &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
      &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
      &quot;joined_members&quot;: 314,
      &quot;joined_local_members&quot;: 20,
      &quot;version&quot;: &quot;4&quot;,
      &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
      &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
      &quot;federatable&quot;: true,
      &quot;public&quot;: false,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 8,
      &quot;room_type&quot;: null
    }
  ],
  &quot;offset&quot;: 0,
  &quot;total_rooms&quot;: 1
}
</code></pre>
<p>Paginating through a list of rooms:</p>
<pre><code>GET /_synapse/admin/v1/rooms?order_by=size
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;rooms&quot;: [
    {
      &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
      &quot;name&quot;: &quot;Matrix HQ&quot;,
      &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
      &quot;joined_members&quot;: 8326,
      &quot;joined_local_members&quot;: 2,
      &quot;version&quot;: &quot;1&quot;,
      &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
      &quot;encryption&quot;: null,
      &quot;federatable&quot;: true,
      &quot;public&quot;: true,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 93534,
      &quot;room_type&quot;: null
    },
    ... (98 hidden items) ...
    {
      &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
      &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
      &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
      &quot;joined_members&quot;: 314,
      &quot;joined_local_members&quot;: 20,
      &quot;version&quot;: &quot;4&quot;,
      &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
      &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
      &quot;federatable&quot;: true,
      &quot;public&quot;: false,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 8345,
      &quot;room_type&quot;: &quot;m.space&quot;
    }
  ],
  &quot;offset&quot;: 0,
  &quot;total_rooms&quot;: 150,
  &quot;next_token&quot;: 100
}
</code></pre>
<p>The presence of the <code>next_token</code> parameter tells us that there are more rooms
than returned in this request, and we need to make another request to get them.
To get the next batch of room results, we repeat our request, setting the <code>from</code>
parameter to the value of <code>next_token</code>.</p>
<pre><code>GET /_synapse/admin/v1/rooms?order_by=size&amp;from=100
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;rooms&quot;: [
    {
      &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
      &quot;name&quot;: &quot;Music Theory&quot;,
      &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
      &quot;joined_members&quot;: 127,
      &quot;joined_local_members&quot;: 2,
      &quot;version&quot;: &quot;1&quot;,
      &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
      &quot;encryption&quot;: null,
      &quot;federatable&quot;: true,
      &quot;public&quot;: true,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 93534,
      &quot;room_type&quot;: &quot;m.space&quot;

    },
    ... (48 hidden items) ...
    {
      &quot;room_id&quot;: &quot;!twcBhHVdZlQWuuxBhN:termina.org.uk&quot;,
      &quot;name&quot;: &quot;weechat-matrix&quot;,
      &quot;canonical_alias&quot;: &quot;#weechat-matrix:termina.org.uk&quot;,
      &quot;joined_members&quot;: 137,
      &quot;joined_local_members&quot;: 20,
      &quot;version&quot;: &quot;4&quot;,
      &quot;creator&quot;: &quot;@foo:termina.org.uk&quot;,
      &quot;encryption&quot;: null,
      &quot;federatable&quot;: true,
      &quot;public&quot;: true,
      &quot;join_rules&quot;: &quot;invite&quot;,
      &quot;guest_access&quot;: null,
      &quot;history_visibility&quot;: &quot;shared&quot;,
      &quot;state_events&quot;: 8345,
      &quot;room_type&quot;: null

    }
  ],
  &quot;offset&quot;: 100,
  &quot;prev_batch&quot;: 0,
  &quot;total_rooms&quot;: 150
}
</code></pre>
<p>Once the <code>next_token</code> parameter is no longer present, we know we've reached the
end of the list.</p>
<h1 id="room-details-api"><a class="header" href="#room-details-api">Room Details API</a></h1>
<p>The Room Details admin API allows server admins to get all details of a room.</p>
<p>The following fields are possible in the JSON response body:</p>
<ul>
<li><code>room_id</code> - The ID of the room.</li>
<li><code>name</code> - The name of the room.</li>
<li><code>topic</code> - The topic of the room.</li>
<li><code>avatar</code> - The <code>mxc</code> URI to the avatar of the room.</li>
<li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
<li><code>joined_members</code> - How many users are currently in the room.</li>
<li><code>joined_local_members</code> - How many local users are currently in the room.</li>
<li><code>joined_local_devices</code> - How many local devices are currently in the room.</li>
<li><code>version</code> - The version of the room as a string.</li>
<li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
<li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
<li><code>federatable</code> - Whether users on other servers can join this room.</li>
<li><code>public</code> - Whether the room is visible in room directory.</li>
<li><code>join_rules</code> - The type of rules used for users wishing to join this room. One of: [&quot;public&quot;, &quot;knock&quot;, &quot;invite&quot;, &quot;private&quot;].</li>
<li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
<li><code>history_visibility</code> - Who can see the room history. One of: [&quot;invited&quot;, &quot;joined&quot;, &quot;shared&quot;, &quot;world_readable&quot;].</li>
<li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
<li><code>room_type</code> - The type of the room taken from the room's creation event; for example &quot;m.space&quot; if the room is a space.
If the room does not define a type, the value will be <code>null</code>.</li>
<li><code>forgotten</code> - Whether all local users have
<a href="https://spec.matrix.org/latest/client-server-api/#leaving-rooms">forgotten</a> the room.</li>
</ul>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  &quot;name&quot;: &quot;Music Theory&quot;,
  &quot;avatar&quot;: &quot;mxc://matrix.org/AQDaVFlbkQoErdOgqWRgiGSV&quot;,
  &quot;topic&quot;: &quot;Theory, Composition, Notation, Analysis&quot;,
  &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  &quot;joined_members&quot;: 127,
  &quot;joined_local_members&quot;: 2,
  &quot;joined_local_devices&quot;: 2,
  &quot;version&quot;: &quot;1&quot;,
  &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  &quot;encryption&quot;: null,
  &quot;federatable&quot;: true,
  &quot;public&quot;: true,
  &quot;join_rules&quot;: &quot;invite&quot;,
  &quot;guest_access&quot;: null,
  &quot;history_visibility&quot;: &quot;shared&quot;,
  &quot;state_events&quot;: 93534,
  &quot;room_type&quot;: &quot;m.space&quot;,
  &quot;forgotten&quot;: false
}
</code></pre>
<p><em>Changed in Synapse 1.66:</em> Added the <code>forgotten</code> key to the response body.</p>
<h1 id="room-members-api"><a class="header" href="#room-members-api">Room Members API</a></h1>
<p>The Room Members admin API allows server admins to get a list of all members of a room.</p>
<p>The response includes the following fields:</p>
<ul>
<li><code>members</code> - A list of all the members that are present in the room, represented by their ids.</li>
<li><code>total</code> - Total number of members in the room.</li>
</ul>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/members
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;members&quot;: [
    &quot;@foo:matrix.org&quot;,
    &quot;@bar:matrix.org&quot;,
    &quot;@foobar:matrix.org&quot;
  ],
  &quot;total&quot;: 3
}
</code></pre>
<h1 id="room-state-api"><a class="header" href="#room-state-api">Room State API</a></h1>
<p>The Room State admin API allows server admins to get a list of all state events in a room.</p>
<p>The response includes the following fields:</p>
<ul>
<li><code>state</code> - The current state of the room at the time of request.</li>
</ul>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/state
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;state&quot;: [
    {&quot;type&quot;: &quot;m.room.create&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
    {&quot;type&quot;: &quot;m.room.power_levels&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
    {&quot;type&quot;: &quot;m.room.name&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true}
  ]
}
</code></pre>
<h1 id="room-messages-api"><a class="header" href="#room-messages-api">Room Messages API</a></h1>
<p>The Room Messages admin API allows server admins to get all messages
sent to a room in a given timeframe. There are various parameters available
that allow for filtering and ordering the returned list. This API supports pagination.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<p>This endpoint mirrors the <a href="https://spec.matrix.org/v1.1/client-server-api/#get_matrixclientv3roomsroomidmessages">Matrix Spec defined Messages API</a>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/messages
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following path parameters are required:</p>
<ul>
<li><code>room_id</code> - The ID of the room you wish you fetch messages from.</li>
</ul>
<p>The following query parameters are available:</p>
<ul>
<li><code>from</code> (required) - The token to start returning events from. This token can be obtained from a prev_batch
or next_batch token returned by the /sync endpoint, or from an end token returned by a previous request to this endpoint.</li>
<li><code>to</code> - The token to stop returning events at.</li>
<li><code>limit</code> - The maximum number of events to return. Defaults to <code>10</code>.</li>
<li><code>filter</code> - A JSON RoomEventFilter to filter returned events with.</li>
<li><code>dir</code> - The direction to return events from. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are possible in the JSON response body:</p>
<ul>
<li><code>chunk</code> - A list of room events. The order depends on the dir parameter.
Note that an empty chunk does not necessarily imply that no more events are available. Clients should continue to paginate until no end property is returned.</li>
<li><code>end</code> - A token corresponding to the end of chunk. This token can be passed back to this endpoint to request further events.
If no further events are available, this property is omitted from the response.</li>
<li><code>start</code> - A token corresponding to the start of chunk.</li>
<li><code>state</code> - A list of state events relevant to showing the chunk.</li>
</ul>
<p><strong>Example</strong></p>
<p>For more details on each chunk, read <a href="https://spec.matrix.org/v1.1/client-server-api/#get_matrixclientv3roomsroomidmessages">the Matrix specification</a>.</p>
<pre><code class="language-json">{
  &quot;chunk&quot;: [
    {
      &quot;content&quot;: {
        &quot;body&quot;: &quot;This is an example text message&quot;,
        &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
        &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;,
        &quot;msgtype&quot;: &quot;m.text&quot;
      },
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;type&quot;: &quot;m.room.message&quot;,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      }
    },
    {
      &quot;content&quot;: {
        &quot;name&quot;: &quot;The room name&quot;
      },
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;state_key&quot;: &quot;&quot;,
      &quot;type&quot;: &quot;m.room.name&quot;,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      }
    },
    {
      &quot;content&quot;: {
        &quot;body&quot;: &quot;Gangnam Style&quot;,
        &quot;info&quot;: {
          &quot;duration&quot;: 2140786,
          &quot;h&quot;: 320,
          &quot;mimetype&quot;: &quot;video/mp4&quot;,
          &quot;size&quot;: 1563685,
          &quot;thumbnail_info&quot;: {
            &quot;h&quot;: 300,
            &quot;mimetype&quot;: &quot;image/jpeg&quot;,
            &quot;size&quot;: 46144,
            &quot;w&quot;: 300
          },
          &quot;thumbnail_url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;,
          &quot;w&quot;: 480
        },
        &quot;msgtype&quot;: &quot;m.video&quot;,
        &quot;url&quot;: &quot;mxc://example.org/a526eYUSFFxlgbQYZmo442&quot;
      },
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;type&quot;: &quot;m.room.message&quot;,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      }
    }
  ],
  &quot;end&quot;: &quot;t47409-4357353_219380_26003_2265&quot;,
  &quot;start&quot;: &quot;t47429-4392820_219380_26003_2265&quot;
}
</code></pre>
<h1 id="room-timestamp-to-event-api"><a class="header" href="#room-timestamp-to-event-api">Room Timestamp to Event API</a></h1>
<p>The Room Timestamp to Event API endpoint fetches the <code>event_id</code> of the closest event to the given
timestamp (<code>ts</code> query parameter) in the given direction (<code>dir</code> query parameter).</p>
<p>Useful for cases like jump to date so you can start paginating messages from
a given date in the archive.</p>
<p>The API is:</p>
<pre><code>  GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/timestamp_to_event
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following path parameters are required:</p>
<ul>
<li><code>room_id</code> - The ID of the room you wish to check.</li>
</ul>
<p>The following query parameters are available:</p>
<ul>
<li><code>ts</code> - a timestamp in milliseconds where we will find the closest event in
the given direction.</li>
<li><code>dir</code> - can be <code>f</code> or <code>b</code> to indicate forwards and backwards in time from the
given timestamp. Defaults to <code>f</code>.</li>
</ul>
<p><strong>Response</strong></p>
<ul>
<li><code>event_id</code> - converted from timestamp</li>
</ul>
<h1 id="block-room-api"><a class="header" href="#block-room-api">Block Room API</a></h1>
<p>The Block Room admin API allows server admins to block and unblock rooms,
and query to see if a given room is blocked.
This API can be used to pre-emptively block a room, even if it's unknown to this
homeserver. Users will be prevented from joining a blocked room.</p>
<h2 id="block-or-unblock-a-room"><a class="header" href="#block-or-unblock-a-room">Block or unblock a room</a></h2>
<p>The API is:</p>
<pre><code>PUT /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
    &quot;block&quot;: true
}
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;block&quot;: true
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>room_id</code> - The ID of the room.</li>
</ul>
<p>The following JSON body parameters are available:</p>
<ul>
<li><code>block</code> - If <code>true</code> the room will be blocked and if <code>false</code> the room will be unblocked.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are possible in the JSON response body:</p>
<ul>
<li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
</ul>
<h2 id="get-block-status"><a class="header" href="#get-block-status">Get block status</a></h2>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;block&quot;: true,
    &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>room_id</code> - The ID of the room.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are possible in the JSON response body:</p>
<ul>
<li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
<li><code>user_id</code> - An optional string. If the room is blocked (<code>block</code> is <code>true</code>) shows
the user who has add the room to blocking list. Otherwise it is not displayed.</li>
</ul>
<h1 id="delete-room-api"><a class="header" href="#delete-room-api">Delete Room API</a></h1>
<p>The Delete Room admin API allows server admins to remove rooms from the server
and block these rooms.</p>
<p>Shuts down a room. Moves all local users and room aliases automatically to a
new room if <code>new_room_user_id</code> is set. Otherwise local users only
leave the room without any information.</p>
<p>The new room will be created with the user specified by the <code>new_room_user_id</code> parameter
as room administrator and will contain a message explaining what happened. Users invited
to the new room will have power level <code>-10</code> by default, and thus be unable to speak.</p>
<p>If <code>block</code> is <code>true</code>, users will be prevented from joining the old room.
This option can in <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> also be used to pre-emptively
block a room, even if it's unknown to this homeserver. In this case, the room will be
blocked, and no further action will be taken. If <code>block</code> is <code>false</code>, attempting to
delete an unknown room is invalid and will be rejected as a bad request.</p>
<p>This API will remove all trace of the old room from your database after removing
all local users. If <code>purge</code> is <code>true</code> (the default), all traces of the old room will
be removed from your database after removing all local users. If you do not want
this to happen, set <code>purge</code> to <code>false</code>.
Depending on the amount of history being purged, a call to the API may take
several minutes or longer.</p>
<p>The local server will only have the power to move local user and room aliases to
the new room. Users on other servers will be unaffected.</p>
<h2 id="version-1-old-version"><a class="header" href="#version-1-old-version">Version 1 (old version)</a></h2>
<p>This version works synchronously. That means you only get the response once the server has
finished the action, which may take a long time. If you request the same action
a second time, and the server has not finished the first one, the second request will block.
This is fixed in version 2 of this API. The parameters are the same in both APIs.
This API will become deprecated in the future.</p>
<p>The API is:</p>
<pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id&gt;
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
    &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
    &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
    &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
    &quot;block&quot;: true,
    &quot;purge&quot;: true
}
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;kicked_users&quot;: [
        &quot;@foobar:example.com&quot;
    ],
    &quot;failed_to_kick_users&quot;: [],
    &quot;local_aliases&quot;: [
        &quot;#badroom:example.com&quot;,
        &quot;#evilsaloon:example.com&quot;
    ],
    &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
}
</code></pre>
<p>The parameters and response values have the same format as
<a href="admin_api/rooms.html#version-2-new-version">version 2</a> of the API.</p>
<h2 id="version-2-new-version"><a class="header" href="#version-2-new-version">Version 2 (new version)</a></h2>
<p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
<p>This version works asynchronously, meaning you get the response from server immediately
while the server works on that task in background. You can then request the status of the action
to check if it has completed.</p>
<p>The API is:</p>
<pre><code>DELETE /_synapse/admin/v2/rooms/&lt;room_id&gt;
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
    &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
    &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
    &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
    &quot;block&quot;: true,
    &quot;purge&quot;: true
}
</code></pre>
<p>The API starts the shut down and purge running, and returns immediately with a JSON body with
a purge id:</p>
<pre><code class="language-json">{
    &quot;delete_id&quot;: &quot;&lt;opaque id&gt;&quot;
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>room_id</code> - The ID of the room.</li>
</ul>
<p>The following JSON body parameters are available:</p>
<ul>
<li><code>new_room_user_id</code> - Optional. If set, a new room will be created with this user ID
as the creator and admin, and all users in the old room will be moved into that
room. If not set, no new room will be created and the users will just be removed
from the old room. The user ID must be on the local server, but does not necessarily
have to belong to a registered user.</li>
<li><code>room_name</code> - Optional. A string representing the name of the room that new users will be
invited to. Defaults to <code>Content Violation Notification</code></li>
<li><code>message</code> - Optional. A string containing the first message that will be sent as
<code>new_room_user_id</code> in the new room. Ideally this will clearly convey why the
original room was shut down. Defaults to <code>Sharing illegal content on this server is not permitted and rooms in violation will be blocked.</code></li>
<li><code>block</code> - Optional. If set to <code>true</code>, this room will be added to a blocking list,
preventing future attempts to join the room. Rooms can be blocked
even if they're not yet known to the homeserver (only with
<a href="admin_api/rooms.html#version-1-old-version">Version 1</a> of the API). Defaults to <code>false</code>.</li>
<li><code>purge</code> - Optional. If set to <code>true</code>, it will remove all traces of the room from your database.
Defaults to <code>true</code>.</li>
<li><code>force_purge</code> - Optional, and ignored unless <code>purge</code> is <code>true</code>. If set to <code>true</code>, it
will force a purge to go ahead even if there are local users still in the room. Do not
use this unless a regular <code>purge</code> operation fails, as it could leave those users'
clients in a confused state.</li>
</ul>
<p>The JSON body must not be empty. The body must be at least <code>{}</code>.</p>
<h2 id="status-of-deleting-rooms"><a class="header" href="#status-of-deleting-rooms">Status of deleting rooms</a></h2>
<p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
<p>It is possible to query the status of the background task for deleting rooms.
The status can be queried up to 24 hours after completion of the task,
or until Synapse is restarted (whichever happens first).</p>
<h3 id="query-by-room_id"><a class="header" href="#query-by-room_id">Query by <code>room_id</code></a></h3>
<p>With this API you can get the status of all active deletion tasks, and all those completed in the last 24h,
for the given <code>room_id</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v2/rooms/&lt;room_id&gt;/delete_status
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;results&quot;: [
        {
            &quot;delete_id&quot;: &quot;delete_id1&quot;,
            &quot;status&quot;: &quot;failed&quot;,
            &quot;error&quot;: &quot;error message&quot;,
            &quot;shutdown_room&quot;: {
                &quot;kicked_users&quot;: [],
                &quot;failed_to_kick_users&quot;: [],
                &quot;local_aliases&quot;: [],
                &quot;new_room_id&quot;: null
            }
        }, {
            &quot;delete_id&quot;: &quot;delete_id2&quot;,
            &quot;status&quot;: &quot;purging&quot;,
            &quot;shutdown_room&quot;: {
                &quot;kicked_users&quot;: [
                    &quot;@foobar:example.com&quot;
                ],
                &quot;failed_to_kick_users&quot;: [],
                &quot;local_aliases&quot;: [
                    &quot;#badroom:example.com&quot;,
                    &quot;#evilsaloon:example.com&quot;
                ],
                &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
            }
        }
    ]
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>room_id</code> - The ID of the room.</li>
</ul>
<h3 id="query-by-delete_id"><a class="header" href="#query-by-delete_id">Query by <code>delete_id</code></a></h3>
<p>With this API you can get the status of one specific task by <code>delete_id</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v2/rooms/delete_status/&lt;delete_id&gt;
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;status&quot;: &quot;purging&quot;,
    &quot;shutdown_room&quot;: {
        &quot;kicked_users&quot;: [
            &quot;@foobar:example.com&quot;
        ],
        &quot;failed_to_kick_users&quot;: [],
        &quot;local_aliases&quot;: [
            &quot;#badroom:example.com&quot;,
            &quot;#evilsaloon:example.com&quot;
        ],
        &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
    }
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>delete_id</code> - The ID for this delete.</li>
</ul>
<h3 id="response"><a class="header" href="#response">Response</a></h3>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>results</code> - An array of objects, each containing information about one task.
This field is omitted from the result when you query by <code>delete_id</code>.
Task objects contain the following fields:
<ul>
<li><code>delete_id</code> - The ID for this purge if you query by <code>room_id</code>.</li>
<li><code>status</code> - The status will be one of:
<ul>
<li><code>shutting_down</code> - The process is removing users from the room.</li>
<li><code>purging</code> - The process is purging the room and event data from database.</li>
<li><code>complete</code> - The process has completed successfully.</li>
<li><code>failed</code> - The process is aborted, an error has occurred.</li>
</ul>
</li>
<li><code>error</code> - A string that shows an error message if <code>status</code> is <code>failed</code>.
Otherwise this field is hidden.</li>
<li><code>shutdown_room</code> - An object containing information about the result of shutting down the room.
<em>Note:</em> The result is shown after removing the room members.
The delete process can still be running. Please pay attention to the <code>status</code>.
<ul>
<li><code>kicked_users</code> - An array of users (<code>user_id</code>) that were kicked.</li>
<li><code>failed_to_kick_users</code> - An array of users (<code>user_id</code>) that that were not kicked.</li>
<li><code>local_aliases</code> - An array of strings representing the local aliases that were
migrated from the old room to the new.</li>
<li><code>new_room_id</code> - A string representing the room ID of the new room, or <code>null</code> if
no such room was created.</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="undoing-room-deletions"><a class="header" href="#undoing-room-deletions">Undoing room deletions</a></h2>
<p><em>Note</em>: This guide may be outdated by the time you read it. By nature of room deletions being performed at the database level,
the structure can and does change without notice.</p>
<p>First, it's important to understand that a room deletion is very destructive. Undoing a deletion is not as simple as pretending it
never happened - work has to be done to move forward instead of resetting the past. In fact, in some cases it might not be possible
to recover at all:</p>
<ul>
<li>If the room was invite-only, your users will need to be re-invited.</li>
<li>If the room no longer has any members at all, it'll be impossible to rejoin.</li>
<li>The first user to rejoin will have to do so via an alias on a different
server (or receive an invite from a user on a different server).</li>
</ul>
<p>With all that being said, if you still want to try and recover the room:</p>
<ol>
<li>
<p>If the room was <code>block</code>ed, you must unblock it on your server. This can be
accomplished as follows:</p>
<ol>
<li>For safety reasons, shut down Synapse.</li>
<li>In the database, run <code>DELETE FROM blocked_rooms WHERE room_id = '!example:example.org';</code>
<ul>
<li>For caution: it's recommended to run this in a transaction: <code>BEGIN; DELETE ...;</code>, verify you got 1 result, then <code>COMMIT;</code>.</li>
<li>The room ID is the same one supplied to the delete room API, not the Content Violation room.</li>
</ul>
</li>
<li>Restart Synapse.</li>
</ol>
<p>This step is unnecessary if <code>block</code> was not set.</p>
</li>
<li>
<p>Any room aliases on your server that pointed to the deleted room may have
been deleted, or redirected to the Content Violation room. These will need
to be restored manually.</p>
</li>
<li>
<p>Users on your server that were in the deleted room will have been kicked
from the room. Consider whether you want to update their membership
(possibly via the <a href="admin_api/room_membership.html">Edit Room Membership API</a>) or let
them handle rejoining themselves.</p>
</li>
<li>
<p>If <code>new_room_user_id</code> was given, a 'Content Violation' will have been
created. Consider whether you want to delete that roomm.</p>
</li>
</ol>
<h1 id="make-room-admin-api"><a class="header" href="#make-room-admin-api">Make Room Admin API</a></h1>
<p>Grants another user the highest power available to a local user who is in the room.
If the user is not in the room, and it is not publicly joinable, then invite the user.</p>
<p>By default the server admin (the caller) is granted power, but another user can
optionally be specified, e.g.:</p>
<pre><code>POST /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/make_room_admin
{
    &quot;user_id&quot;: &quot;@foo:example.com&quot;
}
</code></pre>
<h1 id="forward-extremities-admin-api"><a class="header" href="#forward-extremities-admin-api">Forward Extremities Admin API</a></h1>
<p>Enables querying and deleting forward extremities from rooms. When a lot of forward
extremities accumulate in a room, performance can become degraded. For details, see
<a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
<h2 id="check-for-forward-extremities"><a class="header" href="#check-for-forward-extremities">Check for forward extremities</a></h2>
<p>To check the status of forward extremities for a room:</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
</code></pre>
<p>A response as follows will be returned:</p>
<pre><code class="language-json">{
  &quot;count&quot;: 1,
  &quot;results&quot;: [
    {
      &quot;event_id&quot;: &quot;$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdefgh&quot;,
      &quot;state_group&quot;: 439,
      &quot;depth&quot;: 123,
      &quot;received_ts&quot;: 1611263016761
    }
  ]
}
</code></pre>
<h2 id="deleting-forward-extremities"><a class="header" href="#deleting-forward-extremities">Deleting forward extremities</a></h2>
<p><strong>WARNING</strong>: Please ensure you know what you're doing and have read
the related issue <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.
Under no situations should this API be executed as an automated maintenance task!</p>
<p>If a room has lots of forward extremities, the extra can be
deleted as follows:</p>
<pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
</code></pre>
<p>A response as follows will be returned, indicating the amount of forward extremities
that were deleted.</p>
<pre><code class="language-json">{
  &quot;deleted&quot;: 1
}
</code></pre>
<h1 id="event-context-api"><a class="header" href="#event-context-api">Event Context API</a></h1>
<p>This API lets a client find the context of an event. This is designed primarily to investigate abuse reports.</p>
<pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/context/&lt;event_id&gt;
</code></pre>
<p>This API mimmicks <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-rooms-roomid-context-eventid">GET /_matrix/client/r0/rooms/{roomId}/context/{eventId}</a>. Please refer to the link for all details on parameters and reseponse.</p>
<p>Example response:</p>
<pre><code class="language-json">{
  &quot;end&quot;: &quot;t29-57_2_0_2&quot;,
  &quot;events_after&quot;: [
    {
      &quot;content&quot;: {
        &quot;body&quot;: &quot;This is an example text message&quot;,
        &quot;msgtype&quot;: &quot;m.text&quot;,
        &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
        &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;
      },
      &quot;type&quot;: &quot;m.room.message&quot;,
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      }
    }
  ],
  &quot;event&quot;: {
    &quot;content&quot;: {
      &quot;body&quot;: &quot;filename.jpg&quot;,
      &quot;info&quot;: {
        &quot;h&quot;: 398,
        &quot;w&quot;: 394,
        &quot;mimetype&quot;: &quot;image/jpeg&quot;,
        &quot;size&quot;: 31037
      },
      &quot;url&quot;: &quot;mxc://example.org/JWEIFJgwEIhweiWJE&quot;,
      &quot;msgtype&quot;: &quot;m.image&quot;
    },
    &quot;type&quot;: &quot;m.room.message&quot;,
    &quot;event_id&quot;: &quot;$f3h4d129462ha:example.com&quot;,
    &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
    &quot;sender&quot;: &quot;@example:example.org&quot;,
    &quot;origin_server_ts&quot;: 1432735824653,
    &quot;unsigned&quot;: {
      &quot;age&quot;: 1234
    }
  },
  &quot;events_before&quot;: [
    {
      &quot;content&quot;: {
        &quot;body&quot;: &quot;something-important.doc&quot;,
        &quot;filename&quot;: &quot;something-important.doc&quot;,
        &quot;info&quot;: {
          &quot;mimetype&quot;: &quot;application/msword&quot;,
          &quot;size&quot;: 46144
        },
        &quot;msgtype&quot;: &quot;m.file&quot;,
        &quot;url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;
      },
      &quot;type&quot;: &quot;m.room.message&quot;,
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      }
    }
  ],
  &quot;start&quot;: &quot;t27-54_2_0_2&quot;,
  &quot;state&quot;: [
    {
      &quot;content&quot;: {
        &quot;creator&quot;: &quot;@example:example.org&quot;,
        &quot;room_version&quot;: &quot;1&quot;,
        &quot;m.federate&quot;: true,
        &quot;predecessor&quot;: {
          &quot;event_id&quot;: &quot;$something:example.org&quot;,
          &quot;room_id&quot;: &quot;!oldroom:example.org&quot;
        }
      },
      &quot;type&quot;: &quot;m.room.create&quot;,
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      },
      &quot;state_key&quot;: &quot;&quot;
    },
    {
      &quot;content&quot;: {
        &quot;membership&quot;: &quot;join&quot;,
        &quot;avatar_url&quot;: &quot;mxc://example.org/SEsfnsuifSDFSSEF&quot;,
        &quot;displayname&quot;: &quot;Alice Margatroid&quot;
      },
      &quot;type&quot;: &quot;m.room.member&quot;,
      &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
      &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
      &quot;sender&quot;: &quot;@example:example.org&quot;,
      &quot;origin_server_ts&quot;: 1432735824653,
      &quot;unsigned&quot;: {
        &quot;age&quot;: 1234
      },
      &quot;state_key&quot;: &quot;@alice:example.org&quot;
    }
  ]
}
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices-1"><a class="header" href="#server-notices-1">Server Notices</a></h1>
<p>The API to send notices is as follows:</p>
<pre><code>POST /_synapse/admin/v1/send_server_notice
</code></pre>
<p>or:</p>
<pre><code>PUT /_synapse/admin/v1/send_server_notice/{txnId}
</code></pre>
<p>You will need to authenticate with an access token for an admin user.</p>
<p>When using the <code>PUT</code> form, retransmissions with the same transaction ID will be
ignored in the same way as with <code>PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}</code>.</p>
<p>The request body should look something like the following:</p>
<pre><code class="language-json">{
    &quot;user_id&quot;: &quot;@target_user:server_name&quot;,
    &quot;content&quot;: {
        &quot;msgtype&quot;: &quot;m.text&quot;,
        &quot;body&quot;: &quot;This is my message&quot;
    }
}
</code></pre>
<p>You can optionally include the following additional parameters:</p>
<ul>
<li><code>type</code>: the type of event. Defaults to <code>m.room.message</code>.</li>
<li><code>state_key</code>: Setting this will result in a state event being sent.</li>
</ul>
<p>Once the notice has been sent, the API will return the following response:</p>
<pre><code class="language-json">{
    &quot;event_id&quot;: &quot;&lt;event_id&gt;&quot;
}
</code></pre>
<p>Note that server notices must be enabled in <code>homeserver.yaml</code> before this API
can be used. See <a href="admin_api/../server_notices.html">the server notices documentation</a> for more information.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="users-media-usage-statistics"><a class="header" href="#users-media-usage-statistics">Users' media usage statistics</a></h1>
<p>Returns information about all local media usage of users. Gives the
possibility to filter them by time and user.</p>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/statistics/users/media
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;users&quot;: [
    {
      &quot;displayname&quot;: &quot;foo_user_0&quot;,
      &quot;media_count&quot;: 2,
      &quot;media_length&quot;: 134,
      &quot;user_id&quot;: &quot;@foo_user_0:test&quot;
    },
    {
      &quot;displayname&quot;: &quot;foo_user_1&quot;,
      &quot;media_count&quot;: 2,
      &quot;media_length&quot;: 134,
      &quot;user_id&quot;: &quot;@foo_user_1:test&quot;
    }
  ],
  &quot;next_token&quot;: 3,
  &quot;total&quot;: 10
}
</code></pre>
<p>To paginate, check for <code>next_token</code> and if present, call the endpoint
again with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
<p>If the endpoint does not return a <code>next_token</code> then there are no more
reports to paginate through.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>limit</code>: string representing a positive integer - Is optional but is
used for pagination, denoting the maximum number of items to return
in this call. Defaults to <code>100</code>.</li>
<li><code>from</code>: string representing a positive integer - Is optional but used for pagination,
denoting the offset in the returned results. This should be treated as an opaque value
and not explicitly set to anything other than the return value of <code>next_token</code> from a
previous call. Defaults to <code>0</code>.</li>
<li><code>order_by</code> - string - The method in which to sort the returned list of users. Valid values are:
<ul>
<li><code>user_id</code> - Users are ordered alphabetically by <code>user_id</code>. This is the default.</li>
<li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
<li><code>media_length</code> - Users are ordered by the total size of uploaded media in bytes.
Smallest to largest.</li>
<li><code>media_count</code> - Users are ordered by number of uploaded media. Smallest to largest.</li>
</ul>
</li>
<li><code>from_ts</code> - string representing a positive integer - Considers only
files created at this timestamp or later. Unix timestamp in ms.</li>
<li><code>until_ts</code> - string representing a positive integer - Considers only
files created at this timestamp or earlier. Unix timestamp in ms.</li>
<li><code>search_term</code> - string - Filter users by their user ID localpart <strong>or</strong> displayname.
The search term can be found in any part of the string.
Defaults to no filtering.</li>
<li><code>dir</code> - string - Direction of order. Either <code>f</code> for forwards or <code>b</code> for backwards.
Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>users</code> - An array of objects, each containing information
about the user and their local media. Objects contain the following fields:
<ul>
<li><code>displayname</code> - string - Displayname of this user.</li>
<li><code>media_count</code> - integer - Number of uploaded media by this user.</li>
<li><code>media_length</code> - integer - Size of uploaded media in bytes by this user.</li>
<li><code>user_id</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
</ul>
</li>
<li><code>next_token</code> - integer - Opaque value used for pagination. See above.</li>
<li><code>total</code> - integer - Total number of users after filtering.</li>
</ul>
<h1 id="get-largest-rooms-by-size-in-database"><a class="header" href="#get-largest-rooms-by-size-in-database">Get largest rooms by size in database</a></h1>
<p>Returns the 10 largest rooms and an estimate of how much space in the database
they are taking.</p>
<p>This does not include the size of any associated media associated with the room.</p>
<p>Returns an error on SQLite.</p>
<p><em>Note:</em> This uses the planner statistics from PostgreSQL to do the estimates,
which means that the returned information can vary widely from reality. However,
it should be enough to get a rough idea of where database disk space is going.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/statistics/database/rooms
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;rooms&quot;: [
    {
      &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
      &quot;estimated_size&quot;: 47325417353
    }
  ],
}
</code></pre>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>rooms</code> - An array of objects, sorted by largest room first. Objects contain
the following fields:
<ul>
<li><code>room_id</code> - string - The room ID.</li>
<li><code>estimated_size</code> - integer - Estimated disk space used in bytes by the room
in the database.</li>
</ul>
</li>
</ul>
<p><em>Added in Synapse 1.83.0</em></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="user-admin-api"><a class="header" href="#user-admin-api">User Admin API</a></h1>
<p>To use it, you will need to authenticate by providing an <code>access_token</code>
for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
<h2 id="query-user-account"><a class="header" href="#query-user-account">Query User Account</a></h2>
<p>This API returns information about a specific user account.</p>
<p>The api is:</p>
<pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;
</code></pre>
<p>It returns a JSON body like the following:</p>
<pre><code class="language-jsonc">{
    &quot;name&quot;: &quot;@user:example.com&quot;,
    &quot;displayname&quot;: &quot;User&quot;, // can be null if not set
    &quot;threepids&quot;: [
        {
            &quot;medium&quot;: &quot;email&quot;,
            &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;,
            &quot;added_at&quot;: 1586458409743,
            &quot;validated_at&quot;: 1586458409743
        },
        {
            &quot;medium&quot;: &quot;email&quot;,
            &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;,
            &quot;added_at&quot;: 1586458409743,
            &quot;validated_at&quot;: 1586458409743
        }
    ],
    &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,  // can be null if not set
    &quot;is_guest&quot;: 0,
    &quot;admin&quot;: 0,
    &quot;deactivated&quot;: 0,
    &quot;erased&quot;: false,
    &quot;shadow_banned&quot;: 0,
    &quot;creation_ts&quot;: 1560432506,
    &quot;appservice_id&quot;: null,
    &quot;consent_server_notice_sent&quot;: null,
    &quot;consent_version&quot;: null,
    &quot;consent_ts&quot;: null,
    &quot;external_ids&quot;: [
        {
            &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
            &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
        },
        {
            &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
            &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
        }
    ],
    &quot;user_type&quot;: null
}
</code></pre>
<p>URL parameters:</p>
<ul>
<li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
</ul>
<h2 id="create-or-modify-account"><a class="header" href="#create-or-modify-account">Create or modify account</a></h2>
<p>This API allows an administrator to create or modify a user account with a
specific <code>user_id</code>.</p>
<p>This api is:</p>
<pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
    &quot;password&quot;: &quot;user_password&quot;,
    &quot;logout_devices&quot;: false,
    &quot;displayname&quot;: &quot;Alice Marigold&quot;,
    &quot;avatar_url&quot;: &quot;mxc://example.com/abcde12345&quot;,
    &quot;threepids&quot;: [
        {
            &quot;medium&quot;: &quot;email&quot;,
            &quot;address&quot;: &quot;alice@example.com&quot;
        },
        {
            &quot;medium&quot;: &quot;email&quot;,
            &quot;address&quot;: &quot;alice@domain.org&quot;
        }
    ],
    &quot;external_ids&quot;: [
        {
            &quot;auth_provider&quot;: &quot;example&quot;,
            &quot;external_id&quot;: &quot;12345&quot;
        },
        {
            &quot;auth_provider&quot;: &quot;example2&quot;,
            &quot;external_id&quot;: &quot;abc54321&quot;
        }
    ],
    &quot;admin&quot;: false,
    &quot;deactivated&quot;: false,
    &quot;user_type&quot;: null
}
</code></pre>
<p>Returns HTTP status code:</p>
<ul>
<li><code>201</code> - When a new user object was created.</li>
<li><code>200</code> - When a user was modified.</li>
</ul>
<p>URL parameters:</p>
<ul>
<li><code>user_id</code> - A fully-qualified user id. For example, <code>@user:server.com</code>.</li>
</ul>
<p>Body parameters:</p>
<ul>
<li>
<p><code>password</code> - <strong>string</strong>, optional. If provided, the user's password is updated and all
devices are logged out, unless <code>logout_devices</code> is set to <code>false</code>.</p>
</li>
<li>
<p><code>logout_devices</code> - <strong>bool</strong>, optional, defaults to <code>true</code>. If set to <code>false</code>, devices aren't
logged out even when <code>password</code> is provided.</p>
</li>
<li>
<p><code>displayname</code> - <strong>string</strong>, optional. If set to an empty string (<code>&quot;&quot;</code>), the user's display name
will be removed.</p>
</li>
<li>
<p><code>avatar_url</code> - <strong>string</strong>, optional. Must be a
<a href="https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris">MXC URI</a>.
If set to an empty string (<code>&quot;&quot;</code>), the user's avatar is removed.</p>
</li>
<li>
<p><code>threepids</code> - <strong>array</strong>, optional. If provided, the user's third-party IDs (email, msisdn) are
entirely replaced with the given list. Each item in the array is an object with the following
fields:</p>
<ul>
<li><code>medium</code> - <strong>string</strong>, required. The type of third-party ID, either <code>email</code> or <code>msisdn</code> (phone number).</li>
<li><code>address</code> - <strong>string</strong>, required. The third-party ID itself, e.g. <code>alice@example.com</code> for <code>email</code> or
<code>447470274584</code> (for a phone number with country code &quot;44&quot;) and <code>19254857364</code> (for a phone number
with country code &quot;1&quot;) for <code>msisdn</code>.
Note: If a threepid is removed from a user via this option, Synapse will also attempt to remove
that threepid from any identity servers it is aware has a binding for it.</li>
</ul>
</li>
<li>
<p><code>external_ids</code> - <strong>array</strong>, optional. Allow setting the identifier of the external identity
provider for SSO (Single sign-on). More details are in the configuration manual under the
sections <a href="admin_api/../usage/configuration/config_documentation.html#sso">sso</a> and <a href="admin_api/../usage/configuration/config_documentation.html#oidc_providers">oidc_providers</a>.</p>
<ul>
<li><code>auth_provider</code> - <strong>string</strong>, required. The unique, internal ID of the external identity provider.
The same as <code>idp_id</code> from the homeserver configuration. Note that no error is raised if the
provided value is not in the homeserver configuration.</li>
<li><code>external_id</code> - <strong>string</strong>, required. An identifier for the user in the external identity provider.
When the user logs in to the identity provider, this must be the unique ID that they map to.</li>
</ul>
</li>
<li>
<p><code>admin</code> - <strong>bool</strong>, optional, defaults to <code>false</code>. Whether the user is a homeserver administrator,
granting them access to the Admin API, among other things.</p>
</li>
<li>
<p><code>deactivated</code> - <strong>bool</strong>, optional. If unspecified, deactivation state will be left unchanged.</p>
</li>
<li>
<p><code>locked</code> - <strong>bool</strong>, optional. If unspecified, locked state will be left unchanged.</p>
<p>Note: the <code>password</code> field must also be set if both of the following are true:</p>
<ul>
<li><code>deactivated</code> is set to <code>false</code> and the user was previously deactivated (you are reactivating this user)</li>
<li>Users are allowed to set their password on this homeserver (both <code>password_config.enabled</code> and
<code>password_config.localdb_enabled</code> config options are set to <code>true</code>).
Users' passwords are wiped upon account deactivation, hence the need to set a new one here.</li>
</ul>
<p>Note: a user cannot be erased with this API. For more details on
deactivating and erasing users see <a href="admin_api/user_admin_api.html#deactivate-account">Deactivate Account</a>.</p>
</li>
<li>
<p><code>user_type</code> - <strong>string</strong> or null, optional. If not provided, the user type will be
not be changed. If <code>null</code> is given, the user type will be cleared.
Other allowed options are: <code>bot</code> and <code>support</code>.</p>
</li>
</ul>
<h2 id="list-accounts"><a class="header" href="#list-accounts">List Accounts</a></h2>
<p>This API returns all local user accounts.
By default, the response is ordered by ascending user ID.</p>
<pre><code>GET /_synapse/admin/v2/users?from=0&amp;limit=10&amp;guests=false
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;users&quot;: [
        {
            &quot;name&quot;: &quot;&lt;user_id1&gt;&quot;,
            &quot;is_guest&quot;: 0,
            &quot;admin&quot;: 0,
            &quot;user_type&quot;: null,
            &quot;deactivated&quot;: 0,
            &quot;erased&quot;: false,
            &quot;shadow_banned&quot;: 0,
            &quot;displayname&quot;: &quot;&lt;User One&gt;&quot;,
            &quot;avatar_url&quot;: null,
            &quot;creation_ts&quot;: 1560432668000
        }, {
            &quot;name&quot;: &quot;&lt;user_id2&gt;&quot;,
            &quot;is_guest&quot;: 0,
            &quot;admin&quot;: 1,
            &quot;user_type&quot;: null,
            &quot;deactivated&quot;: 0,
            &quot;erased&quot;: false,
            &quot;shadow_banned&quot;: 0,
            &quot;displayname&quot;: &quot;&lt;User Two&gt;&quot;,
            &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
            &quot;creation_ts&quot;: 1561550621000
        }
    ],
    &quot;next_token&quot;: &quot;100&quot;,
    &quot;total&quot;: 200
}
</code></pre>
<p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
<p>If the endpoint does not return a <code>next_token</code> then there are no more users
to paginate through.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li>
<p><code>user_id</code> - Is optional and filters to only return users with user IDs
that contain this value. This parameter is ignored when using the <code>name</code> parameter.</p>
</li>
<li>
<p><code>name</code> - Is optional and filters to only return users with user ID localparts
<strong>or</strong> displaynames that contain this value.</p>
</li>
<li>
<p><code>guests</code> - string representing a bool - Is optional and if <code>false</code> will <strong>exclude</strong> guest users.
Defaults to <code>true</code> to include guest users. This parameter is not supported when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
</li>
<li>
<p><code>admins</code> - Optional flag to filter admins. If <code>true</code>, only admins are queried. If <code>false</code>, admins are excluded from 
the query. When the flag is absent (the default), <strong>both</strong> admins and non-admins are included in the search results.</p>
</li>
<li>
<p><code>deactivated</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> deactivated users.
Defaults to <code>false</code> to exclude deactivated users.</p>
</li>
<li>
<p><code>limit</code> - string representing a positive integer - Is optional but is used for pagination,
denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
</li>
<li>
<p><code>from</code> - string representing a positive integer - Is optional but used for pagination,
denoting the offset in the returned results. This should be treated as an opaque value and
not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
Defaults to <code>0</code>.</p>
</li>
<li>
<p><code>order_by</code> - The method by which to sort the returned list of users.
If the ordered field has duplicates, the second order is always by ascending <code>name</code>,
which guarantees a stable ordering. Valid values are:</p>
<ul>
<li><code>name</code> - Users are ordered alphabetically by <code>name</code>. This is the default.</li>
<li><code>is_guest</code> - Users are ordered by <code>is_guest</code> status.</li>
<li><code>admin</code> - Users are ordered by <code>admin</code> status.</li>
<li><code>user_type</code> - Users are ordered alphabetically by <code>user_type</code>.</li>
<li><code>deactivated</code> - Users are ordered by <code>deactivated</code> status.</li>
<li><code>shadow_banned</code> - Users are ordered by <code>shadow_banned</code> status.</li>
<li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
<li><code>avatar_url</code> - Users are ordered alphabetically by avatar URL.</li>
<li><code>creation_ts</code> - Users are ordered by when the users was created in ms.</li>
<li><code>last_seen_ts</code> - Users are ordered by when the user was lastly seen in ms.</li>
</ul>
</li>
<li>
<p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
</li>
<li>
<p><code>not_user_type</code> - Exclude certain user types, such as bot users, from the request.
Can be provided multiple times. Possible values are <code>bot</code>, <code>support</code> or &quot;empty string&quot;.
&quot;empty string&quot; here means to exclude users without a type.</p>
</li>
</ul>
<p>Caution. The database only has indexes on the columns <code>name</code> and <code>creation_ts</code>.
This means that if a different sort order is used (<code>is_guest</code>, <code>admin</code>,
<code>user_type</code>, <code>deactivated</code>, <code>shadow_banned</code>, <code>avatar_url</code> or <code>displayname</code>),
this can cause a large load on the database, especially for large environments.</p>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li>
<p><code>users</code> - An array of objects, each containing information about an user.
User objects contain the following fields:</p>
<ul>
<li><code>name</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
<li><code>is_guest</code> - bool - Status if that user is a guest account.</li>
<li><code>admin</code> - bool - Status if that user is a server administrator.</li>
<li><code>user_type</code> - string - Type of the user. Normal users are type <code>None</code>.
This allows user type specific behaviour. There are also types <code>support</code> and <code>bot</code>. </li>
<li><code>deactivated</code> - bool - Status if that user has been marked as deactivated.</li>
<li><code>erased</code> - bool - Status if that user has been marked as erased.</li>
<li><code>shadow_banned</code> - bool - Status if that user has been marked as shadow banned.</li>
<li><code>displayname</code> - string - The user's display name if they have set one.</li>
<li><code>avatar_url</code> - string -  The user's avatar URL if they have set one.</li>
<li><code>creation_ts</code> - integer - The user's creation timestamp in ms.</li>
<li><code>last_seen_ts</code> - integer - The user's last activity timestamp in ms.</li>
</ul>
</li>
<li>
<p><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</p>
</li>
<li>
<p><code>total</code> - integer - Total number of media.</p>
</li>
</ul>
<h2 id="query-current-sessions-for-a-user"><a class="header" href="#query-current-sessions-for-a-user">Query current sessions for a user</a></h2>
<p>This API returns information about the active sessions for a specific user.</p>
<p>The endpoints are:</p>
<pre><code>GET /_synapse/admin/v1/whois/&lt;user_id&gt;
</code></pre>
<p>and:</p>
<pre><code>GET /_matrix/client/r0/admin/whois/&lt;userId&gt;
</code></pre>
<p>See also: <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">Client Server
API Whois</a>.</p>
<p>It returns a JSON body like the following:</p>
<pre><code class="language-json">{
    &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;,
    &quot;devices&quot;: {
        &quot;&quot;: {
            &quot;sessions&quot;: [
                {
                    &quot;connections&quot;: [
                        {
                            &quot;ip&quot;: &quot;1.2.3.4&quot;,
                            &quot;last_seen&quot;: 1417222374433,
                            &quot;user_agent&quot;: &quot;Mozilla/5.0 ...&quot;
                        },
                        {
                            &quot;ip&quot;: &quot;1.2.3.10&quot;,
                            &quot;last_seen&quot;: 1417222374500,
                            &quot;user_agent&quot;: &quot;Dalvik/2.1.0 ...&quot;
                        }
                    ]
                }
            ]
        }
    }
}
</code></pre>
<p><code>last_seen</code> is measured in milliseconds since the Unix epoch.</p>
<h2 id="deactivate-account"><a class="header" href="#deactivate-account">Deactivate Account</a></h2>
<p>This API deactivates an account. It removes active access tokens, resets the
password, and deletes third-party IDs (to prevent the user requesting a
password reset).</p>
<p>It can also mark the user as GDPR-erased. This means messages sent by the
user will still be visible by anyone that was in the room when these messages
were sent, but hidden from users joining the room afterwards.</p>
<p>The api is:</p>
<pre><code>POST /_synapse/admin/v1/deactivate/&lt;user_id&gt;
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
    &quot;erase&quot;: true
}
</code></pre>
<p>The erase parameter is optional and defaults to <code>false</code>.
An empty body may be passed for backwards compatibility.</p>
<p>The following actions are performed when deactivating an user:</p>
<ul>
<li>Try to unbind 3PIDs from the identity server</li>
<li>Remove all 3PIDs from the homeserver</li>
<li>Delete all devices and E2EE keys</li>
<li>Delete all access tokens</li>
<li>Delete all pushers</li>
<li>Delete the password hash</li>
<li>Removal from all rooms the user is a member of</li>
<li>Remove the user from the user directory</li>
<li>Reject all pending invites</li>
<li>Remove all account validity information related to the user</li>
<li>Remove the arbitrary data store known as <em>account data</em>. For example, this includes:
<ul>
<li>list of ignored users;</li>
<li>push rules;</li>
<li>secret storage keys; and</li>
<li>cross-signing keys.</li>
</ul>
</li>
</ul>
<p>The following additional actions are performed during deactivation if <code>erase</code>
is set to <code>true</code>:</p>
<ul>
<li>Remove the user's display name</li>
<li>Remove the user's avatar URL</li>
<li>Mark the user as erased</li>
</ul>
<p>The following actions are <strong>NOT</strong> performed. The list may be incomplete.</p>
<ul>
<li>Remove mappings of SSO IDs</li>
<li><a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">Delete media uploaded</a> by user (included avatar images)</li>
<li>Delete sent and received messages</li>
<li>Remove the user's creation (registration) timestamp</li>
<li><a href="admin_api/user_admin_api.html#override-ratelimiting-for-users">Remove rate limit overrides</a></li>
<li>Remove from monthly active users</li>
<li>Remove user's consent information (consent version and timestamp)</li>
</ul>
<h2 id="reset-password"><a class="header" href="#reset-password">Reset password</a></h2>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>Changes the password of another user. This will automatically log the user out of all their devices.</p>
<p>The api is:</p>
<pre><code>POST /_synapse/admin/v1/reset_password/&lt;user_id&gt;
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
   &quot;new_password&quot;: &quot;&lt;secret&gt;&quot;,
   &quot;logout_devices&quot;: true
}
</code></pre>
<p>The parameter <code>new_password</code> is required.
The parameter <code>logout_devices</code> is optional and defaults to <code>true</code>.</p>
<h2 id="get-whether-a-user-is-a-server-administrator-or-not"><a class="header" href="#get-whether-a-user-is-a-server-administrator-or-not">Get whether a user is a server administrator or not</a></h2>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>The api is:</p>
<pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/admin
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;admin&quot;: true
}
</code></pre>
<h2 id="change-whether-a-user-is-a-server-administrator-or-not"><a class="header" href="#change-whether-a-user-is-a-server-administrator-or-not">Change whether a user is a server administrator or not</a></h2>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>Note that you cannot demote yourself.</p>
<p>The api is:</p>
<pre><code>PUT /_synapse/admin/v1/users/&lt;user_id&gt;/admin
</code></pre>
<p>with a body of:</p>
<pre><code class="language-json">{
    &quot;admin&quot;: true
}
</code></pre>
<h2 id="list-room-memberships-of-a-user"><a class="header" href="#list-room-memberships-of-a-user">List room memberships of a user</a></h2>
<p>Gets a list of all <code>room_id</code> that a specific <code>user_id</code> is member.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/joined_rooms
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">    {
        &quot;joined_rooms&quot;: [
            &quot;!DuGcnbhHGaSZQoNQR:matrix.org&quot;,
            &quot;!ZtSaPCawyWtxfWiIy:matrix.org&quot;
        ],
        &quot;total&quot;: 2
    }
</code></pre>
<p>The server returns the list of rooms of which the user and the server
are member. If the user is local, all the rooms of which the user is
member are returned.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>joined_rooms</code> - An array of <code>room_id</code>.</li>
<li><code>total</code> - Number of rooms.</li>
</ul>
<h2 id="account-data"><a class="header" href="#account-data">Account Data</a></h2>
<p>Gets information about account data for a specific <code>user_id</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/accountdata
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;account_data&quot;: {
        &quot;global&quot;: {
            &quot;m.secret_storage.key.LmIGHTg5W&quot;: {
                &quot;algorithm&quot;: &quot;m.secret_storage.v1.aes-hmac-sha2&quot;,
                &quot;iv&quot;: &quot;fwjNZatxg==&quot;,
                &quot;mac&quot;: &quot;eWh9kNnLWZUNOgnc=&quot;
            },
            &quot;im.vector.hide_profile&quot;: {
                &quot;hide_profile&quot;: true
            },
            &quot;org.matrix.preview_urls&quot;: {
                &quot;disable&quot;: false
            },
            &quot;im.vector.riot.breadcrumb_rooms&quot;: {
                &quot;rooms&quot;: [
                    &quot;!LxcBDAsDUVAfJDEo:matrix.org&quot;,
                    &quot;!MAhRxqasbItjOqxu:matrix.org&quot;
                ]
            },
            &quot;m.accepted_terms&quot;: {
                &quot;accepted&quot;: [
                    &quot;https://example.org/somewhere/privacy-1.2-en.html&quot;,
                    &quot;https://example.org/somewhere/terms-2.0-en.html&quot;
                ]
            },
            &quot;im.vector.setting.breadcrumbs&quot;: {
                &quot;recent_rooms&quot;: [
                    &quot;!MAhRxqasbItqxuEt:matrix.org&quot;,
                    &quot;!ZtSaPCawyWtxiImy:matrix.org&quot;
                ]
            }
        },
        &quot;rooms&quot;: {
            &quot;!GUdfZSHUJibpiVqHYd:matrix.org&quot;: {
                &quot;m.fully_read&quot;: {
                    &quot;event_id&quot;: &quot;$156334540fYIhZ:matrix.org&quot;
                }
            },
            &quot;!tOZwOOiqwCYQkLhV:matrix.org&quot;: {
                &quot;m.fully_read&quot;: {
                    &quot;event_id&quot;: &quot;$xjsIyp4_NaVl2yPvIZs_k1Jl8tsC_Sp23wjqXPno&quot;
                }
            }
        }
    }
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>account_data</code> - A map containing the account data for the user
<ul>
<li><code>global</code> - A map containing the global account data for the user</li>
<li><code>rooms</code> - A map containing the account data per room for the user</li>
</ul>
</li>
</ul>
<h2 id="user-media"><a class="header" href="#user-media">User media</a></h2>
<h3 id="list-media-uploaded-by-a-user"><a class="header" href="#list-media-uploaded-by-a-user">List media uploaded by a user</a></h3>
<p>Gets a list of all local media that a specific <code>user_id</code> has created.
These are media that the user has uploaded themselves
(<a href="admin_api/../media_repository.html#local-media">local media</a>), as well as
<a href="admin_api/../media_repository.html#url-previews">URL preview images</a> requested by the user if the
<a href="admin_api/../usage/configuration/config_documentation.html#url_preview_enabled">feature is enabled</a>.</p>
<p>By default, the response is ordered by descending creation date and ascending media ID.
The newest media is on top. You can change the order with parameters
<code>order_by</code> and <code>dir</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/media
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;media&quot;: [
    {
      &quot;created_ts&quot;: 100400,
      &quot;last_access_ts&quot;: null,
      &quot;media_id&quot;: &quot;qXhyRzulkwLsNHTbpHreuEgo&quot;,
      &quot;media_length&quot;: 67,
      &quot;media_type&quot;: &quot;image/png&quot;,
      &quot;quarantined_by&quot;: null,
      &quot;safe_from_quarantine&quot;: false,
      &quot;upload_name&quot;: &quot;test1.png&quot;
    },
    {
      &quot;created_ts&quot;: 200400,
      &quot;last_access_ts&quot;: null,
      &quot;media_id&quot;: &quot;FHfiSnzoINDatrXHQIXBtahw&quot;,
      &quot;media_length&quot;: 67,
      &quot;media_type&quot;: &quot;image/png&quot;,
      &quot;quarantined_by&quot;: null,
      &quot;safe_from_quarantine&quot;: false,
      &quot;upload_name&quot;: &quot;test2.png&quot;
    }
  ],
  &quot;next_token&quot;: 3,
  &quot;total&quot;: 2
}
</code></pre>
<p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
<p>If the endpoint does not return a <code>next_token</code> then there are no more
reports to paginate through.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li>
<p><code>user_id</code> - string - fully qualified: for example, <code>@user:server.com</code>.</p>
</li>
<li>
<p><code>limit</code>: string representing a positive integer - Is optional but is used for pagination,
denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
</li>
<li>
<p><code>from</code>: string representing a positive integer - Is optional but used for pagination,
denoting the offset in the returned results. This should be treated as an opaque value and
not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
Defaults to <code>0</code>.</p>
</li>
<li>
<p><code>order_by</code> - The method by which to sort the returned list of media.
If the ordered field has duplicates, the second order is always by ascending <code>media_id</code>,
which guarantees a stable ordering. Valid values are:</p>
<ul>
<li><code>media_id</code> - Media are ordered alphabetically by <code>media_id</code>.</li>
<li><code>upload_name</code> - Media are ordered alphabetically by name the media was uploaded with.</li>
<li><code>created_ts</code> - Media are ordered by when the content was uploaded in ms.
Smallest to largest. This is the default.</li>
<li><code>last_access_ts</code> - Media are ordered by when the content was last accessed in ms.
Smallest to largest.</li>
<li><code>media_length</code> - Media are ordered by length of the media in bytes.
Smallest to largest.</li>
<li><code>media_type</code> - Media are ordered alphabetically by MIME-type.</li>
<li><code>quarantined_by</code> - Media are ordered alphabetically by the user ID that
initiated the quarantine request for this media.</li>
<li><code>safe_from_quarantine</code> - Media are ordered by the status if this media is safe
from quarantining.</li>
</ul>
</li>
<li>
<p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
</li>
</ul>
<p>If neither <code>order_by</code> nor <code>dir</code> is set, the default order is newest media on top
(corresponds to <code>order_by</code> = <code>created_ts</code> and <code>dir</code> = <code>b</code>).</p>
<p>Caution. The database only has indexes on the columns <code>media_id</code>,
<code>user_id</code> and <code>created_ts</code>. This means that if a different sort order is used
(<code>upload_name</code>, <code>last_access_ts</code>, <code>media_length</code>, <code>media_type</code>,
<code>quarantined_by</code> or <code>safe_from_quarantine</code>), this can cause a large load on the
database, especially for large environments.</p>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>media</code> - An array of objects, each containing information about a media.
Media objects contain the following fields:
<ul>
<li><code>created_ts</code> - integer - Timestamp when the content was uploaded in ms.</li>
<li><code>last_access_ts</code> - integer - Timestamp when the content was last accessed in ms.</li>
<li><code>media_id</code> - string - The id used to refer to the media. Details about the format
are documented under
<a href="admin_api/../media_repository.html">media repository</a>.</li>
<li><code>media_length</code> - integer - Length of the media in bytes.</li>
<li><code>media_type</code> - string - The MIME-type of the media.</li>
<li><code>quarantined_by</code> - string - The user ID that initiated the quarantine request
for this media.</li>
<li><code>safe_from_quarantine</code> - bool - Status if this media is safe from quarantining.</li>
<li><code>upload_name</code> - string - The name the media was uploaded with.</li>
</ul>
</li>
<li><code>next_token</code>: integer - Indication for pagination. See above.</li>
<li><code>total</code> - integer - Total number of media.</li>
</ul>
<h3 id="delete-media-uploaded-by-a-user-1"><a class="header" href="#delete-media-uploaded-by-a-user-1">Delete media uploaded by a user</a></h3>
<p>This API deletes the <em>local</em> media from the disk of your own server
that a specific <code>user_id</code> has created. This includes any local thumbnails.</p>
<p>This API will not affect media that has been uploaded to external
media repositories (e.g https://github.com/turt2live/matrix-media-repo/).</p>
<p>By default, the API deletes media ordered by descending creation date and ascending media ID.
The newest media is deleted first. You can change the order with parameters
<code>order_by</code> and <code>dir</code>. If no <code>limit</code> is set the API deletes <code>100</code> files per request.</p>
<p>The API is:</p>
<pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/media
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;deleted_media&quot;: [
    &quot;abcdefghijklmnopqrstuvwx&quot;
  ],
  &quot;total&quot;: 1
}
</code></pre>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
<li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
</ul>
<p><strong>Note</strong>: There is no <code>next_token</code>. This is not useful for deleting media, because
after deleting media the remaining media have a new order.</p>
<p><strong>Parameters</strong></p>
<p>This API has the same parameters as
<a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>.
With the parameters you can for example limit the number of files to delete at once or
delete largest/smallest or newest/oldest files first.</p>
<h2 id="login-as-a-user"><a class="header" href="#login-as-a-user">Login as a user</a></h2>
<p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
<p>Get an access token that can be used to authenticate as that user. Useful for
when admins wish to do actions on behalf of a user.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/login
{}
</code></pre>
<p>An optional <code>valid_until_ms</code> field can be specified in the request body as an
integer timestamp that specifies when the token should expire. By default tokens
do not expire. Note that this API does not allow a user to login as themselves
(to create more tokens).</p>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;access_token&quot;: &quot;&lt;opaque_access_token_string&gt;&quot;
}
</code></pre>
<p>This API does <em>not</em> generate a new device for the user, and so will not appear
their <code>/devices</code> list, and in general the target user should not be able to
tell they have been logged in as.</p>
<p>To expire the token call the standard <code>/logout</code> API with the token.</p>
<p>Note: The token will expire if the <em>admin</em> user calls <code>/logout/all</code> from any
of their devices, but the token will <em>not</em> expire if the target user does the
same.</p>
<h2 id="user-devices"><a class="header" href="#user-devices">User devices</a></h2>
<h3 id="list-all-devices"><a class="header" href="#list-all-devices">List all devices</a></h3>
<p>Gets information about all devices for a specific <code>user_id</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;devices&quot;: [
    {
      &quot;device_id&quot;: &quot;QBUAZIFURK&quot;,
      &quot;display_name&quot;: &quot;android&quot;,
      &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
      &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
      &quot;last_seen_ts&quot;: 1474491775024,
      &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
    },
    {
      &quot;device_id&quot;: &quot;AUIECTSRND&quot;,
      &quot;display_name&quot;: &quot;ios&quot;,
      &quot;last_seen_ip&quot;: &quot;1.2.3.5&quot;,
      &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
      &quot;last_seen_ts&quot;: 1474491775025,
      &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
    }
  ],
  &quot;total&quot;: 2
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li>
<p><code>devices</code> - An array of objects, each containing information about a device.
Device objects contain the following fields:</p>
<ul>
<li><code>device_id</code> - Identifier of device.</li>
<li><code>display_name</code> - Display name set by the user for this device.
Absent if no name has been set.</li>
<li><code>last_seen_ip</code> - The IP address where this device was last seen.
(May be a few minutes out of date, for efficiency reasons).</li>
<li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
(May be a few minutes out of date, for efficiency reasons).</li>
<li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
<li><code>user_id</code> - Owner of  device.</li>
</ul>
</li>
<li>
<p><code>total</code> - Total number of user's devices.</p>
</li>
</ul>
<h3 id="create-a-device"><a class="header" href="#create-a-device">Create a device</a></h3>
<p>Creates a new device for a specific <code>user_id</code> and <code>device_id</code>. Does nothing if the <code>device_id</code> 
exists already.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/devices

{
  &quot;device_id&quot;: &quot;QBUAZIFURK&quot;
}
</code></pre>
<p>An empty JSON dict is returned.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
</ul>
<p>The following fields are required in the JSON request body:</p>
<ul>
<li><code>device_id</code> - The device ID to create.</li>
</ul>
<h3 id="delete-multiple-devices"><a class="header" href="#delete-multiple-devices">Delete multiple devices</a></h3>
<p>Deletes the given devices for a specific <code>user_id</code>, and invalidates
any access token associated with them.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/delete_devices

{
  &quot;devices&quot;: [
    &quot;QBUAZIFURK&quot;,
    &quot;AUIECTSRND&quot;
  ]
}
</code></pre>
<p>An empty JSON dict is returned.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
</ul>
<p>The following fields are required in the JSON request body:</p>
<ul>
<li><code>devices</code> - The list of device IDs to delete.</li>
</ul>
<h3 id="show-a-device"><a class="header" href="#show-a-device">Show a device</a></h3>
<p>Gets information on a single device, by <code>device_id</code> for a specific <code>user_id</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;device_id&quot;: &quot;&lt;device_id&gt;&quot;,
  &quot;display_name&quot;: &quot;android&quot;,
  &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  &quot;last_seen_ts&quot;: 1474491775024,
  &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
<li><code>device_id</code> - The device to retrieve.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>device_id</code> - Identifier of device.</li>
<li><code>display_name</code> - Display name set by the user for this device.
Absent if no name has been set.</li>
<li><code>last_seen_ip</code> - The IP address where this device was last seen.
(May be a few minutes out of date, for efficiency reasons).
<ul>
<li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
(May be a few minutes out of date, for efficiency reasons).</li>
</ul>
</li>
<li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
<li><code>user_id</code> - Owner of  device.</li>
</ul>
<h3 id="update-a-device"><a class="header" href="#update-a-device">Update a device</a></h3>
<p>Updates the metadata on the given <code>device_id</code> for a specific <code>user_id</code>.</p>
<p>The API is:</p>
<pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;

{
  &quot;display_name&quot;: &quot;My other phone&quot;
}
</code></pre>
<p>An empty JSON dict is returned.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
<li><code>device_id</code> - The device to update.</li>
</ul>
<p>The following fields are required in the JSON request body:</p>
<ul>
<li><code>display_name</code> - The new display name for this device. If not given,
the display name is unchanged.</li>
</ul>
<h3 id="delete-a-device"><a class="header" href="#delete-a-device">Delete a device</a></h3>
<p>Deletes the given <code>device_id</code> for a specific <code>user_id</code>,
and invalidates any access token associated with it.</p>
<p>The API is:</p>
<pre><code>DELETE /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;

{}
</code></pre>
<p>An empty JSON dict is returned.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
<li><code>device_id</code> - The device to delete.</li>
</ul>
<h2 id="list-all-pushers"><a class="header" href="#list-all-pushers">List all pushers</a></h2>
<p>Gets information about all pushers for a specific <code>user_id</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/pushers
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;pushers&quot;: [
    {
      &quot;app_display_name&quot;:&quot;HTTP Push Notifications&quot;,
      &quot;app_id&quot;:&quot;m.http&quot;,
      &quot;data&quot;: {
        &quot;url&quot;:&quot;example.com&quot;
      },
      &quot;device_display_name&quot;:&quot;pushy push&quot;,
      &quot;kind&quot;:&quot;http&quot;,
      &quot;lang&quot;:&quot;None&quot;,
      &quot;profile_tag&quot;:&quot;&quot;,
      &quot;pushkey&quot;:&quot;a@example.com&quot;
    }
  ],
  &quot;total&quot;: 1
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li>
<p><code>pushers</code> - An array containing the current pushers for the user</p>
<ul>
<li>
<p><code>app_display_name</code> - string - A string that will allow the user to identify
what application owns this pusher.</p>
</li>
<li>
<p><code>app_id</code> - string - This is a reverse-DNS style identifier for the application.
Max length, 64 chars.</p>
</li>
<li>
<p><code>data</code> - A dictionary of information for the pusher implementation itself.</p>
<ul>
<li>
<p><code>url</code> - string - Required if <code>kind</code> is <code>http</code>. The URL to use to send
notifications to.</p>
</li>
<li>
<p><code>format</code> - string - The format to use when sending notifications to the
Push Gateway.</p>
</li>
</ul>
</li>
<li>
<p><code>device_display_name</code> - string -  A string that will allow the user to identify
what device owns this pusher.</p>
</li>
<li>
<p><code>profile_tag</code> - string - This string determines which set of device specific rules
this pusher executes.</p>
</li>
<li>
<p><code>kind</code> - string -  The kind of pusher. &quot;http&quot; is a pusher that sends HTTP pokes.</p>
</li>
<li>
<p><code>lang</code> - string - The preferred language for receiving notifications
(e.g. 'en' or 'en-US')</p>
</li>
<li>
<p><code>profile_tag</code> - string - This string determines which set of device specific rules
this pusher executes.</p>
</li>
<li>
<p><code>pushkey</code> - string - This is a unique identifier for this pusher.
Max length, 512 bytes.</p>
</li>
</ul>
</li>
<li>
<p><code>total</code> - integer - Number of pushers.</p>
</li>
</ul>
<p>See also the
<a href="https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushers">Client-Server API Spec on pushers</a>.</p>
<h2 id="controlling-whether-a-user-is-shadow-banned"><a class="header" href="#controlling-whether-a-user-is-shadow-banned">Controlling whether a user is shadow-banned</a></h2>
<p>Shadow-banning is a useful tool for moderating malicious or egregiously abusive users.
A shadow-banned users receives successful responses to their client-server API requests,
but the events are not propagated into rooms. This can be an effective tool as it
(hopefully) takes longer for the user to realise they are being moderated before
pivoting to another account.</p>
<p>Shadow-banning a user should be used as a tool of last resort and may lead to confusing
or broken behaviour for the client. A shadow-banned user will not receive any
notification and it is generally more appropriate to ban or kick abusive users.
A shadow-banned user will be unable to contact anyone on the server.</p>
<p>To shadow-ban a user the API is:</p>
<pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
</code></pre>
<p>To un-shadow-ban a user the API is:</p>
<pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
</code></pre>
<p>An empty JSON dict is returned in both cases.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
be local.</li>
</ul>
<h2 id="override-ratelimiting-for-users"><a class="header" href="#override-ratelimiting-for-users">Override ratelimiting for users</a></h2>
<p>This API allows to override or disable ratelimiting for a specific user.
There are specific APIs to set, get and delete a ratelimit.</p>
<h3 id="get-status-of-ratelimit"><a class="header" href="#get-status-of-ratelimit">Get status of ratelimit</a></h3>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;messages_per_second&quot;: 0,
  &quot;burst_count&quot;: 0
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
be local.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>messages_per_second</code> - integer - The number of actions that can
be performed in a second. <code>0</code> mean that ratelimiting is disabled for this user.</li>
<li><code>burst_count</code> - integer - How many actions that can be performed before
being limited.</li>
</ul>
<p>If <strong>no</strong> custom ratelimit is set, an empty JSON dict is returned.</p>
<pre><code class="language-json">{}
</code></pre>
<h3 id="set-ratelimit"><a class="header" href="#set-ratelimit">Set ratelimit</a></h3>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
  &quot;messages_per_second&quot;: 0,
  &quot;burst_count&quot;: 0
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
be local.</li>
</ul>
<p>Body parameters:</p>
<ul>
<li><code>messages_per_second</code> - positive integer, optional. The number of actions that can
be performed in a second. Defaults to <code>0</code>.</li>
<li><code>burst_count</code> - positive integer, optional. How many actions that can be performed
before being limited. Defaults to <code>0</code>.</li>
</ul>
<p>To disable users' ratelimit set both values to <code>0</code>.</p>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>messages_per_second</code> - integer - The number of actions that can
be performed in a second.</li>
<li><code>burst_count</code> - integer - How many actions that can be performed before
being limited.</li>
</ul>
<h3 id="delete-ratelimit"><a class="header" href="#delete-ratelimit">Delete ratelimit</a></h3>
<p>The API is:</p>
<pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
</code></pre>
<p>An empty JSON dict is returned.</p>
<pre><code class="language-json">{}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
be local.</li>
</ul>
<h2 id="check-username-availability"><a class="header" href="#check-username-availability">Check username availability</a></h2>
<p>Checks to see if a username is available, and valid, for the server. See <a href="https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-register-available">the client-server 
API</a>
for more information.</p>
<p>This endpoint will work even if registration is disabled on the server, unlike 
<code>/_matrix/client/r0/register/available</code>.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/username_available?username=$localpart
</code></pre>
<p>The request and response format is the same as the
<a href="https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-register-available">/_matrix/client/r0/register/available</a> API.</p>
<h2 id="find-a-user-based-on-their-id-in-an-auth-provider"><a class="header" href="#find-a-user-based-on-their-id-in-an-auth-provider">Find a user based on their ID in an auth provider</a></h2>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/auth_providers/$provider/users/$external_id
</code></pre>
<p>When a user matched the given ID for the given provider, an HTTP code <code>200</code> with a response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;user_id&quot;: &quot;@hello:example.org&quot;
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>provider</code> - The ID of the authentication provider, as advertised by the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3login"><code>GET /_matrix/client/v3/login</code></a> API in the <code>m.login.sso</code> authentication method.</li>
<li><code>external_id</code> - The user ID from the authentication provider. Usually corresponds to the <code>sub</code> claim for OIDC providers, or to the <code>uid</code> attestation for SAML2 providers.</li>
</ul>
<p>The <code>external_id</code> may have characters that are not URL-safe (typically <code>/</code>, <code>:</code> or <code>@</code>), so it is advised to URL-encode those parameters.</p>
<p><strong>Errors</strong></p>
<p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
<pre><code class="language-json">{
    &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
    &quot;error&quot;:&quot;User not found&quot;
}
</code></pre>
<p><em>Added in Synapse 1.68.0.</em></p>
<h2 id="find-a-user-based-on-their-third-party-id-threepid-or-3pid"><a class="header" href="#find-a-user-based-on-their-third-party-id-threepid-or-3pid">Find a user based on their Third Party ID (ThreePID or 3PID)</a></h2>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/threepid/$medium/users/$address
</code></pre>
<p>When a user matched the given address for the given medium, an HTTP code <code>200</code> with a response body like the following is returned:</p>
<pre><code class="language-json">{
    &quot;user_id&quot;: &quot;@hello:example.org&quot;
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>medium</code> - Kind of third-party ID, either <code>email</code> or <code>msisdn</code>.</li>
<li><code>address</code> - Value of the third-party ID.</li>
</ul>
<p>The <code>address</code> may have characters that are not URL-safe, so it is advised to URL-encode those parameters.</p>
<p><strong>Errors</strong></p>
<p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
<pre><code class="language-json">{
    &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
    &quot;error&quot;:&quot;User not found&quot;
}
</code></pre>
<p><em>Added in Synapse 1.72.0.</em></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="version-api"><a class="header" href="#version-api">Version API</a></h1>
<p>This API returns the running Synapse version and the Python version
on which Synapse is being run. This is useful when a Synapse instance
is behind a proxy that does not forward the 'Server' header (which also
contains Synapse version information).</p>
<p>The api is:</p>
<pre><code>GET /_synapse/admin/v1/server_version
</code></pre>
<p>It returns a JSON body like the following:</p>
<pre><code class="language-json">{
    &quot;server_version&quot;: &quot;0.99.2rc1 (b=develop, abcdef123)&quot;,
    &quot;python_version&quot;: &quot;3.7.8&quot;
}
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="federation-api"><a class="header" href="#federation-api">Federation API</a></h1>
<p>This API allows a server administrator to manage Synapse's federation with other homeservers.</p>
<p>Note: This API is new, experimental and &quot;subject to change&quot;.</p>
<h2 id="list-of-destinations"><a class="header" href="#list-of-destinations">List of destinations</a></h2>
<p>This API gets the current destination retry timing info for all remote servers.</p>
<p>The list contains all the servers with which the server federates,
regardless of whether an error occurred or not.
If an error occurs, it may take up to 20 minutes for the error to be displayed here,
as a complete retry must have failed.</p>
<p>The API is:</p>
<p>A standard request with no filtering:</p>
<pre><code>GET /_synapse/admin/v1/federation/destinations
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
   &quot;destinations&quot;:[
      {
         &quot;destination&quot;: &quot;matrix.org&quot;,
         &quot;retry_last_ts&quot;: 1557332397936,
         &quot;retry_interval&quot;: 3000000,
         &quot;failure_ts&quot;: 1557329397936,
         &quot;last_successful_stream_ordering&quot;: null
      }
   ],
   &quot;total&quot;: 1
}
</code></pre>
<p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
<p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
to paginate through.</p>
<p><strong>Parameters</strong></p>
<p>The following query parameters are available:</p>
<ul>
<li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
<li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
<li><code>order_by</code> - The method in which to sort the returned list of destinations.
Valid values are:
<ul>
<li><code>destination</code> - Destinations are ordered alphabetically by remote server name.
This is the default.</li>
<li><code>retry_last_ts</code> - Destinations are ordered by time of last retry attempt in ms.</li>
<li><code>retry_interval</code> - Destinations are ordered by how long until next retry in ms.</li>
<li><code>failure_ts</code> - Destinations are ordered by when the server started failing in ms.</li>
<li><code>last_successful_stream_ordering</code> - Destinations are ordered by the stream ordering
of the most recent successfully-sent PDU.</li>
</ul>
</li>
<li><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
</ul>
<p><em>Caution:</em> The database only has an index on the column <code>destination</code>.
This means that if a different sort order is used,
this can cause a large load on the database, especially for large environments.</p>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>destinations</code> - An array of objects, each containing information about a destination.
Destination objects contain the following fields:
<ul>
<li><code>destination</code> - string - Name of the remote server to federate.</li>
<li><code>retry_last_ts</code> - integer - The last time Synapse tried and failed to reach the
remote server, in ms. This is <code>0</code> if the last attempt to communicate with the
remote server was successful.</li>
<li><code>retry_interval</code> - integer - How long since the last time Synapse tried to reach
the remote server before trying again, in ms. This is <code>0</code> if no further retrying occuring.</li>
<li><code>failure_ts</code> - nullable integer - The first time Synapse tried and failed to reach the
remote server, in ms. This is <code>null</code> if communication with the remote server has never failed.</li>
<li><code>last_successful_stream_ordering</code> - nullable integer - The stream ordering of the most
recent successfully-sent <a href="usage/administration/admin_api/../understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
to this destination, or <code>null</code> if this information has not been tracked yet.</li>
</ul>
</li>
<li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
<li><code>total</code> - integer - Total number of destinations.</li>
</ul>
<h2 id="destination-details-api"><a class="header" href="#destination-details-api">Destination Details API</a></h2>
<p>This API gets the retry timing info for a specific remote server.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
   &quot;destination&quot;: &quot;matrix.org&quot;,
   &quot;retry_last_ts&quot;: 1557332397936,
   &quot;retry_interval&quot;: 3000000,
   &quot;failure_ts&quot;: 1557329397936,
   &quot;last_successful_stream_ordering&quot;: null
}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>destination</code> - Name of the remote server.</li>
</ul>
<p><strong>Response</strong></p>
<p>The response fields are the same like in the <code>destinations</code> array in
<a href="usage/administration/admin_api/federation.html#list-of-destinations">List of destinations</a> response.</p>
<h2 id="destination-rooms"><a class="header" href="#destination-rooms">Destination rooms</a></h2>
<p>This API gets the rooms that federate with a specific remote server.</p>
<p>The API is:</p>
<pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/rooms
</code></pre>
<p>A response body like the following is returned:</p>
<pre><code class="language-json">{
   &quot;rooms&quot;:[
      {
         &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
         &quot;stream_ordering&quot;: 8326
      },
      {
         &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
         &quot;stream_ordering&quot;: 93534
      }
   ],
   &quot;total&quot;: 2
}
</code></pre>
<p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
<p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
to paginate through.</p>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>destination</code> - Name of the remote server.</li>
</ul>
<p>The following query parameters are available:</p>
<ul>
<li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
<li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
<li><code>dir</code> - Direction of room order by <code>room_id</code>. Either <code>f</code> for forwards or <code>b</code> for
backwards. Defaults to <code>f</code>.</li>
</ul>
<p><strong>Response</strong></p>
<p>The following fields are returned in the JSON response body:</p>
<ul>
<li><code>rooms</code> - An array of objects, each containing information about a room.
Room objects contain the following fields:
<ul>
<li><code>room_id</code> - string - The ID of the room.</li>
<li><code>stream_ordering</code> - integer -  The stream ordering of the most recent
successfully-sent <a href="usage/administration/admin_api/../understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
to this destination in this room.</li>
</ul>
</li>
<li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
<li><code>total</code> - integer - Total number of destinations.</li>
</ul>
<h2 id="reset-connection-timeout"><a class="header" href="#reset-connection-timeout">Reset connection timeout</a></h2>
<p>Synapse makes federation requests to other homeservers. If a federation request fails,
Synapse will mark the destination homeserver as offline, preventing any future requests
to that server for a &quot;cooldown&quot; period. This period grows over time if the server
continues to fail its responses
(<a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>).</p>
<p>Admins can cancel the cooldown period with this API.</p>
<p>This API resets the retry timing for a specific remote server and tries to connect to
the remote server again. It does not wait for the next <code>retry_interval</code>.
The connection must have previously run into an error and <code>retry_last_ts</code>
(<a href="usage/administration/admin_api/federation.html#destination-details-api">Destination Details API</a>) must not be equal to <code>0</code>.</p>
<p>The connection attempt is carried out in the background and can take a while
even if the API already returns the http status 200.</p>
<p>The API is:</p>
<pre><code>POST /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/reset_connection

{}
</code></pre>
<p><strong>Parameters</strong></p>
<p>The following parameters should be set in the URL:</p>
<ul>
<li><code>destination</code> - Name of the remote server.</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="using-the-synapse-manhole"><a class="header" href="#using-the-synapse-manhole">Using the synapse manhole</a></h1>
<p>The &quot;manhole&quot; allows server administrators to access a Python shell on a running
Synapse installation. This is a very powerful mechanism for administration and
debugging.</p>
<p><strong><em>Security Warning</em></strong></p>
<p>Note that this will give administrative access to synapse to <strong>all users</strong> with
shell access to the server. It should therefore <strong>not</strong> be enabled in
environments where untrusted users have shell access.</p>
<h2 id="configuring-the-manhole"><a class="header" href="#configuring-the-manhole">Configuring the manhole</a></h2>
<p>To enable it, first add the <code>manhole</code> listener configuration in your
<code>homeserver.yaml</code>. You can find information on how to do that 
in the <a href="usage/configuration/config_documentation.html#manhole_settings">configuration manual</a>.
The configuration is slightly different if you're using docker.</p>
<h4 id="docker-config"><a class="header" href="#docker-config">Docker config</a></h4>
<p>If you are using Docker, set <code>bind_addresses</code> to <code>['0.0.0.0']</code> as shown:</p>
<pre><code class="language-yaml">listeners:
  - port: 9000
    bind_addresses: ['0.0.0.0']
    type: manhole
</code></pre>
<p>When using <code>docker run</code> to start the server, you will then need to change the command to the following to include the
<code>manhole</code> port forwarding. The <code>-p 127.0.0.1:9000:9000</code> below is important: it 
ensures that access to the <code>manhole</code> is only possible for local users.</p>
<pre><code class="language-bash">docker run -d --name synapse \
    --mount type=volume,src=synapse-data,dst=/data \
    -p 8008:8008 \
    -p 127.0.0.1:9000:9000 \
    matrixdotorg/synapse:latest
</code></pre>
<h4 id="native-config"><a class="header" href="#native-config">Native config</a></h4>
<p>If you are not using docker, set <code>bind_addresses</code> to <code>['::1', '127.0.0.1']</code> as shown.
The <code>bind_addresses</code> in the example below is important: it ensures that access to the
<code>manhole</code> is only possible for local users).</p>
<pre><code class="language-yaml">listeners:
  - port: 9000
    bind_addresses: ['::1', '127.0.0.1']
    type: manhole
</code></pre>
<h3 id="security-settings"><a class="header" href="#security-settings">Security settings</a></h3>
<p>The following config options are available:</p>
<ul>
<li><code>username</code> - The username for the manhole (defaults to <code>matrix</code>)</li>
<li><code>password</code> - The password for the manhole (defaults to <code>rabbithole</code>)</li>
<li><code>ssh_priv_key</code> - The path to a private SSH key (defaults to a hardcoded value)</li>
<li><code>ssh_pub_key</code> - The path to a public SSH key (defaults to a hardcoded value)</li>
</ul>
<p>For example:</p>
<pre><code class="language-yaml">manhole_settings:
  username: manhole
  password: mypassword
  ssh_priv_key: &quot;/home/synapse/manhole_keys/id_rsa&quot;
  ssh_pub_key: &quot;/home/synapse/manhole_keys/id_rsa.pub&quot;
</code></pre>
<h2 id="accessing-synapse-manhole"><a class="header" href="#accessing-synapse-manhole">Accessing synapse manhole</a></h2>
<p>Then restart synapse, and point an ssh client at port 9000 on localhost, using
the username and password configured in <code>homeserver.yaml</code> - with the default 
configuration, this would be:</p>
<pre><code class="language-bash">ssh -p9000 matrix@localhost
</code></pre>
<p>Then enter the password when prompted (the default is <code>rabbithole</code>).</p>
<p>This gives a Python REPL in which <code>hs</code> gives access to the
<code>synapse.server.HomeServer</code> object - which in turn gives access to many other
parts of the process.</p>
<p>Note that, prior to Synapse 1.41, any call which returns a coroutine will need to be wrapped in <code>ensureDeferred</code>.</p>
<p>As a simple example, retrieving an event from the database:</p>
<pre><code class="language-pycon">&gt;&gt;&gt; from twisted.internet import defer
&gt;&gt;&gt; defer.ensureDeferred(hs.get_datastores().main.get_event('$1416420717069yeQaw:matrix.org'))
&lt;Deferred at 0x7ff253fc6998 current result: &lt;FrozenEvent event_id='$1416420717069yeQaw:matrix.org', type='m.room.create', state_key=''&gt;&gt;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="how-to-monitor-synapse-metrics-using-prometheus"><a class="header" href="#how-to-monitor-synapse-metrics-using-prometheus">How to monitor Synapse metrics using Prometheus</a></h1>
<ol>
<li>
<p>Install Prometheus:</p>
<p>Follow instructions at
<a href="http://prometheus.io/docs/introduction/install/">http://prometheus.io/docs/introduction/install/</a></p>
</li>
<li>
<p>Enable Synapse metrics:</p>
<p>In <code>homeserver.yaml</code>, make sure <code>enable_metrics</code> is
set to <code>True</code>.</p>
</li>
<li>
<p>Enable the <code>/_synapse/metrics</code> Synapse endpoint that Prometheus uses to
collect data:</p>
<p>There are two methods of enabling the metrics endpoint in Synapse.</p>
<p>The first serves the metrics as a part of the usual web server and
can be enabled by adding the <code>metrics</code> resource to the existing
listener as such as in this example:</p>
<pre><code class="language-yaml">listeners:
  - port: 8008
    tls: false
    type: http
    x_forwarded: true
    bind_addresses: ['::1', '127.0.0.1']

    resources:
      # added &quot;metrics&quot; in this line
      - names: [client, federation, metrics]
        compress: false
</code></pre>
<p>This provides a simple way of adding metrics to your Synapse
installation, and serves under <code>/_synapse/metrics</code>. If you do not
wish your metrics be publicly exposed, you will need to either
filter it out at your load balancer, or use the second method.</p>
<p>The second method runs the metrics server on a different port, in a
different thread to Synapse. This can make it more resilient to
heavy load meaning metrics cannot be retrieved, and can be exposed
to just internal networks easier. The served metrics are available
over HTTP only, and will be available at <code>/_synapse/metrics</code>.</p>
<p>Add a new listener to homeserver.yaml as in this example:</p>
<pre><code class="language-yaml">listeners:
  - port: 8008
    tls: false
    type: http
    x_forwarded: true
    bind_addresses: ['::1', '127.0.0.1']

    resources:
      - names: [client, federation]
        compress: false

  # beginning of the new metrics listener
  - port: 9000
    type: metrics
    bind_addresses: ['::1', '127.0.0.1']
</code></pre>
</li>
<li>
<p>Restart Synapse.</p>
</li>
<li>
<p>Add a Prometheus target for Synapse.</p>
<p>It needs to set the <code>metrics_path</code> to a non-default value (under
<code>scrape_configs</code>):</p>
<pre><code class="language-yaml">  - job_name: &quot;synapse&quot;
    scrape_interval: 15s
    metrics_path: &quot;/_synapse/metrics&quot;
    static_configs:
      - targets: [&quot;my.server.here:port&quot;]
</code></pre>
<p>where <code>my.server.here</code> is the IP address of Synapse, and <code>port</code> is
the listener port configured with the <code>metrics</code> resource.</p>
<p>If your prometheus is older than 1.5.2, you will need to replace
<code>static_configs</code> in the above with <code>target_groups</code>.</p>
</li>
<li>
<p>Restart Prometheus.</p>
</li>
<li>
<p>Consider using the <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana/">grafana dashboard</a>
and required <a href="https://github.com/matrix-org/synapse/tree/master/contrib/prometheus/">recording rules</a> </p>
</li>
</ol>
<h2 id="monitoring-workers"><a class="header" href="#monitoring-workers">Monitoring workers</a></h2>
<p>To monitor a Synapse installation using <a href="workers.html">workers</a>,
every worker needs to be monitored independently, in addition to
the main homeserver process. This is because workers don't send
their metrics to the main homeserver process, but expose them
directly (if they are configured to do so).</p>
<p>To allow collecting metrics from a worker, you need to add a
<code>metrics</code> listener to its configuration, by adding the following
under <code>worker_listeners</code>:</p>
<pre><code class="language-yaml">  - type: metrics
    bind_address: ''
    port: 9101
</code></pre>
<p>The <code>bind_address</code> and <code>port</code> parameters should be set so that
the resulting listener can be reached by prometheus, and they
don't clash with an existing worker.
With this example, the worker's metrics would then be available
on <code>http://127.0.0.1:9101</code>.</p>
<p>Example Prometheus target for Synapse with workers:</p>
<pre><code class="language-yaml">  - job_name: &quot;synapse&quot;
    scrape_interval: 15s
    metrics_path: &quot;/_synapse/metrics&quot;
    static_configs:
      - targets: [&quot;my.server.here:port&quot;]
        labels:
          instance: &quot;my.server&quot;
          job: &quot;master&quot;
          index: 1
      - targets: [&quot;my.workerserver.here:port&quot;]
        labels:
          instance: &quot;my.server&quot;
          job: &quot;generic_worker&quot;
          index: 1
      - targets: [&quot;my.workerserver.here:port&quot;]
        labels:
          instance: &quot;my.server&quot;
          job: &quot;generic_worker&quot;
          index: 2
      - targets: [&quot;my.workerserver.here:port&quot;]
        labels:
          instance: &quot;my.server&quot;
          job: &quot;media_repository&quot;
          index: 1
</code></pre>
<p>Labels (<code>instance</code>, <code>job</code>, <code>index</code>) can be defined as anything.
The labels are used to group graphs in grafana.</p>
<h2 id="renaming-of-metrics--deprecation-of-old-names-in-12"><a class="header" href="#renaming-of-metrics--deprecation-of-old-names-in-12">Renaming of metrics &amp; deprecation of old names in 1.2</a></h2>
<p>Synapse 1.2 updates the Prometheus metrics to match the naming
convention of the upstream <code>prometheus_client</code>. The old names are
considered deprecated and will be removed in a future version of
Synapse.
<strong>The old names will be disabled by default in Synapse v1.71.0 and removed
altogether in Synapse v1.73.0.</strong></p>
<table><thead><tr><th>New Name</th><th>Old Name</th></tr></thead><tbody>
<tr><td>python_gc_objects_collected_total</td><td>python_gc_objects_collected</td></tr>
<tr><td>python_gc_objects_uncollectable_total</td><td>python_gc_objects_uncollectable</td></tr>
<tr><td>python_gc_collections_total</td><td>python_gc_collections</td></tr>
<tr><td>process_cpu_seconds_total</td><td>process_cpu_seconds</td></tr>
<tr><td>synapse_federation_client_sent_transactions_total</td><td>synapse_federation_client_sent_transactions</td></tr>
<tr><td>synapse_federation_client_events_processed_total</td><td>synapse_federation_client_events_processed</td></tr>
<tr><td>synapse_event_processing_loop_count_total</td><td>synapse_event_processing_loop_count</td></tr>
<tr><td>synapse_event_processing_loop_room_count_total</td><td>synapse_event_processing_loop_room_count</td></tr>
<tr><td>synapse_util_caches_cache_hits</td><td>synapse_util_caches_cache:hits</td></tr>
<tr><td>synapse_util_caches_cache_size</td><td>synapse_util_caches_cache:size</td></tr>
<tr><td>synapse_util_caches_cache_evicted_size</td><td>synapse_util_caches_cache:evicted_size</td></tr>
<tr><td>synapse_util_caches_cache</td><td>synapse_util_caches_cache:total</td></tr>
<tr><td>synapse_util_caches_response_cache_size</td><td>synapse_util_caches_response_cache:size</td></tr>
<tr><td>synapse_util_caches_response_cache_hits</td><td>synapse_util_caches_response_cache:hits</td></tr>
<tr><td>synapse_util_caches_response_cache_evicted_size</td><td>synapse_util_caches_response_cache:evicted_size</td></tr>
<tr><td>synapse_util_metrics_block_count_total</td><td>synapse_util_metrics_block_count</td></tr>
<tr><td>synapse_util_metrics_block_time_seconds_total</td><td>synapse_util_metrics_block_time_seconds</td></tr>
<tr><td>synapse_util_metrics_block_ru_utime_seconds_total</td><td>synapse_util_metrics_block_ru_utime_seconds</td></tr>
<tr><td>synapse_util_metrics_block_ru_stime_seconds_total</td><td>synapse_util_metrics_block_ru_stime_seconds</td></tr>
<tr><td>synapse_util_metrics_block_db_txn_count_total</td><td>synapse_util_metrics_block_db_txn_count</td></tr>
<tr><td>synapse_util_metrics_block_db_txn_duration_seconds_total</td><td>synapse_util_metrics_block_db_txn_duration_seconds</td></tr>
<tr><td>synapse_util_metrics_block_db_sched_duration_seconds_total</td><td>synapse_util_metrics_block_db_sched_duration_seconds</td></tr>
<tr><td>synapse_background_process_start_count_total</td><td>synapse_background_process_start_count</td></tr>
<tr><td>synapse_background_process_ru_utime_seconds_total</td><td>synapse_background_process_ru_utime_seconds</td></tr>
<tr><td>synapse_background_process_ru_stime_seconds_total</td><td>synapse_background_process_ru_stime_seconds</td></tr>
<tr><td>synapse_background_process_db_txn_count_total</td><td>synapse_background_process_db_txn_count</td></tr>
<tr><td>synapse_background_process_db_txn_duration_seconds_total</td><td>synapse_background_process_db_txn_duration_seconds</td></tr>
<tr><td>synapse_background_process_db_sched_duration_seconds_total</td><td>synapse_background_process_db_sched_duration_seconds</td></tr>
<tr><td>synapse_storage_events_persisted_events_total</td><td>synapse_storage_events_persisted_events</td></tr>
<tr><td>synapse_storage_events_persisted_events_sep_total</td><td>synapse_storage_events_persisted_events_sep</td></tr>
<tr><td>synapse_storage_events_state_delta_total</td><td>synapse_storage_events_state_delta</td></tr>
<tr><td>synapse_storage_events_state_delta_single_event_total</td><td>synapse_storage_events_state_delta_single_event</td></tr>
<tr><td>synapse_storage_events_state_delta_reuse_delta_total</td><td>synapse_storage_events_state_delta_reuse_delta</td></tr>
<tr><td>synapse_federation_server_received_pdus_total</td><td>synapse_federation_server_received_pdus</td></tr>
<tr><td>synapse_federation_server_received_edus_total</td><td>synapse_federation_server_received_edus</td></tr>
<tr><td>synapse_handler_presence_notified_presence_total</td><td>synapse_handler_presence_notified_presence</td></tr>
<tr><td>synapse_handler_presence_federation_presence_out_total</td><td>synapse_handler_presence_federation_presence_out</td></tr>
<tr><td>synapse_handler_presence_presence_updates_total</td><td>synapse_handler_presence_presence_updates</td></tr>
<tr><td>synapse_handler_presence_timers_fired_total</td><td>synapse_handler_presence_timers_fired</td></tr>
<tr><td>synapse_handler_presence_federation_presence_total</td><td>synapse_handler_presence_federation_presence</td></tr>
<tr><td>synapse_handler_presence_bump_active_time_total</td><td>synapse_handler_presence_bump_active_time</td></tr>
<tr><td>synapse_federation_client_sent_edus_total</td><td>synapse_federation_client_sent_edus</td></tr>
<tr><td>synapse_federation_client_sent_pdu_destinations_count_total</td><td>synapse_federation_client_sent_pdu_destinations:count</td></tr>
<tr><td>synapse_federation_client_sent_pdu_destinations_total</td><td>synapse_federation_client_sent_pdu_destinations:total</td></tr>
<tr><td>synapse_handlers_appservice_events_processed_total</td><td>synapse_handlers_appservice_events_processed</td></tr>
<tr><td>synapse_notifier_notified_events_total</td><td>synapse_notifier_notified_events</td></tr>
<tr><td>synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter_total</td><td>synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter</td></tr>
<tr><td>synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter_total</td><td>synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter</td></tr>
<tr><td>synapse_http_httppusher_http_pushes_processed_total</td><td>synapse_http_httppusher_http_pushes_processed</td></tr>
<tr><td>synapse_http_httppusher_http_pushes_failed_total</td><td>synapse_http_httppusher_http_pushes_failed</td></tr>
<tr><td>synapse_http_httppusher_badge_updates_processed_total</td><td>synapse_http_httppusher_badge_updates_processed</td></tr>
<tr><td>synapse_http_httppusher_badge_updates_failed_total</td><td>synapse_http_httppusher_badge_updates_failed</td></tr>
<tr><td>synapse_admin_mau_current</td><td>synapse_admin_mau:current</td></tr>
<tr><td>synapse_admin_mau_max</td><td>synapse_admin_mau:max</td></tr>
<tr><td>synapse_admin_mau_registered_reserved_users</td><td>synapse_admin_mau:registered_reserved_users</td></tr>
</tbody></table>
<h2 id="removal-of-deprecated-metrics--time-based-counters-becoming-histograms-in-0310"><a class="header" href="#removal-of-deprecated-metrics--time-based-counters-becoming-histograms-in-0310">Removal of deprecated metrics &amp; time based counters becoming histograms in 0.31.0</a></h2>
<p>The duplicated metrics deprecated in Synapse 0.27.0 have been removed.</p>
<p>All time duration-based metrics have been changed to be seconds. This
affects:</p>
<table><thead><tr><th>msec -&gt; sec metrics</th></tr></thead><tbody>
<tr><td>python_gc_time</td></tr>
<tr><td>python_twisted_reactor_tick_time</td></tr>
<tr><td>synapse_storage_query_time</td></tr>
<tr><td>synapse_storage_schedule_time</td></tr>
<tr><td>synapse_storage_transaction_time</td></tr>
</tbody></table>
<p>Several metrics have been changed to be histograms, which sort entries
into buckets and allow better analysis. The following metrics are now
histograms:</p>
<table><thead><tr><th>Altered metrics</th></tr></thead><tbody>
<tr><td>python_gc_time</td></tr>
<tr><td>python_twisted_reactor_pending_calls</td></tr>
<tr><td>python_twisted_reactor_tick_time</td></tr>
<tr><td>synapse_http_server_response_time_seconds</td></tr>
<tr><td>synapse_storage_query_time</td></tr>
<tr><td>synapse_storage_schedule_time</td></tr>
<tr><td>synapse_storage_transaction_time</td></tr>
</tbody></table>
<h2 id="block-and-response-metrics-renamed-for-0270"><a class="header" href="#block-and-response-metrics-renamed-for-0270">Block and response metrics renamed for 0.27.0</a></h2>
<p>Synapse 0.27.0 begins the process of rationalising the duplicate
<code>*:count</code> metrics reported for the resource tracking for code blocks and
HTTP requests.</p>
<p>At the same time, the corresponding <code>*:total</code> metrics are being renamed,
as the <code>:total</code> suffix no longer makes sense in the absence of a
corresponding <code>:count</code> metric.</p>
<p>To enable a graceful migration path, this release just adds new names
for the metrics being renamed. A future release will remove the old
ones.</p>
<p>The following table shows the new metrics, and the old metrics which
they are replacing.</p>
<table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
<tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_timer:count</td></tr>
<tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_utime:count</td></tr>
<tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_stime:count</td></tr>
<tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_count:count</td></tr>
<tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_duration:count</td></tr>
<tr><td>synapse_util_metrics_block_time_seconds</td><td>synapse_util_metrics_block_timer:total</td></tr>
<tr><td>synapse_util_metrics_block_ru_utime_seconds</td><td>synapse_util_metrics_block_ru_utime:total</td></tr>
<tr><td>synapse_util_metrics_block_ru_stime_seconds</td><td>synapse_util_metrics_block_ru_stime:total</td></tr>
<tr><td>synapse_util_metrics_block_db_txn_count</td><td>synapse_util_metrics_block_db_txn_count:total</td></tr>
<tr><td>synapse_util_metrics_block_db_txn_duration_seconds</td><td>synapse_util_metrics_block_db_txn_duration:total</td></tr>
<tr><td>synapse_http_server_response_count</td><td>synapse_http_server_requests</td></tr>
<tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_time:count</td></tr>
<tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_utime:count</td></tr>
<tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_stime:count</td></tr>
<tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_count:count</td></tr>
<tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_duration:count</td></tr>
<tr><td>synapse_http_server_response_time_seconds</td><td>synapse_http_server_response_time:total</td></tr>
<tr><td>synapse_http_server_response_ru_utime_seconds</td><td>synapse_http_server_response_ru_utime:total</td></tr>
<tr><td>synapse_http_server_response_ru_stime_seconds</td><td>synapse_http_server_response_ru_stime:total</td></tr>
<tr><td>synapse_http_server_response_db_txn_count</td><td>synapse_http_server_response_db_txn_count:total</td></tr>
<tr><td>synapse_http_server_response_db_txn_duration_seconds</td><td>synapse_http_server_response_db_txn_duration:total</td></tr>
</tbody></table>
<h2 id="standard-metric-names"><a class="header" href="#standard-metric-names">Standard Metric Names</a></h2>
<p>As of synapse version 0.18.2, the format of the process-wide metrics has
been changed to fit prometheus standard naming conventions. Additionally
the units have been changed to seconds, from milliseconds.</p>
<table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
<tr><td>process_cpu_user_seconds_total</td><td>process_resource_utime / 1000</td></tr>
<tr><td>process_cpu_system_seconds_total</td><td>process_resource_stime / 1000</td></tr>
<tr><td>process_open_fds (no 'type' label)</td><td>process_fds</td></tr>
</tbody></table>
<p>The python-specific counts of garbage collector performance have been
renamed.</p>
<table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
<tr><td>python_gc_time</td><td>reactor_gc_time</td></tr>
<tr><td>python_gc_unreachable_total</td><td>reactor_gc_unreachable</td></tr>
<tr><td>python_gc_counts</td><td>reactor_gc_counts</td></tr>
</tbody></table>
<p>The twisted-specific reactor metrics have been renamed.</p>
<table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
<tr><td>python_twisted_reactor_pending_calls</td><td>reactor_pending_calls</td></tr>
<tr><td>python_twisted_reactor_tick_time</td><td>reactor_tick_time</td></tr>
</tbody></table>
<div style="break-before: page; page-break-before: always;"></div><h1 id="reporting-homeserver-usage-statistics"><a class="header" href="#reporting-homeserver-usage-statistics">Reporting Homeserver Usage Statistics</a></h1>
<p>When generating your Synapse configuration file, you are asked whether you
would like to report usage statistics to Matrix.org. These statistics
provide the foundation a glimpse into the number of Synapse homeservers
participating in the network, as well as statistics such as the number of
rooms being created and messages being sent. This feature is sometimes
affectionately called &quot;phone home&quot; stats. Reporting
<a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats">is optional</a>
and the reporting endpoint
<a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint">can be configured</a>,
in case you would like to instead report statistics from a set of homeservers
to your own infrastructure.</p>
<p>This documentation aims to define the statistics available and the
homeserver configuration options that exist to tweak it.</p>
<h2 id="available-statistics"><a class="header" href="#available-statistics">Available Statistics</a></h2>
<p>The following statistics are sent to the configured reporting endpoint:</p>
<table><thead><tr><th>Statistic Name</th><th>Type</th><th>Description</th></tr></thead><tbody>
<tr><td><code>homeserver</code></td><td>string</td><td>The homeserver's server name.</td></tr>
<tr><td><code>memory_rss</code></td><td>int</td><td>The memory usage of the process (in kilobytes on Unix-based systems, bytes on MacOS).</td></tr>
<tr><td><code>cpu_average</code></td><td>int</td><td>CPU time in % of a single core (not % of all cores).</td></tr>
<tr><td><code>server_context</code></td><td>string</td><td>An arbitrary string used to group statistics from a set of homeservers.</td></tr>
<tr><td><code>timestamp</code></td><td>int</td><td>The current time, represented as the number of seconds since the epoch.</td></tr>
<tr><td><code>uptime_seconds</code></td><td>int</td><td>The number of seconds since the homeserver was last started.</td></tr>
<tr><td><code>python_version</code></td><td>string</td><td>The Python version number in use (e.g &quot;3.7.1&quot;). Taken from <code>sys.version_info</code>.</td></tr>
<tr><td><code>total_users</code></td><td>int</td><td>The number of registered users on the homeserver.</td></tr>
<tr><td><code>total_nonbridged_users</code></td><td>int</td><td>The number of users, excluding those created by an Application Service.</td></tr>
<tr><td><code>daily_user_type_native</code></td><td>int</td><td>The number of native users created in the last 24 hours.</td></tr>
<tr><td><code>daily_user_type_guest</code></td><td>int</td><td>The number of guest users created in the last 24 hours.</td></tr>
<tr><td><code>daily_user_type_bridged</code></td><td>int</td><td>The number of users created by Application Services in the last 24 hours.</td></tr>
<tr><td><code>total_room_count</code></td><td>int</td><td>The total number of rooms present on the homeserver.</td></tr>
<tr><td><code>daily_active_users</code></td><td>int</td><td>The number of unique users<sup class="footnote-reference"><a href="#1">1</a></sup> that have used the homeserver in the last 24 hours.</td></tr>
<tr><td><code>monthly_active_users</code></td><td>int</td><td>The number of unique users<sup class="footnote-reference"><a href="#1">1</a></sup> that have used the homeserver in the last 30 days.</td></tr>
<tr><td><code>daily_active_rooms</code></td><td>int</td><td>The number of rooms that have had a (state) event with the type <code>m.room.message</code> sent in them in the last 24 hours.</td></tr>
<tr><td><code>daily_active_e2ee_rooms</code></td><td>int</td><td>The number of rooms that have had a (state) event with the type <code>m.room.encrypted</code> sent in them in the last 24 hours.</td></tr>
<tr><td><code>daily_messages</code></td><td>int</td><td>The number of (state) events with the type <code>m.room.message</code> seen in the last 24 hours.</td></tr>
<tr><td><code>daily_e2ee_messages</code></td><td>int</td><td>The number of (state) events with the type <code>m.room.encrypted</code> seen in the last 24 hours.</td></tr>
<tr><td><code>daily_sent_messages</code></td><td>int</td><td>The number of (state) events sent by a local user with the type <code>m.room.message</code> seen in the last 24 hours.</td></tr>
<tr><td><code>daily_sent_e2ee_messages</code></td><td>int</td><td>The number of (state) events sent by a local user with the type <code>m.room.encrypted</code> seen in the last 24 hours.</td></tr>
<tr><td><code>r30v2_users_all</code></td><td>int</td><td>The number of 30 day retained users, with a revised algorithm. Defined as users that appear more than once in the past 60 days, and have more than 30 days between the most and least recent appearances in the past 60 days. Includes clients that do not fit into the below r30 client types.</td></tr>
<tr><td><code>r30v2_users_android</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with (&quot;riot&quot; or &quot;element&quot;) and &quot;android&quot; (case-insensitive) in the user agent string.</td></tr>
<tr><td><code>r30v2_users_ios</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with (&quot;riot&quot; or &quot;element&quot;) and &quot;ios&quot; (case-insensitive) in the user agent string.</td></tr>
<tr><td><code>r30v2_users_electron</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with (&quot;riot&quot; or &quot;element&quot;) and &quot;electron&quot; (case-insensitive) in the user agent string.</td></tr>
<tr><td><code>r30v2_users_web</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with &quot;mozilla&quot; or &quot;gecko&quot; (case-insensitive) in the user agent string.</td></tr>
<tr><td><code>cache_factor</code></td><td>int</td><td>The configured <a href="usage/administration/monitoring/../../configuration/config_documentation.html#caching"><code>global factor</code></a> value for caching.</td></tr>
<tr><td><code>event_cache_size</code></td><td>int</td><td>The configured <a href="usage/administration/monitoring/../../configuration/config_documentation.html#caching"><code>event_cache_size</code></a> value for caching.</td></tr>
<tr><td><code>database_engine</code></td><td>string</td><td>The database engine that is in use. Either &quot;psycopg2&quot; meaning PostgreSQL is in use, or &quot;sqlite3&quot; for SQLite3.</td></tr>
<tr><td><code>database_server_version</code></td><td>string</td><td>The version of the database server. Examples being &quot;10.10&quot; for PostgreSQL server version 10.0, and &quot;3.38.5&quot; for SQLite 3.38.5 installed on the system.</td></tr>
<tr><td><code>log_level</code></td><td>string</td><td>The log level in use. Examples are &quot;INFO&quot;, &quot;WARNING&quot;, &quot;ERROR&quot;, &quot;DEBUG&quot;, etc.</td></tr>
</tbody></table>
<div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
<p>Native matrix users and guests are always counted. If the
<a href="usage/administration/monitoring/../../configuration/config_documentation.html#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a>
option is set to <code>true</code>, &quot;puppeted&quot; users (users that an Application Service have performed
<a href="https://spec.matrix.org/v1.3/application-service-api/#identity-assertion">an action on behalf of</a>)
will also be counted. Note that an Application Service can &quot;puppet&quot; any user in their
<a href="https://spec.matrix.org/v1.3/application-service-api/#registration">user namespace</a>,
not only users that the Application Service has created. If this happens, the Application Service
will additionally be counted as a user (irrespective of <code>track_puppeted_user_ips</code>).</p>
</div>
<h2 id="using-a-custom-statistics-collection-server"><a class="header" href="#using-a-custom-statistics-collection-server">Using a Custom Statistics Collection Server</a></h2>
<p>If statistics reporting is enabled, the endpoint that Synapse sends metrics to is configured by the
<a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint"><code>report_stats_endpoint</code></a> config
option. By default, statistics are sent to Matrix.org.</p>
<p>If you would like to set up your own statistics collection server and send metrics there, you may
consider using one of the following known implementations:</p>
<ul>
<li><a href="https://github.com/matrix-org/panopticon">Matrix.org's Panopticon</a></li>
<li><a href="https://gitlab.com/famedly/infra/services/barad-dur">Famedly's Barad-dûr</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="monthly-active-users"><a class="header" href="#monthly-active-users">Monthly Active Users</a></h1>
<p>Synapse can be configured to record the number of monthly active users (also referred to as MAU) on a given homeserver.
For clarity's sake, MAU only tracks local users.</p>
<p>Please note that the metrics recorded by the <a href="usage/administration/../../usage/administration/monitoring/reporting_homeserver_usage_statistics.html">Homeserver Usage Stats</a>
are calculated differently. The <code>monthly_active_users</code> from the usage stats does not take into account any
of the rules below, and counts any users who have made a request to the homeserver in the last 30 days.</p>
<p>See the <a href="usage/administration/../../usage/configuration/config_documentation.html#limit_usage_by_mau">configuration manual</a> for details on how to configure MAU.</p>
<h2 id="calculating-active-users"><a class="header" href="#calculating-active-users">Calculating active users</a></h2>
<p>Individual user activity is measured in active days. If a user performs an action, the exact time of that action is then recorded. When
calculating the MAU figure, any users with a recorded action in the last 30 days are considered part of the cohort. Days are measured
as a rolling window from the current system time to 30 days ago.</p>
<p>So for example, if Synapse were to calculate the active users on the 15th July at 13:25, it would include any activity from 15th June 13:25 onwards.</p>
<p>A user is <strong>never</strong> considered active if they are either:</p>
<ul>
<li>Part of the trial day cohort (described below)</li>
<li>Owned by an application service.
<ul>
<li>Note: This <strong>only</strong> covers users that are part of an application service <code>namespaces.users</code> registration. The namespace
must also be marked as <code>exclusive</code>.</li>
</ul>
</li>
</ul>
<p>Otherwise, any request to Synapse will mark the user as active. Please note that registration will not mark a user as active <em>unless</em> 
they register with a 3pid that is included in the config field <code>mau_limits_reserved_threepids</code>.</p>
<p>The Prometheus metric for MAU is refreshed every 5 minutes.</p>
<p>Once an hour, Synapse checks to see if any users are inactive (with only activity timestamps later than 30 days). These users
are removed from the active users cohort. If they then become active, they are immediately restored to the cohort.</p>
<p>It is important to note that <strong>deactivated</strong> users are not immediately removed from the pool of active users, but as these users won't
perform actions they will eventually be removed from the cohort.</p>
<h3 id="trial-days"><a class="header" href="#trial-days">Trial days</a></h3>
<p>If the config option <code>mau_trial_days</code> is set, a user must have been active this many days <strong>after</strong> registration to be active. A user is in the
trial period if their registration timestamp (also known as the <code>creation_ts</code>) is less than <code>mau_trial_days</code> old.</p>
<p>As an example, if <code>mau_trial_days</code> is set to <code>3</code> and a user is active <strong>after</strong> 3 days (72 hours from registration time) then they will be counted as active.</p>
<p>The <code>mau_appservice_trial_days</code> config further extends this rule by applying different durations depending on the <code>appservice_id</code> of the user.
Users registered by an application service will be recorded with an <code>appservice_id</code> matching the <code>id</code> key in the registration file for that service.</p>
<h2 id="limiting-usage-of-the-homeserver-when-the-maximum-mau-is-reached"><a class="header" href="#limiting-usage-of-the-homeserver-when-the-maximum-mau-is-reached">Limiting usage of the homeserver when the maximum MAU is reached</a></h2>
<p>If both config options <code>limit_usage_by_mau</code> and <code>max_mau_value</code> is set, and the current MAU value exceeds the maximum value, the 
homeserver will begin to block some actions.</p>
<p>Individual users matching <strong>any</strong> of the below criteria never have their actions blocked:</p>
<ul>
<li>Considered part of the cohort of MAU users.</li>
<li>Considered part of the trial period.</li>
<li>Registered as a <code>support</code> user.</li>
<li>Application service users if <code>track_appservice_user_ips</code> is NOT set.</li>
</ul>
<p>Please not that server admins are <strong>not</strong> exempt from blocking.</p>
<p>The following actions are blocked when the MAU limit is exceeded:</p>
<ul>
<li>Logging in</li>
<li>Sending events</li>
<li>Creating rooms</li>
<li>Syncing</li>
</ul>
<p>Registration is also blocked for all new signups <em>unless</em> the user is registering with a threepid included in the <code>mau_limits_reserved_threepids</code>
config value.</p>
<p>When a request is blocked, the response will have the <code>errcode</code> <code>M_RESOURCE_LIMIT_EXCEEDED</code>.</p>
<h2 id="metrics-1"><a class="header" href="#metrics-1">Metrics</a></h2>
<p>Synapse records several different prometheus metrics for MAU.</p>
<p><code>synapse_admin_mau_current</code> records the current MAU figure for native (non-application-service) users.</p>
<p><code>synapse_admin_mau_max</code> records the maximum MAU as dictated by the <code>max_mau_value</code> config value.</p>
<p><code>synapse_admin_mau_current_mau_by_service</code> records the current MAU including application service users. The label <code>app_service</code> can be used
to filter by a specific service ID. This <em>also</em> includes non-application-service users under <code>app_service=native</code> .</p>
<p><code>synapse_admin_mau_registered_reserved_users</code> records the number of users specified in <code>mau_limits_reserved_threepids</code> which have
registered accounts on the homeserver.</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="understanding-synapse-through-grafana-graphs"><a class="header" href="#understanding-synapse-through-grafana-graphs">Understanding Synapse through Grafana graphs</a></h2>
<p>It is possible to monitor much of the internal state of Synapse using <a href="https://prometheus.io">Prometheus</a> 
metrics and <a href="https://grafana.com/">Grafana</a>. 
A guide for configuring Synapse to provide metrics is available <a href="usage/administration/../../metrics-howto.html">here</a> 
and information on setting up Grafana is <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana">here</a>.
In this setup, Prometheus will periodically scrape the information Synapse provides and
store a record of it over time. Grafana is then used as an interface to query and
present this information through a series of pretty graphs.</p>
<p>Once you have grafana set up, and assuming you're using <a href="https://github.com/matrix-org/synapse/blob/master/contrib/grafana/synapse.json">our grafana dashboard template</a>, look for the following graphs when debugging a slow/overloaded Synapse:</p>
<h2 id="message-event-send-time"><a class="header" href="#message-event-send-time">Message Event Send Time</a></h2>
<p><img src="https://user-images.githubusercontent.com/1342360/82239409-a1c8e900-9930-11ea-8081-e4614e0c63f4.png" alt="image" /></p>
<p>This, along with the CPU and Memory graphs, is a good way to check the general health of your Synapse instance. It represents how long it takes for a user on your homeserver to send a message.</p>
<h2 id="transaction-count-and-transaction-duration"><a class="header" href="#transaction-count-and-transaction-duration">Transaction Count and Transaction Duration</a></h2>
<p><img src="https://user-images.githubusercontent.com/1342360/82239985-8d392080-9931-11ea-80d0-843ab2f22e1e.png" alt="image" /></p>
<p><img src="https://user-images.githubusercontent.com/1342360/82240050-ab068580-9931-11ea-98f1-f94671cbac9a.png" alt="image" /></p>
<p>These graphs show the database transactions that are occurring the most frequently, as well as those are that are taking the most amount of time to execute.</p>
<p><img src="https://user-images.githubusercontent.com/1342360/82240192-e86b1300-9931-11ea-9aac-3e2c9bfa6fdc.png" alt="image" /></p>
<p>In the first graph, we can see obvious spikes corresponding to lots of <code>get_user_by_id</code> transactions. This would be useful information to figure out which part of the Synapse codebase is potentially creating a heavy load on the system. However, be sure to cross-reference this with Transaction Duration, which states that <code>get_users_by_id</code> is actually a very quick database transaction and isn't causing as much load as others, like <code>persist_events</code>:</p>
<p><img src="https://user-images.githubusercontent.com/1342360/82240467-62030100-9932-11ea-8db9-917f2d977fe1.png" alt="image" /></p>
<p>Still, it's probably worth investigating why we're getting users from the database that often, and whether it's possible to reduce the amount of queries we make by adjusting our cache factor(s).</p>
<p>The <code>persist_events</code> transaction is responsible for saving new room events to the Synapse database, so can often show a high transaction duration.</p>
<h2 id="federation-2"><a class="header" href="#federation-2">Federation</a></h2>
<p>The charts in the &quot;Federation&quot; section show information about incoming and outgoing federation requests. Federation data can be divided into two basic types:</p>
<ul>
<li>PDU (Persistent Data Unit) - room events: messages, state events (join/leave), etc. These are permanently stored in the database.</li>
<li>EDU (Ephemeral Data Unit) - other data, which need not be stored permanently, such as read receipts, typing notifications.</li>
</ul>
<p>The &quot;Outgoing EDUs by type&quot; chart shows the EDUs within outgoing federation requests by type: <code>m.device_list_update</code>, <code>m.direct_to_device</code>, <code>m.presence</code>, <code>m.receipt</code>, <code>m.typing</code>.</p>
<p>If you see a large number of <code>m.presence</code> EDUs and are having trouble with too much CPU load, you can disable <code>presence</code> in the Synapse config. See also <a href="https://github.com/matrix-org/synapse/issues/3971">#3971</a>.</p>
<h2 id="caches"><a class="header" href="#caches">Caches</a></h2>
<p><img src="https://user-images.githubusercontent.com/1342360/82240572-8b239180-9932-11ea-96ff-6b5f0e57ebe5.png" alt="image" /></p>
<p><img src="https://user-images.githubusercontent.com/1342360/82240666-b8703f80-9932-11ea-86af-9f663988d8da.png" alt="image" /></p>
<p>This is quite a useful graph. It shows how many times Synapse attempts to retrieve a piece of data from a cache which the cache did not contain, thus resulting in a call to the database. We can see here that the <code>_get_joined_profile_from_event_id</code> cache is being requested a lot, and often the data we're after is not cached.</p>
<p>Cross-referencing this with the Eviction Rate graph, which shows that entries are being evicted from <code>_get_joined_profile_from_event_id</code> quite often:</p>
<p><img src="https://user-images.githubusercontent.com/1342360/82240766-de95df80-9932-11ea-8c15-5acfc57c48da.png" alt="image" /></p>
<p>we should probably consider raising the size of that cache by raising its cache factor (a multiplier value for the size of an individual cache). Information on doing so is available <a href="https://github.com/matrix-org/synapse/blob/ee421e524478c1ad8d43741c27379499c2f6135c/docs/sample_config.yaml#L608-L642">here</a> (note that the configuration of individual cache factors through the configuration file is available in Synapse v1.14.0+, whereas doing so through environment variables has been supported for a very long time). Note that this will increase Synapse's overall memory usage.</p>
<h2 id="forward-extremities"><a class="header" href="#forward-extremities">Forward Extremities</a></h2>
<p><img src="https://user-images.githubusercontent.com/1342360/82241440-13566680-9934-11ea-8b88-ba468db937ed.png" alt="image" /></p>
<p>Forward extremities are the leaf events at the end of a DAG in a room, aka events that have no children. The more that exist in a room, the more <a href="https://spec.matrix.org/v1.1/server-server-api/#room-state-resolution">state resolution</a> that Synapse needs to perform (hint: it's an expensive operation). While Synapse has code to prevent too many of these existing at one time in a room, bugs can sometimes make them crop up again.</p>
<p>If a room has &gt;10 forward extremities, it's worth checking which room is the culprit and potentially removing them using the SQL queries mentioned in <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
<h2 id="garbage-collection"><a class="header" href="#garbage-collection">Garbage Collection</a></h2>
<p><img src="https://user-images.githubusercontent.com/1342360/82241911-da6ac180-9934-11ea-9a0d-a311fe22acd0.png" alt="image" /></p>
<p>Large spikes in garbage collection times (bigger than shown here, I'm talking in the 
multiple seconds range), can cause lots of problems in Synapse performance. It's more an 
indicator of problems, and a symptom of other problems though, so check other graphs for what might be causing it.</p>
<h2 id="final-thoughts"><a class="header" href="#final-thoughts">Final Thoughts</a></h2>
<p>If you're still having performance problems with your Synapse instance and you've 
tried everything you can, it may just be a lack of system resources. Consider adding
more CPU and RAM, and make use of <a href="usage/administration/../../workers.html">worker mode</a> 
to make use of multiple CPU cores / multiple machines for your homeserver.</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="some-useful-sql-queries-for-synapse-admins"><a class="header" href="#some-useful-sql-queries-for-synapse-admins">Some useful SQL queries for Synapse Admins</a></h2>
<h2 id="size-of-full-matrix-db"><a class="header" href="#size-of-full-matrix-db">Size of full matrix db</a></h2>
<pre><code class="language-sql">SELECT pg_size_pretty( pg_database_size( 'matrix' ) );
</code></pre>
<h3 id="result-example"><a class="header" href="#result-example">Result example:</a></h3>
<pre><code>pg_size_pretty 
----------------
 6420 MB
(1 row)
</code></pre>
<h2 id="show-top-20-larger-tables-by-row-count"><a class="header" href="#show-top-20-larger-tables-by-row-count">Show top 20 larger tables by row count</a></h2>
<pre><code class="language-sql">SELECT relname, n_live_tup AS &quot;rows&quot;
  FROM pg_stat_user_tables
  ORDER BY n_live_tup DESC
  LIMIT 20;
</code></pre>
<p>This query is quick, but may be very approximate, for exact number of rows use:</p>
<pre><code class="language-sql">SELECT COUNT(*) FROM &lt;table_name&gt;;
</code></pre>
<h3 id="result-example-1"><a class="header" href="#result-example-1">Result example:</a></h3>
<pre><code>state_groups_state - 161687170
event_auth - 8584785
event_edges - 6995633
event_json - 6585916
event_reference_hashes - 6580990
events - 6578879
received_transactions - 5713989
event_to_state_groups - 4873377
stream_ordering_to_exterm - 4136285
current_state_delta_stream - 3770972
event_search - 3670521
state_events - 2845082
room_memberships - 2785854
cache_invalidation_stream - 2448218
state_groups - 1255467
state_group_edges - 1229849
current_state_events - 1222905
users_in_public_rooms - 364059
device_lists_stream - 326903
user_directory_search - 316433
</code></pre>
<h2 id="show-top-20-larger-tables-by-storage-size"><a class="header" href="#show-top-20-larger-tables-by-storage-size">Show top 20 larger tables by storage size</a></h2>
<pre><code class="language-sql">SELECT nspname || '.' || relname AS &quot;relation&quot;,
    pg_size_pretty(pg_total_relation_size(c.oid)) AS &quot;total_size&quot;
  FROM pg_class c
  LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
  WHERE nspname NOT IN ('pg_catalog', 'information_schema')
    AND c.relkind &lt;&gt; 'i'
    AND nspname !~ '^pg_toast'
  ORDER BY pg_total_relation_size(c.oid) DESC
  LIMIT 20;
</code></pre>
<h3 id="result-example-2"><a class="header" href="#result-example-2">Result example:</a></h3>
<pre><code>public.state_groups_state - 27 GB
public.event_json - 9855 MB
public.events - 3675 MB
public.event_edges - 3404 MB
public.received_transactions - 2745 MB
public.event_reference_hashes - 1864 MB
public.event_auth - 1775 MB
public.stream_ordering_to_exterm - 1663 MB
public.event_search - 1370 MB
public.room_memberships - 1050 MB
public.event_to_state_groups - 948 MB
public.current_state_delta_stream - 711 MB
public.state_events - 611 MB
public.presence_stream - 530 MB
public.current_state_events - 525 MB
public.cache_invalidation_stream - 466 MB
public.receipts_linearized - 279 MB
public.state_groups - 160 MB
public.device_lists_remote_cache - 124 MB
public.state_group_edges - 122 MB
</code></pre>
<h2 id="show-top-20-larger-rooms-by-state-events-count"><a class="header" href="#show-top-20-larger-rooms-by-state-events-count">Show top 20 larger rooms by state events count</a></h2>
<p>You get the same information when you use the
<a href="usage/administration/../../admin_api/rooms.html#list-room-api">admin API</a>
and set parameter <code>order_by=state_events</code>.</p>
<pre><code class="language-sql">SELECT r.name, s.room_id, s.current_state_events
  FROM room_stats_current s
  LEFT JOIN room_stats_state r USING (room_id)
  ORDER BY current_state_events DESC
  LIMIT 20;
</code></pre>
<p>and by state_group_events count:</p>
<pre><code class="language-sql">SELECT rss.name, s.room_id, COUNT(s.room_id)
  FROM state_groups_state s
  LEFT JOIN room_stats_state rss USING (room_id)
  GROUP BY s.room_id, rss.name
  ORDER BY COUNT(s.room_id) DESC
  LIMIT 20;
</code></pre>
<p>plus same, but with join removed for performance reasons:</p>
<pre><code class="language-sql">SELECT s.room_id, COUNT(s.room_id)
  FROM state_groups_state s
  GROUP BY s.room_id 
  ORDER BY COUNT(s.room_id) DESC
  LIMIT 20;
</code></pre>
<h2 id="show-top-20-rooms-by-new-events-count-in-last-1-day"><a class="header" href="#show-top-20-rooms-by-new-events-count-in-last-1-day">Show top 20 rooms by new events count in last 1 day:</a></h2>
<pre><code class="language-sql">SELECT e.room_id, r.name, COUNT(e.event_id) cnt
  FROM events e
  LEFT JOIN room_stats_state r USING (room_id)
  WHERE e.origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 day') * 1000
  GROUP BY e.room_id, r.name 
  ORDER BY cnt DESC
  LIMIT 20;
</code></pre>
<h2 id="show-top-20-users-on-homeserver-by-sent-events-messages-at-last-month"><a class="header" href="#show-top-20-users-on-homeserver-by-sent-events-messages-at-last-month">Show top 20 users on homeserver by sent events (messages) at last month:</a></h2>
<p>Caution. This query does not use any indexes, can be slow and create load on the database.</p>
<pre><code class="language-sql">SELECT COUNT(*), sender
  FROM events
  WHERE (type = 'm.room.encrypted' OR type = 'm.room.message')
    AND origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 month') * 1000
  GROUP BY sender
  ORDER BY COUNT(*) DESC
  LIMIT 20;
</code></pre>
<h2 id="show-last-100-messages-from-needed-user-with-room-names"><a class="header" href="#show-last-100-messages-from-needed-user-with-room-names">Show last 100 messages from needed user, with room names:</a></h2>
<pre><code class="language-sql">SELECT e.room_id, r.name, e.event_id, e.type, e.content, j.json
  FROM events e
  LEFT JOIN event_json j USING (room_id)
  LEFT JOIN room_stats_state r USING (room_id)
  WHERE sender = '@LOGIN:example.com'
    AND e.type = 'm.room.message'
  ORDER BY stream_ordering DESC
  LIMIT 100;
</code></pre>
<h2 id="show-rooms-with-names-sorted-by-events-in-this-rooms"><a class="header" href="#show-rooms-with-names-sorted-by-events-in-this-rooms">Show rooms with names, sorted by events in this rooms</a></h2>
<p><strong>Sort and order with bash</strong></p>
<pre><code class="language-bash">echo &quot;SELECT event_json.room_id, room_stats_state.name FROM event_json, room_stats_state \
WHERE room_stats_state.room_id = event_json.room_id&quot; | psql -d synapse -h localhost -U synapse_user -t \
| sort | uniq -c | sort -n
</code></pre>
<p>Documentation for <code>psql</code> command line parameters: https://www.postgresql.org/docs/current/app-psql.html</p>
<p><strong>Sort and order with SQL</strong></p>
<pre><code class="language-sql">SELECT COUNT(*), event_json.room_id, room_stats_state.name
  FROM event_json, room_stats_state
  WHERE room_stats_state.room_id = event_json.room_id
  GROUP BY event_json.room_id, room_stats_state.name
  ORDER BY COUNT(*) DESC
  LIMIT 50;
</code></pre>
<h3 id="result-example-3"><a class="header" href="#result-example-3">Result example:</a></h3>
<pre><code>   9459  !FPUfgzXYWTKgIrwKxW:matrix.org              | This Week in Matrix
   9459  !FPUfgzXYWTKgIrwKxW:matrix.org              | This Week in Matrix (TWIM)
  17799  !iDIOImbmXxwNngznsa:matrix.org              | Linux in Russian
  18739  !GnEEPYXUhoaHbkFBNX:matrix.org              | Riot Android
  23373  !QtykxKocfZaZOUrTwp:matrix.org              | Matrix HQ
  39504  !gTQfWzbYncrtNrvEkB:matrix.org              | ru.[matrix]
  43601  !iNmaIQExDMeqdITdHH:matrix.org              | Riot
  43601  !iNmaIQExDMeqdITdHH:matrix.org              | Riot Web/Desktop
</code></pre>
<h2 id="lookup-room-state-info-by-list-of-room_id"><a class="header" href="#lookup-room-state-info-by-list-of-room_id">Lookup room state info by list of room_id</a></h2>
<p>You get the same information when you use the
<a href="usage/administration/../../admin_api/rooms.html#room-details-api">admin API</a>.</p>
<pre><code class="language-sql">SELECT rss.room_id, rss.name, rss.canonical_alias, rss.topic, rss.encryption,
    rsc.joined_members, rsc.local_users_in_room, rss.join_rules
  FROM room_stats_state rss
  LEFT JOIN room_stats_current rsc USING (room_id)
  WHERE room_id IN ( WHERE room_id IN (
    '!OGEhHVWSdvArJzumhm:matrix.org',
    '!YTvKGNlinIzlkMTVRl:matrix.org' 
  );
</code></pre>
<h2 id="show-users-and-devices-that-have-not-been-online-for-a-while"><a class="header" href="#show-users-and-devices-that-have-not-been-online-for-a-while">Show users and devices that have not been online for a while</a></h2>
<pre><code class="language-sql">SELECT user_id, device_id, user_agent, TO_TIMESTAMP(last_seen / 1000) AS &quot;last_seen&quot;
  FROM devices
  WHERE last_seen &lt; DATE_PART('epoch', NOW() - INTERVAL '3 month') * 1000;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><p><em>This <a href="https://jacksonchen666.com/posts/2022-12-03/14-33-00/">blog post by Jackson Chen</a> (Dec 2022) explains how to use many of the tools listed on this page. There is also an <a href="https://levans.fr/shrink-synapse-database.html">earlier blog by Victor Berger</a> (June 2020), though this may be outdated in places.</em></p>
<h1 id="list-of-useful-tools-and-scripts-for-maintenance-synapse-database"><a class="header" href="#list-of-useful-tools-and-scripts-for-maintenance-synapse-database">List of useful tools and scripts for maintenance Synapse database:</a></h1>
<h2 id="purge-remote-media-api-1"><a class="header" href="#purge-remote-media-api-1"><a href="usage/administration/../../admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a></a></h2>
<p>The purge remote media API allows server admins to purge old cached remote media.</p>
<h2 id="purge-local-media-api"><a class="header" href="#purge-local-media-api"><a href="usage/administration/../../admin_api/media_admin_api.html#delete-local-media">Purge Local Media API</a></a></h2>
<p>This API deletes the <em>local</em> media from the disk of your own server.</p>
<h2 id="purge-history-api-1"><a class="header" href="#purge-history-api-1"><a href="usage/administration/../../admin_api/purge_history_api.html">Purge History API</a></a></h2>
<p>The purge history API allows server admins to purge historic events from their database, reclaiming disk space.</p>
<h2 id="synapse-compress-state"><a class="header" href="#synapse-compress-state"><a href="https://github.com/matrix-org/rust-synapse-compress-state">synapse-compress-state</a></a></h2>
<p>Tool for compressing (deduplicating) <code>state_groups_state</code> table.</p>
<h2 id="sql-for-analyzing-synapse-postgresql-database-stats"><a class="header" href="#sql-for-analyzing-synapse-postgresql-database-stats"><a href="usage/administration/useful_sql_for_admins.html">SQL for analyzing Synapse PostgreSQL database stats</a></a></h2>
<p>Some easy SQL that reports useful stats about your Synapse database.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="how-do-state-groups-work"><a class="header" href="#how-do-state-groups-work">How do State Groups work?</a></h1>
<p>As a general rule, I encourage people who want to understand the deepest darkest secrets of the database schema to drop by #synapse-dev:matrix.org and ask questions.</p>
<p>However, one question that comes up frequently is that of how &quot;state groups&quot; work, and why the <code>state_groups_state</code> table gets so big, so here's an attempt to answer that question.</p>
<p>We need to be able to relatively quickly calculate the state of a room at any point in that room's history. In other words, we need to know the state of the room at each event in that room. This is done as follows:</p>
<p>A sequence of events where the state is the same are grouped together into a <code>state_group</code>; the mapping is recorded in <code>event_to_state_groups</code>. (Technically speaking, since a state event usually changes the state in the room, we are recording the state of the room <em>after</em> the given event id: which is to say, to a handwavey simplification, the first event in a state group is normally a state event, and others in the same state group are normally non-state-events.)</p>
<p><code>state_groups</code> records, for each state group, the id of the room that we're looking at, and also the id of the first event in that group. (I'm not sure if that event id is used much in practice.) </p>
<p>Now, if we stored all the room state for each <code>state_group</code>, that would be a huge amount of data. Instead, for each state group, we normally store the difference between the state in that group and some other state group, and only occasionally (every 100 state changes or so) record the full state.</p>
<p>So, most state groups have an entry in <code>state_group_edges</code> (don't ask me why it's not a column in <code>state_groups</code>) which records the previous state group in the room, and <code>state_groups_state</code> records the differences in state since that previous state group.</p>
<p>A full state group just records the event id for each piece of state in the room at that point.</p>
<h2 id="known-bugs-with-state-groups"><a class="header" href="#known-bugs-with-state-groups">Known bugs with state groups</a></h2>
<p>There are various reasons that we can end up creating many more state groups than we need: see https://github.com/matrix-org/synapse/issues/3364 for more details.</p>
<h2 id="compression-tool"><a class="header" href="#compression-tool">Compression tool</a></h2>
<p>There is a tool at https://github.com/matrix-org/rust-synapse-compress-state which can compress the <code>state_groups_state</code> on a room by-room basis (essentially, it reduces the number of &quot;full&quot; state groups). This can result in dramatic reductions of the storage used.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="request-log-format"><a class="header" href="#request-log-format">Request log format</a></h1>
<p>HTTP request logs are written by synapse (see <a href="https://github.com/matrix-org/synapse/tree/develop/synapse/http/site.py"><code>synapse/http/site.py</code></a> for details).</p>
<p>See the following for how to decode the dense data available from the default logging configuration.</p>
<pre><code>2020-10-01 12:00:00,000 - synapse.access.http.8008 - 311 - INFO - PUT-1000- 192.168.0.1 - 8008 - {another-matrix-server.com} Processed request: 0.100sec/-0.000sec (0.000sec, 0.000sec) (0.001sec/0.090sec/3) 11B !200 &quot;PUT /_matrix/federation/v1/send/1600000000000 HTTP/1.1&quot; &quot;Synapse/1.20.1&quot; [0 dbevts]
-AAAAAAAAAAAAAAAAAAAAA-   -BBBBBBBBBBBBBBBBBBBBBB-   -C-   -DD-   -EEEEEE-  -FFFFFFFFF-   -GG-    -HHHHHHHHHHHHHHHHHHHHHHH-                     -IIIIII- -JJJJJJJ-  -KKKKKK-, -LLLLLL-  -MMMMMMM- -NNNNNN- O  -P- -QQ-  -RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR-   -SSSSSSSSSSSS-   -TTTTTT-
</code></pre>
<table><thead><tr><th>Part</th><th>Explanation</th></tr></thead><tbody>
<tr><td>AAAA</td><td>Timestamp request was logged (not received)</td></tr>
<tr><td>BBBB</td><td>Logger name (<code>synapse.access.(http\|https).&lt;tag&gt;</code>, where 'tag' is defined in the <a href="usage/administration/../configuration/config_documentation.html#listeners"><code>listeners</code></a> config section, normally the port)</td></tr>
<tr><td>CCCC</td><td>Line number in code</td></tr>
<tr><td>DDDD</td><td>Log Level</td></tr>
<tr><td>EEEE</td><td>Request Identifier (This identifier is shared by related log lines)</td></tr>
<tr><td>FFFF</td><td>Source IP (Or X-Forwarded-For if enabled)</td></tr>
<tr><td>GGGG</td><td>Server Port</td></tr>
<tr><td>HHHH</td><td>Federated Server or Local User making request (blank if unauthenticated or not supplied).<br/>If this is of the form `@aaa:example.com</td></tr>
<tr><td>IIII</td><td>Total Time to process the request</td></tr>
<tr><td>JJJJ</td><td>Time to send response over network once generated (this may be negative if the socket is closed before the response is generated)</td></tr>
<tr><td>KKKK</td><td>Userland CPU time</td></tr>
<tr><td>LLLL</td><td>System CPU time</td></tr>
<tr><td>MMMM</td><td>Total time waiting for a free DB connection from the pool across all parallel DB work from this request</td></tr>
<tr><td>NNNN</td><td>Total time waiting for response to DB queries across all parallel DB work from this request</td></tr>
<tr><td>OOOO</td><td>Count of DB transactions performed</td></tr>
<tr><td>PPPP</td><td>Response body size</td></tr>
<tr><td>QQQQ</td><td>Response status code<br/>Suffixed with <code>!</code> if the socket was closed before the response was generated.<br/>A <code>499!</code> status code indicates that Synapse also cancelled request processing after the socket was closed.<br/></td></tr>
<tr><td>RRRR</td><td>Request</td></tr>
<tr><td>SSSS</td><td>User-agent</td></tr>
<tr><td>TTTT</td><td>Events fetched from DB to service this request (note that this does not include events fetched from the cache)</td></tr>
</tbody></table>
<p>MMMM / NNNN can be greater than IIII if there are multiple slow database queries
running in parallel.</p>
<p>Some actions can result in multiple identical http requests, which will return
the same data, but only the first request will report time/transactions in
<code>KKKK</code>/<code>LLLL</code>/<code>MMMM</code>/<code>NNNN</code>/<code>OOOO</code> - the others will be awaiting the first query to return a
response and will simultaneously return with the first request, but with very
small processing times.</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="admin-faq"><a class="header" href="#admin-faq">Admin FAQ</a></h2>
<h2 id="how-do-i-become-a-server-admin"><a class="header" href="#how-do-i-become-a-server-admin">How do I become a server admin?</a></h2>
<p>If your server already has an admin account you should use the
<a href="usage/administration/../../admin_api/user_admin_api.html#change-whether-a-user-is-a-server-administrator-or-not">User Admin API</a>
to promote other accounts to become admins.</p>
<p>If you don't have any admin accounts yet you won't be able to use the admin API,
so you'll have to edit the database manually. Manually editing the database is
generally not recommended so once you have an admin account: use the admin APIs
to make further changes.</p>
<pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
</code></pre>
<h2 id="what-servers-are-my-server-talking-to"><a class="header" href="#what-servers-are-my-server-talking-to">What servers are my server talking to?</a></h2>
<p>Run this sql query on your db:</p>
<pre><code class="language-sql">SELECT * FROM destinations;
</code></pre>
<h2 id="what-servers-are-currently-participating-in-this-room"><a class="header" href="#what-servers-are-currently-participating-in-this-room">What servers are currently participating in this room?</a></h2>
<p>Run this sql query on your db:</p>
<pre><code class="language-sql">SELECT DISTINCT split_part(state_key, ':', 2)
FROM current_state_events
WHERE room_id = '!cURbafjkfsMDVwdRDQ:matrix.org' AND membership = 'join';
</code></pre>
<h2 id="what-users-are-registered-on-my-server"><a class="header" href="#what-users-are-registered-on-my-server">What users are registered on my server?</a></h2>
<pre><code class="language-sql">SELECT NAME from users;
</code></pre>
<h2 id="how-can-i-export-user-data"><a class="header" href="#how-can-i-export-user-data">How can I export user data?</a></h2>
<p>Synapse includes a Python command to export data for a specific user. It takes the homeserver
configuration file and the full Matrix ID of the user to export:</p>
<pre><code class="language-console">python -m synapse.app.admin_cmd -c &lt;config_file&gt; export-data &lt;user_id&gt; --output-directory &lt;directory_path&gt;
</code></pre>
<p>If you uses <a href="usage/administration/../../development/dependencies.html#managing-dependencies-with-poetry">Poetry</a>
to run Synapse:</p>
<pre><code class="language-console">poetry run python -m synapse.app.admin_cmd -c &lt;config_file&gt; export-data &lt;user_id&gt; --output-directory &lt;directory_path&gt;
</code></pre>
<p>The directory to store the export data in can be customised with the
<code>--output-directory</code> parameter; ensure that the provided directory is
empty. If this parameter is not provided, Synapse defaults to creating
a temporary directory (which starts with &quot;synapse-exfiltrate&quot;) in <code>/tmp</code>,
<code>/var/tmp</code>, or <code>/usr/tmp</code>, in that order.</p>
<p>The exported data has the following layout:</p>
<pre><code>output-directory
├───rooms
│   └───&lt;room_id&gt;
│       ├───events
│       ├───state
│       ├───invite_state
│       └───knock_state
├───user_data
│   ├───account_data
│   │   ├───global
│   │   └───&lt;room_id&gt;
│   ├───connections
│   ├───devices
│   └───profile
└───media_ids
    └───&lt;media_id&gt;
</code></pre>
<p>The <code>media_ids</code> folder contains only the metadata of the media uploaded by the user.
It does not contain the media itself.
Furthermore, only the <code>media_ids</code> that Synapse manages itself are exported.
If another media repository (e.g. <a href="https://github.com/turt2live/matrix-media-repo">matrix-media-repo</a>)
is used, the data must be exported separately.</p>
<p>With the <code>media_ids</code> the media files can be downloaded.
Media that have been sent in encrypted rooms are only retrieved in encrypted form.
The following script can help with download the media files:</p>
<pre><code class="language-bash">#!/usr/bin/env bash

# Parameters
#
#   source_directory: Directory which contains the export with the media_ids.
#   target_directory: Directory into which all files are to be downloaded.
#   repository_url: Address of the media repository resp. media worker.
#   serverName: Name of the server (`server_name` from homeserver.yaml).
#
#   Example:
#       ./download_media.sh /tmp/export_data/media_ids/ /tmp/export_data/media_files/ http://localhost:8008 matrix.example.com

source_directory=$1
target_directory=$2
repository_url=$3
serverName=$4

mkdir -p $target_directory

for file in $source_directory/*; do
    filename=$(basename ${file})
    url=$repository_url/_matrix/media/v3/download/$serverName/$filename
    echo &quot;Downloading $filename - $url&quot;
    if ! wget -o /dev/null -P $target_directory $url; then
        echo &quot;Could not download $filename&quot;
    fi
done
</code></pre>
<h2 id="manually-resetting-passwords"><a class="header" href="#manually-resetting-passwords">Manually resetting passwords</a></h2>
<p>Users can reset their password through their client. Alternatively, a server admin
can reset a user's password using the <a href="usage/administration/../../admin_api/user_admin_api.html#reset-password">admin API</a>.</p>
<h2 id="i-have-a-problem-with-my-server-can-i-just-delete-my-database-and-start-again"><a class="header" href="#i-have-a-problem-with-my-server-can-i-just-delete-my-database-and-start-again">I have a problem with my server. Can I just delete my database and start again?</a></h2>
<p>Deleting your database is unlikely to make anything better.</p>
<p>It's easy to make the mistake of thinking that you can start again from a clean
slate by dropping your database, but things don't work like that in a federated
network: lots of other servers have information about your server.</p>
<p>For example: other servers might think that you are in a room, your server will
think that you are not, and you'll probably be unable to interact with that room
in a sensible way ever again.</p>
<p>In general, there are better solutions to any problem than dropping the database.
Come and seek help in https://matrix.to/#/#synapse:matrix.org.</p>
<p>There are two exceptions when it might be sensible to delete your database and start again:</p>
<ul>
<li>You have <em>never</em> joined any rooms which are federated with other servers. For
instance, a local deployment which the outside world can't talk to.</li>
<li>You are changing the <code>server_name</code> in the homeserver configuration. In effect
this makes your server a completely new one from the point of view of the network,
so in this case it makes sense to start with a clean database.
(In both cases you probably also want to clear out the media_store.)</li>
</ul>
<h2 id="ive-stuffed-up-access-to-my-room-how-can-i-delete-it-to-free-up-the-alias"><a class="header" href="#ive-stuffed-up-access-to-my-room-how-can-i-delete-it-to-free-up-the-alias">I've stuffed up access to my room, how can I delete it to free up the alias?</a></h2>
<p>Using the following curl command:</p>
<pre><code class="language-console">curl -H 'Authorization: Bearer &lt;access-token&gt;' -X DELETE https://matrix.org/_matrix/client/r0/directory/room/&lt;room-alias&gt;
</code></pre>
<p><code>&lt;access-token&gt;</code> - can be obtained in riot by looking in the riot settings, down the bottom is:
Access Token:&lt;click to reveal&gt;</p>
<p><code>&lt;room-alias&gt;</code> - the room alias, eg. #my_room:matrix.org this possibly needs to be URL encoded also, for example  %23my_room%3Amatrix.org</p>
<h2 id="how-can-i-find-the-lines-corresponding-to-a-given-http-request-in-my-homeserver-log"><a class="header" href="#how-can-i-find-the-lines-corresponding-to-a-given-http-request-in-my-homeserver-log">How can I find the lines corresponding to a given HTTP request in my homeserver log?</a></h2>
<p>Synapse tags each log line according to the HTTP request it is processing. When
it finishes processing each request, it logs a line containing the words
<code>Processed request: </code>. For example:</p>
<pre><code>2019-02-14 22:35:08,196 - synapse.access.http.8008 - 302 - INFO - GET-37 - ::1 - 8008 - {@richvdh:localhost} Processed request: 0.173sec/0.001sec (0.002sec, 0.000sec) (0.027sec/0.026sec/2) 687B 200 &quot;GET /_matrix/client/r0/sync HTTP/1.1&quot; &quot;Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36&quot; [0 dbevts]&quot;
</code></pre>
<p>Here we can see that the request has been tagged with <code>GET-37</code>. (The tag depends
on the method of the HTTP request, so might start with <code>GET-</code>, <code>PUT-</code>, <code>POST-</code>,
<code>OPTIONS-</code> or <code>DELETE-</code>.) So to find all lines corresponding to this request, we can do:</p>
<pre><code class="language-console">grep 'GET-37' homeserver.log
</code></pre>
<p>If you want to paste that output into a github issue or matrix room, please
remember to surround it with triple-backticks (```) to make it legible
(see <a href="https://help.github.com/en/articles/basic-writing-and-formatting-syntax#quoting-code">quoting code</a>).</p>
<h2 id="what-do-all-those-fields-in-the-processed-line-mean"><a class="header" href="#what-do-all-those-fields-in-the-processed-line-mean">What do all those fields in the 'Processed' line mean?</a></h2>
<p>See <a href="usage/administration/request_log.html">Request log format</a>.</p>
<h2 id="what-are-the-biggest-rooms-on-my-server"><a class="header" href="#what-are-the-biggest-rooms-on-my-server">What are the biggest rooms on my server?</a></h2>
<pre><code class="language-sql">SELECT s.canonical_alias, g.room_id, count(*) AS num_rows
FROM
  state_groups_state AS g,
  room_stats_state AS s
WHERE g.room_id = s.room_id
GROUP BY s.canonical_alias, g.room_id
ORDER BY num_rows desc
LIMIT 10;
</code></pre>
<p>You can also use the <a href="usage/administration/../../admin_api/rooms.html#list-room-api">List Room API</a>
and <code>order_by</code> <code>state_events</code>.</p>
<h2 id="people-cant-accept-room-invitations-from-me"><a class="header" href="#people-cant-accept-room-invitations-from-me">People can't accept room invitations from me</a></h2>
<p>The typical failure mode here is that you send an invitation to someone
to join a room or direct chat, but when they go to accept it, they get an
error (typically along the lines of &quot;Invalid signature&quot;). They might see
something like the following in their logs:</p>
<pre><code>2019-09-11 19:32:04,271 - synapse.federation.transport.server - 288 - WARNING - GET-11752 - authenticate_request failed: 401: Invalid signature for server &lt;server&gt; with key ed25519:a_EqML: Unable to verify signature for &lt;server&gt;
</code></pre>
<p>This is normally caused by a misconfiguration in your reverse-proxy. See <a href="usage/administration/../../reverse_proxy.html">the reverse proxy docs</a> and double-check that your settings are correct.</p>
<h2 id="help-synapse-is-slow-and-eats-all-my-ramcpu"><a class="header" href="#help-synapse-is-slow-and-eats-all-my-ramcpu">Help!! Synapse is slow and eats all my RAM/CPU!</a></h2>
<p>First, ensure you are running the latest version of Synapse, using Python 3
with a <a href="usage/administration/../../postgres.html">PostgreSQL database</a>.</p>
<p>Synapse's architecture is quite RAM hungry currently - we deliberately
cache a lot of recent room data and metadata in RAM in order to speed up
common requests. We'll improve this in the future, but for now the easiest
way to either reduce the RAM usage (at the risk of slowing things down)
is to set the almost-undocumented <code>SYNAPSE_CACHE_FACTOR</code> environment
variable. The default is 0.5, which can be decreased to reduce RAM usage
in memory constrained environments, or increased if performance starts to
degrade.</p>
<p>However, degraded performance due to a low cache factor, common on
machines with slow disks, often leads to explosions in memory use due
backlogged requests. In this case, reducing the cache factor will make
things worse. Instead, try increasing it drastically. 2.0 is a good
starting value.</p>
<p>Using <a href="https://jemalloc.net">libjemalloc</a> can also yield a significant
improvement in overall memory use, and especially in terms of giving back
RAM to the OS. To use it, the library must simply be put in the
LD_PRELOAD environment variable when launching Synapse. On Debian, this
can be done by installing the <code>libjemalloc1</code> package and adding this
line to <code>/etc/default/matrix-synapse</code>:</p>
<pre><code>LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.1
</code></pre>
<p>This made a significant difference on Python 2.7 - it's unclear how
much of an improvement it provides on Python 3.x.</p>
<p>If you're encountering high CPU use by the Synapse process itself, you
may be affected by a bug with presence tracking that leads to a
massive excess of outgoing federation requests (see <a href="https://github.com/matrix-org/synapse/issues/3971">discussion</a>). If metrics
indicate that your server is also issuing far more outgoing federation
requests than can be accounted for by your users' activity, this is a
likely cause. The misbehavior can be worked around by disabling presence
in the Synapse config file: <a href="usage/administration/../configuration/config_documentation.html#presence">see here</a>.</p>
<h2 id="running-out-of-file-handles"><a class="header" href="#running-out-of-file-handles">Running out of File Handles</a></h2>
<p>If Synapse runs out of file handles, it typically fails badly - live-locking
at 100% CPU, and/or failing to accept new TCP connections (blocking the
connecting client).  Matrix currently can legitimately use a lot of file handles,
thanks to busy rooms like <code>#matrix:matrix.org</code> containing hundreds of participating
servers.  The first time a server talks in a room it will try to connect
simultaneously to all participating servers, which could exhaust the available
file descriptors between DNS queries &amp; HTTPS sockets, especially if DNS is slow
to respond. (We need to improve the routing algorithm used to be better than
full mesh, but as of March 2019 this hasn't happened yet).</p>
<p>If you hit this failure mode, we recommend increasing the maximum number of
open file handles to be at least 4096 (assuming a default of 1024 or 256).
This is typically done by editing <code>/etc/security/limits.conf</code></p>
<p>Separately, Synapse may leak file handles if inbound HTTP requests get stuck
during processing - e.g. blocked behind a lock or talking to a remote server etc.
This is best diagnosed by matching up the 'Received request' and 'Processed request'
log lines and looking for any 'Processed request' lines which take more than
a few seconds to execute. Please let us know at <a href="https://matrix.to/#/#synapse-dev:matrix.org"><code>#synapse:matrix.org</code></a> if
you see this failure mode so we can help debug it, however.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="contributing"><a class="header" href="#contributing">Contributing</a></h1>
<p>This document aims to get you started with contributing to Synapse!</p>
<h1 id="1-who-can-contribute-to-synapse"><a class="header" href="#1-who-can-contribute-to-synapse">1. Who can contribute to Synapse?</a></h1>
<p>Everyone is welcome to contribute code to <a href="https://github.com/matrix-org">matrix.org
projects</a>, provided that they are willing to
license their contributions under the same license as the project itself. We
follow a simple 'inbound=outbound' model for contributions: the act of
submitting an 'inbound' contribution means that the contributor agrees to
license the code under the same terms as the project's overall 'outbound'
license - in our case, this is almost always Apache Software License v2 (see
<a href="https://github.com/matrix-org/synapse/blob/develop/LICENSE">LICENSE</a>).</p>
<h1 id="2-what-do-i-need"><a class="header" href="#2-what-do-i-need">2. What do I need?</a></h1>
<p>If you are running Windows, the Windows Subsystem for Linux (WSL) is strongly
recommended for development. More information about WSL can be found at
<a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>. Running Synapse natively
on Windows is not officially supported.</p>
<p>The code of Synapse is written in Python 3. To do pretty much anything, you'll need <a href="https://www.python.org/downloads/">a recent version of Python 3</a>. Your Python also needs support for <a href="https://docs.python.org/3/library/venv.html">virtual environments</a>. This is usually built-in, but some Linux distributions like Debian and Ubuntu split it out into its own package. Running <code>sudo apt install python3-venv</code> should be enough.</p>
<p>A recent version of the Rust compiler is needed to build the native modules. The
easiest way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
<p>Synapse can connect to PostgreSQL via the <a href="https://pypi.org/project/psycopg2/">psycopg2</a> Python library. Building this library from source requires access to PostgreSQL's C header files. On Debian or Ubuntu Linux, these can be installed with <code>sudo apt install libpq-dev</code>.</p>
<p>Synapse has an optional, improved user search with better Unicode support. For that you need the development package of <code>libicu</code>. On Debian or Ubuntu Linux, this can be installed with <code>sudo apt install libicu-dev</code>.</p>
<p>The source code of Synapse is hosted on GitHub. You will also need <a href="https://github.com/git-guides/install-git">a recent version of git</a>.</p>
<p>For some tests, you will need <a href="https://docs.docker.com/get-docker/">a recent version of Docker</a>.</p>
<h1 id="3-get-the-source"><a class="header" href="#3-get-the-source">3. Get the source.</a></h1>
<p>The preferred and easiest way to contribute changes is to fork the relevant
project on GitHub, and then <a href="https://help.github.com/articles/using-pull-requests/">create a pull request</a> to ask us to pull your
changes into our repo.</p>
<p>Please base your changes on the <code>develop</code> branch.</p>
<pre><code class="language-sh">git clone git@github.com:YOUR_GITHUB_USER_NAME/synapse.git
git checkout develop
</code></pre>
<p>If you need help getting started with git, this is beyond the scope of the document, but you
can find many good git tutorials on the web.</p>
<h1 id="4-install-the-dependencies"><a class="header" href="#4-install-the-dependencies">4. Install the dependencies</a></h1>
<p>Before installing the Python dependencies, make sure you have installed a recent version
of Rust (see the &quot;What do I need?&quot; section above). The easiest way of installing the
latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
<p>Synapse uses the <a href="https://python-poetry.org/">poetry</a> project to manage its dependencies
and development environment. Once you have installed Python 3 and added the
source, you should install <code>poetry</code>.
Of their installation methods, we recommend
<a href="https://python-poetry.org/docs/#installing-with-pipx">installing <code>poetry</code> using <code>pipx</code></a>,</p>
<pre><code class="language-shell">pip install --user pipx
pipx install poetry
</code></pre>
<p>but see poetry's <a href="https://python-poetry.org/docs/#installation">installation instructions</a>
for other installation methods.</p>
<p>Developing Synapse requires Poetry version 1.3.2 or later.</p>
<p>Next, open a terminal and install dependencies as follows:</p>
<pre><code class="language-sh">cd path/where/you/have/cloned/the/repository
poetry install --extras all
</code></pre>
<p>This will install the runtime and developer dependencies for the project.  Be sure to check
that the <code>poetry install</code> step completed cleanly.</p>
<h2 id="running-synapse-via-poetry"><a class="header" href="#running-synapse-via-poetry">Running Synapse via poetry</a></h2>
<p>To start a local instance of Synapse in the locked poetry environment, create a config file:</p>
<pre><code class="language-sh">cp docs/sample_config.yaml homeserver.yaml
cp docs/sample_log_config.yaml log_config.yaml
</code></pre>
<p>Now edit <code>homeserver.yaml</code>, things you might want to change include:</p>
<ul>
<li>Set a <code>server_name</code></li>
<li>Adjusting paths to be correct for your system like the <code>log_config</code> to point to the log config you just copied</li>
<li>Using a <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#database">PostgreSQL database instead of SQLite</a></li>
<li>Adding a <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a> so you can use <a href="https://matrix-org.github.io/synapse/latest/setup/installation.html#registering-a-user"><code>register_new_matrix_user</code> command</a>.</li>
</ul>
<p>And then run Synapse with the following command:</p>
<pre><code class="language-sh">poetry run python -m synapse.app.homeserver -c homeserver.yaml
</code></pre>
<p>If you get an error like the following:</p>
<pre><code>importlib.metadata.PackageNotFoundError: matrix-synapse
</code></pre>
<p>this probably indicates that the <code>poetry install</code> step did not complete cleanly - go back and
resolve any issues and re-run until successful.</p>
<h1 id="5-get-in-touch"><a class="header" href="#5-get-in-touch">5. Get in touch.</a></h1>
<p>Join our developer community on Matrix: <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>!</p>
<h1 id="6-pick-an-issue"><a class="header" href="#6-pick-an-issue">6. Pick an issue.</a></h1>
<p>Fix your favorite problem or perhaps find a <a href="https://github.com/matrix-org/synapse/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+First+Issue%22">Good First Issue</a>
to work on.</p>
<h1 id="7-turn-coffee-into-code-and-documentation"><a class="header" href="#7-turn-coffee-into-code-and-documentation">7. Turn coffee into code and documentation!</a></h1>
<p>There is a growing amount of documentation located in the
<a href="https://github.com/matrix-org/synapse/tree/develop/docs"><code>docs</code></a>
directory, with a rendered version <a href="https://matrix-org.github.io/synapse">available online</a>.
This documentation is intended primarily for sysadmins running their
own Synapse instance, as well as developers interacting externally with
Synapse.
<a href="https://github.com/matrix-org/synapse/tree/develop/docs/development"><code>docs/development</code></a>
exists primarily to house documentation for
Synapse developers.
<a href="https://github.com/matrix-org/synapse/tree/develop/docs/admin_api"><code>docs/admin_api</code></a> houses documentation
regarding Synapse's Admin API, which is used mostly by sysadmins and external
service developers.</p>
<p>Synapse's code style is documented <a href="development/../code_style.html">here</a>. Please follow
it, including the conventions for <a href="development/../code_style.html#configuration-code-and-documentation-format">configuration
options and documentation</a>.</p>
<p>We welcome improvements and additions to our documentation itself! When
writing new pages, please
<a href="https://github.com/matrix-org/synapse/tree/develop/docs#adding-to-the-documentation">build <code>docs</code> to a book</a>
to check that your contributions render correctly. The docs are written in
<a href="https://guides.github.com/features/mastering-markdown/">GitHub-Flavoured Markdown</a>.</p>
<p>Some documentation also exists in <a href="https://github.com/matrix-org/synapse/wiki">Synapse's GitHub
Wiki</a>, although this is primarily
contributed to by community authors.</p>
<p>When changes are made to any Rust code then you must call either <code>poetry install</code>
or <code>maturin develop</code> (if installed) to rebuild the Rust code. Using <a href="https://github.com/PyO3/maturin"><code>maturin</code></a>
is quicker than <code>poetry install</code>, so is recommended when making frequent
changes to the Rust code.</p>
<h1 id="8-test-test-test"><a class="header" href="#8-test-test-test">8. Test, test, test!</a></h1>
<p><a name="test-test-test" id="test-test-test"></a></p>
<p>While you're developing and before submitting a patch, you'll
want to test your code.</p>
<h2 id="run-the-linters"><a class="header" href="#run-the-linters">Run the linters.</a></h2>
<p>The linters look at your code and do two things:</p>
<ul>
<li>ensure that your code follows the coding style adopted by the project;</li>
<li>catch a number of errors in your code.</li>
</ul>
<p>The linter takes no time at all to run as soon as you've <a href="development/contributing_guide.html#4-install-the-dependencies">downloaded the dependencies</a>.</p>
<pre><code class="language-sh">poetry run ./scripts-dev/lint.sh
</code></pre>
<p>Note that this script <em>will modify your files</em> to fix styling errors.
Make sure that you have saved all your files.</p>
<p>If you wish to restrict the linters to only the files changed since the last commit
(much faster!), you can instead run:</p>
<pre><code class="language-sh">poetry run ./scripts-dev/lint.sh -d
</code></pre>
<p>Or if you know exactly which files you wish to lint, you can instead run:</p>
<pre><code class="language-sh">poetry run ./scripts-dev/lint.sh path/to/file1.py path/to/file2.py path/to/folder
</code></pre>
<h2 id="run-the-unit-tests-twisted-trial"><a class="header" href="#run-the-unit-tests-twisted-trial">Run the unit tests (Twisted trial).</a></h2>
<p>The unit tests run parts of Synapse, including your changes, to see if anything
was broken. They are slower than the linters but will typically catch more errors.</p>
<pre><code class="language-sh">poetry run trial tests
</code></pre>
<p>You can run unit tests in parallel by specifying <code>-jX</code> argument to <code>trial</code> where <code>X</code> is the number of parallel runners you want. To use 4 cpu cores, you would run them like:</p>
<pre><code class="language-sh">poetry run trial -j4 tests
</code></pre>
<p>If you wish to only run <em>some</em> unit tests, you may specify
another module instead of <code>tests</code> - or a test class or a method:</p>
<pre><code class="language-sh">poetry run trial tests.rest.admin.test_room tests.handlers.test_admin.ExfiltrateData.test_invite
</code></pre>
<p>If your tests fail, you may wish to look at the logs (the default log level is <code>ERROR</code>):</p>
<pre><code class="language-sh">less _trial_temp/test.log
</code></pre>
<p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>:</p>
<pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG poetry run trial tests
</code></pre>
<p>By default, tests will use an in-memory SQLite database for test data. For additional
help with debugging, one can use an on-disk SQLite database file instead, in order to
review database state during and after running tests. This can be done by setting
the <code>SYNAPSE_TEST_PERSIST_SQLITE_DB</code> environment variable. Doing so will cause the
database state to be stored in a file named <code>test.db</code> under the trial process'
working directory. Typically, this ends up being <code>_trial_temp/test.db</code>. For example:</p>
<pre><code class="language-sh">SYNAPSE_TEST_PERSIST_SQLITE_DB=1 poetry run trial tests
</code></pre>
<p>The database file can then be inspected with:</p>
<pre><code class="language-sh">sqlite3 _trial_temp/test.db
</code></pre>
<p>Note that the database file is cleared at the beginning of each test run. Thus it
will always only contain the data generated by the <em>last run test</em>. Though generally
when debugging, one is only running a single test anyway.</p>
<h3 id="running-tests-under-postgresql"><a class="header" href="#running-tests-under-postgresql">Running tests under PostgreSQL</a></h3>
<p>Invoking <code>trial</code> as above will use an in-memory SQLite database. This is great for
quick development and testing. However, we recommend using a PostgreSQL database
in production (and indeed, we have some code paths specific to each database).
This means that we need to run our unit tests against PostgreSQL too. Our CI does
this automatically for pull requests and release candidates, but it's sometimes
useful to reproduce this locally.</p>
<h4 id="using-docker"><a class="header" href="#using-docker">Using Docker</a></h4>
<p>The easiest way to do so is to run Postgres via a docker container. In one
terminal:</p>
<pre><code class="language-shell">docker run --rm -e POSTGRES_PASSWORD=mysecretpassword -e POSTGRES_USER=postgres -e POSTGRES_DB=postgress -p 5432:5432 postgres:14
</code></pre>
<p>If you see an error like</p>
<pre><code>docker: Error response from daemon: driver failed programming external connectivity on endpoint nice_ride (b57bbe2e251b70015518d00c9981e8cb8346b5c785250341a6c53e3c899875f1): Error starting userland proxy: listen tcp4 0.0.0.0:5432: bind: address already in use.
</code></pre>
<p>then something is already bound to port 5432. You're probably already running postgres locally.</p>
<p>Once you have a postgres server running, invoke <code>trial</code> in a second terminal:</p>
<pre><code class="language-shell">SYNAPSE_POSTGRES=1 SYNAPSE_POSTGRES_HOST=127.0.0.1 SYNAPSE_POSTGRES_USER=postgres SYNAPSE_POSTGRES_PASSWORD=mysecretpassword poetry run trial tests
</code></pre>
<h4 id="using-an-existing-postgres-installation"><a class="header" href="#using-an-existing-postgres-installation">Using an existing Postgres installation</a></h4>
<p>If you have postgres already installed on your system, you can run <code>trial</code> with the
following environment variables matching your configuration:</p>
<ul>
<li><code>SYNAPSE_POSTGRES</code> to anything nonempty</li>
<li><code>SYNAPSE_POSTGRES_HOST</code> (optional if it's the default: UNIX socket)</li>
<li><code>SYNAPSE_POSTGRES_PORT</code> (optional if it's the default: 5432)</li>
<li><code>SYNAPSE_POSTGRES_USER</code> (optional if using a UNIX socket)</li>
<li><code>SYNAPSE_POSTGRES_PASSWORD</code> (optional if using a UNIX socket)</li>
</ul>
<p>For example:</p>
<pre><code class="language-shell">export SYNAPSE_POSTGRES=1
export SYNAPSE_POSTGRES_HOST=localhost
export SYNAPSE_POSTGRES_USER=postgres
export SYNAPSE_POSTGRES_PASSWORD=mydevenvpassword
trial
</code></pre>
<p>You don't need to specify the host, user, port or password if your Postgres
server is set to authenticate you over the UNIX socket (i.e. if the <code>psql</code> command
works without further arguments).</p>
<p>Your Postgres account needs to be able to create databases; see the postgres
docs for <a href="https://www.postgresql.org/docs/current/sql-alterrole.html"><code>ALTER ROLE</code></a>.</p>
<h2 id="run-the-integration-tests-sytest"><a class="header" href="#run-the-integration-tests-sytest">Run the integration tests (<a href="https://github.com/matrix-org/sytest">Sytest</a>).</a></h2>
<p>The integration tests are a more comprehensive suite of tests. They
run a full version of Synapse, including your changes, to check if
anything was broken. They are slower than the unit tests but will
typically catch more errors.</p>
<p>The following command will let you run the integration test with the most common
configuration:</p>
<pre><code class="language-sh">$ docker run --rm -it -v /path/where/you/have/cloned/the/repository\:/src:ro -v /path/to/where/you/want/logs\:/logs matrixdotorg/sytest-synapse:focal
</code></pre>
<p>(Note that the paths must be full paths! You could also write <code>$(realpath relative/path)</code> if needed.)</p>
<p>This configuration should generally cover your needs.</p>
<ul>
<li>To run with Postgres, supply the <code>-e POSTGRES=1 -e MULTI_POSTGRES=1</code> environment flags.</li>
<li>To run with Synapse in worker mode, supply the <code>-e WORKERS=1 -e REDIS=1</code> environment flags (in addition to the Postgres flags).</li>
</ul>
<p>For more details about other configurations, see the <a href="https://github.com/matrix-org/sytest/blob/develop/docker/README.md">Docker-specific documentation in the SyTest repo</a>.</p>
<h2 id="run-the-integration-tests-complement"><a class="header" href="#run-the-integration-tests-complement">Run the integration tests (<a href="https://github.com/matrix-org/complement">Complement</a>).</a></h2>
<p><a href="https://github.com/matrix-org/complement">Complement</a> is a suite of black box tests that can be run on any homeserver implementation. It can also be thought of as end-to-end (e2e) tests.</p>
<p>It's often nice to develop on Synapse and write Complement tests at the same time.
Here is how to run your local Synapse checkout against your local Complement checkout.</p>
<p>(checkout <a href="https://github.com/matrix-org/complement"><code>complement</code></a> alongside your <code>synapse</code> checkout)</p>
<pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh
</code></pre>
<p>To run a specific test file, you can pass the test name at the end of the command. The name passed comes from the naming structure in your Complement tests. If you're unsure of the name, you can do a full run and copy it from the test output:</p>
<pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
</code></pre>
<p>To run a specific test, you can specify the whole name structure:</p>
<pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages/parallel/Historical_events_resolve_in_the_correct_order
</code></pre>
<p>The above will run a monolithic (single-process) Synapse with SQLite as the database. For other configurations, try:</p>
<ul>
<li>Passing <code>POSTGRES=1</code> as an environment variable to use the Postgres database instead.</li>
<li>Passing <code>WORKERS=1</code> as an environment variable to use a workerised setup instead. This option implies the use of Postgres.
<ul>
<li>If setting <code>WORKERS=1</code>, optionally set <code>WORKER_TYPES=</code> to declare which worker
types you wish to test. A simple comma-delimited string containing the worker types
defined from the <code>WORKERS_CONFIG</code> template in
<a href="https://github.com/matrix-org/synapse/blob/develop/docker/configure_workers_and_start.py#L54">here</a>.
A safe example would be <code>WORKER_TYPES=&quot;federation_inbound, federation_sender, synchrotron&quot;</code>.
See the <a href="development/../workers.html">worker documentation</a> for additional information on workers.</li>
</ul>
</li>
<li>Passing <code>ASYNCIO_REACTOR=1</code> as an environment variable to use the Twisted asyncio reactor instead of the default one.</li>
<li>Passing <code>PODMAN=1</code> will use the <a href="https://podman.io/">podman</a> container runtime, instead of docker.</li>
<li>Passing <code>UNIX_SOCKETS=1</code> will utilise Unix socket functionality for Synapse, Redis, and Postgres(when applicable).</li>
</ul>
<p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>, e.g:</p>
<pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
</code></pre>
<h3 id="prettier-formatting-with-gotestfmt"><a class="header" href="#prettier-formatting-with-gotestfmt">Prettier formatting with <code>gotestfmt</code></a></h3>
<p>If you want to format the output of the tests the same way as it looks in CI,
install <a href="https://github.com/GoTestTools/gotestfmt">gotestfmt</a>.</p>
<p>You can then use this incantation to format the tests appropriately:</p>
<pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -json | gotestfmt -hide successful-tests
</code></pre>
<p>(Remove <code>-hide successful-tests</code> if you don't want to hide successful tests.)</p>
<h3 id="access-database-for-homeserver-after-complement-test-runs"><a class="header" href="#access-database-for-homeserver-after-complement-test-runs">Access database for homeserver after Complement test runs.</a></h3>
<p>If you're curious what the database looks like after you run some tests, here are some steps to get you going in Synapse:</p>
<ol>
<li>In your Complement test comment out <code>defer deployment.Destroy(t)</code> and replace with <code>defer time.Sleep(2 * time.Hour)</code> to keep the homeserver running after the tests complete</li>
<li>Start the Complement tests</li>
<li>Find the name of the container, <code>docker ps -f name=complement_</code> (this will filter for just the Compelement related Docker containers)</li>
<li>Access the container replacing the name with what you found in the previous step: <code>docker exec -it complement_1_hs_with_application_service.hs1_2 /bin/bash</code></li>
<li>Install sqlite (database driver), <code>apt-get update &amp;&amp; apt-get install -y sqlite3</code></li>
<li>Then run <code>sqlite3</code> and open the database <code>.open /conf/homeserver.db</code> (this db path comes from the Synapse homeserver.yaml)</li>
</ol>
<h1 id="9-submit-your-patch"><a class="header" href="#9-submit-your-patch">9. Submit your patch.</a></h1>
<p>Once you're happy with your patch, it's time to prepare a Pull Request.</p>
<p>To prepare a Pull Request, please:</p>
<ol>
<li>verify that <a href="development/contributing_guide.html#test-test-test">all the tests pass</a>, including the coding style;</li>
<li><a href="development/contributing_guide.html#sign-off">sign off</a> your contribution;</li>
<li><code>git push</code> your commit to your fork of Synapse;</li>
<li>on GitHub, <a href="https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request">create the Pull Request</a>;</li>
<li>add a <a href="development/contributing_guide.html#changelog">changelog entry</a> and push it to your Pull Request;</li>
<li>that's it for now, a non-draft pull request will automatically request review from the team;</li>
<li>if you need to update your PR, please avoid rebasing and just add new commits to your branch.</li>
</ol>
<h2 id="changelog"><a class="header" href="#changelog">Changelog</a></h2>
<p>All changes, even minor ones, need a corresponding changelog / newsfragment
entry. These are managed by <a href="https://github.com/twisted/towncrier">Towncrier</a>.</p>
<p>To create a changelog entry, make a new file in the <code>changelog.d</code> directory named
in the format of <code>PRnumber.type</code>. The type can be one of the following:</p>
<ul>
<li><code>feature</code></li>
<li><code>bugfix</code></li>
<li><code>docker</code> (for updates to the Docker image)</li>
<li><code>doc</code> (for updates to the documentation)</li>
<li><code>removal</code> (also used for deprecations)</li>
<li><code>misc</code> (for internal-only changes)</li>
</ul>
<p>This file will become part of our <a href="https://github.com/matrix-org/synapse/blob/master/CHANGES.md">changelog</a> at the next
release, so the content of the file should be a short description of your
change in the same style as the rest of the changelog. The file can contain Markdown
formatting, and must end with a full stop (.) or an exclamation mark (!) for
consistency.</p>
<p>Adding credits to the changelog is encouraged, we value your
contributions and would like to have you shouted out in the release notes!</p>
<p>For example, a fix in PR #1234 would have its changelog entry in
<code>changelog.d/1234.bugfix</code>, and contain content like:</p>
<blockquote>
<p>The security levels of Florbs are now validated when received
via the <code>/federation/florb</code> endpoint. Contributed by Jane Matrix.</p>
</blockquote>
<p>If there are multiple pull requests involved in a single bugfix/feature/etc,
then the content for each <code>changelog.d</code> file should be the same. Towncrier will
merge the matching files together into a single changelog entry when we come to
release.</p>
<h3 id="how-do-i-know-what-to-call-the-changelog-file-before-i-create-the-pr"><a class="header" href="#how-do-i-know-what-to-call-the-changelog-file-before-i-create-the-pr">How do I know what to call the changelog file before I create the PR?</a></h3>
<p>Obviously, you don't know if you should call your newsfile
<code>1234.bugfix</code> or <code>5678.bugfix</code> until you create the PR, which leads to a
chicken-and-egg problem.</p>
<p>There are two options for solving this:</p>
<ol>
<li>
<p>Open the PR without a changelog file, see what number you got, and <em>then</em>
add the changelog file to your branch, or:</p>
</li>
<li>
<p>Look at the <a href="https://github.com/matrix-org/synapse/issues?q=">list of all
issues/PRs</a>, add one to the
highest number you see, and quickly open the PR before somebody else claims
your number.</p>
<p><a href="https://github.com/richvdh/scripts/blob/master/next_github_number.sh">This
script</a>
might be helpful if you find yourself doing this a lot.</p>
</li>
</ol>
<p>Sorry, we know it's a bit fiddly, but it's <em>really</em> helpful for us when we come
to put together a release!</p>
<h3 id="debian-changelog"><a class="header" href="#debian-changelog">Debian changelog</a></h3>
<p>Changes which affect the debian packaging files (in <code>debian</code>) are an
exception to the rule that all changes require a <code>changelog.d</code> file.</p>
<p>In this case, you will need to add an entry to the debian changelog for the
next release. For this, run the following command:</p>
<pre><code>dch
</code></pre>
<p>This will make up a new version number (if there isn't already an unreleased
version in flight), and open an editor where you can add a new changelog entry.
(Our release process will ensure that the version number and maintainer name is
corrected for the release.)</p>
<p>If your change affects both the debian packaging <em>and</em> files outside the debian
directory, you will need both a regular newsfragment <em>and</em> an entry in the
debian changelog. (Though typically such changes should be submitted as two
separate pull requests.)</p>
<h2 id="sign-off"><a class="header" href="#sign-off">Sign off</a></h2>
<p>In order to have a concrete record that your contribution is intentional
and you agree to license it under the same terms as the project's license, we've adopted the
same lightweight approach that the Linux Kernel
<a href="https://www.kernel.org/doc/html/latest/process/submitting-patches.html#sign-your-work-the-developer-s-certificate-of-origin%3E">submitting patches process</a>,
<a href="https://github.com/docker/docker/blob/master/CONTRIBUTING.md">Docker</a>, and many other
projects use: the DCO (<a href="http://developercertificate.org/">Developer Certificate of Origin</a>).
This is a simple declaration that you wrote
the contribution or otherwise have the right to contribute it to Matrix:</p>
<pre><code>Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
</code></pre>
<p>If you agree to this for your contribution, then all that's needed is to
include the line in your commit or pull request comment:</p>
<pre><code>Signed-off-by: Your Name &lt;your@email.example.org&gt;
</code></pre>
<p>We accept contributions under a legally identifiable name, such as
your name on government documentation or common-law names (names
claimed by legitimate usage or repute). Unfortunately, we cannot
accept anonymous contributions at this time.</p>
<p>Git allows you to add this signoff automatically when using the <code>-s</code>
flag to <code>git commit</code>, which uses the name and email set in your
<code>user.name</code> and <code>user.email</code> git configs.</p>
<h3 id="private-sign-off"><a class="header" href="#private-sign-off">Private Sign off</a></h3>
<p>If you would like to provide your legal name privately to the Matrix.org
Foundation (instead of in a public commit or comment), you can do so
by emailing your legal name and a link to the pull request to
<a href="mailto:dco@matrix.org?subject=Private%20sign%20off">dco@matrix.org</a>.
It helps to include &quot;sign off&quot; or similar in the subject line. You will then
be instructed further.</p>
<p>Once private sign off is complete, doing so for future contributions will not
be required.</p>
<h1 id="10-turn-feedback-into-better-code"><a class="header" href="#10-turn-feedback-into-better-code">10. Turn feedback into better code.</a></h1>
<p>Once the Pull Request is opened, you will see a few things:</p>
<ol>
<li>our automated CI (Continuous Integration) pipeline will run (again) the linters, the unit tests, the integration tests and more;</li>
<li>one or more of the developers will take a look at your Pull Request and offer feedback.</li>
</ol>
<p>From this point, you should:</p>
<ol>
<li>Look at the results of the CI pipeline.
<ul>
<li>If there is any error, fix the error.</li>
</ul>
</li>
<li>If a developer has requested changes, make these changes and let us know if it is ready for a developer to review again.
<ul>
<li>A pull request is a conversation, if you disagree with the suggestions, please respond and discuss it.</li>
</ul>
</li>
<li>Create a new commit with the changes.
<ul>
<li>Please do NOT overwrite the history. New commits make the reviewer's life easier.</li>
<li>Push this commits to your Pull Request.</li>
</ul>
</li>
<li>Back to 1.</li>
<li>Once the pull request is ready for review again please re-request review from whichever developer did your initial
review (or leave a comment in the pull request that you believe all required changes have been done).</li>
</ol>
<p>Once both the CI and the developers are happy, the patch will be merged into Synapse and released shortly!</p>
<h1 id="11-find-a-new-issue"><a class="header" href="#11-find-a-new-issue">11. Find a new issue.</a></h1>
<p>By now, you know the drill!</p>
<h1 id="notes-for-maintainers-on-merging-prs-etc"><a class="header" href="#notes-for-maintainers-on-merging-prs-etc">Notes for maintainers on merging PRs etc</a></h1>
<p>There are some notes for those with commit access to the project on how we
manage git <a href="development/git.html">here</a>.</p>
<h1 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h1>
<p>That's it! Matrix is a very open and collaborative project as you might expect
given our obsession with open communication. If we're going to successfully
matrix together all the fragmented communication technologies out there we are
reliant on contributions and collaboration from the community to do so. So
please get involved - and we hope you have as much fun hacking on Matrix as we
do!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="code-style"><a class="header" href="#code-style">Code Style</a></h1>
<h2 id="formatting-tools"><a class="header" href="#formatting-tools">Formatting tools</a></h2>
<p>The Synapse codebase uses a number of code formatting tools in order to
quickly and automatically check for formatting (and sometimes logical)
errors in code.</p>
<p>The necessary tools are:</p>
<ul>
<li><a href="https://black.readthedocs.io/en/stable/">black</a>, a source code formatter;</li>
<li><a href="https://pycqa.github.io/isort/">isort</a>, which organises each file's imports;</li>
<li><a href="https://github.com/charliermarsh/ruff">ruff</a>, which can spot common errors; and</li>
<li><a href="https://mypy.readthedocs.io/en/stable/">mypy</a>, a type checker.</li>
</ul>
<p>See <a href="development/contributing_guide.html#run-the-linters">the contributing guide</a> for instructions
on how to install the above tools and run the linters.</p>
<p>It's worth noting that modern IDEs and text editors can run these tools
automatically on save. It may be worth looking into whether this
functionality is supported in your editor for a more convenient
development workflow. It is not, however, recommended to run <code>mypy</code>
on save as it takes a while and can be very resource intensive.</p>
<h2 id="general-rules"><a class="header" href="#general-rules">General rules</a></h2>
<ul>
<li><strong>Naming</strong>:
<ul>
<li>Use <code>CamelCase</code> for class and type names</li>
<li>Use underscores for <code>function_names</code> and <code>variable_names</code>.</li>
</ul>
</li>
<li><strong>Docstrings</strong>: should follow the <a href="https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings">google code
style</a>.
See the
<a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html">examples</a>
in the sphinx documentation.</li>
<li><strong>Imports</strong>:
<ul>
<li>
<p>Imports should be sorted by <code>isort</code> as described above.</p>
</li>
<li>
<p>Prefer to import classes and functions rather than packages or
modules.</p>
<p>Example:</p>
<pre><code class="language-python">from synapse.types import UserID
...
user_id = UserID(local, server)
</code></pre>
<p>is preferred over:</p>
<pre><code class="language-python">from synapse import types
...
user_id = types.UserID(local, server)
</code></pre>
<p>(or any other variant).</p>
<p>This goes against the advice in the Google style guide, but it
means that errors in the name are caught early (at import time).</p>
</li>
<li>
<p>Avoid wildcard imports (<code>from synapse.types import *</code>) and
relative imports (<code>from .types import UserID</code>).</p>
</li>
</ul>
</li>
</ul>
<h2 id="configuration-code-and-documentation-format"><a class="header" href="#configuration-code-and-documentation-format">Configuration code and documentation format</a></h2>
<p>When adding a configuration option to the code, if several settings are grouped into a single dict, ensure that your code
correctly handles the top-level option being set to <code>None</code> (as it will be if no sub-options are enabled).</p>
<p>The <a href="usage/configuration/config_documentation.html">configuration manual</a> acts as a
reference to Synapse's configuration options for server administrators.
Remember that many readers will be unfamiliar with YAML and server
administration in general, so it is important that when you add
a configuration option the documentation be as easy to understand as possible, which 
includes following a consistent format.</p>
<p>Some guidelines follow:</p>
<ul>
<li>
<p>Each option should be listed in the config manual with the following format:</p>
<ul>
<li>
<p>The name of the option, prefixed by <code>###</code>. </p>
</li>
<li>
<p>A comment which describes the default behaviour (i.e. what
happens if the setting is omitted), as well as what the effect
will be if the setting is changed.</p>
</li>
<li>
<p>An example setting, using backticks to define the code block</p>
<p>For boolean (on/off) options, convention is that this example
should be the <em>opposite</em> to the default. For other options, the example should give
some non-default value which is likely to be useful to the reader.</p>
</li>
</ul>
</li>
<li>
<p>There should be a horizontal rule between each option, which can be achieved by adding <code>---</code> before and
after the option.</p>
</li>
<li>
<p><code>true</code> and <code>false</code> are spelt thus (as opposed to <code>True</code>, etc.)</p>
</li>
</ul>
<p>Example:</p>
<hr />
<h3 id="modules-3"><a class="header" href="#modules-3"><code>modules</code></a></h3>
<p>Use the <code>module</code> sub-option to add a module under <code>modules</code> to extend functionality. 
The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
for the <code>module</code>.</p>
<p>Defaults to none.</p>
<p>Example configuration:</p>
<pre><code class="language-yaml">modules:
  - module: my_super_module.MySuperClass
    config:
      do_thing: true
  - module: my_other_super_module.SomeClass
    config: {}
</code></pre>
<hr />
<p>Note that the sample configuration is generated from the synapse code
and is maintained by a script, <code>scripts-dev/generate_sample_config.sh</code>.
Making sure that the output from this script matches the desired format
is left as an exercise for the reader!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="some-notes-on-how-we-do-reviews"><a class="header" href="#some-notes-on-how-we-do-reviews">Some notes on how we do reviews</a></h1>
<p>The Synapse team works off a shared review queue -- any new pull requests for
Synapse (or related projects) has a review requested from the entire team. Team
members should process this queue using the following rules:</p>
<ul>
<li>Any high urgency pull requests (e.g. fixes for broken continuous integration
or fixes for release blockers);</li>
<li>Follow-up reviews for pull requests which have previously received reviews;</li>
<li>Any remaining pull requests.</li>
</ul>
<p>For the latter two categories above, older pull requests should be prioritised.</p>
<p>It is explicit that there is no priority given to pull requests from the team
(vs from the community). If a pull request requires a quick turn around, please
explicitly communicate this via <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>
or as a comment on the pull request.</p>
<p>Once an initial review has been completed and the author has made additional changes,
follow-up reviews should go back to the same reviewer. This helps build a shared
context and conversation between author and reviewer.</p>
<p>As a team we aim to keep the number of inflight pull requests to a minimum to ensure
that ongoing work is finished before starting new work.</p>
<h2 id="performing-a-review"><a class="header" href="#performing-a-review">Performing a review</a></h2>
<p>To communicate to the rest of the team the status of each pull request, team
members should do the following:</p>
<ul>
<li>Assign themselves to the pull request (they should be left assigned to the
pull request until it is merged, closed, or are no longer the reviewer);</li>
<li>Review the pull request by leaving comments, questions, and suggestions;</li>
<li>Mark the pull request appropriately (as needing changes or accepted).</li>
</ul>
<p>If you are unsure about a particular part of the pull request (or are not confident
in your understanding of part of the code) then ask questions or request review
from the team again. When requesting review from the team be sure to leave a comment
with the rationale on why you're putting it back in the queue.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="synapse-release-cycle"><a class="header" href="#synapse-release-cycle">Synapse Release Cycle</a></h1>
<p>Releases of Synapse follow a two week release cycle with new releases usually
occurring on Tuesdays:</p>
<ul>
<li>Day 0: Synapse <code>N - 1</code> is released.</li>
<li>Day 7: Synapse <code>N</code> release candidate 1 is released.</li>
<li>Days 7 - 13: Synapse <code>N</code> release candidates 2+ are released, if bugs are found.</li>
<li>Day 14: Synapse <code>N</code> is released.</li>
</ul>
<p>Note that this schedule might be modified depending on the availability of the
Synapse team, e.g. releases may be skipped to avoid holidays.</p>
<p>Release announcements can be found in the
<a href="https://matrix.org/category/releases">release category of the Matrix blog</a>.</p>
<h2 id="bugfix-releases"><a class="header" href="#bugfix-releases">Bugfix releases</a></h2>
<p>If a bug is found after release that is deemed severe enough (by a combination
of the impacted users and the impact on those users) then a bugfix release may
be issued. This may be at any point in the release cycle.</p>
<h2 id="security-releases"><a class="header" href="#security-releases">Security releases</a></h2>
<p>Security will sometimes be backported to the previous version and released
immediately before the next release candidate. An example of this might be:</p>
<ul>
<li>Day 0: Synapse N - 1 is released.</li>
<li>Day 7: Synapse (N - 1).1 is released as Synapse N - 1 + the security fix.</li>
<li>Day 7: Synapse N release candidate 1 is released (including the security fix).</li>
</ul>
<p>Depending on the impact and complexity of security fixes, multiple fixes might
be held to be released together.</p>
<p>In some cases, a pre-disclosure of a security release will be issued as a notice
to Synapse operators that there is an upcoming security release. These can be
found in the <a href="https://matrix.org/category/security">security category of the Matrix blog</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="some-notes-on-how-we-use-git"><a class="header" href="#some-notes-on-how-we-use-git">Some notes on how we use git</a></h1>
<h2 id="on-keeping-the-commit-history-clean"><a class="header" href="#on-keeping-the-commit-history-clean">On keeping the commit history clean</a></h2>
<p>In an ideal world, our git commit history would be a linear progression of
commits each of which contains a single change building on what came
before. Here, by way of an arbitrary example, is the top of <code>git log --graph b2dba0607</code>:</p>
<img src="development/img/git/clean.png" alt="clean git graph" width="500px">
<p>Note how the commit comment explains clearly what is changing and why. Also
note the <em>absence</em> of merge commits, as well as the absence of commits called
things like (to pick a few culprits):
<a href="https://github.com/matrix-org/synapse/commit/84691da6c">“pep8”</a>, <a href="https://github.com/matrix-org/synapse/commit/474810d9d">“fix broken
test”</a>,
<a href="https://github.com/matrix-org/synapse/commit/c9d72e457">“oops”</a>,
<a href="https://github.com/matrix-org/synapse/commit/836358823">“typo”</a>, or <a href="https://github.com/matrix-org/synapse/commit/707374d5d">“Who's
the president?”</a>.</p>
<p>There are a number of reasons why keeping a clean commit history is a good
thing:</p>
<ul>
<li>
<p>From time to time, after a change lands, it turns out to be necessary to
revert it, or to backport it to a release branch. Those operations are
<em>much</em> easier when the change is contained in a single commit.</p>
</li>
<li>
<p>Similarly, it's much easier to answer questions like “is the fix for
<code>/publicRooms</code> on the release branch?” if that change consists of a single
commit.</p>
</li>
<li>
<p>Likewise: “what has changed on this branch in the last week?” is much
clearer without merges and “pep8” commits everywhere.</p>
</li>
<li>
<p>Sometimes we need to figure out where a bug got introduced, or some
behaviour changed. One way of doing that is with <code>git bisect</code>: pick an
arbitrary commit between the known good point and the known bad point, and
see how the code behaves. However, that strategy fails if the commit you
chose is the middle of someone's epic branch in which they broke the world
before putting it back together again.</p>
</li>
</ul>
<p>One counterargument is that it is sometimes useful to see how a PR evolved as
it went through review cycles. This is true, but that information is always
available via the GitHub UI (or via the little-known <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/checking-out-pull-requests-locally">refs/pull
namespace</a>).</p>
<p>Of course, in reality, things are more complicated than that. We have release
branches as well as <code>develop</code> and <code>master</code>, and we deliberately merge changes
between them. Bugs often slip through and have to be fixed later. That's all
fine: this not a cast-iron rule which must be obeyed, but an ideal to aim
towards.</p>
<h2 id="merges-squashes-rebases-wtf"><a class="header" href="#merges-squashes-rebases-wtf">Merges, squashes, rebases: wtf?</a></h2>
<p>Ok, so that's what we'd like to achieve. How do we achieve it?</p>
<p>The TL;DR is: when you come to merge a pull request, you <em>probably</em> want to
“squash and merge”:</p>
<p><img src="development/img/git/squash.png" alt="squash and merge" />.</p>
<p>(This applies whether you are merging your own PR, or that of another
contributor.)</p>
<p>“Squash and merge”<sup id="a1"><a href="development/git.html#f1">1</a></sup> takes all of the changes in the
PR, and bundles them into a single commit. GitHub gives you the opportunity to
edit the commit message before you confirm, and normally you should do so,
because the default will be useless (again: <code>* woops typo</code> is not a useful
thing to keep in the historical record).</p>
<p>The main problem with this approach comes when you have a series of pull
requests which build on top of one another: as soon as you squash-merge the
first PR, you'll end up with a stack of conflicts to resolve in all of the
others. In general, it's best to avoid this situation in the first place by
trying not to have multiple related PRs in flight at the same time. Still,
sometimes that's not possible and doing a regular merge is the lesser evil.</p>
<p>Another occasion in which a regular merge makes more sense is a PR where you've
deliberately created a series of commits each of which makes sense in its own
right. For example: <a href="https://github.com/matrix-org/synapse/pull/6837">a PR which gradually propagates a refactoring operation
through the codebase</a>, or <a href="https://github.com/matrix-org/synapse/pull/5987">a
PR which is the culmination of several other
PRs</a>. In this case the ability
to figure out when a particular change/bug was introduced could be very useful.</p>
<p>Ultimately: <strong>this is not a hard-and-fast-rule</strong>. If in doubt, ask yourself “do
each of the commits I am about to merge make sense in their own right”, but
remember that we're just doing our best to balance “keeping the commit history
clean” with other factors.</p>
<h2 id="git-branching-model"><a class="header" href="#git-branching-model">Git branching model</a></h2>
<p>A <a href="https://nvie.com/posts/a-successful-git-branching-model/">lot</a>
<a href="http://scottchacon.com/2011/08/31/github-flow.html">of</a>
<a href="https://www.endoflineblog.com/gitflow-considered-harmful">words</a> have been
written in the past about git branching models (no really, <a href="https://martinfowler.com/articles/branching-patterns.html">a
lot</a>). I tend to
think the whole thing is overblown. Fundamentally, it's not that
complicated. Here's how we do it.</p>
<p>Let's start with a picture:</p>
<p><img src="development/img/git/branches.jpg" alt="branching model" /></p>
<p>It looks complicated, but it's really not. There's one basic rule: <em>anyone</em> is
free to merge from <em>any</em> more-stable branch to <em>any</em> less-stable branch at
<em>any</em> time<sup id="a2"><a href="development/git.html#f2">2</a></sup>. (The principle behind this is that if a
change is good enough for the more-stable branch, then it's also good enough go
put in a less-stable branch.)</p>
<p>Meanwhile, merging (or squashing, as per the above) from a less-stable to a
more-stable branch is a deliberate action in which you want to publish a change
or a set of changes to (some subset of) the world: for example, this happens
when a PR is landed, or as part of our release process.</p>
<p>So, what counts as a more- or less-stable branch? A little reflection will show
that our active branches are ordered thus, from more-stable to less-stable:</p>
<ul>
<li><code>master</code> (tracks our last release).</li>
<li><code>release-vX.Y</code> (the branch where we prepare the next release)<sup
id="a3"><a href="development/git.html#f3">3</a></sup>.</li>
<li>PR branches which are targeting the release.</li>
<li><code>develop</code> (our &quot;mainline&quot; branch containing our bleeding-edge).</li>
<li>regular PR branches.</li>
</ul>
<p>The corollary is: if you have a bugfix that needs to land in both
<code>release-vX.Y</code> <em>and</em> <code>develop</code>, then you should base your PR on
<code>release-vX.Y</code>, get it merged there, and then merge from <code>release-vX.Y</code> to
<code>develop</code>. (If a fix lands in <code>develop</code> and we later need it in a
release-branch, we can of course cherry-pick it, but landing it in the release
branch first helps reduce the chance of annoying conflicts.)</p>
<hr />
<p><b id="f1">[1]</b>: “Squash and merge” is GitHub's term for this
operation. Given that there is no merge involved, I'm not convinced it's the
most intuitive name. <a href="development/git.html#a1">^</a></p>
<p><b id="f2">[2]</b>: Well, anyone with commit access.<a href="development/git.html#a2">^</a></p>
<p><b id="f3">[3]</b>: Very, very occasionally (I think this has happened once in
the history of Synapse), we've had two releases in flight at once. Obviously,
<code>release-v1.2</code> is more-stable than <code>release-v1.3</code>. <a href="development/git.html#a3">^</a></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="synapse-demo-setup"><a class="header" href="#synapse-demo-setup">Synapse demo setup</a></h1>
<p><strong>DO NOT USE THESE DEMO SERVERS IN PRODUCTION</strong></p>
<p>Requires you to have a <a href="https://matrix-org.github.io/synapse/develop/development/contributing_guide.html#4-install-the-dependencies">Synapse development environment setup</a>.</p>
<p>The demo setup allows running three federation Synapse servers, with server
names <code>localhost:8480</code>, <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
<p>You can access them via any Matrix client over HTTP at <code>localhost:8080</code>,
<code>localhost:8081</code>, and <code>localhost:8082</code> or over HTTPS at <code>localhost:8480</code>,
<code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
<p>To enable the servers to communicate, self-signed SSL certificates are generated
and the servers are configured in a highly insecure way, including:</p>
<ul>
<li>Not checking certificates over federation.</li>
<li>Not verifying keys.</li>
</ul>
<p>The servers are configured to store their data under <code>demo/8080</code>, <code>demo/8081</code>, and
<code>demo/8082</code>. This includes configuration, logs, SQLite databases, and media.</p>
<p>Note that when joining a public room on a different homeserver via &quot;#foo:bar.net&quot;,
then you are (in the current implementation) joining a room with room_id &quot;foo&quot;.
This means that it won't work if your homeserver already has a room with that
name.</p>
<h2 id="using-the-demo-scripts"><a class="header" href="#using-the-demo-scripts">Using the demo scripts</a></h2>
<p>There's three main scripts with straightforward purposes:</p>
<ul>
<li><code>start.sh</code> will start the Synapse servers, generating any missing configuration.
<ul>
<li>This accepts a single parameter <code>--no-rate-limit</code> to &quot;disable&quot; rate limits
(they actually still exist, but are very high).</li>
</ul>
</li>
<li><code>stop.sh</code> will stop the Synapse servers.</li>
<li><code>clean.sh</code> will delete the configuration, databases, log files, etc.</li>
</ul>
<p>To start a completely new set of servers, run:</p>
<pre><code class="language-sh">./demo/stop.sh; ./demo/clean.sh &amp;&amp; ./demo/start.sh
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="opentracing-2"><a class="header" href="#opentracing-2">OpenTracing</a></h1>
<h2 id="background"><a class="header" href="#background">Background</a></h2>
<p>OpenTracing is a semi-standard being adopted by a number of distributed
tracing platforms. It is a common api for facilitating vendor-agnostic
tracing instrumentation. That is, we can use the OpenTracing api and
select one of a number of tracer implementations to do the heavy lifting
in the background. Our current selected implementation is Jaeger.</p>
<p>OpenTracing is a tool which gives an insight into the causal
relationship of work done in and between servers. The servers each track
events and report them to a centralised server - in Synapse's case:
Jaeger. The basic unit used to represent events is the span. The span
roughly represents a single piece of work that was done and the time at
which it occurred. A span can have child spans, meaning that the work of
the child had to be completed for the parent span to complete, or it can
have follow-on spans which represent work that is undertaken as a result
of the parent but is not depended on by the parent to in order to
finish.</p>
<p>Since this is undertaken in a distributed environment a request to
another server, such as an RPC or a simple GET, can be considered a span
(a unit or work) for the local server. This causal link is what
OpenTracing aims to capture and visualise. In order to do this metadata
about the local server's span, i.e the 'span context', needs to be
included with the request to the remote.</p>
<p>It is up to the remote server to decide what it does with the spans it
creates. This is called the sampling policy and it can be configured
through Jaeger's settings.</p>
<p>For OpenTracing concepts see
<a href="https://opentracing.io/docs/overview/what-is-tracing/">https://opentracing.io/docs/overview/what-is-tracing/</a>.</p>
<p>For more information about Jaeger's implementation see
<a href="https://www.jaegertracing.io/docs/">https://www.jaegertracing.io/docs/</a></p>
<h2 id="setting-up-opentracing"><a class="header" href="#setting-up-opentracing">Setting up OpenTracing</a></h2>
<p>To receive OpenTracing spans, start up a Jaeger server. This can be done
using docker like so:</p>
<pre><code class="language-sh">docker run -d --name jaeger \
  -p 6831:6831/udp \
  -p 6832:6832/udp \
  -p 5778:5778 \
  -p 16686:16686 \
  -p 14268:14268 \
  jaegertracing/all-in-one:1
</code></pre>
<p>Latest documentation is probably at
https://www.jaegertracing.io/docs/latest/getting-started.</p>
<h2 id="enable-opentracing-in-synapse"><a class="header" href="#enable-opentracing-in-synapse">Enable OpenTracing in Synapse</a></h2>
<p>OpenTracing is not enabled by default. It must be enabled in the
homeserver config by adding the <code>opentracing</code> option to your config file. You can find 
documentation about how to do this in the <a href="usage/configuration/config_documentation.html#opentracing">config manual under the header 'Opentracing'</a>.
See below for an example Opentracing configuration: </p>
<pre><code class="language-yaml">opentracing:
  enabled: true
  homeserver_whitelist:
    - &quot;mytrustedhomeserver.org&quot;
    - &quot;*.myotherhomeservers.com&quot;
</code></pre>
<h2 id="homeserver-whitelisting"><a class="header" href="#homeserver-whitelisting">Homeserver whitelisting</a></h2>
<p>The homeserver whitelist is configured using regular expressions. A list
of regular expressions can be given and their union will be compared
when propagating any spans contexts to another homeserver.</p>
<p>Though it's mostly safe to send and receive span contexts to and from
untrusted users since span contexts are usually opaque ids it can lead
to two problems, namely:</p>
<ul>
<li>If the span context is marked as sampled by the sending homeserver
the receiver will sample it. Therefore two homeservers with wildly
different sampling policies could incur higher sampling counts than
intended.</li>
<li>Sending servers can attach arbitrary data to spans, known as
'baggage'. For safety this has been disabled in Synapse but that
doesn't prevent another server sending you baggage which will be
logged to OpenTracing's logs.</li>
</ul>
<h2 id="configuring-jaeger"><a class="header" href="#configuring-jaeger">Configuring Jaeger</a></h2>
<p>Sampling strategies can be set as in this document:
<a href="https://www.jaegertracing.io/docs/latest/sampling/">https://www.jaegertracing.io/docs/latest/sampling/</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="synapse-database-schema-files"><a class="header" href="#synapse-database-schema-files">Synapse database schema files</a></h1>
<p>Synapse's database schema is stored in the <code>synapse.storage.schema</code> module.</p>
<h2 id="logical-databases"><a class="header" href="#logical-databases">Logical databases</a></h2>
<p>Synapse supports splitting its datastore across multiple physical databases (which can
be useful for large installations), and the schema files are therefore split according
to the logical database they apply to.</p>
<p>At the time of writing, the following &quot;logical&quot; databases are supported:</p>
<ul>
<li><code>state</code> - used to store Matrix room state (more specifically, <code>state_groups</code>,
their relationships and contents).</li>
<li><code>main</code> - stores everything else.</li>
</ul>
<p>Additionally, the <code>common</code> directory contains schema files for tables which must be
present on <em>all</em> physical databases.</p>
<h2 id="synapse-schema-versions"><a class="header" href="#synapse-schema-versions">Synapse schema versions</a></h2>
<p>Synapse manages its database schema via &quot;schema versions&quot;. These are mainly used to
help avoid confusion if the Synapse codebase is rolled back after the database is
updated. They work as follows:</p>
<ul>
<li>
<p>The Synapse codebase defines a constant <code>synapse.storage.schema.SCHEMA_VERSION</code>
which represents the expectations made about the database by that version. For
example, as of Synapse v1.36, this is <code>59</code>.</p>
</li>
<li>
<p>The database stores a &quot;compatibility version&quot; in
<code>schema_compat_version.compat_version</code> which defines the <code>SCHEMA_VERSION</code> of the
oldest version of Synapse which will work with the database. On startup, if
<code>compat_version</code> is found to be newer than <code>SCHEMA_VERSION</code>, Synapse will refuse to
start.</p>
<p>Synapse automatically updates this field from
<code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code>.</p>
</li>
<li>
<p>Whenever a backwards-incompatible change is made to the database format (normally
via a <code>delta</code> file), <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code> is also updated
so that administrators can not accidentally roll back to a too-old version of Synapse.</p>
</li>
</ul>
<p>Generally, the goal is to maintain compatibility with at least one or two previous
releases of Synapse, so any substantial change tends to require multiple releases and a
bit of forward-planning to get right.</p>
<p>As a worked example: we want to remove the <code>room_stats_historical</code> table. Here is how it
might pan out.</p>
<ol>
<li>
<p>Replace any code that <em>reads</em> from <code>room_stats_historical</code> with alternative
implementations, but keep writing to it in case of rollback to an earlier version.
Also, increase <code>synapse.storage.schema.SCHEMA_VERSION</code>.  In this
instance, there is no existing code which reads from <code>room_stats_historical</code>, so
our starting point is:</p>
<p>v1.36.0: <code>SCHEMA_VERSION=59</code>, <code>SCHEMA_COMPAT_VERSION=59</code></p>
</li>
<li>
<p>Next (say in Synapse v1.37.0): remove the code that <em>writes</em> to
<code>room_stats_historical</code>, but don’t yet remove the table in case of rollback to
v1.36.0. Again, we increase <code>synapse.storage.schema.SCHEMA_VERSION</code>, but
because we have not broken compatibility with v1.36, we do not yet update
<code>SCHEMA_COMPAT_VERSION</code>. We now have:</p>
<p>v1.37.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=59</code>.</p>
</li>
<li>
<p>Later (say in Synapse v1.38.0): we can remove the table altogether. This will
break compatibility with v1.36.0, so we must update <code>SCHEMA_COMPAT_VERSION</code> accordingly.
There is no need to update <code>synapse.storage.schema.SCHEMA_VERSION</code>, since there is no
change to the Synapse codebase here. So we end up with:</p>
<p>v1.38.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=60</code>.</p>
</li>
</ol>
<p>If in doubt about whether to update <code>SCHEMA_VERSION</code> or not, it is generally best to
lean towards doing so.</p>
<h2 id="full-schema-dumps"><a class="header" href="#full-schema-dumps">Full schema dumps</a></h2>
<p>In the <code>full_schemas</code> directories, only the most recently-numbered snapshot is used
(<code>54</code> at the time of writing). Older snapshots (eg, <code>16</code>) are present for historical
reference only.</p>
<h3 id="building-full-schema-dumps"><a class="header" href="#building-full-schema-dumps">Building full schema dumps</a></h3>
<p>If you want to recreate these schemas, they need to be made from a database that
has had all background updates run.</p>
<p>To do so, use <code>scripts-dev/make_full_schema.sh</code>. This will produce new
<code>full.sql.postgres</code> and <code>full.sql.sqlite</code> files.</p>
<p>Ensure postgres is installed, then run:</p>
<pre><code class="language-sh">./scripts-dev/make_full_schema.sh -p postgres_username -o output_dir/
</code></pre>
<p>NB at the time of writing, this script predates the split into separate <code>state</code>/<code>main</code>
databases so will require updates to handle that correctly.</p>
<h2 id="delta-files"><a class="header" href="#delta-files">Delta files</a></h2>
<p>Delta files define the steps required to upgrade the database from an earlier version.
They can be written as either a file containing a series of SQL statements, or a Python
module.</p>
<p>Synapse remembers which delta files it has applied to a database (they are stored in the
<code>applied_schema_deltas</code> table) and will not re-apply them (even if a given file is
subsequently updated).</p>
<p>Delta files should be placed in a directory named <code>synapse/storage/schema/&lt;database&gt;/delta/&lt;version&gt;/</code>.
They are applied in alphanumeric order, so  by convention the first two characters
of the filename should be an integer such as <code>01</code>, to put the file in the right order.</p>
<h3 id="sql-delta-files"><a class="header" href="#sql-delta-files">SQL delta files</a></h3>
<p>These should be named <code>*.sql</code>, or —  for changes which should only be applied for a
given database engine — <code>*.sql.posgres</code> or <code>*.sql.sqlite</code>. For example, a delta which
adds a new column to the <code>foo</code> table might be called <code>01add_bar_to_foo.sql</code>.</p>
<p>Note that our SQL parser is a bit simple - it understands comments (<code>--</code> and <code>/*...*/</code>),
but complex statements which require a <code>;</code> in the middle of them (such as <code>CREATE TRIGGER</code>) are beyond it and you'll have to use a Python delta file.</p>
<h3 id="python-delta-files"><a class="header" href="#python-delta-files">Python delta files</a></h3>
<p>For more flexibility, a delta file can take the form of a python module. These should
be named <code>*.py</code>. Note that database-engine-specific modules are not supported here –
instead you can write <code>if isinstance(database_engine, PostgresEngine)</code> or similar.</p>
<p>A Python delta module should define either or both of the following functions:</p>
<pre><code class="language-python">import synapse.config.homeserver
import synapse.storage.engines
import synapse.storage.types


def run_create(
    cur: synapse.storage.types.Cursor,
    database_engine: synapse.storage.engines.BaseDatabaseEngine,
) -&gt; None:
    &quot;&quot;&quot;Called whenever an existing or new database is to be upgraded&quot;&quot;&quot;
    ...

def run_upgrade(
    cur: synapse.storage.types.Cursor,
    database_engine: synapse.storage.engines.BaseDatabaseEngine,
    config: synapse.config.homeserver.HomeServerConfig,
) -&gt; None:
    &quot;&quot;&quot;Called whenever an existing database is to be upgraded.&quot;&quot;&quot;
    ...
</code></pre>
<h2 id="boolean-columns"><a class="header" href="#boolean-columns">Boolean columns</a></h2>
<p>Boolean columns require special treatment, since SQLite treats booleans the
same as integers.</p>
<p>Any new boolean column must be added to the <code>BOOLEAN_COLUMNS</code> list in
<code>synapse/_scripts/synapse_port_db.py</code>. This tells the port script to cast
the integer value from SQLite to a boolean before writing the value to the
postgres database.</p>
<h2 id="event_id-global-uniqueness"><a class="header" href="#event_id-global-uniqueness"><code>event_id</code> global uniqueness</a></h2>
<p><code>event_id</code>'s can be considered globally unique although there has been a lot of
debate on this topic in places like
<a href="https://github.com/matrix-org/matrix-spec-proposals/issues/2779">MSC2779</a> and
<a href="https://github.com/matrix-org/matrix-spec-proposals/pull/2848">MSC2848</a> which
has no resolution yet (as of 2022-09-01). There are several places in Synapse
and even in the Matrix APIs like <a href="https://spec.matrix.org/v1.1/server-server-api/#get_matrixfederationv1eventeventid"><code>GET /_matrix/federation/v1/event/{eventId}</code></a>
where we assume that event IDs are globally unique.</p>
<p>When scoping <code>event_id</code> in a database schema, it is often nice to accompany it
with <code>room_id</code> (<code>PRIMARY KEY (room_id, event_id)</code> and a <code>FOREIGN KEY(room_id) REFERENCES rooms(room_id)</code>) which makes flexible lookups easy. For example it
makes it very easy to find and clean up everything in a room when it needs to be
purged (no need to use sub-<code>select</code> query or join from the <code>events</code> table).</p>
<p>A note on collisions: In room versions <code>1</code> and <code>2</code> it's possible to end up with
two events with the same <code>event_id</code> (in the same or different rooms). After room
version <code>3</code>, that can only happen with a hash collision, which we basically hope
will never happen (SHA256 has a massive big key space).</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="implementing-experimental-features-in-synapse"><a class="header" href="#implementing-experimental-features-in-synapse">Implementing experimental features in Synapse</a></h1>
<p>It can be desirable to implement &quot;experimental&quot; features which are disabled by
default and must be explicitly enabled via the Synapse configuration. This is
applicable for features which:</p>
<ul>
<li>Are unstable in the Matrix spec (e.g. those defined by an MSC that has not yet been merged).</li>
<li>Developers are not confident in their use by general Synapse administrators/users
(e.g. a feature is incomplete, buggy, performs poorly, or needs further testing).</li>
</ul>
<p>Note that this only really applies to features which are expected to be desirable
to a broad audience. The <a href="development/../modules/index.html">module infrastructure</a> should
instead be investigated for non-standard features.</p>
<p>Guarding experimental features behind configuration flags should help with some
of the following scenarios:</p>
<ul>
<li>Ensure that clients do not assume that unstable features exist (failing
gracefully if they do not).</li>
<li>Unstable features do not become de-facto standards and can be removed
aggressively (since only those who have opted-in will be affected).</li>
<li>Ease finding the implementation of unstable features in Synapse (for future
removal or stabilization).</li>
<li>Ease testing a feature (or removal of feature) due to enabling/disabling without
code changes. It also becomes possible to ask for wider testing, if desired.</li>
</ul>
<p>Experimental configuration flags should be disabled by default (requiring Synapse
administrators to explicitly opt-in), although there are situations where it makes
sense (from a product point-of-view) to enable features by default. This is
expected and not an issue.</p>
<p>It is not a requirement for experimental features to be behind a configuration flag,
but one should be used if unsure.</p>
<p>New experimental configuration flags should be added under the <code>experimental</code>
configuration key (see the <code>synapse.config.experimental</code> file) and either explain
(briefly) what is being enabled, or include the MSC number.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="managing-dependencies-with-poetry"><a class="header" href="#managing-dependencies-with-poetry">Managing dependencies with Poetry</a></h1>
<p>This is a quick cheat sheet for developers on how to use <a href="https://python-poetry.org/"><code>poetry</code></a>.</p>
<h1 id="installing"><a class="header" href="#installing">Installing</a></h1>
<p>See the <a href="development/contributing_guide.html#4-install-the-dependencies">contributing guide</a>.</p>
<p>Developers should use Poetry 1.3.2 or higher. If you encounter problems related
to poetry, please <a href="development/dependencies.html#check-the-version-of-poetry-with-poetry---version">double-check your poetry version</a>.</p>
<h1 id="background-1"><a class="header" href="#background-1">Background</a></h1>
<p>Synapse uses a variety of third-party Python packages to function as a homeserver.
Some of these are direct dependencies, listed in <code>pyproject.toml</code> under the
<code>[tool.poetry.dependencies]</code> section. The rest are transitive dependencies (the
things that our direct dependencies themselves depend on, and so on recursively.)</p>
<p>We maintain a locked list of all our dependencies (transitive included) so that
we can track exactly which version of each dependency appears in a given release.
See <a href="https://github.com/matrix-org/synapse/issues/11537#issue-1074469665">here</a>
for discussion of why we wanted this for Synapse. We chose to use
<a href="https://python-poetry.org/"><code>poetry</code></a> to manage this locked list; see
<a href="https://github.com/matrix-org/synapse/issues/11537#issuecomment-1015975819">this comment</a>
for the reasoning.</p>
<p>The locked dependencies get included in our &quot;self-contained&quot; releases: namely,
our docker images and our debian packages. We also use the locked dependencies
in development and our continuous integration.</p>
<p>Separately, our &quot;broad&quot; dependencies—the version ranges specified in
<code>pyproject.toml</code>—are included as metadata in our &quot;sdists&quot; and &quot;wheels&quot; <a href="https://pypi.org/project/matrix-synapse">uploaded
to PyPI</a>. Installing from PyPI or from
the Synapse source tree directly will <em>not</em> use the locked dependencies; instead,
they'll pull in the latest version of each package available at install time.</p>
<h2 id="example-dependency"><a class="header" href="#example-dependency">Example dependency</a></h2>
<p>An example may help. We have a broad dependency on
<a href="https://pypi.org/project/phonenumbers/"><code>phonenumbers</code></a>, as declared in
this snippet from pyproject.toml <a href="https://github.com/matrix-org/synapse/blob/release-v1.57/pyproject.toml#L133">as of Synapse 1.57</a>:</p>
<pre><code class="language-toml">[tool.poetry.dependencies]
# ...
phonenumbers = &quot;&gt;=8.2.0&quot;
</code></pre>
<p>In our lockfile this is
<a href="https://github.com/matrix-org/synapse/blob/dfc7646504cef3e4ff396c36089e1c6f1b1634de/poetry.lock#L679-L685">pinned</a>
to version 8.12.44, even though
<a href="https://pypi.org/project/phonenumbers/#history">newer versions are available</a>.</p>
<pre><code class="language-toml">[[package]]
name = &quot;phonenumbers&quot;
version = &quot;8.12.44&quot;
description = &quot;Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.&quot;
category = &quot;main&quot;
optional = false
python-versions = &quot;*&quot;
</code></pre>
<p>The lockfile also includes a
<a href="https://github.com/matrix-org/synapse/blob/release-v1.57/poetry.lock#L2178-L2181">cryptographic checksum</a>
of the sdists and wheels provided for this version of <code>phonenumbers</code>.</p>
<pre><code class="language-toml">[metadata.files]
# ...
phonenumbers = [
    {file = &quot;phonenumbers-8.12.44-py2.py3-none-any.whl&quot;, hash = &quot;sha256:cc1299cf37b309ecab6214297663ab86cb3d64ae37fd5b88e904fe7983a874a6&quot;},
    {file = &quot;phonenumbers-8.12.44.tar.gz&quot;, hash = &quot;sha256:26cfd0257d1704fe2f88caff2caabb70d16a877b1e65b6aae51f9fbbe10aa8ce&quot;},
]
</code></pre>
<p>We can see this pinned version inside the docker image for that release:</p>
<pre><code>$ docker pull matrixdotorg/synapse:v1.57.0
...
$ docker run --entrypoint pip matrixdotorg/synapse:v1.57.0 show phonenumbers
Name: phonenumbers
Version: 8.12.44
Summary: Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.
Home-page: https://github.com/daviddrysdale/python-phonenumbers
Author: David Drysdale
Author-email: dmd@lurklurk.org
License: Apache License 2.0
Location: /usr/local/lib/python3.9/site-packages
Requires:
Required-by: matrix-synapse
</code></pre>
<p>Whereas the wheel metadata just contains the broad dependencies:</p>
<pre><code>$ cd /tmp
$ wget https://files.pythonhosted.org/packages/ca/5e/d722d572cc5b3092402b783d6b7185901b444427633bd8a6b00ea0dd41b7/matrix_synapse-1.57.0rc1-py3-none-any.whl
...
$ unzip -c matrix_synapse-1.57.0rc1-py3-none-any.whl matrix_synapse-1.57.0rc1.dist-info/METADATA | grep phonenumbers
Requires-Dist: phonenumbers (&gt;=8.2.0)
</code></pre>
<h1 id="tooling-recommendation-direnv"><a class="header" href="#tooling-recommendation-direnv">Tooling recommendation: direnv</a></h1>
<p><a href="https://direnv.net/"><code>direnv</code></a> is a tool for activating environments in your
shell inside a given directory. Its support for poetry is unofficial (a
community wiki recipe only), but works solidly in our experience. We thoroughly
recommend it for daily use. To use it:</p>
<ol>
<li><a href="https://direnv.net/docs/installation.html">Install <code>direnv</code></a> - it's likely
packaged for your system already.</li>
<li>Teach direnv about poetry. The <a href="https://github.com/direnv/direnv/wiki/Python#poetry">shell config here</a>
needs to be added to <code>~/.config/direnv/direnvrc</code> (or more generally <code>$XDG_CONFIG_HOME/direnv/direnvrc</code>).</li>
<li>Mark the synapse checkout as a poetry project: <code>echo layout poetry &gt; .envrc</code>.</li>
<li>Convince yourself that you trust this <code>.envrc</code> configuration and project.
Then formally confirm this to <code>direnv</code> by running <code>direnv allow</code>.</li>
</ol>
<p>Then whenever you navigate to the synapse checkout, you should be able to run
e.g. <code>mypy</code> instead of <code>poetry run mypy</code>; <code>python</code> instead of
<code>poetry run python</code>; and your shell commands will automatically run in the
context of poetry's venv, without having to run <code>poetry shell</code> beforehand.</p>
<h1 id="how-do-i"><a class="header" href="#how-do-i">How do I...</a></h1>
<h2 id="reset-my-venv-to-the-locked-environment"><a class="header" href="#reset-my-venv-to-the-locked-environment">...reset my venv to the locked environment?</a></h2>
<pre><code class="language-shell">poetry install --all-extras --sync
</code></pre>
<h2 id="delete-everything-and-start-over-from-scratch"><a class="header" href="#delete-everything-and-start-over-from-scratch">...delete everything and start over from scratch?</a></h2>
<pre><code class="language-shell"># Stop the current virtualenv if active
$ deactivate

# Remove all of the files from the current environment.
# Don't worry, even though it says &quot;all&quot;, this will only
# remove the Poetry virtualenvs for the current project.
$ poetry env remove --all

# Reactivate Poetry shell to create the virtualenv again
$ poetry shell
# Install everything again
$ poetry install --extras all
</code></pre>
<h2 id="run-a-command-in-the-poetry-virtualenv"><a class="header" href="#run-a-command-in-the-poetry-virtualenv">...run a command in the <code>poetry</code> virtualenv?</a></h2>
<p>Use <code>poetry run cmd args</code> when you need the python virtualenv context.
To avoid typing <code>poetry run</code> all the time, you can run  <code>poetry shell</code>
to start a new shell in the poetry virtualenv context. Within <code>poetry shell</code>,
<code>python</code>, <code>pip</code>, <code>mypy</code>, <code>trial</code>, etc. are all run inside the project virtualenv
and isolated from the rest o the system.</p>
<p>Roughly speaking, the translation from a traditional virtualenv is:</p>
<ul>
<li><code>env/bin/activate</code> -&gt; <code>poetry shell</code>, and</li>
<li><code>deactivate</code> -&gt; close the terminal (Ctrl-D, <code>exit</code>, etc.)</li>
</ul>
<p>See also the direnv recommendation above, which makes <code>poetry run</code> and
<code>poetry shell</code> unnecessary.</p>
<h2 id="inspect-the-poetry-virtualenv"><a class="header" href="#inspect-the-poetry-virtualenv">...inspect the <code>poetry</code> virtualenv?</a></h2>
<p>Some suggestions:</p>
<pre><code class="language-shell"># Current env only
poetry env info
# All envs: this allows you to have e.g. a poetry managed venv for Python 3.7,
# and another for Python 3.10.
poetry env list --full-path
poetry run pip list
</code></pre>
<p>Note that <code>poetry show</code> describes the abstract <em>lock file</em> rather than your
on-disk environment. With that said, <code>poetry show --tree</code> can sometimes be
useful.</p>
<h2 id="add-a-new-dependency"><a class="header" href="#add-a-new-dependency">...add a new dependency?</a></h2>
<p>Either:</p>
<ul>
<li>manually update <code>pyproject.toml</code>; then <code>poetry lock --no-update</code>; or else</li>
<li><code>poetry add packagename</code>. See <code>poetry add --help</code>; note the <code>--dev</code>,
<code>--extras</code> and <code>--optional</code> flags in particular.</li>
</ul>
<p>Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> files in your commit.</p>
<h2 id="remove-a-dependency"><a class="header" href="#remove-a-dependency">...remove a dependency?</a></h2>
<p>This is not done often and is untested, but</p>
<pre><code class="language-shell">poetry remove packagename
</code></pre>
<p>ought to do the trick. Alternatively, manually update <code>pyproject.toml</code> and
<code>poetry lock --no-update</code>. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code>
files in your commit.</p>
<h2 id="update-the-version-range-for-an-existing-dependency"><a class="header" href="#update-the-version-range-for-an-existing-dependency">...update the version range for an existing dependency?</a></h2>
<p>Best done by manually editing <code>pyproject.toml</code>, then <code>poetry lock --no-update</code>.
Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> in your commit.</p>
<h2 id="update-a-dependency-in-the-locked-environment"><a class="header" href="#update-a-dependency-in-the-locked-environment">...update a dependency in the locked environment?</a></h2>
<p>Use</p>
<pre><code class="language-shell">poetry update packagename
</code></pre>
<p>to use the latest version of <code>packagename</code> in the locked environment, without
affecting the broad dependencies listed in the wheel.</p>
<p>There doesn't seem to be a way to do this whilst locking a <em>specific</em> version of
<code>packagename</code>. We can workaround this (crudely) as follows:</p>
<pre><code class="language-shell">poetry add packagename==1.2.3
# This should update pyproject.lock.

# Now undo the changes to pyproject.toml. For example
# git restore pyproject.toml

# Get poetry to recompute the content-hash of pyproject.toml without changing
# the locked package versions.
poetry lock --no-update
</code></pre>
<p>Either way, include the updated <code>poetry.lock</code> file in your commit.</p>
<h2 id="export-a-requirementstxt-file"><a class="header" href="#export-a-requirementstxt-file">...export a <code>requirements.txt</code> file?</a></h2>
<pre><code class="language-shell">poetry export --extras all
</code></pre>
<p>Be wary of bugs in <code>poetry export</code> and <code>pip install -r requirements.txt</code>.</p>
<h2 id="build-a-test-wheel"><a class="header" href="#build-a-test-wheel">...build a test wheel?</a></h2>
<p>I usually use</p>
<pre><code class="language-shell">poetry run pip install build &amp;&amp; poetry run python -m build
</code></pre>
<p>because <a href="https://github.com/pypa/build"><code>build</code></a> is a standardish tool which
doesn't require poetry. (It's what we use in CI too). However, you could try
<code>poetry build</code> too.</p>
<h2 id="handle-a-dependabot-pull-request"><a class="header" href="#handle-a-dependabot-pull-request">...handle a Dependabot pull request?</a></h2>
<p>Synapse uses Dependabot to keep the <code>poetry.lock</code> and <code>Cargo.lock</code> file 
up-to-date with the latest releases of our dependencies. The changelog check is
omitted for Dependabot PRs; the release script will include them in the 
changelog.</p>
<p>When reviewing a dependabot PR, ensure that:</p>
<ul>
<li>the lockfile changes look reasonable;</li>
<li>the upstream changelog file (linked in the description) doesn't include any
breaking changes;</li>
<li>continuous integration passes.</li>
</ul>
<p>In particular, any updates to the type hints (usually packages which start with <code>types-</code>)
should be safe to merge if linting passes.</p>
<h1 id="troubleshooting-4"><a class="header" href="#troubleshooting-4">Troubleshooting</a></h1>
<h2 id="check-the-version-of-poetry-with-poetry---version"><a class="header" href="#check-the-version-of-poetry-with-poetry---version">Check the version of poetry with <code>poetry --version</code>.</a></h2>
<p>The minimum version of poetry supported by Synapse is 1.3.2.</p>
<p>It can also be useful to check the version of <code>poetry-core</code> in use. If you've
installed <code>poetry</code> with <code>pipx</code>, try <code>pipx runpip poetry list | grep poetry-core</code>.</p>
<h2 id="clear-caches-poetry-cache-clear---all-pypi"><a class="header" href="#clear-caches-poetry-cache-clear---all-pypi">Clear caches: <code>poetry cache clear --all pypi</code>.</a></h2>
<p>Poetry caches a bunch of information about packages that isn't readily available
from PyPI. (This is what makes poetry seem slow when doing the first
<code>poetry install</code>.) Try <code>poetry cache list</code> and <code>poetry cache clear --all &lt;name of cache&gt;</code> to see if that fixes things.</p>
<h2 id="remove-outdated-egg-info"><a class="header" href="#remove-outdated-egg-info">Remove outdated egg-info</a></h2>
<p>Delete the <code>matrix_synapse.egg-info/</code> directory from the root of your Synapse
install.</p>
<p>This stores some cached information about dependencies and often conflicts with
letting Poetry do the right thing.</p>
<h2 id="try---verbose-or---dry-run-arguments"><a class="header" href="#try---verbose-or---dry-run-arguments">Try <code>--verbose</code> or <code>--dry-run</code> arguments.</a></h2>
<p>Sometimes useful to see what poetry's internal logic is.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="cancellation"><a class="header" href="#cancellation">Cancellation</a></h1>
<p>Sometimes, requests take a long time to service and clients disconnect
before Synapse produces a response. To avoid wasting resources, Synapse
can cancel request processing for select endpoints marked with the
<code>@cancellable</code> decorator.</p>
<p>Synapse makes use of Twisted's <code>Deferred.cancel()</code> feature to make
cancellation work. The <code>@cancellable</code> decorator does nothing by itself
and merely acts as a flag, signalling to developers and other code alike
that a method can be cancelled.</p>
<h2 id="enabling-cancellation-for-an-endpoint"><a class="header" href="#enabling-cancellation-for-an-endpoint">Enabling cancellation for an endpoint</a></h2>
<ol>
<li>Check that the endpoint method, and any <code>async</code> functions in its call
tree handle cancellation correctly. See
<a href="development/synapse_architecture/cancellation.html#handling-cancellation-correctly">Handling cancellation correctly</a>
for a list of things to look out for.</li>
<li>Add the <code>@cancellable</code> decorator to the <code>on_GET/POST/PUT/DELETE</code>
method. It's not recommended to make non-<code>GET</code> methods cancellable,
since cancellation midway through some database updates is less
likely to be handled correctly.</li>
</ol>
<h2 id="mechanics"><a class="header" href="#mechanics">Mechanics</a></h2>
<p>There are two stages to cancellation: downward propagation of a
<code>cancel()</code> call, followed by upwards propagation of a <code>CancelledError</code>
out of a blocked <code>await</code>.
Both Twisted and asyncio have a cancellation mechanism.</p>
<table><thead><tr><th></th><th>Method</th><th>Exception</th><th>Exception inherits from</th></tr></thead><tbody>
<tr><td>Twisted</td><td><code>Deferred.cancel()</code></td><td><code>twisted.internet.defer.CancelledError</code></td><td><code>Exception</code> (!)</td></tr>
<tr><td>asyncio</td><td><code>Task.cancel()</code></td><td><code>asyncio.CancelledError</code></td><td><code>BaseException</code></td></tr>
</tbody></table>
<h3 id="deferredcancel"><a class="header" href="#deferredcancel">Deferred.cancel()</a></h3>
<p>When Synapse starts handling a request, it runs the async method
responsible for handling it using <code>defer.ensureDeferred</code>, which returns
a <code>Deferred</code>. For example:</p>
<pre><code class="language-python">def do_something() -&gt; Deferred[None]:
    ...

@cancellable
async def on_GET() -&gt; Tuple[int, JsonDict]:
    d = make_deferred_yieldable(do_something())
    await d
    return 200, {}

request = defer.ensureDeferred(on_GET())
</code></pre>
<p>When a client disconnects early, Synapse checks for the presence of the
<code>@cancellable</code> decorator on <code>on_GET</code>. Since <code>on_GET</code> is cancellable,
<code>Deferred.cancel()</code> is called on the <code>Deferred</code> from
<code>defer.ensureDeferred</code>, ie. <code>request</code>. Twisted knows which <code>Deferred</code>
<code>request</code> is waiting on and passes the <code>cancel()</code> call on to <code>d</code>.</p>
<p>The <code>Deferred</code> being waited on, <code>d</code>, may have its own handling for
<code>cancel()</code> and pass the call on to other <code>Deferred</code>s.</p>
<p>Eventually, a <code>Deferred</code> handles the <code>cancel()</code> call by resolving itself
with a <code>CancelledError</code>.</p>
<h3 id="cancellederror"><a class="header" href="#cancellederror">CancelledError</a></h3>
<p>The <code>CancelledError</code> gets raised out of the <code>await</code> and bubbles up, as
per normal Python exception handling.</p>
<h2 id="handling-cancellation-correctly"><a class="header" href="#handling-cancellation-correctly">Handling cancellation correctly</a></h2>
<p>In general, when writing code that might be subject to cancellation, two
things must be considered:</p>
<ul>
<li>The effect of <code>CancelledError</code>s raised out of <code>await</code>s.</li>
<li>The effect of <code>Deferred</code>s being <code>cancel()</code>ed.</li>
</ul>
<p>Examples of code that handles cancellation incorrectly include:</p>
<ul>
<li><code>try-except</code> blocks which swallow <code>CancelledError</code>s.</li>
<li>Code that shares the same <code>Deferred</code>, which may be cancelled, between
multiple requests.</li>
<li>Code that starts some processing that's exempt from cancellation, but
uses a logging context from cancellable code. The logging context
will be finished upon cancellation, while the uncancelled processing
is still using it.</li>
</ul>
<p>Some common patterns are listed below in more detail.</p>
<h3 id="async-function-calls"><a class="header" href="#async-function-calls"><code>async</code> function calls</a></h3>
<p>Most functions in Synapse are relatively straightforward from a
cancellation standpoint: they don't do anything with <code>Deferred</code>s and
purely call and <code>await</code> other <code>async</code> functions.</p>
<p>An <code>async</code> function handles cancellation correctly if its own code
handles cancellation correctly and all the async function it calls
handle cancellation correctly. For example:</p>
<pre><code class="language-python">async def do_two_things() -&gt; None:
    check_something()
    await do_something()
    await do_something_else()
</code></pre>
<p><code>do_two_things</code> handles cancellation correctly if <code>do_something</code> and
<code>do_something_else</code> handle cancellation correctly.</p>
<p>That is, when checking whether a function handles cancellation
correctly, its implementation and all its <code>async</code> function calls need to
be checked, recursively.</p>
<p>As <code>check_something</code> is not <code>async</code>, it does not need to be checked.</p>
<h3 id="cancellederrors"><a class="header" href="#cancellederrors">CancelledErrors</a></h3>
<p>Because Twisted's <code>CancelledError</code>s are <code>Exception</code>s, it's easy to
accidentally catch and suppress them. Care must be taken to ensure that
<code>CancelledError</code>s are allowed to propagate upwards.</p>
<table width="100%">
<tr>
<td width="50%" valign="top">
<p><strong>Bad</strong>:</p>
<pre><code class="language-python">try:
    await do_something()
except Exception:
    # `CancelledError` gets swallowed here.
    logger.info(...)
</code></pre>
</td>
<td width="50%" valign="top">
<p><strong>Good</strong>:</p>
<pre><code class="language-python">try:
    await do_something()
except CancelledError:
    raise
except Exception:
    logger.info(...)
</code></pre>
</td>
</tr>
<tr>
<td width="50%" valign="top">
<p><strong>OK</strong>:</p>
<pre><code class="language-python">try:
    check_something()
    # A `CancelledError` won't ever be raised here.
except Exception:
    logger.info(...)
</code></pre>
</td>
<td width="50%" valign="top">
<p><strong>Good</strong>:</p>
<pre><code class="language-python">try:
    await do_something()
except ValueError:
    logger.info(...)
</code></pre>
</td>
</tr>
</table>
<h4 id="defergatherresults"><a class="header" href="#defergatherresults">defer.gatherResults</a></h4>
<p><code>defer.gatherResults</code> produces a <code>Deferred</code> which:</p>
<ul>
<li>broadcasts <code>cancel()</code> calls to every <code>Deferred</code> being waited on.</li>
<li>wraps the first exception it sees in a <code>FirstError</code>.</li>
</ul>
<p>Together, this means that <code>CancelledError</code>s will be wrapped in
a <code>FirstError</code> unless unwrapped. Such <code>FirstError</code>s are liable to be
swallowed, so they must be unwrapped.</p>
<table width="100%">
<tr>
<td width="50%" valign="top">
<p><strong>Bad</strong>:</p>
<pre><code class="language-python">async def do_something() -&gt; None:
    await make_deferred_yieldable(
        defer.gatherResults([...], consumeErrors=True)
    )

try:
    await do_something()
except CancelledError:
    raise
except Exception:
    # `FirstError(CancelledError)` gets swallowed here.
    logger.info(...)
</code></pre>
</td>
<td width="50%" valign="top">
<p><strong>Good</strong>:</p>
<pre><code class="language-python">async def do_something() -&gt; None:
    await make_deferred_yieldable(
        defer.gatherResults([...], consumeErrors=True)
    ).addErrback(unwrapFirstError)

try:
    await do_something()
except CancelledError:
    raise
except Exception:
    logger.info(...)
</code></pre>
</td>
</tr>
</table>
<h3 id="creation-of-deferreds"><a class="header" href="#creation-of-deferreds">Creation of <code>Deferred</code>s</a></h3>
<p>If a function creates a <code>Deferred</code>, the effect of cancelling it must be considered. <code>Deferred</code>s that get shared are likely to have unintended behaviour when cancelled.</p>
<table width="100%">
<tr>
<td width="50%" valign="top">
<p><strong>Bad</strong>:</p>
<pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}

def wait_for_room(room_id: str) -&gt; Deferred[None]:
    deferred = cache.get(room_id)
    if deferred is None:
        deferred = Deferred()
        cache[room_id] = deferred
    # `deferred` can have multiple waiters.
    # All of them will observe a `CancelledError`
    # if any one of them is cancelled.
    return make_deferred_yieldable(deferred)

# Request 1
await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
# Request 2
await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
</code></pre>
</td>
<td width="50%" valign="top">
<p><strong>Good</strong>:</p>
<pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}

def wait_for_room(room_id: str) -&gt; Deferred[None]:
    deferred = cache.get(room_id)
    if deferred is None:
        deferred = Deferred()
        cache[room_id] = deferred
    # `deferred` will never be cancelled now.
    # A `CancelledError` will still come out of
    # the `await`.
    # `delay_cancellation` may also be used.
    return make_deferred_yieldable(stop_cancellation(deferred))

# Request 1
await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
# Request 2
await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
</code></pre>
</td>
</tr>
<tr>
<td width="50%" valign="top">
</td>
<td width="50%" valign="top">
<p><strong>Good</strong>:</p>
<pre><code class="language-python">cache: Dict[str, List[Deferred[None]]] = {}

def wait_for_room(room_id: str) -&gt; Deferred[None]:
    if room_id not in cache:
        cache[room_id] = []
    # Each request gets its own `Deferred` to wait on.
    deferred = Deferred()
    cache[room_id]].append(deferred)
    return make_deferred_yieldable(deferred)

# Request 1
await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
# Request 2
await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
</code></pre>
</td>
</table>
<h3 id="uncancelled-processing"><a class="header" href="#uncancelled-processing">Uncancelled processing</a></h3>
<p>Some <code>async</code> functions may kick off some <code>async</code> processing which is
intentionally protected from cancellation, by <code>stop_cancellation</code> or
other means. If the <code>async</code> processing inherits the logcontext of the
request which initiated it, care must be taken to ensure that the
logcontext is not finished before the <code>async</code> processing completes.</p>
<table width="100%">
<tr>
<td width="50%" valign="top">
<p><strong>Bad</strong>:</p>
<pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None

async def do_something_else(
    to_resolve: Deferred[None]
) -&gt; None:
    await ...
    logger.info(&quot;done!&quot;)
    to_resolve.callback(None)

async def do_something() -&gt; None:
    if not cache:
        to_resolve = Deferred()
        cache = ObservableDeferred(to_resolve)
        # `do_something_else` will never be cancelled and
        # can outlive the `request-1` logging context.
        run_in_background(do_something_else, to_resolve)

    await make_deferred_yieldable(cache.observe())

with LoggingContext(&quot;request-1&quot;):
    await do_something()
</code></pre>
</td>
<td width="50%" valign="top">
<p><strong>Good</strong>:</p>
<pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None

async def do_something_else(
    to_resolve: Deferred[None]
) -&gt; None:
    await ...
    logger.info(&quot;done!&quot;)
    to_resolve.callback(None)

async def do_something() -&gt; None:
    if not cache:
        to_resolve = Deferred()
        cache = ObservableDeferred(to_resolve)
        run_in_background(do_something_else, to_resolve)
        # We'll wait until `do_something_else` is
        # done before raising a `CancelledError`.
        await make_deferred_yieldable(
            delay_cancellation(cache.observe())
        )
    else:
        await make_deferred_yieldable(cache.observe())

with LoggingContext(&quot;request-1&quot;):
    await do_something()
</code></pre>
</td>
</tr>
<tr>
<td width="50%">
<p><strong>OK</strong>:</p>
<pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None

async def do_something_else(
    to_resolve: Deferred[None]
) -&gt; None:
    await ...
    logger.info(&quot;done!&quot;)
    to_resolve.callback(None)

async def do_something() -&gt; None:
    if not cache:
        to_resolve = Deferred()
        cache = ObservableDeferred(to_resolve)
        # `do_something_else` will get its own independent
        # logging context. `request-1` will not count any
        # metrics from `do_something_else`.
        run_as_background_process(
            &quot;do_something_else&quot;,
            do_something_else,
            to_resolve,
        )

    await make_deferred_yieldable(cache.observe())

with LoggingContext(&quot;request-1&quot;):
    await do_something()
</code></pre>
</td>
<td width="50%">
</td>
</tr>
</table>
<div style="break-before: page; page-break-before: always;"></div><h1 id="log-contexts"><a class="header" href="#log-contexts">Log Contexts</a></h1>
<p>To help track the processing of individual requests, synapse uses a
'<code>log context</code>' to track which request it is handling at any given
moment. This is done via a thread-local variable; a <code>logging.Filter</code> is
then used to fish the information back out of the thread-local variable
and add it to each log record.</p>
<p>Logcontexts are also used for CPU and database accounting, so that we
can track which requests were responsible for high CPU use or database
activity.</p>
<p>The <code>synapse.logging.context</code> module provides facilities for managing
the current log context (as well as providing the <code>LoggingContextFilter</code>
class).</p>
<p>Asynchronous functions make the whole thing complicated, so this document describes
how it all works, and how to write code which follows the rules.</p>
<p>In this document, &quot;awaitable&quot; refers to any object which can be <code>await</code>ed. In the context of
Synapse, that normally means either a coroutine or a Twisted 
<a href="https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html"><code>Deferred</code></a>.</p>
<h2 id="logcontexts-without-asynchronous-code"><a class="header" href="#logcontexts-without-asynchronous-code">Logcontexts without asynchronous code</a></h2>
<p>In the absence of any asynchronous voodoo, things are simple enough. As with
any code of this nature, the rule is that our function should leave
things as it found them:</p>
<pre><code class="language-python">from synapse.logging import context         # omitted from future snippets

def handle_request(request_id):
    request_context = context.LoggingContext()

    calling_context = context.set_current_context(request_context)
    try:
        request_context.request = request_id
        do_request_handling()
        logger.debug(&quot;finished&quot;)
    finally:
        context.set_current_context(calling_context)

def do_request_handling():
    logger.debug(&quot;phew&quot;)  # this will be logged against request_id
</code></pre>
<p>LoggingContext implements the context management methods, so the above
can be written much more succinctly as:</p>
<pre><code class="language-python">def handle_request(request_id):
    with context.LoggingContext() as request_context:
        request_context.request = request_id
        do_request_handling()
        logger.debug(&quot;finished&quot;)

def do_request_handling():
    logger.debug(&quot;phew&quot;)
</code></pre>
<h2 id="using-logcontexts-with-awaitables"><a class="header" href="#using-logcontexts-with-awaitables">Using logcontexts with awaitables</a></h2>
<p>Awaitables break the linear flow of code so that there is no longer a single entry point
where we should set the logcontext and a single exit point where we should remove it.</p>
<p>Consider the example above, where <code>do_request_handling</code> needs to do some
blocking operation, and returns an awaitable:</p>
<pre><code class="language-python">async def handle_request(request_id):
    with context.LoggingContext() as request_context:
        request_context.request = request_id
        await do_request_handling()
        logger.debug(&quot;finished&quot;)
</code></pre>
<p>In the above flow:</p>
<ul>
<li>The logcontext is set</li>
<li><code>do_request_handling</code> is called, and returns an awaitable</li>
<li><code>handle_request</code> awaits the awaitable</li>
<li>Execution of <code>handle_request</code> is suspended</li>
</ul>
<p>So we have stopped processing the request (and will probably go on to
start processing the next), without clearing the logcontext.</p>
<p>To circumvent this problem, synapse code assumes that, wherever you have
an awaitable, you will want to <code>await</code> it. To that end, whereever
functions return awaitables, we adopt the following conventions:</p>
<p><strong>Rules for functions returning awaitables:</strong></p>
<blockquote>
<ul>
<li>If the awaitable is already complete, the function returns with the
same logcontext it started with.</li>
<li>If the awaitable is incomplete, the function clears the logcontext
before returning; when the awaitable completes, it restores the
logcontext before running any callbacks.</li>
</ul>
</blockquote>
<p>That sounds complicated, but actually it means a lot of code (including
the example above) &quot;just works&quot;. There are two cases:</p>
<ul>
<li>
<p>If <code>do_request_handling</code> returns a completed awaitable, then the
logcontext will still be in place. In this case, execution will
continue immediately after the <code>await</code>; the &quot;finished&quot; line will
be logged against the right context, and the <code>with</code> block restores
the original context before we return to the caller.</p>
</li>
<li>
<p>If the returned awaitable is incomplete, <code>do_request_handling</code> clears
the logcontext before returning. The logcontext is therefore clear
when <code>handle_request</code> <code>await</code>s the awaitable.</p>
<p>Once <code>do_request_handling</code>'s awaitable completes, it will reinstate
the logcontext, before running the second half of <code>handle_request</code>,
so again the &quot;finished&quot; line will be logged against the right context,
and the <code>with</code> block restores the original context.</p>
</li>
</ul>
<p>As an aside, it's worth noting that <code>handle_request</code> follows our rules</p>
<ul>
<li>though that only matters if the caller has its own logcontext which it
cares about.</li>
</ul>
<p>The following sections describe pitfalls and helpful patterns when
implementing these rules.</p>
<h2 id="always-await-your-awaitables"><a class="header" href="#always-await-your-awaitables">Always await your awaitables</a></h2>
<p>Whenever you get an awaitable back from a function, you should <code>await</code> on
it as soon as possible. Do not pass go; do not do any logging; do not
call any other functions.</p>
<pre><code class="language-python">async def fun():
    logger.debug(&quot;starting&quot;)
    await do_some_stuff()       # just like this

    coro = more_stuff()
    result = await coro         # also fine, of course

    return result
</code></pre>
<p>Provided this pattern is followed all the way back up to the callchain
to where the logcontext was set, this will make things work out ok:
provided <code>do_some_stuff</code> and <code>more_stuff</code> follow the rules above, then
so will <code>fun</code>.</p>
<p>It's all too easy to forget to <code>await</code>: for instance if we forgot that
<code>do_some_stuff</code> returned an awaitable, we might plough on regardless. This
leads to a mess; it will probably work itself out eventually, but not
before a load of stuff has been logged against the wrong context.
(Normally, other things will break, more obviously, if you forget to
<code>await</code>, so this tends not to be a major problem in practice.)</p>
<p>Of course sometimes you need to do something a bit fancier with your
awaitable - not all code follows the linear A-then-B-then-C pattern.
Notes on implementing more complex patterns are in later sections.</p>
<h2 id="where-you-create-a-new-awaitable-make-it-follow-the-rules"><a class="header" href="#where-you-create-a-new-awaitable-make-it-follow-the-rules">Where you create a new awaitable, make it follow the rules</a></h2>
<p>Most of the time, an awaitable comes from another synapse function.
Sometimes, though, we need to make up a new awaitable, or we get an awaitable
back from external code. We need to make it follow our rules.</p>
<p>The easy way to do it is by using <code>context.make_deferred_yieldable</code>. Suppose we want to implement
<code>sleep</code>, which returns a deferred which will run its callbacks after a
given number of seconds. That might look like:</p>
<pre><code class="language-python"># not a logcontext-rules-compliant function
def get_sleep_deferred(seconds):
    d = defer.Deferred()
    reactor.callLater(seconds, d.callback, None)
    return d
</code></pre>
<p>That doesn't follow the rules, but we can fix it by calling it through
<code>context.make_deferred_yieldable</code>:</p>
<pre><code class="language-python">async def sleep(seconds):
    return await context.make_deferred_yieldable(get_sleep_deferred(seconds))
</code></pre>
<h2 id="fire-and-forget"><a class="header" href="#fire-and-forget">Fire-and-forget</a></h2>
<p>Sometimes you want to fire off a chain of execution, but not wait for
its result. That might look a bit like this:</p>
<pre><code class="language-python">async def do_request_handling():
    await foreground_operation()

    # *don't* do this
    background_operation()

    logger.debug(&quot;Request handling complete&quot;)

async def background_operation():
    await first_background_step()
    logger.debug(&quot;Completed first step&quot;)
    await second_background_step()
    logger.debug(&quot;Completed second step&quot;)
</code></pre>
<p>The above code does a couple of steps in the background after
<code>do_request_handling</code> has finished. The log lines are still logged
against the <code>request_context</code> logcontext, which may or may not be
desirable. There are two big problems with the above, however. The first
problem is that, if <code>background_operation</code> returns an incomplete
awaitable, it will expect its caller to <code>await</code> immediately, so will have
cleared the logcontext. In this example, that means that 'Request
handling complete' will be logged without any context.</p>
<p>The second problem, which is potentially even worse, is that when the
awaitable returned by <code>background_operation</code> completes, it will restore
the original logcontext. There is nothing waiting on that awaitable, so
the logcontext will leak into the reactor and possibly get attached to
some arbitrary future operation.</p>
<p>There are two potential solutions to this.</p>
<p>One option is to surround the call to <code>background_operation</code> with a
<code>PreserveLoggingContext</code> call. That will reset the logcontext before
starting <code>background_operation</code> (so the context restored when the
deferred completes will be the empty logcontext), and will restore the
current logcontext before continuing the foreground process:</p>
<pre><code class="language-python">async def do_request_handling():
    await foreground_operation()

    # start background_operation off in the empty logcontext, to
    # avoid leaking the current context into the reactor.
    with PreserveLoggingContext():
        background_operation()

    # this will now be logged against the request context
    logger.debug(&quot;Request handling complete&quot;)
</code></pre>
<p>Obviously that option means that the operations done in
<code>background_operation</code> would be not be logged against a logcontext
(though that might be fixed by setting a different logcontext via a
<code>with LoggingContext(...)</code> in <code>background_operation</code>).</p>
<p>The second option is to use <code>context.run_in_background</code>, which wraps a
function so that it doesn't reset the logcontext even when it returns
an incomplete awaitable, and adds a callback to the returned awaitable to
reset the logcontext. In other words, it turns a function that follows
the Synapse rules about logcontexts and awaitables into one which behaves
more like an external function --- the opposite operation to that
described in the previous section. It can be used like this:</p>
<pre><code class="language-python">async def do_request_handling():
    await foreground_operation()

    context.run_in_background(background_operation)

    # this will now be logged against the request context
    logger.debug(&quot;Request handling complete&quot;)
</code></pre>
<h2 id="passing-synapse-deferreds-into-third-party-functions"><a class="header" href="#passing-synapse-deferreds-into-third-party-functions">Passing synapse deferreds into third-party functions</a></h2>
<p>A typical example of this is where we want to collect together two or
more awaitables via <code>defer.gatherResults</code>:</p>
<pre><code class="language-python">a1 = operation1()
a2 = operation2()
a3 = defer.gatherResults([a1, a2])
</code></pre>
<p>This is really a variation of the fire-and-forget problem above, in that
we are firing off <code>a1</code> and <code>a2</code> without awaiting on them. The difference
is that we now have third-party code attached to their callbacks. Anyway
either technique given in the <a href="log_contexts.html#fire-and-forget">Fire-and-forget</a>
section will work.</p>
<p>Of course, the new awaitable returned by <code>gather</code> needs to be
wrapped in order to make it follow the logcontext rules before we can
yield it, as described in <a href="log_contexts.html#where-you-create-a-new-awaitable-make-it-follow-the-rules">Where you create a new awaitable, make it
follow the
rules</a>.</p>
<p>So, option one: reset the logcontext before starting the operations to
be gathered:</p>
<pre><code class="language-python">async def do_request_handling():
    with PreserveLoggingContext():
        a1 = operation1()
        a2 = operation2()
        result = await defer.gatherResults([a1, a2])
</code></pre>
<p>In this case particularly, though, option two, of using
<code>context.run_in_background</code> almost certainly makes more sense, so that
<code>operation1</code> and <code>operation2</code> are both logged against the original
logcontext. This looks like:</p>
<pre><code class="language-python">async def do_request_handling():
    a1 = context.run_in_background(operation1)
    a2 = context.run_in_background(operation2)

    result = await make_deferred_yieldable(defer.gatherResults([a1, a2]))
</code></pre>
<h2 id="a-note-on-garbage-collection-of-awaitable-chains"><a class="header" href="#a-note-on-garbage-collection-of-awaitable-chains">A note on garbage-collection of awaitable chains</a></h2>
<p>It turns out that our logcontext rules do not play nicely with awaitable
chains which get orphaned and garbage-collected.</p>
<p>Imagine we have some code that looks like this:</p>
<pre><code class="language-python">listener_queue = []

def on_something_interesting():
    for d in listener_queue:
        d.callback(&quot;foo&quot;)

async def await_something_interesting():
    new_awaitable = defer.Deferred()
    listener_queue.append(new_awaitable)

    with PreserveLoggingContext():
        await new_awaitable
</code></pre>
<p>Obviously, the idea here is that we have a bunch of things which are
waiting for an event. (It's just an example of the problem here, but a
relatively common one.)</p>
<p>Now let's imagine two further things happen. First of all, whatever was
waiting for the interesting thing goes away. (Perhaps the request times
out, or something <em>even more</em> interesting happens.)</p>
<p>Secondly, let's suppose that we decide that the interesting thing is
never going to happen, and we reset the listener queue:</p>
<pre><code class="language-python">def reset_listener_queue():
    listener_queue.clear()
</code></pre>
<p>So, both ends of the awaitable chain have now dropped their references,
and the awaitable chain is now orphaned, and will be garbage-collected at
some point. Note that <code>await_something_interesting</code> is a coroutine, 
which Python implements as a generator function.  When Python
garbage-collects generator functions, it gives them a chance to 
clean up by making the <code>await</code> (or <code>yield</code>) raise a <code>GeneratorExit</code>
exception. In our case, that means that the <code>__exit__</code> handler of
<code>PreserveLoggingContext</code> will carefully restore the request context, but
there is now nothing waiting for its return, so the request context is
never cleared.</p>
<p>To reiterate, this problem only arises when <em>both</em> ends of a awaitable
chain are dropped. Dropping the the reference to an awaitable you're
supposed to be awaiting is bad practice, so this doesn't
actually happen too much. Unfortunately, when it does happen, it will
lead to leaked logcontexts which are incredibly hard to track down.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="replication-architecture"><a class="header" href="#replication-architecture">Replication Architecture</a></h1>
<h2 id="motivation"><a class="header" href="#motivation">Motivation</a></h2>
<p>We'd like to be able to split some of the work that synapse does into
multiple python processes. In theory multiple synapse processes could
share a single postgresql database and we'd scale up by running more
synapse processes. However much of synapse assumes that only one process
is interacting with the database, both for assigning unique identifiers
when inserting into tables, notifying components about new updates, and
for invalidating its caches.</p>
<p>So running multiple copies of the current code isn't an option. One way
to run multiple processes would be to have a single writer process and
multiple reader processes connected to the same database. In order to do
this we'd need a way for the reader process to invalidate its in-memory
caches when an update happens on the writer. One way to do this is for
the writer to present an append-only log of updates which the readers
can consume to invalidate their caches and to push updates to listening
clients or pushers.</p>
<p>Synapse already stores much of its data as an append-only log so that it
can correctly respond to <code>/sync</code> requests so the amount of code changes
needed to expose the append-only log to the readers should be fairly
minimal.</p>
<h2 id="architecture"><a class="header" href="#architecture">Architecture</a></h2>
<h3 id="the-replication-protocol"><a class="header" href="#the-replication-protocol">The Replication Protocol</a></h3>
<p>See <a href="tcp_replication.html">the TCP replication documentation</a>.</p>
<h3 id="the-tcp-replication-module"><a class="header" href="#the-tcp-replication-module">The TCP Replication Module</a></h3>
<p>Information about how the tcp replication module is structured, including how
the classes interact, can be found in
<code>synapse/replication/tcp/__init__.py</code></p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="streams"><a class="header" href="#streams">Streams</a></h2>
<p>Synapse has a concept of &quot;streams&quot;, which are roughly described in <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/storage/util/id_generators.py"><code>id_generators.py</code></a>.
Generally speaking, streams are a series of notifications that something in Synapse's database has changed that the application might need to respond to.
For example:</p>
<ul>
<li>The events stream reports new events (PDUs) that Synapse creates, or that Synapse accepts from another homeserver.</li>
<li>The account data stream reports changes to users' <a href="https://spec.matrix.org/v1.7/client-server-api/#client-config">account data</a>.</li>
<li>The to-device stream reports when a device has a new <a href="https://spec.matrix.org/v1.7/client-server-api/#send-to-device-messaging">to-device message</a>.</li>
</ul>
<p>See <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/replication/tcp/streams/__init__.py"><code>synapse.replication.tcp.streams</code></a> for the full list of streams.</p>
<p>It is very helpful to understand the streams mechanism when working on any part of Synapse that needs to respond to changes—especially if those changes are made by different workers.
To that end, let's describe streams formally, paraphrasing from the docstring of <a href="https://github.com/matrix-org/synapse/blob/a719b703d9bd0dade2565ddcad0e2f3a7a9d4c37/synapse/storage/util/id_generators.py#L96"><code>AbstractStreamIdGenerator</code></a>.</p>
<h3 id="definition"><a class="header" href="#definition">Definition</a></h3>
<p>A stream is an append-only log <code>T1, T2, ..., Tn, ...</code> of facts<sup class="footnote-reference"><a href="#1">1</a></sup> which grows over time.
Only &quot;writers&quot; can add facts to a stream, and there may be multiple writers.</p>
<p>Each fact has an ID, called its &quot;stream ID&quot;.
Readers should only process facts in ascending stream ID order.</p>
<p>Roughly speaking, each stream is backed by a database table.
It should have a <code>stream_id</code> (or similar) bigint column holding stream IDs, plus additional columns as necessary to describe the fact.
Typically, a fact is expressed with a single row in its backing table.<sup class="footnote-reference"><a href="#2">2</a></sup>
Within a stream, no two facts may have the same stream_id.</p>
<blockquote>
<p><em>Aside</em>. Some additional notes on streams' backing tables.</p>
<ol>
<li>Rich would like to <a href="https://github.com/matrix-org/synapse/issues/13456">ditch the backing tables</a>.</li>
<li>The backing tables may have other uses.
&gt;    For example, the events table serves backs the events stream, and is read when processing new events.
&gt;    But old rows are read from the table all the time, whenever Synapse needs to lookup some facts about an event.</li>
<li>Rich suspects that sometimes the stream is backed by multiple tables, so the stream proper is the union of those tables.</li>
</ol>
</blockquote>
<p>Stream writers can &quot;reserve&quot; a stream ID, and then later mark it as having being completed.
Stream writers need to track the completion of each stream fact.
In the happy case, completion means a fact has been written to the stream table.
But unhappy cases (e.g. transaction rollback due to an error) also count as completion.
Once completed, the rows written with that stream ID are fixed, and no new rows
will be inserted with that ID.</p>
<h3 id="current-stream-id"><a class="header" href="#current-stream-id">Current stream ID</a></h3>
<p>For any given stream reader (including writers themselves), we may define a per-writer current stream ID:</p>
<blockquote>
<p>The current stream ID <em>for a writer W</em> is the largest stream ID such that
all transactions added by W with equal or smaller ID have completed.</p>
</blockquote>
<p>Similarly, there is a &quot;linear&quot; notion of current stream ID:</p>
<blockquote>
<p>The &quot;linear&quot; current stream ID is the largest stream ID such that
all facts (added by any writer) with equal or smaller ID have completed.</p>
</blockquote>
<p>Because different stream readers A and B learn about new facts at different times, A and B may disagree about current stream IDs.
Put differently: we should think of stream readers as being independent of each other, proceeding through a stream of facts at different rates.</p>
<p><strong>NB.</strong> For both senses of &quot;current&quot;, that if a writer opens a transaction that never completes, the current stream ID will never advance beyond that writer's last written stream ID.</p>
<p>For single-writer streams, the per-writer current ID and the linear current ID are the same.
Both senses of current ID are monotonic, but they may &quot;skip&quot; or jump over IDs because facts complete out of order.</p>
<p><em>Example</em>.
Consider a single-writer stream which is initially at ID 1.</p>
<table><thead><tr><th>Action</th><th>Current stream ID</th><th>Notes</th></tr></thead><tbody>
<tr><td></td><td>1</td><td></td></tr>
<tr><td>Reserve 2</td><td>1</td><td></td></tr>
<tr><td>Reserve 3</td><td>1</td><td></td></tr>
<tr><td>Complete 3</td><td>1</td><td>current ID unchanged, waiting for 2 to complete</td></tr>
<tr><td>Complete 2</td><td>3</td><td>current ID jumps from 1 -&gt; 3</td></tr>
<tr><td>Reserve 4</td><td>3</td><td></td></tr>
<tr><td>Reserve 5</td><td>3</td><td></td></tr>
<tr><td>Reserve 6</td><td>3</td><td></td></tr>
<tr><td>Complete 5</td><td>3</td><td></td></tr>
<tr><td>Complete 4</td><td>5</td><td>current ID jumps 3-&gt;5, even though 6 is pending</td></tr>
<tr><td>Complete 6</td><td>6</td><td></td></tr>
</tbody></table>
<h3 id="multi-writer-streams"><a class="header" href="#multi-writer-streams">Multi-writer streams</a></h3>
<p>There are two ways to view a multi-writer stream.</p>
<ol>
<li>Treat it as a collection of distinct single-writer streams, one
for each writer.</li>
<li>Treat it as a single stream.</li>
</ol>
<p>The single stream (option 2) is conceptually simpler, and easier to represent (a single stream id).
However, it requires each reader to know about the entire set of writers, to ensures that readers don't erroneously advance their current stream position too early and miss a fact from an unknown writer.
In contrast, multiple parallel streams (option 1) are more complex, requiring more state to represent (map from writer to stream id).
The payoff for doing so is that readers can &quot;peek&quot; ahead to facts that completed on one writer no matter the state of the others, reducing latency.</p>
<p>Note that a multi-writer stream can be viewed in both ways.
For example, the events stream is treated as multiple single-writer streams (option 1) by the sync handler, so that events are sent to clients as soon as possible.
But the background process that works through events treats them as a single linear stream.</p>
<p>Another useful example is the cache invalidation stream.
The facts this stream holds are instructions to &quot;you should now invalidate these cache entries&quot;.
We only ever treat this as a multiple single-writer streams as there is no important ordering between cache invalidations.
(Invalidations are self-contained facts; and the invalidations commute/are idempotent).</p>
<h3 id="writing-to-streams"><a class="header" href="#writing-to-streams">Writing to streams</a></h3>
<p>Writers need to track:</p>
<ul>
<li>track their current position (i.e. its own per-writer stream ID).</li>
<li>their facts currently awaiting completion.</li>
</ul>
<p>At startup, </p>
<ul>
<li>the current position of that writer can be found by querying the database (which suggests that facts need to be written to the database atomically, in a transaction); and</li>
<li>there are no facts awaiting completion.</li>
</ul>
<p>To reserve a stream ID, call <a href="https://www.postgresql.org/docs/current/functions-sequence.html"><code>nextval</code></a> on the appropriate postgres sequence.</p>
<p>To write a fact to the stream: insert the appropriate rows to the appropriate backing table.</p>
<p>To complete a fact, first remove it from your map of facts currently awaiting completion.
Then, if no earlier fact is awaiting completion, the writer can advance its current position in that stream.
Upon doing so it should emit an <code>RDATA</code> message<sup class="footnote-reference"><a href="#3">3</a></sup>, once for every fact between the old and the new stream ID.</p>
<h3 id="subscribing-to-streams"><a class="header" href="#subscribing-to-streams">Subscribing to streams</a></h3>
<p>Readers need to track the current position of every writer.</p>
<p>At startup, they can find this by contacting each writer with a <code>REPLICATE</code> message,
requesting that all writers reply describing their current position in their streams.
Writers reply with a <code>POSITION</code> message.</p>
<p>To learn about new facts, readers should listen for <code>RDATA</code> messages and process them to respond to the new fact.
The <code>RDATA</code> itself is not a self-contained representation of the fact;
readers will have to query the stream tables for the full details.
Readers must also advance their record of the writer's current position for that stream.</p>
<h1 id="summary"><a class="header" href="#summary">Summary</a></h1>
<p>In a nutshell: we have an append-only log with a &quot;buffer/scratchpad&quot; at the end where we have to wait for the sequence to be linear and contiguous.</p>
<hr />
<div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
<p>we use the word <em>fact</em> here for two reasons.
Firstly, the word &quot;event&quot; is already heavily overloaded (PDUs, EDUs, account data, ...) and we don't need to make that worse.
Secondly, &quot;fact&quot; emphasises that the things we append to a stream cannot change after the fact.</p>
</div>
<div class="footnote-definition" id="2"><sup class="footnote-definition-label">2</sup>
<p>A fact might be expressed with 0 rows, e.g. if we opened a transaction to persist an event, but failed and rolled the transaction back before marking the fact as completed.
In principle a fact might be expressed with 2 or more rows; if so, each of those rows should share the fact's stream ID.</p>
</div>
<div class="footnote-definition" id="3"><sup class="footnote-definition-label">3</sup>
<p>This communication used to happen directly with the writers <a href="development/synapse_architecture/../../tcp_replication.html">over TCP</a>;
nowadays it's done via Redis's Pubsub.</p>
</div>
<div style="break-before: page; page-break-before: always;"></div><h1 id="tcp-replication"><a class="header" href="#tcp-replication">TCP Replication</a></h1>
<h2 id="motivation-1"><a class="header" href="#motivation-1">Motivation</a></h2>
<p>Previously the workers used an HTTP long poll mechanism to get updates
from the master, which had the problem of causing a lot of duplicate
work on the server. This TCP protocol replaces those APIs with the aim
of increased efficiency.</p>
<h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
<p>The protocol is based on fire and forget, line based commands. An
example flow would be (where '&gt;' indicates master to worker and
'&lt;' worker to master flows):</p>
<pre><code>&gt; SERVER example.com
&lt; REPLICATE
&gt; POSITION events master 53 53
&gt; RDATA events master 54 [&quot;$foo1:bar.com&quot;, ...]
&gt; RDATA events master 55 [&quot;$foo4:bar.com&quot;, ...]
</code></pre>
<p>The example shows the server accepting a new connection and sending its identity
with the <code>SERVER</code> command, followed by the client server to respond with the
position of all streams. The server then periodically sends <code>RDATA</code> commands
which have the format <code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row&gt;</code>, where
the format of <code>&lt;row&gt;</code> is defined by the individual streams. The
<code>&lt;instance_name&gt;</code> is the name of the Synapse process that generated the data
(usually &quot;master&quot;). We expect an RDATA for every row in the DB.</p>
<p>Error reporting happens by either the client or server sending an ERROR
command, and usually the connection will be closed.</p>
<p>Since the protocol is a simple line based, its possible to manually
connect to the server using a tool like netcat. A few things should be
noted when manually using the protocol:</p>
<ul>
<li>The federation stream is only available if federation sending has
been disabled on the main process.</li>
<li>The server will only time connections out that have sent a <code>PING</code>
command. If a ping is sent then the connection will be closed if no
further commands are receieved within 15s. Both the client and
server protocol implementations will send an initial PING on
connection and ensure at least one command every 5s is sent (not
necessarily <code>PING</code>).</li>
<li><code>RDATA</code> commands <em>usually</em> include a numeric token, however if the
stream has multiple rows to replicate per token the server will send
multiple <code>RDATA</code> commands, with all but the last having a token of
<code>batch</code>. See the documentation on <code>commands.RdataCommand</code> for
further details.</li>
</ul>
<h2 id="architecture-1"><a class="header" href="#architecture-1">Architecture</a></h2>
<p>The basic structure of the protocol is line based, where the initial
word of each line specifies the command. The rest of the line is parsed
based on the command. For example, the RDATA command is defined as:</p>
<pre><code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row_json&gt;
</code></pre>
<p>(Note that &lt;row_json&gt; may contains spaces, but cannot contain
newlines.)</p>
<p>Blank lines are ignored.</p>
<h3 id="keep-alives"><a class="header" href="#keep-alives">Keep alives</a></h3>
<p>Both sides are expected to send at least one command every 5s or so, and
should send a <code>PING</code> command if necessary. If either side do not receive
a command within e.g. 15s then the connection should be closed.</p>
<p>Because the server may be connected to manually using e.g. netcat, the
timeouts aren't enabled until an initial <code>PING</code> command is seen. Both
the client and server implementations below send a <code>PING</code> command
immediately on connection to ensure the timeouts are enabled.</p>
<p>This ensures that both sides can quickly realize if the tcp connection
has gone and handle the situation appropriately.</p>
<h3 id="start-up"><a class="header" href="#start-up">Start up</a></h3>
<p>When a new connection is made, the server:</p>
<ul>
<li>Sends a <code>SERVER</code> command, which includes the identity of the server,
allowing the client to detect if its connected to the expected
server</li>
<li>Sends a <code>PING</code> command as above, to enable the client to time out
connections promptly.</li>
</ul>
<p>The client:</p>
<ul>
<li>Sends a <code>NAME</code> command, allowing the server to associate a human
friendly name with the connection. This is optional.</li>
<li>Sends a <code>PING</code> as above</li>
<li>Sends a <code>REPLICATE</code> to get the current position of all streams.</li>
<li>On receipt of a <code>SERVER</code> command, checks that the server name
matches the expected server name.</li>
</ul>
<h3 id="error-handling"><a class="header" href="#error-handling">Error handling</a></h3>
<p>If either side detects an error it can send an <code>ERROR</code> command and close
the connection.</p>
<p>If the client side loses the connection to the server it should
reconnect, following the steps above.</p>
<h3 id="congestion"><a class="header" href="#congestion">Congestion</a></h3>
<p>If the server sends messages faster than the client can consume them the
server will first buffer a (fairly large) number of commands and then
disconnect the client. This ensures that we don't queue up an unbounded
number of commands in memory and gives us a potential opportunity to
squawk loudly. When/if the client recovers it can reconnect to the
server and ask for missed messages.</p>
<h3 id="reliability"><a class="header" href="#reliability">Reliability</a></h3>
<p>In general the replication stream should be considered an unreliable
transport since e.g. commands are not resent if the connection
disappears.</p>
<p>The exception to that are the replication streams, i.e. RDATA commands,
since these include tokens which can be used to restart the stream on
connection errors.</p>
<p>The client should keep track of the token in the last RDATA command
received for each stream so that on reconnection it can start streaming
from the correct place. Note: not all RDATA have valid tokens due to
batching. See <code>RdataCommand</code> for more details.</p>
<h3 id="example-5"><a class="header" href="#example-5">Example</a></h3>
<p>An example iteraction is shown below. Each line is prefixed with '&gt;'
or '&lt;' to indicate which side is sending, these are <em>not</em> included on
the wire:</p>
<pre><code>* connection established *
&gt; SERVER localhost:8823
&gt; PING 1490197665618
&lt; NAME synapse.app.appservice
&lt; PING 1490197665618
&lt; REPLICATE
&gt; POSITION events master 1 1
&gt; POSITION backfill master 1 1
&gt; POSITION caches master 1 1
&gt; RDATA caches master 2 [&quot;get_user_by_id&quot;,[&quot;@01register-user:localhost:8823&quot;],1490197670513]
&gt; RDATA events master 14 [&quot;$149019767112vOHxz:localhost:8823&quot;,
    &quot;!AFDCvgApUmpdfVjIXm:localhost:8823&quot;,&quot;m.room.guest_access&quot;,&quot;&quot;,null]
&lt; PING 1490197675618
&gt; ERROR server stopping
* connection closed by server *
</code></pre>
<p>The <code>POSITION</code> command sent by the server is used to set the clients
position without needing to send data with the <code>RDATA</code> command.</p>
<p>An example of a batched set of <code>RDATA</code> is:</p>
<pre><code>&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test:localhost:8823&quot;],1490197670513]
&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test2:localhost:8823&quot;],1490197670513]
&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test3:localhost:8823&quot;],1490197670513]
&gt; RDATA caches master 54 [&quot;get_user_by_id&quot;,[&quot;@test4:localhost:8823&quot;],1490197670513]
</code></pre>
<p>In this case the client shouldn't advance their caches token until it
sees the the last <code>RDATA</code>.</p>
<h3 id="list-of-commands"><a class="header" href="#list-of-commands">List of commands</a></h3>
<p>The list of valid commands, with which side can send it: server (S) or
client (C):</p>
<h4 id="server-s"><a class="header" href="#server-s">SERVER (S)</a></h4>
<p>Sent at the start to identify which server the client is talking to</p>
<h4 id="rdata-s"><a class="header" href="#rdata-s">RDATA (S)</a></h4>
<p>A single update in a stream</p>
<h4 id="position-s"><a class="header" href="#position-s">POSITION (S)</a></h4>
<p>On receipt of a POSITION command clients should check if they have missed any
updates, and if so then fetch them out of band. Sent in response to a
REPLICATE command (but can happen at any time).</p>
<p>The POSITION command includes the source of the stream. Currently all streams
are written by a single process (usually &quot;master&quot;). If fetching missing
updates via HTTP API, rather than via the DB, then processes should make the
request to the appropriate process.</p>
<p>Two positions are included, the &quot;new&quot; position and the last position sent respectively.
This allows servers to tell instances that the positions have advanced but no
data has been written, without clients needlessly checking to see if they
have missed any updates. Instances will only fetch stuff if there is a gap between
their current position and the given last position.</p>
<h4 id="error-s-c"><a class="header" href="#error-s-c">ERROR (S, C)</a></h4>
<p>There was an error</p>
<h4 id="ping-s-c"><a class="header" href="#ping-s-c">PING (S, C)</a></h4>
<p>Sent periodically to ensure the connection is still alive</p>
<h4 id="name-c"><a class="header" href="#name-c">NAME (C)</a></h4>
<p>Sent at the start by client to inform the server who they are</p>
<h4 id="replicate-c"><a class="header" href="#replicate-c">REPLICATE (C)</a></h4>
<p>Asks the server for the current position of all streams.</p>
<h4 id="user_sync-c"><a class="header" href="#user_sync-c">USER_SYNC (C)</a></h4>
<p>A user has started or stopped syncing on this process.</p>
<h4 id="clear_user_sync-c"><a class="header" href="#clear_user_sync-c">CLEAR_USER_SYNC (C)</a></h4>
<p>The server should clear all associated user sync data from the worker.</p>
<p>This is used when a worker is shutting down.</p>
<h4 id="federation_ack-c"><a class="header" href="#federation_ack-c">FEDERATION_ACK (C)</a></h4>
<p>Acknowledge receipt of some federation data</p>
<h3 id="remote_server_up-s-c"><a class="header" href="#remote_server_up-s-c">REMOTE_SERVER_UP (S, C)</a></h3>
<p>Inform other processes that a remote server may have come back online.</p>
<p>See <code>synapse/replication/tcp/commands.py</code> for a detailed description and
the format of each command.</p>
<h3 id="cache-invalidation-stream"><a class="header" href="#cache-invalidation-stream">Cache Invalidation Stream</a></h3>
<p>The cache invalidation stream is used to inform workers when they need
to invalidate any of their caches in the data store. This is done by
streaming all cache invalidations done on master down to the workers,
assuming that any caches on the workers also exist on the master.</p>
<p>Each individual cache invalidation results in a row being sent down
replication, which includes the cache name (the name of the function)
and they key to invalidate. For example:</p>
<pre><code>&gt; RDATA caches master 550953771 [&quot;get_user_by_id&quot;, [&quot;@bob:example.com&quot;], 1550574873251]
</code></pre>
<p>Alternatively, an entire cache can be invalidated by sending down a <code>null</code>
instead of the key. For example:</p>
<pre><code>&gt; RDATA caches master 550953772 [&quot;get_user_by_id&quot;, null, 1550574873252]
</code></pre>
<p>However, there are times when a number of caches need to be invalidated
at the same time with the same key. To reduce traffic we batch those
invalidations into a single poke by defining a special cache name that
workers understand to mean to expand to invalidate the correct caches.</p>
<p>Currently the special cache names are declared in
<code>synapse/storage/_base.py</code> and are:</p>
<ol>
<li><code>cs_cache_fake</code> ─ invalidates caches that depend on the current
state</li>
</ol>
<div style="break-before: page; page-break-before: always;"></div><h1 id="how-do-faster-joins-work"><a class="header" href="#how-do-faster-joins-work">How do faster joins work?</a></h1>
<p>This is a work-in-progress set of notes with two goals:</p>
<ul>
<li>act as a reference, explaining how Synapse implements faster joins; and</li>
<li>record the rationale behind our choices.</li>
</ul>
<p>See also <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3902">MSC3902</a>.</p>
<p>The key idea is described by <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3706">MSC3706</a>. This allows servers to
request a lightweight response to the federation <code>/send_join</code> endpoint.
This is called a <strong>faster join</strong>, also known as a <strong>partial join</strong>. In these
notes we'll usually use the word &quot;partial&quot; as it matches the database schema.</p>
<h2 id="overview-processing-events-in-a-partially-joined-room"><a class="header" href="#overview-processing-events-in-a-partially-joined-room">Overview: processing events in a partially-joined room</a></h2>
<p>The response to a partial join consists of</p>
<ul>
<li>the requested join event <code>J</code>,</li>
<li>a list of the servers in the room (according to the state before <code>J</code>),</li>
<li>a subset of the state of the room before <code>J</code>,</li>
<li>the full auth chain of that state subset.</li>
</ul>
<p>Synapse marks the room as partially joined by adding a row to the database table
<code>partial_state_rooms</code>. It also marks the join event <code>J</code> as &quot;partially stated&quot;,
meaning that we have neither received nor computed the full state before/after
<code>J</code>. This is done by adding a row to <code>partial_state_events</code>.</p>
<details><summary>DB schema</summary>
<pre><code>matrix=&gt; \d partial_state_events
Table &quot;matrix.partial_state_events&quot;
  Column  │ Type │ Collation │ Nullable │ Default
══════════╪══════╪═══════════╪══════════╪═════════
 room_id  │ text │           │ not null │
 event_id │ text │           │ not null │
 
matrix=&gt; \d partial_state_rooms
                Table &quot;matrix.partial_state_rooms&quot;
         Column         │  Type  │ Collation │ Nullable │ Default 
════════════════════════╪════════╪═══════════╪══════════╪═════════
 room_id                │ text   │           │ not null │ 
 device_lists_stream_id │ bigint │           │ not null │ 0
 join_event_id          │ text   │           │          │ 
 joined_via             │ text   │           │          │ 

matrix=&gt; \d partial_state_rooms_servers
     Table &quot;matrix.partial_state_rooms_servers&quot;
   Column    │ Type │ Collation │ Nullable │ Default 
═════════════╪══════╪═══════════╪══════════╪═════════
 room_id     │ text │           │ not null │ 
 server_name │ text │           │ not null │ 
</code></pre>
<p>Indices, foreign-keys and check constraints are omitted for brevity.</p>
</details>
<p>While partially joined to a room, Synapse receives events <code>E</code> from remote
homeservers as normal, and can create events at the request of its local users.
However, we run into trouble when we enforce the <a href="https://spec.matrix.org/v1.5/server-server-api/#checks-performed-on-receipt-of-a-pdu">checks on an event</a>.</p>
<blockquote>
<ol>
<li>Is a valid event, otherwise it is dropped. For an event to be valid, it
must contain a room_id, and it must comply with the event format of that
room version.</li>
<li>Passes signature checks, otherwise it is dropped.</li>
<li>Passes hash checks, otherwise it is redacted before being processed further.</li>
<li>Passes authorization rules based on the event’s auth events, otherwise it
is rejected.</li>
<li><strong>Passes authorization rules based on the state before the event, otherwise
it is rejected.</strong></li>
<li><strong>Passes authorization rules based on the current state of the room,
otherwise it is “soft failed”.</strong></li>
</ol>
</blockquote>
<p>We can enforce checks 1--4 without any problems.
But we cannot enforce checks 5 or 6 with complete certainty, since Synapse does
not know the full state before <code>E</code>, nor that of the room.</p>
<h3 id="partial-state"><a class="header" href="#partial-state">Partial state</a></h3>
<p>Instead, we make a best-effort approximation.
While the room is considered partially joined, Synapse tracks the &quot;partial
state&quot; before events.
This works in a similar way as regular state:</p>
<ul>
<li>The partial state before <code>J</code> is that given to us by the partial join response.</li>
<li>The partial state before an event <code>E</code> is the resolution of the partial states
after each of <code>E</code>'s <code>prev_event</code>s.</li>
<li>If <code>E</code> is rejected or a message event, the partial state after <code>E</code> is the
partial state before <code>E</code>.</li>
<li>Otherwise, the partial state after <code>E</code> is the partial state before <code>E</code>, plus
<code>E</code> itself.</li>
</ul>
<p>More concisely, partial state propagates just like full state; the only
difference is that we &quot;seed&quot; it with an incomplete initial state.
Synapse records that we have only calculated partial state for this event with
a row in <code>partial_state_events</code>.</p>
<p>While the room remains partially stated, check 5 on incoming events to that
room becomes:</p>
<blockquote>
<ol start="5">
<li>Passes authorization rules based on <strong>the resolution between the partial
state before <code>E</code> and <code>E</code>'s auth events.</strong> If the event fails to pass
authorization rules, it is rejected.</li>
</ol>
</blockquote>
<p>Additionally, check 6 is deleted: no soft-failures are enforced.</p>
<p>While partially joined, the current partial state of the room is defined as the
resolution across the partial states after all forward extremities in the room.</p>
<p><em>Remark.</em> Events with partial state are <em>not</em> considered
<a href="development/synapse_architecture/../room-dag-concepts.html#outliers">outliers</a>.</p>
<h3 id="approximation-error"><a class="header" href="#approximation-error">Approximation error</a></h3>
<p>Using partial state means the auth checks can fail in a few different ways<sup class="footnote-reference"><a href="#2">1</a></sup>.</p>
<div class="footnote-definition" id="2"><sup class="footnote-definition-label">1</sup>
<p>Is this exhaustive?</p>
</div>
<ul>
<li>We may erroneously accept an incoming event in check 5 based on partial state
when it would have been rejected based on full state, or vice versa.</li>
<li>This means that an event could erroneously be added to the current partial
state of the room when it would not be present in the full state of the room,
or vice versa.</li>
<li>Additionally, we may have skipped soft-failing an event that would have been
soft-failed based on full state.</li>
</ul>
<p>(Note that the discrepancies described in the last two bullets are user-visible.)</p>
<p>This means that we have to be very careful when we want to lookup pieces of room
state in a partially-joined room. Our approximation of the state may be
incorrect or missing. But we can make some educated guesses. If</p>
<ul>
<li>our partial state is likely to be correct, or</li>
<li>the consequences of our partial state being incorrect are minor,</li>
</ul>
<p>then we proceed as normal, and let the resync process fix up any mistakes (see
below).</p>
<p>When is our partial state likely to be correct?</p>
<ul>
<li>It's more accurate the closer we are to the partial join event. (So we should
ideally complete the resync as soon as possible.)</li>
<li>Non-member events: we will have received them as part of the partial join
response, if they were part of the room state at that point. We may
incorrectly accept or reject updates to that state (at first because we lack
remote membership information; later because of compounding errors), so these
can become incorrect over time.</li>
<li>Local members' memberships: we are the only ones who can create join and
knock events for our users. We can't be completely confident in the
correctness of bans, invites and kicks from other homeservers, but the resync
process should correct any mistakes.</li>
<li>Remote members' memberships: we did not receive these in the /send_join
response, so we have essentially no idea if these are correct or not.</li>
</ul>
<p>In short, we deem it acceptable to trust the partial state for non-membership
and local membership events. For remote membership events, we wait for the
resync to complete, at which point we have the full state of the room and can
proceed as normal.</p>
<h3 id="fixing-the-approximation-with-a-resync"><a class="header" href="#fixing-the-approximation-with-a-resync">Fixing the approximation with a resync</a></h3>
<p>The partial-state approximation is only a temporary affair. In the background,
synapse beings a &quot;resync&quot; process. This is a continuous loop, starting at the
partial join event and proceeding downwards through the event graph. For each 
<code>E</code> seen in the room since partial join, Synapse will fetch </p>
<ul>
<li>the event ids in the state of the room before <code>E</code>, via 
<a href="https://spec.matrix.org/v1.5/server-server-api/#get_matrixfederationv1state_idsroomid"><code>/state_ids</code></a>;</li>
<li>the event ids in the full auth chain of <code>E</code>, included in the <code>/state_ids</code> 
response; and</li>
<li>any events from the previous two bullets that Synapse hasn't persisted, via
<a href="https://spec.matrix.org/v1.5/server-server-api/#get_matrixfederationv1stateroomid">`/state</a>.</li>
</ul>
<p>This means Synapse has (or can compute) the full state before <code>E</code>, which allows
Synapse to properly authorise or reject <code>E</code>. At this point ,the event
is considered to have &quot;full state&quot; rather than &quot;partial state&quot;. We record this
by removing <code>E</code> from the <code>partial_state_events</code> table.</p>
<p>[<strong>TODO:</strong> Does Synapse persist a new state group for the full state
before <code>E</code>, or do we alter the (partial-)state group in-place? Are state groups
ever marked as partially-stated? ]</p>
<p>This scheme means it is possible for us to have accepted and sent an event to 
clients, only to reject it during the resync. From a client's perspective, the 
effect is similar to a retroactive 
state change due to state resolution---i.e. a &quot;state reset&quot;.<sup class="footnote-reference"><a href="#3">2</a></sup></p>
<div class="footnote-definition" id="3"><sup class="footnote-definition-label">2</sup>
<p>Clients should refresh caches to detect such a change. Rumour has it that 
sliding sync will fix this.</p>
</div>
<p>When all events since the join <code>J</code> have been fully-stated, the room resync
process is complete. We record this by removing the room from
<code>partial_state_rooms</code>.</p>
<h2 id="faster-joins-on-workers"><a class="header" href="#faster-joins-on-workers">Faster joins on workers</a></h2>
<p>For the time being, the resync process happens on the master worker.
A new replication stream <code>un_partial_stated_room</code> is added. Whenever a resync
completes and a partial-state room becomes fully stated, a new message is sent
into that stream containing the room ID.</p>
<h2 id="notes-on-specific-cases"><a class="header" href="#notes-on-specific-cases">Notes on specific cases</a></h2>
<blockquote>
<p><strong>NB.</strong> The notes below are rough. Some of them are hidden under <code>&lt;details&gt;</code>
disclosures because they have yet to be implemented in mainline Synapse.</p>
</blockquote>
<h3 id="creating-events-during-a-partial-join"><a class="header" href="#creating-events-during-a-partial-join">Creating events during a partial join</a></h3>
<p>When sending out messages during a partial join, we assume our partial state is 
accurate and proceed as normal. For this to have any hope of succeeding at all,
our partial state must contain an entry for each of the (type, state key) pairs
<a href="https://spec.matrix.org/v1.3/rooms/v10/#authorization-rules">specified by the auth rules</a>:</p>
<ul>
<li><code>m.room.create</code></li>
<li><code>m.room.join_rules</code></li>
<li><code>m.room.power_levels</code></li>
<li><code>m.room.third_party_invite</code></li>
<li><code>m.room.member</code></li>
</ul>
<p>The first four of these should be present in the state before <code>J</code> that is given
to us in the partial join response; only membership events are omitted. In order
for us to consider the user joined, we must have their membership event. That
means the only possible omission is the target's membership in an invite, kick
or ban.</p>
<p>The worst possibility is that we locally invite someone who is banned according to
the full state, because we lack their ban in our current partial state. The rest 
of the federation---at least, those who are fully joined---should correctly 
enforce the <a href="https://spec.matrix.org/v1.3/client-server-api/#room-membership">membership transition constraints</a>. So any the erroneous invite should be ignored by fully-joined
homeservers and resolved by the resync for partially-joined homeservers.</p>
<p>In more generality, there are two problems we're worrying about here:</p>
<ul>
<li>We might create an event that is valid under our partial state, only to later
find out that is actually invalid according to the full state.</li>
<li>Or: we might refuse to create an event that is invalid under our partial
state, even though it would be perfectly valid under the full state.</li>
</ul>
<p>However we expect such problems to be unlikely in practise, because</p>
<ul>
<li>We trust that the room has sensible power levels, e.g. that bad actors with
high power levels are demoted before their ban.</li>
<li>We trust that the resident server provides us up-to-date power levels, join
rules, etc.</li>
<li>State changes in rooms are relatively infrequent, and the resync period is
relatively quick.</li>
</ul>
<h4 id="sending-out-the-event-over-federation"><a class="header" href="#sending-out-the-event-over-federation">Sending out the event over federation</a></h4>
<p><strong>TODO:</strong> needs prose fleshing out.</p>
<p>Normally: send out in a fed txn to all HSes in the room.
We only know that some HSes were in the room at some point. Wat do.
Send it out to the list of servers from the first join.
<strong>TODO</strong> what do we do here if we have full state?
If the prev event was created by us, we can risk sending it to the wrong HS. (Motivation: privacy concern of the content. Not such a big deal for a public room or an encrypted room. But non-encrypted invite-only...)
But don't want to send out sensitive data in other HS's events in this way.</p>
<p>Suppose we discover after resync that we shouldn't have sent out one our events (not a prev_event) to a target HS. Not much we can do.
What about if we didn't send them an event but shouldn't've?
E.g. what if someone joined from a new HS shortly after you did? We wouldn't talk to them.
Could imagine sending out the &quot;Missed&quot; events after the resync but... painful to work out what they shuld have seen if they joined/left.
Instead, just send them the latest event (if they're still in the room after resync) and let them backfill.(?)</p>
<ul>
<li>Don't do this currently.</li>
<li>If anyone who has received our messages sends a message to a HS we missed, they can backfill our messages</li>
<li>Gap: rooms which are infrequently used and take a long time to resync.</li>
</ul>
<h3 id="joining-after-a-partial-join"><a class="header" href="#joining-after-a-partial-join">Joining after a partial join</a></h3>
<p><strong>NB.</strong> Not yet implemented.</p>
<details>
<p><strong>TODO:</strong> needs prose fleshing out. Liase with Matthieu. Explain why /send_join
(Rich was surprised we didn't just create it locally. Answer: to try and avoid
a join which then gets rejected after resync.)</p>
<p>We don't know for sure that any join we create would be accepted.
E.g. the joined user might have been banned; the join rules might have changed in a way that we didn't realise... some way in which the partial state was mistaken.
Instead, do another partial make-join/send-join handshake to confirm that the join works.</p>
<ul>
<li>Probably going to get a bunch of duplicate state events and auth events.... but the point of partial joins is that these should be small. Many are already persisted = good.</li>
<li>What if the second send_join response includes a different list of reisdent HSes? Could ignore it.
<ul>
<li>Could even have a special flag that says &quot;just make me a join&quot;, i.e. don't bother giving me state or servers in room. Deffo want the auth chain tho.</li>
</ul>
</li>
<li>SQ: wrt device lists it's a lot safer to ignore it!!!!!</li>
<li>What if the state at the second join is inconsistent with what we have? Ignore it?</li>
</ul>
</details>
<h3 id="leaving-and-kicks-and-bans-after-a-partial-join"><a class="header" href="#leaving-and-kicks-and-bans-after-a-partial-join">Leaving (and kicks and bans) after a partial join</a></h3>
<p><strong>NB.</strong> Not yet implemented.</p>
<details>
<p>When you're fully joined to a room, to have <code>U</code> leave a room their homeserver
needs to</p>
<ul>
<li>create a new leave event for <code>U</code> which will be accepted by other homeservers,
and</li>
<li>send that event <code>U</code> out to the homeservers in the federation.</li>
</ul>
<p>When is a leave event accepted? See
<a href="https://spec.matrix.org/v1.5/rooms/v10/#authorization-rules">v10 auth rules</a>:</p>
<blockquote>
<ol start="4">
<li>If type is m.room.member: [...]
&gt;
&gt;    5. If membership is leave:
&gt;
&gt;       1. If the sender matches state_key, allow if and only if that user’s current membership state is invite, join, or knock.
2. [...]</li>
</ol>
</blockquote>
<p>I think this means that (well-formed!) self-leaves are governed entirely by
4.5.1. This means that if we correctly calculate state which says that <code>U</code> is
invited, joined or knocked and include it in the leave's auth events, our event
is accepted by checks 4 and 5 on incoming events.</p>
<blockquote>
<ol start="4">
<li>Passes authorization rules based on the event’s auth events, otherwise
&gt;    it is rejected.</li>
<li>Passes authorization rules based on the state before the event, otherwise
&gt;    it is rejected.</li>
</ol>
</blockquote>
<p>The only way to fail check 6 is if the receiving server's current state of the
room says that <code>U</code> is banned, has left, or has no membership event. But this is
fine: the receiving server already thinks that <code>U</code> isn't in the room.</p>
<blockquote>
<ol start="6">
<li>Passes authorization rules based on the current state of the room,
&gt;    otherwise it is “soft failed”.</li>
</ol>
</blockquote>
<p>For the second point (publishing the leave event), the best thing we can do is
to is publish to all HSes we know to be currently in the room. If they miss that
event, they might send us traffic in the room that we don't care about. This is
a problem with leaving after a &quot;full&quot; join; we don't seek to fix this with
partial joins.</p>
<p>(With that said: there's nothing machine-readable in the /send response. I don't
think we can deduce &quot;destination has left the room&quot; from a failure to /send an
event into that room?)</p>
<h4 id="can-we-still-do-this-during-a-partial-join"><a class="header" href="#can-we-still-do-this-during-a-partial-join">Can we still do this during a partial join?</a></h4>
<p>We can create leave events and can choose what gets included in our auth events,
so we can be sure that we pass check 4 on incoming events. For check 5, we might
have an incorrect view of the state before an event.
The only way we might erroneously think a leave is valid is if</p>
<ul>
<li>the partial state before the leave has <code>U</code> joined, invited or knocked, but</li>
<li>the full state before the leave has <code>U</code> banned, left or not present,</li>
</ul>
<p>in which case the leave doesn't make anything worse: other HSes already consider
us as not in the room, and will continue to do so after seeing the leave.</p>
<p>The remaining obstacle is then: can we safely broadcast the leave event? We may
miss servers or incorrectly think that a server is in the room. Or the
destination server may be offline and miss the transaction containing our leave
event.This should self-heal when they see an event whose <code>prev_events</code> descends
from our leave.</p>
<p>Another option we considered was to use federation <code>/send_leave</code> to ask a
fully-joined server to send out the event on our behalf. But that introduces
complexity without much benefit. Besides, as Rich put it,</p>
<blockquote>
<p>sending out leaves is pretty best-effort currently</p>
</blockquote>
<p>so this is probably good enough as-is.</p>
<h4 id="cleanup-after-the-last-leave"><a class="header" href="#cleanup-after-the-last-leave">Cleanup after the last leave</a></h4>
<p><strong>TODO</strong>: what cleanup is necessary? Is it all just nice-to-have to save unused
work?</p>
</details>
<div style="break-before: page; page-break-before: always;"></div><h1 id="internal-documentation"><a class="header" href="#internal-documentation">Internal Documentation</a></h1>
<p>This section covers implementation documentation for various parts of Synapse.</p>
<p>If a developer is planning to make a change to a feature of Synapse, it can be useful for
general documentation of how that feature is implemented to be available. This saves the
developer time in place of needing to understand how the feature works by reading the
code.</p>
<p>Documentation that would be more useful for the perspective of a system administrator,
rather than a developer who's intending to change to code, should instead be placed
under the Usage section of the documentation.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="how-to-test-saml-as-a-developer-without-a-server"><a class="header" href="#how-to-test-saml-as-a-developer-without-a-server">How to test SAML as a developer without a server</a></h1>
<p>https://fujifish.github.io/samling/samling.html (https://github.com/fujifish/samling) is a great resource for being able to tinker with the 
SAML options within Synapse without needing to deploy and configure a complicated software stack.</p>
<p>To make Synapse (and therefore Element) use it:</p>
<ol>
<li>Use the samling.html URL above or deploy your own and visit the IdP Metadata tab.</li>
<li>Copy the XML to your clipboard.</li>
<li>On your Synapse server, create a new file <code>samling.xml</code> next to your <code>homeserver.yaml</code> with
the XML from step 2 as the contents.</li>
<li>Edit your <code>homeserver.yaml</code> to include:
<pre><code class="language-yaml">saml2_config:
  sp_config:
    allow_unknown_attributes: true  # Works around a bug with AVA Hashes: https://github.com/IdentityPython/pysaml2/issues/388
    metadata:
      local: [&quot;samling.xml&quot;]
</code></pre>
</li>
<li>Ensure that your <code>homeserver.yaml</code> has a setting for <code>public_baseurl</code>:
<pre><code class="language-yaml">public_baseurl: http://localhost:8080/
</code></pre>
</li>
<li>Run <code>apt-get install xmlsec1</code> and <code>pip install --upgrade --force 'pysaml2&gt;=4.5.0'</code> to ensure
the dependencies are installed and ready to go.</li>
<li>Restart Synapse.</li>
</ol>
<p>Then in Element:</p>
<ol>
<li>Visit the login page and point Element towards your homeserver using the <code>public_baseurl</code> above.</li>
<li>Click the Single Sign-On button.</li>
<li>On the samling page, enter a Name Identifier and add a SAML Attribute for <code>uid=your_localpart</code>.
The response must also be signed.</li>
<li>Click &quot;Next&quot;.</li>
<li>Click &quot;Post Response&quot; (change nothing).</li>
<li>You should be logged in.</li>
</ol>
<p>If you try and repeat this process, you may be automatically logged in using the information you
gave previously. To fix this, open your developer console (<code>F12</code> or <code>Ctrl+Shift+I</code>) while on the
samling page and clear the site data. In Chrome, this will be a button on the Application tab.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="how-to-test-cas-as-a-developer-without-a-server"><a class="header" href="#how-to-test-cas-as-a-developer-without-a-server">How to test CAS as a developer without a server</a></h1>
<p>The <a href="https://github.com/jbittel/django-mama-cas">django-mama-cas</a> project is an
easy to run CAS implementation built on top of Django.</p>
<h2 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h2>
<ol>
<li>Create a new virtualenv: <code>python3 -m venv &lt;your virtualenv&gt;</code></li>
<li>Activate your virtualenv: <code>source /path/to/your/virtualenv/bin/activate</code></li>
<li>Install Django and django-mama-cas:
<pre><code class="language-sh">python -m pip install &quot;django&lt;3&quot; &quot;django-mama-cas==2.4.0&quot;
</code></pre>
</li>
<li>Create a Django project in the current directory:
<pre><code class="language-sh">django-admin startproject cas_test .
</code></pre>
</li>
<li>Follow the <a href="https://django-mama-cas.readthedocs.io/en/latest/installation.html#configuring">install directions</a> for django-mama-cas</li>
<li>Setup the SQLite database: <code>python manage.py migrate</code></li>
<li>Create a user:
<pre><code class="language-sh">python manage.py createsuperuser
</code></pre>
<ol>
<li>Use whatever you want as the username and password.</li>
<li>Leave the other fields blank.</li>
</ol>
</li>
<li>Use the built-in Django test server to serve the CAS endpoints on port 8000:
<pre><code class="language-sh">python manage.py runserver
</code></pre>
</li>
</ol>
<p>You should now have a Django project configured to serve CAS authentication with
a single user created.</p>
<h2 id="configure-synapse-and-element-to-use-cas"><a class="header" href="#configure-synapse-and-element-to-use-cas">Configure Synapse (and Element) to use CAS</a></h2>
<ol>
<li>Modify your <code>homeserver.yaml</code> to enable CAS and point it to your locally
running Django test server:
<pre><code class="language-yaml">cas_config:
  enabled: true
  server_url: &quot;http://localhost:8000&quot;
  service_url: &quot;http://localhost:8081&quot;
  #displayname_attribute: name
  #required_attributes:
  #    name: value
</code></pre>
</li>
<li>Restart Synapse.</li>
</ol>
<p>Note that the above configuration assumes the homeserver is running on port 8081
and that the CAS server is on port 8000, both on localhost.</p>
<h2 id="testing-the-configuration"><a class="header" href="#testing-the-configuration">Testing the configuration</a></h2>
<p>Then in Element:</p>
<ol>
<li>Visit the login page with a Element pointing at your homeserver.</li>
<li>Click the Single Sign-On button.</li>
<li>Login using the credentials created with <code>createsuperuser</code>.</li>
<li>You should be logged in.</li>
</ol>
<p>If you want to repeat this process you'll need to manually logout first:</p>
<ol>
<li>http://localhost:8000/admin/</li>
<li>Click &quot;logout&quot; in the top right.</li>
</ol>
<div style="break-before: page; page-break-before: always;"></div><h1 id="room-dag-concepts"><a class="header" href="#room-dag-concepts">Room DAG concepts</a></h1>
<h2 id="edges"><a class="header" href="#edges">Edges</a></h2>
<p>The word &quot;edge&quot; comes from graph theory lingo. An edge is just a connection
between two events. In Synapse, we connect events by specifying their
<code>prev_events</code>. A subsequent event points back at a previous event.</p>
<pre><code>A (oldest) &lt;---- B &lt;---- C (most recent)
</code></pre>
<h2 id="depth-and-stream-ordering"><a class="header" href="#depth-and-stream-ordering">Depth and stream ordering</a></h2>
<p>Events are normally sorted by <code>(topological_ordering, stream_ordering)</code> where
<code>topological_ordering</code> is just <code>depth</code>. In other words, we first sort by <code>depth</code>
and then tie-break based on <code>stream_ordering</code>. <code>depth</code> is incremented as new
messages are added to the DAG. Normally, <code>stream_ordering</code> is an auto
incrementing integer, but backfilled events start with <code>stream_ordering=-1</code> and decrement.</p>
<hr />
<ul>
<li><code>/sync</code> returns things in the order they arrive at the server (<code>stream_ordering</code>).</li>
<li><code>/messages</code> (and <code>/backfill</code> in the federation API) return them in the order determined by the event graph <code>(topological_ordering, stream_ordering)</code>.</li>
</ul>
<p>The general idea is that, if you're following a room in real-time (i.e.
<code>/sync</code>), you probably want to see the messages as they arrive at your server,
rather than skipping any that arrived late; whereas if you're looking at a
historical section of timeline (i.e. <code>/messages</code>), you want to see the best
representation of the state of the room as others were seeing it at the time.</p>
<h2 id="outliers"><a class="header" href="#outliers">Outliers</a></h2>
<p>We mark an event as an <code>outlier</code> when we haven't figured out the state for the
room at that point in the DAG yet. They are &quot;floating&quot; events that we haven't
yet correlated to the DAG.</p>
<p>Outliers typically arise when we fetch the auth chain or state for a given
event. When that happens, we just grab the events in the state/auth chain,
without calculating the state at those events, or backfilling their
<code>prev_events</code>. Since we don't have the state at any events fetched in that
way, we mark them as outliers.</p>
<p>So, typically, we won't have the <code>prev_events</code> of an <code>outlier</code> in the database,
(though it's entirely possible that we <em>might</em> have them for some other
reason). Other things that make outliers different from regular events:</p>
<ul>
<li>
<p>We don't have state for them, so there should be no entry in
<code>event_to_state_groups</code> for an outlier. (In practice this isn't always
the case, though I'm not sure why: see https://github.com/matrix-org/synapse/issues/12201).</p>
</li>
<li>
<p>We don't record entries for them in the <code>event_edges</code>,
<code>event_forward_extremeties</code> or <code>event_backward_extremities</code> tables.</p>
</li>
</ul>
<p>Since outliers are not tied into the DAG, they do not normally form part of the
timeline sent down to clients via <code>/sync</code> or <code>/messages</code>; however there is an
exception:</p>
<h3 id="out-of-band-membership-events"><a class="header" href="#out-of-band-membership-events">Out-of-band membership events</a></h3>
<p>A special case of outlier events are some membership events for federated rooms
that we aren't full members of. For example:</p>
<ul>
<li>invites received over federation, before we join the room</li>
<li><em>rejections</em> for said invites</li>
<li>knock events for rooms that we would like to join but have not yet joined.</li>
</ul>
<p>In all the above cases, we don't have the state for the room, which is why they
are treated as outliers. They are a bit special though, in that they are
proactively sent to clients via <code>/sync</code>.</p>
<h2 id="forward-extremity"><a class="header" href="#forward-extremity">Forward extremity</a></h2>
<p>Most-recent-in-time events in the DAG which are not referenced by any other
events' <code>prev_events</code> yet. (In this definition, outliers, rejected events, and
soft-failed events don't count.)</p>
<p>The forward extremities of a room (or at least, a subset of them, if there are
more than ten) are used as the <code>prev_events</code> when the next event is sent.</p>
<p>The &quot;current state&quot; of a room (ie: the state which would be used if we
generated a new event) is, therefore, the resolution of the room states
at each of the forward extremities.</p>
<h2 id="backward-extremity"><a class="header" href="#backward-extremity">Backward extremity</a></h2>
<p>The current marker of where we have backfilled up to and will generally be the
<code>prev_events</code> of the oldest-in-time events we have in the DAG. This gives a starting point when
backfilling history.</p>
<p>Note that, unlike forward extremities, we typically don't have any backward
extremity events themselves in the database - or, if we do, they will be &quot;outliers&quot; (see
above). Either way, we don't expect to have the room state at a backward extremity.</p>
<p>When we persist a non-outlier event, if it was previously a backward extremity,
we clear it as a backward extremity and set all of its <code>prev_events</code> as the new
backward extremities if they aren't already persisted as non-outliers. This
therefore keeps the backward extremities up-to-date.</p>
<h2 id="state-groups"><a class="header" href="#state-groups">State groups</a></h2>
<p>For every non-outlier event we need to know the state at that event. Instead of
storing the full state for each event in the DB (i.e. a <code>event_id -&gt; state</code>
mapping), which is <em>very</em> space inefficient when state doesn't change, we
instead assign each different set of state a &quot;state group&quot; and then have
mappings of <code>event_id -&gt; state_group</code> and <code>state_group -&gt; state</code>.</p>
<h3 id="stage-group-edges"><a class="header" href="#stage-group-edges">Stage group edges</a></h3>
<p>TODO: <code>state_group_edges</code> is a further optimization...
notes from @Azrenbeth, https://pastebin.com/seUGVGeT</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="auth-chain-difference-algorithm"><a class="header" href="#auth-chain-difference-algorithm">Auth Chain Difference Algorithm</a></h1>
<p>The auth chain difference algorithm is used by V2 state resolution, where a
naive implementation can be a significant source of CPU and DB usage.</p>
<h3 id="definitions"><a class="header" href="#definitions">Definitions</a></h3>
<p>A <em>state set</em> is a set of state events; e.g. the input of a state resolution
algorithm is a collection of state sets.</p>
<p>The <em>auth chain</em> of a set of events are all the events' auth events and <em>their</em>
auth events, recursively (i.e. the events reachable by walking the graph induced
by an event's auth events links).</p>
<p>The <em>auth chain difference</em> of a collection of state sets is the union minus the
intersection of the sets of auth chains corresponding to the state sets, i.e an
event is in the auth chain difference if it is reachable by walking the auth
event graph from at least one of the state sets but not from <em>all</em> of the state
sets.</p>
<h2 id="breadth-first-walk-algorithm"><a class="header" href="#breadth-first-walk-algorithm">Breadth First Walk Algorithm</a></h2>
<p>A way of calculating the auth chain difference without calculating the full auth
chains for each state set is to do a parallel breadth first walk (ordered by
depth) of each state set's auth chain. By tracking which events are reachable
from each state set we can finish early if every pending event is reachable from
every state set.</p>
<p>This can work well for state sets that have a small auth chain difference, but
can be very inefficient for larger differences. However, this algorithm is still
used if we don't have a chain cover index for the room (e.g. because we're in
the process of indexing it).</p>
<h2 id="chain-cover-index"><a class="header" href="#chain-cover-index">Chain Cover Index</a></h2>
<p>Synapse computes auth chain differences by pre-computing a &quot;chain cover&quot; index
for the auth chain in a room, allowing us to efficiently make reachability queries
like &quot;is event <code>A</code> in the auth chain of event <code>B</code>?&quot;. We could do this with an index
that tracks all pairs <code>(A, B)</code> such that <code>A</code> is in the auth chain of <code>B</code>. However, this
would be prohibitively large, scaling poorly as the room accumulates more state
events.</p>
<p>Instead, we break down the graph into <em>chains</em>. A chain is a subset of a DAG
with the following property: for any pair of events <code>E</code> and <code>F</code> in the chain,
the chain contains a path <code>E -&gt; F</code> or a path <code>F -&gt; E</code>. This forces a chain to be
linear (without forks), e.g. <code>E -&gt; F -&gt; G -&gt; ... -&gt; H</code>. Each event in the chain
is given a <em>sequence number</em> local to that chain. The oldest event <code>E</code> in the
chain has sequence number 1. If <code>E</code> has a child <code>F</code> in the chain, then <code>F</code> has
sequence number 2. If <code>E</code> has a grandchild <code>G</code> in the chain, then <code>G</code> has
sequence number 3; and so on.</p>
<p>Synapse ensures that each persisted event belongs to exactly one chain, and
tracks how the chains are connected to one another. This allows us to
efficiently answer reachability queries. Doing so uses less storage than
tracking reachability on an event-by-event basis, particularly when we have
fewer and longer chains. See</p>
<blockquote>
<p>Jagadish, H. (1990). <a href="https://doi.org/10.1145/99935.99944">A compression technique to materialize transitive closure</a>.
<em>ACM Transactions on Database Systems (TODS)</em>, 15*(4)*, 558-598.</p>
</blockquote>
<p>for the original idea or</p>
<blockquote>
<p>Y. Chen, Y. Chen, <a href="https://doi.org/10.1109/ICDE.2008.4497498">An efficient algorithm for answering graph
reachability queries</a>,
in: 2008 IEEE 24th International Conference on Data Engineering, April 2008,
pp. 893–902. (PDF available via <a href="https://scholar.google.com/scholar?q=Y.%20Chen,%20Y.%20Chen,%20An%20efficient%20algorithm%20for%20answering%20graph%20reachability%20queries,%20in:%202008%20IEEE%2024th%20International%20Conference%20on%20Data%20Engineering,%20April%202008,%20pp.%20893902.">Google Scholar</a>.)</p>
</blockquote>
<p>for a more modern take.</p>
<p>In practical terms, the chain cover assigns every event a
<em>chain ID</em> and <em>sequence number</em> (e.g. <code>(5,3)</code>), and maintains a map of <em>links</em>
between events in chains (e.g. <code>(5,3) -&gt; (2,4)</code>) such that <code>A</code> is reachable by <code>B</code>
(i.e. <code>A</code> is in the auth chain of <code>B</code>) if and only if either:</p>
<ol>
<li><code>A</code> and <code>B</code> have the same chain ID and <code>A</code>'s sequence number is less than <code>B</code>'s
sequence number; or</li>
<li>there is a link <code>L</code> between <code>B</code>'s chain ID and <code>A</code>'s chain ID such that
<code>L.start_seq_no</code> &lt;= <code>B.seq_no</code> and <code>A.seq_no</code> &lt;= <code>L.end_seq_no</code>.</li>
</ol>
<p>There are actually two potential implementations, one where we store links from
each chain to every other reachable chain (the transitive closure of the links
graph), and one where we remove redundant links (the transitive reduction of the
links graph) e.g. if we have chains <code>C3 -&gt; C2 -&gt; C1</code> then the link <code>C3 -&gt; C1</code>
would not be stored. Synapse uses the former implementation so that it doesn't
need to recurse to test reachability between chains. This trades-off extra storage
in order to save CPU cycles and DB queries.</p>
<h3 id="example-6"><a class="header" href="#example-6">Example</a></h3>
<p>An example auth graph would look like the following, where chains have been
formed based on type/state_key and are denoted by colour and are labelled with
<code>(chain ID, sequence number)</code>. Links are denoted by the arrows (links in grey
are those that would be remove in the second implementation described above).</p>
<p><img src="auth_chain_diff.dot.png" alt="Example" /></p>
<p>Note that we don't include all links between events and their auth events, as
most of those links would be redundant. For example, all events point to the
create event, but each chain only needs the one link from it's base to the
create event.</p>
<h2 id="using-the-index"><a class="header" href="#using-the-index">Using the Index</a></h2>
<p>This index can be used to calculate the auth chain difference of the state sets
by looking at the chain ID and sequence numbers reachable from each state set:</p>
<ol>
<li>For every state set lookup the chain ID/sequence numbers of each state event</li>
<li>Use the index to find all chains and the maximum sequence number reachable
from each state set.</li>
<li>The auth chain difference is then all events in each chain that have sequence
numbers between the maximum sequence number reachable from <em>any</em> state set and
the minimum reachable by <em>all</em> state sets (if any).</li>
</ol>
<p>Note that steps 2 is effectively calculating the auth chain for each state set
(in terms of chain IDs and sequence numbers), and step 3 is calculating the
difference between the union and intersection of the auth chains.</p>
<h3 id="worked-example"><a class="header" href="#worked-example">Worked Example</a></h3>
<p>For example, given the above graph, we can calculate the difference between
state sets consisting of:</p>
<ol>
<li><code>S1</code>: Alice's invite <code>(4,1)</code> and Bob's second join <code>(2,2)</code>; and</li>
<li><code>S2</code>: Alice's second join <code>(4,3)</code> and Bob's first join <code>(2,1)</code>.</li>
</ol>
<p>Using the index we see that the following auth chains are reachable from each
state set:</p>
<ol>
<li><code>S1</code>: <code>(1,1)</code>, <code>(2,2)</code>, <code>(3,1)</code> &amp; <code>(4,1)</code></li>
<li><code>S2</code>: <code>(1,1)</code>, <code>(2,1)</code>, <code>(3,2)</code> &amp; <code>(4,3)</code></li>
</ol>
<p>And so, for each the ranges that are in the auth chain difference:</p>
<ol>
<li>Chain 1: None, (since everything can reach the create event).</li>
<li>Chain 2: The range <code>(1, 2]</code> (i.e. just <code>2</code>), as <code>1</code> is reachable by all state
sets and the maximum reachable is <code>2</code> (corresponding to Bob's second join).</li>
<li>Chain 3: Similarly the range <code>(1, 2]</code> (corresponding to the second power
level).</li>
<li>Chain 4: The range <code>(1, 3]</code> (corresponding to both of Alice's joins).</li>
</ol>
<p>So the final result is: Bob's second join <code>(2,2)</code>, the second power level
<code>(3,2)</code> and both of Alice's joins <code>(4,2)</code> &amp; <code>(4,3)</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="media-repository"><a class="header" href="#media-repository">Media Repository</a></h1>
<p><em>Synapse implementation-specific details for the media repository</em></p>
<p>The media repository</p>
<ul>
<li>stores avatars, attachments and their thumbnails for media uploaded by local
users.</li>
<li>caches avatars, attachments and their thumbnails for media uploaded by remote
users.</li>
<li>caches resources and thumbnails used for URL previews.</li>
</ul>
<p>All media in Matrix can be identified by a unique
<a href="https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris">MXC URI</a>,
consisting of a server name and media ID:</p>
<pre><code>mxc://&lt;server-name&gt;/&lt;media-id&gt;
</code></pre>
<h2 id="local-media"><a class="header" href="#local-media">Local Media</a></h2>
<p>Synapse generates 24 character media IDs for content uploaded by local users.
These media IDs consist of upper and lowercase letters and are case-sensitive.
Other homeserver implementations may generate media IDs differently.</p>
<p>Local media is recorded in the <code>local_media_repository</code> table, which includes
metadata such as MIME types, upload times and file sizes.
Note that this table is shared by the URL cache, which has a different media ID
scheme.</p>
<h3 id="paths"><a class="header" href="#paths">Paths</a></h3>
<p>A file with media ID <code>aabbcccccccccccccccccccc</code> and its <code>128x96</code> <code>image/jpeg</code>
thumbnail, created by scaling, would be stored at:</p>
<pre><code>local_content/aa/bb/cccccccccccccccccccc
local_thumbnails/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
</code></pre>
<h2 id="remote-media"><a class="header" href="#remote-media">Remote Media</a></h2>
<p>When media from a remote homeserver is requested from Synapse, it is assigned
a local <code>filesystem_id</code>, with the same format as locally-generated media IDs,
as described above.</p>
<p>A record of remote media is stored in the <code>remote_media_cache</code> table, which
can be used to map remote MXC URIs (server names and media IDs) to local
<code>filesystem_id</code>s.</p>
<h3 id="paths-1"><a class="header" href="#paths-1">Paths</a></h3>
<p>A file from <code>matrix.org</code> with <code>filesystem_id</code> <code>aabbcccccccccccccccccccc</code> and its
<code>128x96</code> <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
<pre><code>remote_content/matrix.org/aa/bb/cccccccccccccccccccc
remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
</code></pre>
<p>Older thumbnails may omit the thumbnailing method:</p>
<pre><code>remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg
</code></pre>
<p>Note that <code>remote_thumbnail/</code> does not have an <code>s</code>.</p>
<h2 id="url-previews-1"><a class="header" href="#url-previews-1">URL Previews</a></h2>
<p>When generating previews for URLs, Synapse may download and cache various
resources, including images. These resources are assigned temporary media IDs
of the form <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code>, where <code>yyyy-mm-dd</code> is the current
date and <code>aaaaaaaaaaaaaaaa</code> is a random sequence of 16 case-sensitive letters.</p>
<p>The metadata for these cached resources is stored in the
<code>local_media_repository</code> and <code>local_media_repository_url_cache</code> tables.</p>
<p>Resources for URL previews are deleted after a few days.</p>
<h3 id="paths-2"><a class="header" href="#paths-2">Paths</a></h3>
<p>The file with media ID <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code> and its <code>128x96</code>
<code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
<pre><code>url_cache/yyyy-mm-dd/aaaaaaaaaaaaaaaa
url_cache_thumbnails/yyyy-mm-dd/aaaaaaaaaaaaaaaa/128-96-image-jpeg-scale
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="room-and-user-statistics"><a class="header" href="#room-and-user-statistics">Room and User Statistics</a></h1>
<p>Synapse maintains room and user statistics in various tables. These can be used
for administrative purposes but are also used when generating the public room
directory.</p>
<h1 id="synapse-developer-documentation"><a class="header" href="#synapse-developer-documentation">Synapse Developer Documentation</a></h1>
<h2 id="high-level-concepts"><a class="header" href="#high-level-concepts">High-Level Concepts</a></h2>
<h3 id="definitions-1"><a class="header" href="#definitions-1">Definitions</a></h3>
<ul>
<li><strong>subject</strong>: Something we are tracking stats about – currently a room or user.</li>
<li><strong>current row</strong>: An entry for a subject in the appropriate current statistics
table. Each subject can have only one.</li>
</ul>
<h3 id="overview-4"><a class="header" href="#overview-4">Overview</a></h3>
<p>Stats correspond to the present values. Current rows contain the most up-to-date
statistics for a room. Each subject can only have one entry.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="deprecation-policy-for-platform-dependencies"><a class="header" href="#deprecation-policy-for-platform-dependencies">Deprecation Policy for Platform Dependencies</a></h1>
<p>Synapse has a number of platform dependencies, including Python, Rust, 
PostgreSQL and SQLite. This document outlines the policy towards which versions 
we support, and when we drop support for versions in the future.</p>
<h2 id="policy"><a class="header" href="#policy">Policy</a></h2>
<p>Synapse follows the upstream support life cycles for Python and PostgreSQL,
i.e. when a version reaches End of Life Synapse will withdraw support for that
version in future releases.</p>
<p>Details on the upstream support life cycles for Python and PostgreSQL are
documented at <a href="https://endoflife.date/python">https://endoflife.date/python</a> and
<a href="https://endoflife.date/postgresql">https://endoflife.date/postgresql</a>.</p>
<p>A Rust compiler is required to build Synapse from source. For any given release
the minimum required version may be bumped up to a recent Rust version, and so
people building from source should ensure they can fetch recent versions of Rust
(e.g. by using <a href="https://rustup.rs/">rustup</a>).</p>
<p>The oldest supported version of SQLite is the version
<a href="https://packages.debian.org/bullseye/libsqlite3-0">provided</a> by
<a href="https://wiki.debian.org/DebianOldStable">Debian oldstable</a>.</p>
<h2 id="context"><a class="header" href="#context">Context</a></h2>
<p>It is important for system admins to have a clear understanding of the platform
requirements of Synapse and its deprecation policies so that they can
effectively plan upgrading their infrastructure ahead of time. This is
especially important in contexts where upgrading the infrastructure requires
auditing and approval from a security team, or where otherwise upgrading is a
long process.</p>
<p>By following the upstream support life cycles Synapse can ensure that its
dependencies continue to get security patches, while not requiring system admins
to constantly update their platform dependencies to the latest versions.</p>
<p>For Rust, the situation is a bit different given that a) the Rust foundation
does not generally support older Rust versions, and b) the library ecosystem
generally bump their minimum support Rust versions frequently. In general, the
Synapse team will try to avoid updating the dependency on Rust to the absolute
latest version, but introducing a formal policy is hard given the constraints of
the ecosystem.</p>
<p>On a similar note, SQLite does not generally have a concept of &quot;supported 
release&quot;; bugfixes are published for the latest minor release only. We chose to
track Debian's oldstable as this is relatively conservative, predictably updated
and is consistent with the <code>.deb</code> packages released by Matrix.org.</p>
<div style="break-before: page; page-break-before: always;"></div><h2 id="summary-of-performance-impact-of-running-on-resource-constrained-devices-such-as-sbcs"><a class="header" href="#summary-of-performance-impact-of-running-on-resource-constrained-devices-such-as-sbcs">Summary of performance impact of running on resource constrained devices such as SBCs</a></h2>
<p>I've been running my homeserver on a cubietruck at home now for some time and am often replying to statements like &quot;you need loads of ram to join large rooms&quot; with &quot;it works fine for me&quot;. I thought it might be useful to curate a summary of the issues you're likely to run into to help as a scaling-down guide, maybe highlight these for development work or end up as documentation. It seems that once you get up to about 4x1.5GHz arm64 4GiB these issues are no longer a problem.</p>
<ul>
<li><strong>Platform</strong>: 2x1GHz armhf 2GiB ram <a href="https://wiki.debian.org/CheapServerBoxHardware">Single-board computers</a>, SSD, postgres.</li>
</ul>
<h3 id="presence-1"><a class="header" href="#presence-1">Presence</a></h3>
<p>This is the main reason people have a poor matrix experience on resource constrained homeservers. Element web will frequently be saying the server is offline while the python process will be pegged at 100% cpu. This feature is used to tell when other users are active (have a client app in the foreground) and therefore more likely to respond, but requires a lot of network activity to maintain even when nobody is talking in a room.</p>
<p><img src="https://user-images.githubusercontent.com/71895/94848963-a47a3580-041c-11eb-8b6e-acb772b4259e.png" alt="Screenshot_2020-10-01_19-29-46" /></p>
<p>While synapse does have some performance issues with presence <a href="https://github.com/matrix-org/synapse/issues/3971">#3971</a>, the fundamental problem is that this is an easy feature to implement for a centralised service at nearly no overhead, but federation makes it combinatorial <a href="https://github.com/matrix-org/synapse/issues/8055">#8055</a>. There is also a client-side config option which disables the UI and idle tracking <a href="https://github.com/vector-im/element-web/blob/v1.7.8/config.sample.json#L45">enable_presence_by_hs_url</a> to blacklist the largest instances but I didn't notice much difference, so I recommend disabling the feature entirely at the server level as well.</p>
<h3 id="joining"><a class="header" href="#joining">Joining</a></h3>
<p>Joining a &quot;large&quot;, federated room will initially fail with the below message in Element web, but waiting a while (10-60mins) and trying again will succeed without any issue. What counts as &quot;large&quot; is not message history, user count, connections to homeservers or even a simple count of the state events, it is instead how long the state resolution algorithm takes. However, each of those numbers are reasonable proxies, so we can use them as estimates since user count is one of the few things you see before joining.</p>
<p><img src="https://user-images.githubusercontent.com/71895/94945781-18771500-04d3-11eb-8419-83c2da73a341.png" alt="Screenshot_2020-10-02_17-15-06" /></p>
<p>This is <a href="https://github.com/matrix-org/synapse/issues/1211">#1211</a> and will also hopefully be mitigated by peeking <a href="https://github.com/matrix-org/matrix-doc/pull/2753">matrix-org/matrix-doc#2753</a> so at least you don't need to wait for a join to complete before finding out if it's the kind of room you want. Note that you should first disable presence, otherwise it'll just make the situation worse <a href="https://github.com/matrix-org/synapse/issues/3120">#3120</a>. There is a lot of database interaction too, so make sure you've <a href="other/../postgres.html">migrated your data</a> from the default sqlite to postgresql. Personally, I recommend patience - once the initial join is complete there's rarely any issues with actually interacting with the room, but if you like you can just block &quot;large&quot; rooms entirely.</p>
<h3 id="sessions"><a class="header" href="#sessions">Sessions</a></h3>
<p>Anything that requires modifying the device list <a href="https://github.com/matrix-org/synapse/issues/7721">#7721</a> will take a while to propagate, again taking the client &quot;Offline&quot; until it's complete. This includes signing in and out, editing the public name and verifying e2ee. The main mitigation I recommend is to keep long-running sessions open e.g. by using Firefox SSB &quot;Use this site in App mode&quot; or Chromium PWA &quot;Install Element&quot;.</p>
<h3 id="recommended-configuration"><a class="header" href="#recommended-configuration">Recommended configuration</a></h3>
<p>Put the below in a new file at /etc/matrix-synapse/conf.d/sbc.yaml to override the defaults in homeserver.yaml.</p>
<pre><code># Disable presence tracking, which is currently fairly resource intensive
# More info: https://github.com/matrix-org/synapse/issues/9478
use_presence: false

# Set a small complexity limit, preventing users from joining large rooms
# which may be resource-intensive to remain a part of.
#
# Note that this will not prevent users from joining smaller rooms that
# eventually become complex.
limit_remote_rooms:
  enabled: true
  complexity: 3.0

# Database configuration
database:
  # Use postgres for the best performance
  name: psycopg2
  args:
    user: matrix-synapse
    # Generate a long, secure password using a password manager
    password: hunter2
    database: matrix-synapse
    host: localhost
</code></pre>
<p>Currently the complexity is measured by <a href="https://github.com/matrix-org/synapse/blob/v1.20.1/synapse/storage/databases/main/events_worker.py#L986">current_state_events / 500</a>. You can find join times and your most complex rooms like this:</p>
<pre><code>admin@homeserver:~$ zgrep '/client/r0/join/' /var/log/matrix-synapse/homeserver.log* | awk '{print $18, $25}' | sort --human-numeric-sort
29.922sec/-0.002sec /_matrix/client/r0/join/%23debian-fasttrack%3Apoddery.com
182.088sec/0.003sec /_matrix/client/r0/join/%23decentralizedweb-general%3Amatrix.org
911.625sec/-570.847sec /_matrix/client/r0/join/%23synapse%3Amatrix.org

admin@homeserver:~$ sudo --user postgres psql matrix-synapse --command 'select canonical_alias, joined_members, current_state_events from room_stats_state natural join room_stats_current where canonical_alias is not null order by current_state_events desc fetch first 5 rows only'
        canonical_alias        | joined_members | current_state_events 
-------------------------------+----------------+----------------------
 #_oftc_#debian:matrix.org             |  871   |  52355
 #matrix:matrix.org                    |  6379  |  10684
 #irc:matrix.org                       |  461   |  3751
 #decentralizedweb-general:matrix.org  |  997   |  1509
 #whatsapp:maunium.net                 |  554   |  854
</code></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
            </nav>

        </div>

        <script type="text/javascript">
            window.playground_copyable = true;
        </script>
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        <script type="text/javascript" src="docs/website_files/table-of-contents.js"></script>
        <script type="text/javascript">
        window.addEventListener('load', function() {
            window.setTimeout(window.print, 100);
        });
        </script>
    </body>
</html>