print.html 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972
  1. <!DOCTYPE HTML>
  2. <html lang="en" class="sidebar-visible no-js light">
  3. <head>
  4. <!-- Book generated using mdBook -->
  5. <meta charset="UTF-8">
  6. <title>Synapse</title>
  7. <meta name="robots" content="noindex" />
  8. <!-- Custom HTML head -->
  9. <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  10. <meta name="description" content="">
  11. <meta name="viewport" content="width=device-width, initial-scale=1">
  12. <meta name="theme-color" content="#ffffff" />
  13. <link rel="icon" href="favicon.svg">
  14. <link rel="shortcut icon" href="favicon.png">
  15. <link rel="stylesheet" href="css/variables.css">
  16. <link rel="stylesheet" href="css/general.css">
  17. <link rel="stylesheet" href="css/chrome.css">
  18. <link rel="stylesheet" href="css/print.css" media="print">
  19. <!-- Fonts -->
  20. <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
  21. <link rel="stylesheet" href="fonts/fonts.css">
  22. <!-- Highlight.js Stylesheets -->
  23. <link rel="stylesheet" href="highlight.css">
  24. <link rel="stylesheet" href="tomorrow-night.css">
  25. <link rel="stylesheet" href="ayu-highlight.css">
  26. <!-- Custom theme stylesheets -->
  27. <link rel="stylesheet" href="docs/website_files/table-of-contents.css">
  28. <link rel="stylesheet" href="docs/website_files/remove-nav-buttons.css">
  29. <link rel="stylesheet" href="docs/website_files/indent-section-headers.css">
  30. <link rel="stylesheet" href="docs/website_files/version-picker.css">
  31. </head>
  32. <body>
  33. <!-- Provide site root to javascript -->
  34. <script type="text/javascript">
  35. var path_to_root = "";
  36. var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
  37. </script>
  38. <!-- Work around some values being stored in localStorage wrapped in quotes -->
  39. <script type="text/javascript">
  40. try {
  41. var theme = localStorage.getItem('mdbook-theme');
  42. var sidebar = localStorage.getItem('mdbook-sidebar');
  43. if (theme.startsWith('"') && theme.endsWith('"')) {
  44. localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
  45. }
  46. if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
  47. localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
  48. }
  49. } catch (e) { }
  50. </script>
  51. <!-- Set the theme before any content is loaded, prevents flash -->
  52. <script type="text/javascript">
  53. var theme;
  54. try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
  55. if (theme === null || theme === undefined) { theme = default_theme; }
  56. var html = document.querySelector('html');
  57. html.classList.remove('no-js')
  58. html.classList.remove('light')
  59. html.classList.add(theme);
  60. html.classList.add('js');
  61. </script>
  62. <!-- Hide / unhide sidebar before it is displayed -->
  63. <script type="text/javascript">
  64. var html = document.querySelector('html');
  65. var sidebar = 'hidden';
  66. if (document.body.clientWidth >= 1080) {
  67. try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
  68. sidebar = sidebar || 'visible';
  69. }
  70. html.classList.remove('sidebar-visible');
  71. html.classList.add("sidebar-" + sidebar);
  72. </script>
  73. <nav id="sidebar" class="sidebar" aria-label="Table of contents">
  74. <div class="sidebar-scrollbox">
  75. <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="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>
  76. </div>
  77. <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
  78. </nav>
  79. <div id="page-wrapper" class="page-wrapper">
  80. <div class="page">
  81. <div id="menu-bar-hover-placeholder"></div>
  82. <div id="menu-bar" class="menu-bar sticky bordered">
  83. <div class="left-buttons">
  84. <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
  85. <i class="fa fa-bars"></i>
  86. </button>
  87. <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">
  88. <i class="fa fa-paint-brush"></i>
  89. </button>
  90. <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
  91. <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
  92. <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
  93. <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
  94. <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
  95. <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
  96. </ul>
  97. <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">
  98. <i class="fa fa-search"></i>
  99. </button>
  100. <div class="version-picker">
  101. <div class="dropdown">
  102. <div class="select">
  103. <span></span>
  104. <i class="fa fa-chevron-down"></i>
  105. </div>
  106. <input type="hidden" name="version">
  107. <ul class="dropdown-menu">
  108. <!-- Versions will be added dynamically in version-picker.js -->
  109. </ul>
  110. </div>
  111. </div>
  112. </div>
  113. <h1 class="menu-title">Synapse</h1>
  114. <div class="right-buttons">
  115. <a href="print.html" title="Print this book" aria-label="Print this book">
  116. <i id="print-button" class="fa fa-print"></i>
  117. </a>
  118. <a href="https://github.com/matrix-org/synapse" title="Git repository" aria-label="Git repository">
  119. <i id="git-repository-button" class="fa fa-github"></i>
  120. </a>
  121. </div>
  122. </div>
  123. <div id="search-wrapper" class="hidden">
  124. <form id="searchbar-outer" class="searchbar-outer">
  125. <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
  126. </form>
  127. <div id="searchresults-outer" class="searchresults-outer hidden">
  128. <div id="searchresults-header" class="searchresults-header"></div>
  129. <ul id="searchresults">
  130. </ul>
  131. </div>
  132. </div>
  133. <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
  134. <script type="text/javascript">
  135. document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
  136. document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
  137. Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
  138. link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
  139. });
  140. </script>
  141. <div id="content" class="content">
  142. <main>
  143. <!-- Page table of contents -->
  144. <div class="sidetoc">
  145. <nav class="pagetoc"></nav>
  146. </div>
  147. <div style="break-before: page; page-break-before: always;"></div><h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
  148. <p>Welcome to the documentation repository for Synapse, a
  149. <a href="https://matrix.org">Matrix</a> homeserver implementation developed by the matrix.org core
  150. team.</p>
  151. <h2 id="installing-and-using-synapse"><a class="header" href="#installing-and-using-synapse">Installing and using Synapse</a></h2>
  152. <p>This documentation covers topics for <strong>installation</strong>, <strong>configuration</strong> and
  153. <strong>maintenance</strong> of your Synapse process:</p>
  154. <ul>
  155. <li>
  156. <p>Learn how to <a href="setup/installation.html">install</a> and
  157. <a href="usage/configuration/config_documentation.html">configure</a> your own instance, perhaps with <a href="usage/configuration/user_authentication/index.html">Single
  158. Sign-On</a>.</p>
  159. </li>
  160. <li>
  161. <p>See how to <a href="upgrade.html">upgrade</a> between Synapse versions.</p>
  162. </li>
  163. <li>
  164. <p>Administer your instance using the <a href="usage/administration/admin_api/index.html">Admin
  165. API</a>, installing <a href="modules/index.html">pluggable
  166. modules</a>, or by accessing the <a href="manhole.html">manhole</a>.</p>
  167. </li>
  168. <li>
  169. <p>Learn how to <a href="usage/administration/request_log.html">read log lines</a>, configure
  170. <a href="usage/configuration/logging_sample_config.html">logging</a> or set up <a href="structured_logging.html">structured
  171. logging</a>.</p>
  172. </li>
  173. <li>
  174. <p>Scale Synapse through additional <a href="workers.html">worker processes</a>.</p>
  175. </li>
  176. <li>
  177. <p>Set up <a href="metrics-howto.html">monitoring and metrics</a> to keep an eye on your
  178. Synapse instance's performance.</p>
  179. </li>
  180. </ul>
  181. <h2 id="developing-on-synapse"><a class="header" href="#developing-on-synapse">Developing on Synapse</a></h2>
  182. <p>Contributions are welcome! Synapse is primarily written in
  183. <a href="https://python.org">Python</a>. As a developer, you may be interested in the
  184. following documentation:</p>
  185. <ul>
  186. <li>
  187. <p>Read the <a href="development/contributing_guide.html">Contributing Guide</a>. It is meant
  188. to walk new contributors through the process of developing and submitting a
  189. change to the Synapse codebase (which is <a href="https://github.com/matrix-org/synapse">hosted on
  190. GitHub</a>).</p>
  191. </li>
  192. <li>
  193. <p>Set up your <a href="development/contributing_guide.html#2-what-do-i-need">development
  194. environment</a>, then learn
  195. how to <a href="development/contributing_guide.html#run-the-linters">lint</a> and
  196. <a href="development/contributing_guide.html#8-test-test-test">test</a> your code.</p>
  197. </li>
  198. <li>
  199. <p>Look at <a href="https://github.com/matrix-org/synapse/issues">the issue tracker</a> for
  200. bugs to fix or features to add. If you're new, it may be best to start with
  201. those labeled <a href="https://github.com/matrix-org/synapse/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22">good first
  202. issue</a>.</p>
  203. </li>
  204. <li>
  205. <p>Understand <a href="development/internal_documentation/index.html">how Synapse is
  206. built</a>, how to <a href="development/database_schema.html">migrate
  207. database schemas</a>, learn about
  208. <a href="federate.html">federation</a> and how to <a href="federate.html#running-a-demo-federation-of-synapses">set up a local
  209. federation</a> for development.</p>
  210. </li>
  211. <li>
  212. <p>We like to keep our <code>git</code> history clean. <a href="development/git.html">Learn</a> how to
  213. do so!</p>
  214. </li>
  215. <li>
  216. <p>And finally, contribute to this documentation! The source for which is
  217. <a href="https://github.com/matrix-org/synapse/tree/develop/docs">located here</a>.</p>
  218. </li>
  219. </ul>
  220. <h2 id="donating-to-synapse-development"><a class="header" href="#donating-to-synapse-development">Donating to Synapse development</a></h2>
  221. <p>Want to help keep Synapse going but don't know how to code? Synapse is a
  222. <a href="https://matrix.org">Matrix.org Foundation</a> project. Consider becoming a
  223. supporter on <a href="https://liberapay.com/matrixdotorg">Liberapay</a>,
  224. <a href="https://patreon.com/matrixdotorg">Patreon</a> or through
  225. <a href="https://paypal.me/matrixdotorg">PayPal</a> via a one-time donation.</p>
  226. <p>If you are an organisation or enterprise and would like to sponsor development,
  227. reach out to us over email at: support (at) matrix.org</p>
  228. <h2 id="reporting-a-security-vulnerability"><a class="header" href="#reporting-a-security-vulnerability">Reporting a security vulnerability</a></h2>
  229. <p>If you've found a security issue in Synapse or any other Matrix.org Foundation
  230. project, please report it to us in accordance with our <a href="https://www.matrix.org/security-disclosure-policy/">Security Disclosure
  231. Policy</a>. Thank you!</p>
  232. <div style="break-before: page; page-break-before: always;"></div><h1 id="installation-instructions"><a class="header" href="#installation-instructions">Installation Instructions</a></h1>
  233. <h2 id="choosing-your-server-name"><a class="header" href="#choosing-your-server-name">Choosing your server name</a></h2>
  234. <p>It is important to choose the name for your server before you install Synapse,
  235. because it cannot be changed later.</p>
  236. <p>The server name determines the &quot;domain&quot; part of user-ids for users on your
  237. server: these will all be of the format <code>@user:my.domain.name</code>. It also
  238. determines how other matrix servers will reach yours for federation.</p>
  239. <p>For a test configuration, set this to the hostname of your server. For a more
  240. production-ready setup, you will probably want to specify your domain
  241. (<code>example.com</code>) rather than a matrix-specific hostname here (in the same way
  242. that your email address is probably <code>user@example.com</code> rather than
  243. <code>user@email.example.com</code>) - but doing so may require more advanced setup: see
  244. <a href="setup/../federate.html">Setting up Federation</a>.</p>
  245. <h2 id="installing-synapse"><a class="header" href="#installing-synapse">Installing Synapse</a></h2>
  246. <h3 id="prebuilt-packages"><a class="header" href="#prebuilt-packages">Prebuilt packages</a></h3>
  247. <p>Prebuilt packages are available for a number of platforms. These are recommended
  248. for most users.</p>
  249. <h4 id="docker-images-and-ansible-playbooks"><a class="header" href="#docker-images-and-ansible-playbooks">Docker images and Ansible playbooks</a></h4>
  250. <p>There is an official synapse image available at
  251. <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>
  252. which can be used with the docker-compose file available at
  253. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/docker">contrib/docker</a>.
  254. Further information on this including configuration options is available in the README
  255. on hub.docker.com.</p>
  256. <p>Alternatively, Andreas Peters (previously Silvio Fricke) has contributed a
  257. Dockerfile to automate a synapse server in a single Docker image, at
  258. <a href="https://hub.docker.com/r/avhost/docker-matrix/tags/">https://hub.docker.com/r/avhost/docker-matrix/tags/</a></p>
  259. <p>Slavi Pantaleev has created an Ansible playbook,
  260. which installs the offical Docker image of Matrix Synapse
  261. along with many other Matrix-related services (Postgres database, Element, coturn,
  262. ma1sd, SSL support, etc.).
  263. For more details, see
  264. <a href="https://github.com/spantaleev/matrix-docker-ansible-deploy">https://github.com/spantaleev/matrix-docker-ansible-deploy</a></p>
  265. <h4 id="debianubuntu"><a class="header" href="#debianubuntu">Debian/Ubuntu</a></h4>
  266. <h5 id="matrixorg-packages"><a class="header" href="#matrixorg-packages">Matrix.org packages</a></h5>
  267. <p>Matrix.org provides Debian/Ubuntu packages of Synapse, for the amd64
  268. architecture via <a href="https://packages.matrix.org/debian/">https://packages.matrix.org/debian/</a>.</p>
  269. <p>To install the latest release:</p>
  270. <pre><code class="language-sh">sudo apt install -y lsb-release wget apt-transport-https
  271. sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
  272. echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main&quot; |
  273. sudo tee /etc/apt/sources.list.d/matrix-org.list
  274. sudo apt update
  275. sudo apt install matrix-synapse-py3
  276. </code></pre>
  277. <p>Packages are also published for release candidates. To enable the prerelease
  278. channel, add <code>prerelease</code> to the <code>sources.list</code> line. For example:</p>
  279. <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
  280. echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main prerelease&quot; |
  281. sudo tee /etc/apt/sources.list.d/matrix-org.list
  282. sudo apt update
  283. sudo apt install matrix-synapse-py3
  284. </code></pre>
  285. <p>The fingerprint of the repository signing key (as shown by <code>gpg /usr/share/keyrings/matrix-org-archive-keyring.gpg</code>) is
  286. <code>AAF9AE843A7584B5A3E4CD2BCF45A512DE2DA058</code>.</p>
  287. <p>When installing with Debian packages, you might prefer to place files in
  288. <code>/etc/matrix-synapse/conf.d/</code> to override your configuration without editing
  289. the main configuration file at <code>/etc/matrix-synapse/homeserver.yaml</code>.
  290. By doing that, you won't be asked if you want to replace your configuration
  291. file when you upgrade the Debian package to a later version.</p>
  292. <h5 id="downstream-debian-packages"><a class="header" href="#downstream-debian-packages">Downstream Debian packages</a></h5>
  293. <p>Andrej Shadura maintains a
  294. <a href="https://packages.debian.org/sid/matrix-synapse"><code>matrix-synapse</code></a> package in
  295. the Debian repositories.
  296. For <code>bookworm</code> and <code>sid</code>, it can be installed simply with:</p>
  297. <pre><code class="language-sh">sudo apt install matrix-synapse
  298. </code></pre>
  299. <p>Synapse is also avaliable in <code>bullseye-backports</code>. Please
  300. see the <a href="https://backports.debian.org/Instructions/">Debian documentation</a>
  301. for information on how to use backports.</p>
  302. <p><code>matrix-synapse</code> is no longer maintained for <code>buster</code> and older.</p>
  303. <h5 id="downstream-ubuntu-packages"><a class="header" href="#downstream-ubuntu-packages">Downstream Ubuntu packages</a></h5>
  304. <p>We do not recommend using the packages in the default Ubuntu repository
  305. 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>.
  306. The latest version of Synapse can be installed from <a href="setup/installation.html#matrixorg-packages">our repository</a>.</p>
  307. <h4 id="fedora"><a class="header" href="#fedora">Fedora</a></h4>
  308. <p>Synapse is in the Fedora repositories as
  309. <a href="https://src.fedoraproject.org/rpms/matrix-synapse"><code>matrix-synapse</code></a>:</p>
  310. <pre><code class="language-sh">sudo dnf install matrix-synapse
  311. </code></pre>
  312. <p>Additionally, Oleg Girko provides Fedora RPMs at
  313. <a href="https://obs.infoserver.lv/project/monitor/matrix-synapse">https://obs.infoserver.lv/project/monitor/matrix-synapse</a></p>
  314. <h4 id="opensuse"><a class="header" href="#opensuse">OpenSUSE</a></h4>
  315. <p>Synapse is in the OpenSUSE repositories as
  316. <a href="https://software.opensuse.org/package/matrix-synapse"><code>matrix-synapse</code></a>:</p>
  317. <pre><code class="language-sh">sudo zypper install matrix-synapse
  318. </code></pre>
  319. <h4 id="suse-linux-enterprise-server"><a class="header" href="#suse-linux-enterprise-server">SUSE Linux Enterprise Server</a></h4>
  320. <p>Unofficial package are built for SLES 15 in the openSUSE:Backports:SLE-15 repository at
  321. <a href="https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/">https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/</a></p>
  322. <h4 id="archlinux"><a class="header" href="#archlinux">ArchLinux</a></h4>
  323. <p>The quickest way to get up and running with ArchLinux is probably with the package provided by ArchLinux
  324. <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
  325. the necessary dependencies.</p>
  326. <p>pip may be outdated (6.0.7-1 and needs to be upgraded to 6.0.8-1 ):</p>
  327. <pre><code class="language-sh">sudo pip install --upgrade pip
  328. </code></pre>
  329. <p>If you encounter an error with lib bcrypt causing an Wrong ELF Class:
  330. ELFCLASS32 (x64 Systems), you may need to reinstall py-bcrypt to correctly
  331. compile it under the right architecture. (This should not be needed if
  332. installing under virtualenv):</p>
  333. <pre><code class="language-sh">sudo pip uninstall py-bcrypt
  334. sudo pip install py-bcrypt
  335. </code></pre>
  336. <h4 id="void-linux"><a class="header" href="#void-linux">Void Linux</a></h4>
  337. <p>Synapse can be found in the void repositories as
  338. <a href="https://github.com/void-linux/void-packages/tree/master/srcpkgs/synapse">'synapse'</a>:</p>
  339. <pre><code class="language-sh">xbps-install -Su
  340. xbps-install -S synapse
  341. </code></pre>
  342. <h4 id="freebsd"><a class="header" href="#freebsd">FreeBSD</a></h4>
  343. <p>Synapse can be installed via FreeBSD Ports or Packages contributed by Brendan Molloy from:</p>
  344. <ul>
  345. <li>Ports: <code>cd /usr/ports/net-im/py-matrix-synapse &amp;&amp; make install clean</code></li>
  346. <li>Packages: <code>pkg install py38-matrix-synapse</code></li>
  347. </ul>
  348. <h4 id="openbsd"><a class="header" href="#openbsd">OpenBSD</a></h4>
  349. <p>As of OpenBSD 6.7 Synapse is available as a pre-compiled binary. The filesystem
  350. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  351. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  352. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  353. <p>Installing Synapse:</p>
  354. <pre><code class="language-sh">doas pkg_add synapse
  355. </code></pre>
  356. <h4 id="nixos"><a class="header" href="#nixos">NixOS</a></h4>
  357. <p>Robin Lambertz has packaged Synapse for NixOS at:
  358. <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>
  359. <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>
  360. <p>It's also possible to install Synapse as a Python module from PyPI.</p>
  361. <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>
  362. <p>System requirements:</p>
  363. <ul>
  364. <li>POSIX-compliant system (tested on Linux &amp; OS X)</li>
  365. <li>Python 3.8 or later, up to Python 3.11.</li>
  366. <li>At least 1GB of free RAM if you want to join large public rooms like #matrix:matrix.org</li>
  367. </ul>
  368. <p>If building on an uncommon architecture for which pre-built wheels are
  369. unavailable, you will need to have a recent Rust compiler installed. The easiest
  370. way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  371. <p>To install the Synapse homeserver run:</p>
  372. <pre><code class="language-sh">mkdir -p ~/synapse
  373. virtualenv -p python3 ~/synapse/env
  374. source ~/synapse/env/bin/activate
  375. pip install --upgrade pip
  376. pip install --upgrade setuptools
  377. pip install matrix-synapse
  378. </code></pre>
  379. <p>This will download Synapse from <a href="https://pypi.org/project/matrix-synapse">PyPI</a>
  380. and install it, along with the python libraries it uses, into a virtual environment
  381. under <code>~/synapse/env</code>. Feel free to pick a different directory if you
  382. prefer.</p>
  383. <p>This Synapse installation can then be later upgraded by using pip again with the
  384. update flag:</p>
  385. <pre><code class="language-sh">source ~/synapse/env/bin/activate
  386. pip install -U matrix-synapse
  387. </code></pre>
  388. <p>Before you can start Synapse, you will need to generate a configuration
  389. file. To do this, run (in your virtualenv, as before):</p>
  390. <pre><code class="language-sh">cd ~/synapse
  391. python -m synapse.app.homeserver \
  392. --server-name my.domain.name \
  393. --config-path homeserver.yaml \
  394. --generate-config \
  395. --report-stats=[yes|no]
  396. </code></pre>
  397. <p>... substituting an appropriate value for <code>--server-name</code> and choosing whether
  398. or not to report usage statistics (hostname, Synapse version, uptime, total
  399. users, etc.) to the developers via the <code>--report-stats</code> argument.</p>
  400. <p>This command will generate you a config file that you can then customise, but it will
  401. also generate a set of keys for you. These keys will allow your homeserver to
  402. identify itself to other homeserver, so don't lose or delete them. It would be
  403. wise to back them up somewhere safe. (If, for whatever reason, you do need to
  404. change your homeserver's keys, you may find that other homeserver have the
  405. old key cached. If you update the signing key, you should change the name of the
  406. key in the <code>&lt;server name&gt;.signing.key</code> file (the second word) to something
  407. 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>
  408. <p>To actually run your new homeserver, pick a working directory for Synapse to
  409. run (e.g. <code>~/synapse</code>), and:</p>
  410. <pre><code class="language-sh">cd ~/synapse
  411. source env/bin/activate
  412. synctl start
  413. </code></pre>
  414. <h4 id="platform-specific-prerequisites"><a class="header" href="#platform-specific-prerequisites">Platform-specific prerequisites</a></h4>
  415. <p>Synapse is written in Python but some of the libraries it uses are written in
  416. C. So before we can install Synapse itself we need a working C compiler and the
  417. header files for Python C extensions.</p>
  418. <h5 id="debianubunturaspbian"><a class="header" href="#debianubunturaspbian">Debian/Ubuntu/Raspbian</a></h5>
  419. <p>Installing prerequisites on Ubuntu or Debian:</p>
  420. <pre><code class="language-sh">sudo apt install build-essential python3-dev libffi-dev \
  421. python3-pip python3-setuptools sqlite3 \
  422. libssl-dev virtualenv libjpeg-dev libxslt1-dev libicu-dev
  423. </code></pre>
  424. <h5 id="archlinux-1"><a class="header" href="#archlinux-1">ArchLinux</a></h5>
  425. <p>Installing prerequisites on ArchLinux:</p>
  426. <pre><code class="language-sh">sudo pacman -S base-devel python python-pip \
  427. python-setuptools python-virtualenv sqlite3 icu
  428. </code></pre>
  429. <h5 id="centosfedora"><a class="header" href="#centosfedora">CentOS/Fedora</a></h5>
  430. <p>Installing prerequisites on CentOS or Fedora Linux:</p>
  431. <pre><code class="language-sh">sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
  432. libwebp-devel libxml2-devel libxslt-devel libpq-devel \
  433. python3-virtualenv libffi-devel openssl-devel python3-devel \
  434. libicu-devel
  435. sudo dnf groupinstall &quot;Development Tools&quot;
  436. </code></pre>
  437. <h5 id="macos"><a class="header" href="#macos">macOS</a></h5>
  438. <p>Installing prerequisites on macOS:</p>
  439. <p>You may need to install the latest Xcode developer tools:</p>
  440. <pre><code class="language-sh">xcode-select --install
  441. </code></pre>
  442. <p>Some extra dependencies may be needed. You can use Homebrew (https://brew.sh) for them.</p>
  443. <p>You may need to install icu, and make the icu binaries and libraries accessible.
  444. Please follow <a href="https://pypi.org/project/PyICU/">the official instructions of PyICU</a> to do so.</p>
  445. <p>On ARM-based Macs you may also need to install libjpeg and libpq:</p>
  446. <pre><code class="language-sh"> brew install jpeg libpq
  447. </code></pre>
  448. <p>On macOS Catalina (10.15) you may need to explicitly install OpenSSL
  449. via brew and inform <code>pip</code> about it so that <code>psycopg2</code> builds:</p>
  450. <pre><code class="language-sh">brew install openssl@1.1
  451. export LDFLAGS=&quot;-L/usr/local/opt/openssl/lib&quot;
  452. export CPPFLAGS=&quot;-I/usr/local/opt/openssl/include&quot;
  453. </code></pre>
  454. <h5 id="opensuse-1"><a class="header" href="#opensuse-1">OpenSUSE</a></h5>
  455. <p>Installing prerequisites on openSUSE:</p>
  456. <pre><code class="language-sh">sudo zypper in -t pattern devel_basis
  457. sudo zypper in python-pip python-setuptools sqlite3 python-virtualenv \
  458. python-devel libffi-devel libopenssl-devel libjpeg62-devel \
  459. libicu-devel
  460. </code></pre>
  461. <h5 id="openbsd-1"><a class="header" href="#openbsd-1">OpenBSD</a></h5>
  462. <p>A port of Synapse is available under <code>net/synapse</code>. The filesystem
  463. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  464. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  465. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  466. <p>To be able to build Synapse's dependency on python the <code>WRKOBJDIR</code>
  467. (cf. <code>bsd.port.mk(5)</code>) for building python, too, needs to be on a filesystem
  468. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>).</p>
  469. <p>Creating a <code>WRKOBJDIR</code> for building python under <code>/usr/local</code> (which on a
  470. default OpenBSD installation is mounted with <code>wxallowed</code>):</p>
  471. <pre><code class="language-sh">doas mkdir /usr/local/pobj_wxallowed
  472. </code></pre>
  473. <p>Assuming <code>PORTS_PRIVSEP=Yes</code> (cf. <code>bsd.port.mk(5)</code>) and <code>SUDO=doas</code> are
  474. configured in <code>/etc/mk.conf</code>:</p>
  475. <pre><code class="language-sh">doas chown _pbuild:_pbuild /usr/local/pobj_wxallowed
  476. </code></pre>
  477. <p>Setting the <code>WRKOBJDIR</code> for building python:</p>
  478. <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
  479. </code></pre>
  480. <p>Building Synapse:</p>
  481. <pre><code class="language-sh">cd /usr/ports/net/synapse
  482. make install
  483. </code></pre>
  484. <h5 id="windows"><a class="header" href="#windows">Windows</a></h5>
  485. <p>Running Synapse natively on Windows is not officially supported.</p>
  486. <p>If you wish to run or develop Synapse on Windows, the Windows Subsystem for
  487. Linux provides a Linux environment which is capable of using the Debian, Fedora,
  488. or source installation methods. More information about WSL can be found at
  489. <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
  490. <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
  491. Windows Server.</p>
  492. <h2 id="setting-up-synapse"><a class="header" href="#setting-up-synapse">Setting up Synapse</a></h2>
  493. <p>Once you have installed synapse as above, you will need to configure it.</p>
  494. <h3 id="using-postgresql"><a class="header" href="#using-postgresql">Using PostgreSQL</a></h3>
  495. <p>By default Synapse uses an <a href="https://sqlite.org/">SQLite</a> database and in doing so trades
  496. performance for convenience. Almost all installations should opt to use <a href="https://www.postgresql.org">PostgreSQL</a>
  497. instead. Advantages include:</p>
  498. <ul>
  499. <li>significant performance improvements due to the superior threading and
  500. caching model, smarter query optimiser</li>
  501. <li>allowing the DB to be run on separate hardware</li>
  502. </ul>
  503. <p>For information on how to install and use PostgreSQL in Synapse, please see
  504. <a href="setup/../postgres.html">Using Postgres</a></p>
  505. <p>SQLite is only acceptable for testing purposes. SQLite should not be used in
  506. a production server. Synapse will perform poorly when using
  507. SQLite, especially when participating in large rooms.</p>
  508. <h3 id="tls-certificates"><a class="header" href="#tls-certificates">TLS certificates</a></h3>
  509. <p>The default configuration exposes a single HTTP port on the local
  510. interface: <code>http://localhost:8008</code>. It is suitable for local testing,
  511. but for any practical use, you will need Synapse's APIs to be served
  512. over HTTPS.</p>
  513. <p>The recommended way to do so is to set up a reverse proxy on port
  514. <code>8448</code>. You can find documentation on doing so in
  515. <a href="setup/../reverse_proxy.html">the reverse proxy documentation</a>.</p>
  516. <p>Alternatively, you can configure Synapse to expose an HTTPS port. To do
  517. so, you will need to edit <code>homeserver.yaml</code>, as follows:</p>
  518. <ul>
  519. <li>First, under the <code>listeners</code> option, add the configuration for the
  520. TLS-enabled listener like so:</li>
  521. </ul>
  522. <pre><code class="language-yaml">listeners:
  523. - port: 8448
  524. type: http
  525. tls: true
  526. resources:
  527. - names: [client, federation]
  528. </code></pre>
  529. <ul>
  530. <li>
  531. <p>You will also need to add the options <code>tls_certificate_path</code> and
  532. <code>tls_private_key_path</code>. to your configuration file. You will need to manage provisioning of
  533. these certificates yourself.</p>
  534. </li>
  535. <li>
  536. <p>You can find more information about these options as well as how to configure synapse in the
  537. <a href="setup/../usage/configuration/config_documentation.html">configuration manual</a>.</p>
  538. <p>If you are using your own certificate, be sure to use a <code>.pem</code> file that
  539. includes the full certificate chain including any intermediate certificates
  540. (for instance, if using certbot, use <code>fullchain.pem</code> as your certificate, not
  541. <code>cert.pem</code>).</p>
  542. </li>
  543. </ul>
  544. <p>For a more detailed guide to configuring your server for federation, see
  545. <a href="setup/../federate.html">Federation</a>.</p>
  546. <h3 id="client-well-known-uri"><a class="header" href="#client-well-known-uri">Client Well-Known URI</a></h3>
  547. <p>Setting up the client Well-Known URI is optional but if you set it up, it will
  548. allow users to enter their full username (e.g. <code>@user:&lt;server_name&gt;</code>) into clients
  549. which support well-known lookup to automatically configure the homeserver and
  550. identity server URLs. This is useful so that users don't have to memorize or think
  551. about the actual homeserver URL you are using.</p>
  552. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/client</code> should return JSON in
  553. the following format.</p>
  554. <pre><code class="language-json">{
  555. &quot;m.homeserver&quot;: {
  556. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  557. }
  558. }
  559. </code></pre>
  560. <p>It can optionally contain identity server information as well.</p>
  561. <pre><code class="language-json">{
  562. &quot;m.homeserver&quot;: {
  563. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  564. },
  565. &quot;m.identity_server&quot;: {
  566. &quot;base_url&quot;: &quot;https://&lt;identity.example.com&gt;&quot;
  567. }
  568. }
  569. </code></pre>
  570. <p>To work in browser based clients, the file must be served with the appropriate
  571. Cross-Origin Resource Sharing (CORS) headers. A recommended value would be
  572. <code>Access-Control-Allow-Origin: *</code> which would allow all browser based clients to
  573. view it.</p>
  574. <p>In nginx this would be something like:</p>
  575. <pre><code class="language-nginx">location /.well-known/matrix/client {
  576. return 200 '{&quot;m.homeserver&quot;: {&quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;}}';
  577. default_type application/json;
  578. add_header Access-Control-Allow-Origin *;
  579. }
  580. </code></pre>
  581. <p>You should also ensure the <code>public_baseurl</code> option in <code>homeserver.yaml</code> is set
  582. correctly. <code>public_baseurl</code> should be set to the URL that clients will use to
  583. connect to your server. This is the same URL you put for the <code>m.homeserver</code>
  584. <code>base_url</code> above.</p>
  585. <pre><code class="language-yaml">public_baseurl: &quot;https://&lt;matrix.example.com&gt;&quot;
  586. </code></pre>
  587. <h3 id="email"><a class="header" href="#email">Email</a></h3>
  588. <p>It is desirable for Synapse to have the capability to send email. This allows
  589. Synapse to send password reset emails, send verifications when an email address
  590. is added to a user's account, and send email notifications to users when they
  591. receive new messages.</p>
  592. <p>To configure an SMTP server for Synapse, modify the configuration section
  593. headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>, <code>smtp_port</code>
  594. and <code>notif_from</code> fields filled out. You may also need to set <code>smtp_user</code>,
  595. <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  596. <p>If email is not configured, password reset, registration and notifications via
  597. email will be disabled.</p>
  598. <h3 id="registering-a-user"><a class="header" href="#registering-a-user">Registering a user</a></h3>
  599. <p>One way to create a new user is to do so from a client like
  600. <a href="https://element.io/">Element</a>. This requires registration to be enabled via
  601. the
  602. <a href="setup/../usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a>
  603. setting.</p>
  604. <p>Alternatively, you can create new users from the command line. This can be done as follows:</p>
  605. <ol>
  606. <li>If synapse was installed via pip, activate the virtualenv as follows (if Synapse was
  607. installed via a prebuilt package, <code>register_new_matrix_user</code> should already be
  608. on the search path):
  609. <pre><code class="language-sh">cd ~/synapse
  610. source env/bin/activate
  611. synctl start # if not already running
  612. </code></pre>
  613. </li>
  614. <li>Run the following command:
  615. <pre><code class="language-sh">register_new_matrix_user -c homeserver.yaml
  616. </code></pre>
  617. </li>
  618. </ol>
  619. <p>This will prompt you to add details for the new user, and will then connect to
  620. the running Synapse to create the new user. For example:</p>
  621. <pre><code>New user localpart: erikj
  622. Password:
  623. Confirm password:
  624. Make admin [no]:
  625. Success!
  626. </code></pre>
  627. <p>This process uses a setting
  628. <a href="setup/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>,
  629. which is shared between Synapse itself and the <code>register_new_matrix_user</code>
  630. script. It doesn't matter what it is (a random value is generated by
  631. <code>--generate-config</code>), but it should be kept secret, as anyone with knowledge of
  632. it can register users, including admin accounts, on your server even if
  633. <code>enable_registration</code> is <code>false</code>.</p>
  634. <h3 id="setting-up-a-turn-server"><a class="header" href="#setting-up-a-turn-server">Setting up a TURN server</a></h3>
  635. <p>For reliable VoIP calls to be routed via this homeserver, you MUST configure
  636. a TURN server. See <a href="setup/../turn-howto.html">TURN setup</a> for details.</p>
  637. <h3 id="url-previews"><a class="header" href="#url-previews">URL previews</a></h3>
  638. <p>Synapse includes support for previewing URLs, which is disabled by default. To
  639. turn it on you must enable the <code>url_preview_enabled: True</code> config parameter
  640. and explicitly specify the IP ranges that Synapse is not allowed to spider for
  641. previewing in the <code>url_preview_ip_range_blacklist</code> configuration parameter.
  642. This is critical from a security perspective to stop arbitrary Matrix users
  643. spidering 'internal' URLs on your network. At the very least we recommend that
  644. your loopback and RFC1918 IP addresses are blacklisted.</p>
  645. <p>This also requires the optional <code>lxml</code> python dependency to be installed. This
  646. in turn requires the <code>libxml2</code> library to be available - on Debian/Ubuntu this
  647. means <code>apt-get install libxml2-dev</code>, or equivalent for your OS.</p>
  648. <h3 id="troubleshooting-installation"><a class="header" href="#troubleshooting-installation">Troubleshooting Installation</a></h3>
  649. <p><code>pip</code> seems to leak <em>lots</em> of memory during installation. For instance, a Linux
  650. host with 512MB of RAM may run out of memory whilst installing Twisted. If this
  651. happens, you will have to individually install the dependencies which are
  652. failing, e.g.:</p>
  653. <pre><code class="language-sh">pip install twisted
  654. </code></pre>
  655. <p>If you have any other problems, feel free to ask in
  656. <a href="https://matrix.to/#/#synapse:matrix.org">#synapse:matrix.org</a>.</p>
  657. <div style="break-before: page; page-break-before: always;"></div><h1 id="using-postgres"><a class="header" href="#using-postgres">Using Postgres</a></h1>
  658. <p>The minimum supported version of PostgreSQL is determined by the <a href="deprecation_policy.html">Dependency
  659. Deprecation Policy</a>.</p>
  660. <h2 id="install-postgres-client-libraries"><a class="header" href="#install-postgres-client-libraries">Install postgres client libraries</a></h2>
  661. <p>Synapse will require the python postgres client library in order to
  662. connect to a postgres database.</p>
  663. <ul>
  664. <li>
  665. <p>If you are using the <a href="setup/installation.html#matrixorg-packages">matrix.org debian/ubuntu
  666. packages</a>, the necessary python
  667. library will already be installed, but you will need to ensure the
  668. low-level postgres library is installed, which you can do with
  669. <code>apt install libpq5</code>.</p>
  670. </li>
  671. <li>
  672. <p>For other pre-built packages, please consult the documentation from
  673. the relevant package.</p>
  674. </li>
  675. <li>
  676. <p>If you installed synapse <a href="setup/installation.html#installing-as-a-python-module-from-pypi">in a
  677. virtualenv</a>, you can install
  678. the library with:</p>
  679. <pre><code>~/synapse/env/bin/pip install &quot;matrix-synapse[postgres]&quot;
  680. </code></pre>
  681. <p>(substituting the path to your virtualenv for <code>~/synapse/env</code>, if
  682. you used a different path). You will require the postgres
  683. development files. These are in the <code>libpq-dev</code> package on
  684. Debian-derived distributions.</p>
  685. </li>
  686. </ul>
  687. <h2 id="set-up-database"><a class="header" href="#set-up-database">Set up database</a></h2>
  688. <p>Assuming your PostgreSQL database user is called <code>postgres</code>, first authenticate as the database user with:</p>
  689. <pre><code class="language-sh">su - postgres
  690. # Or, if your system uses sudo to get administrative rights
  691. sudo -u postgres bash
  692. </code></pre>
  693. <p>Then, create a postgres user and a database with:</p>
  694. <pre><code class="language-sh"># this will prompt for a password for the new user
  695. createuser --pwprompt synapse_user
  696. createdb --encoding=UTF8 --locale=C --template=template0 --owner=synapse_user synapse
  697. </code></pre>
  698. <p>The above will create a user called <code>synapse_user</code>, and a database called
  699. <code>synapse</code>.</p>
  700. <p>Note that the PostgreSQL database <em>must</em> have the correct encoding set
  701. (as shown above), otherwise it will not be able to store UTF8 strings.</p>
  702. <p>You may need to enable password authentication so <code>synapse_user</code> can
  703. connect to the database. See
  704. <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>
  705. <h2 id="synapse-config"><a class="header" href="#synapse-config">Synapse config</a></h2>
  706. <p>When you are ready to start using PostgreSQL, edit the <code>database</code>
  707. section in your config file to match the following lines:</p>
  708. <pre><code class="language-yaml">database:
  709. name: psycopg2
  710. args:
  711. user: &lt;user&gt;
  712. password: &lt;pass&gt;
  713. database: &lt;db&gt;
  714. host: &lt;host&gt;
  715. cp_min: 5
  716. cp_max: 10
  717. </code></pre>
  718. <p>All key, values in <code>args</code> are passed to the <code>psycopg2.connect(..)</code>
  719. function, except keys beginning with <code>cp_</code>, which are consumed by the
  720. twisted adbapi connection pool. See the <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">libpq
  721. documentation</a>
  722. for a list of options which can be passed.</p>
  723. <p>You should consider tuning the <code>args.keepalives_*</code> options if there is any danger of
  724. the connection between your homeserver and database dropping, otherwise Synapse
  725. may block for an extended period while it waits for a response from the
  726. database server. Example values might be:</p>
  727. <pre><code class="language-yaml">database:
  728. args:
  729. # ... as above
  730. # seconds of inactivity after which TCP should send a keepalive message to the server
  731. keepalives_idle: 10
  732. # the number of seconds after which a TCP keepalive message that is not
  733. # acknowledged by the server should be retransmitted
  734. keepalives_interval: 10
  735. # the number of TCP keepalives that can be lost before the client's connection
  736. # to the server is considered dead
  737. keepalives_count: 3
  738. </code></pre>
  739. <h2 id="tuning-postgres"><a class="header" href="#tuning-postgres">Tuning Postgres</a></h2>
  740. <p>The default settings should be fine for most deployments. For larger
  741. scale deployments tuning some of the settings is recommended, details of
  742. which can be found at
  743. <a href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server">https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server</a>.</p>
  744. <p>In particular, we've found tuning the following values helpful for
  745. performance:</p>
  746. <ul>
  747. <li><code>shared_buffers</code></li>
  748. <li><code>effective_cache_size</code></li>
  749. <li><code>work_mem</code></li>
  750. <li><code>maintenance_work_mem</code></li>
  751. <li><code>autovacuum_work_mem</code></li>
  752. </ul>
  753. <p>Note that the appropriate values for those fields depend on the amount
  754. of free memory the database host has available.</p>
  755. <p>Additionally, admins of large deployments might want to consider using huge pages
  756. to help manage memory, especially when using large values of <code>shared_buffers</code>. You
  757. can read more about that <a href="https://www.postgresql.org/docs/10/kernel-resources.html#LINUX-HUGE-PAGES">here</a>.</p>
  758. <h2 id="porting-from-sqlite"><a class="header" href="#porting-from-sqlite">Porting from SQLite</a></h2>
  759. <h3 id="overview"><a class="header" href="#overview">Overview</a></h3>
  760. <p>The script <code>synapse_port_db</code> allows porting an existing synapse server
  761. backed by SQLite to using PostgreSQL. This is done in as a two phase
  762. process:</p>
  763. <ol>
  764. <li>Copy the existing SQLite database to a separate location and run
  765. the port script against that offline database.</li>
  766. <li>Shut down the server. Rerun the port script to port any data that
  767. has come in since taking the first snapshot. Restart server against
  768. the PostgreSQL database.</li>
  769. </ol>
  770. <p>The port script is designed to be run repeatedly against newer snapshots
  771. of the SQLite database file. This makes it safe to repeat step 1 if
  772. there was a delay between taking the previous snapshot and being ready
  773. to do step 2.</p>
  774. <p>It is safe to at any time kill the port script and restart it.</p>
  775. <p>However, under no circumstances should the SQLite database be <code>VACUUM</code>ed between
  776. multiple runs of the script. Doing so can lead to an inconsistent copy of your database
  777. into Postgres.
  778. To avoid accidental error, the script will check that SQLite's <code>auto_vacuum</code> mechanism
  779. is disabled, but the script is not able to protect against a manual <code>VACUUM</code> operation
  780. performed either by the administrator or by any automated task that the administrator
  781. may have configured.</p>
  782. <p>Note that the database may take up significantly more (25% - 100% more)
  783. space on disk after porting to Postgres.</p>
  784. <h3 id="using-the-port-script"><a class="header" href="#using-the-port-script">Using the port script</a></h3>
  785. <p>Firstly, shut down the currently running synapse server and copy its
  786. database file (typically <code>homeserver.db</code>) to another location. Once the
  787. copy is complete, restart synapse. For instance:</p>
  788. <pre><code class="language-sh">synctl stop
  789. cp homeserver.db homeserver.db.snapshot
  790. synctl start
  791. </code></pre>
  792. <p>Copy the old config file into a new config file:</p>
  793. <pre><code class="language-sh">cp homeserver.yaml homeserver-postgres.yaml
  794. </code></pre>
  795. <p>Edit the database section as described in the section <em>Synapse config</em>
  796. above and with the SQLite snapshot located at <code>homeserver.db.snapshot</code>
  797. simply run:</p>
  798. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db.snapshot \
  799. --postgres-config homeserver-postgres.yaml
  800. </code></pre>
  801. <p>The flag <code>--curses</code> displays a coloured curses progress UI.</p>
  802. <p>If the script took a long time to complete, or time has otherwise passed
  803. since the original snapshot was taken, repeat the previous steps with a
  804. newer snapshot.</p>
  805. <p>To complete the conversion shut down the synapse server and run the port
  806. script one last time, e.g. if the SQLite database is at <code>homeserver.db</code>
  807. run:</p>
  808. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db \
  809. --postgres-config homeserver-postgres.yaml
  810. </code></pre>
  811. <p>Once that has completed, change the synapse config to point at the
  812. PostgreSQL database configuration file <code>homeserver-postgres.yaml</code>:</p>
  813. <pre><code class="language-sh">synctl stop
  814. mv homeserver.yaml homeserver-old-sqlite.yaml
  815. mv homeserver-postgres.yaml homeserver.yaml
  816. synctl start
  817. </code></pre>
  818. <p>Synapse should now be running against PostgreSQL.</p>
  819. <h2 id="troubleshooting"><a class="header" href="#troubleshooting">Troubleshooting</a></h2>
  820. <h3 id="alternative-auth-methods"><a class="header" href="#alternative-auth-methods">Alternative auth methods</a></h3>
  821. <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
  822. <code>ident</code>:</p>
  823. <ul>
  824. <li>
  825. <p>If the <code>synapse_user</code> user has a password, add the password to the <code>database:</code>
  826. section of <code>homeserver.yaml</code>. Then add the following to <code>pg_hba.conf</code>:</p>
  827. <pre><code>host synapse synapse_user ::1/128 md5 # or `scram-sha-256` instead of `md5` if you use that
  828. </code></pre>
  829. </li>
  830. <li>
  831. <p>If the <code>synapse_user</code> user does not have a password, then a password doesn't
  832. have to be added to <code>homeserver.yaml</code>. But the following does need to be added
  833. to <code>pg_hba.conf</code>:</p>
  834. <pre><code>host synapse synapse_user ::1/128 trust
  835. </code></pre>
  836. </li>
  837. </ul>
  838. <p>Note that line order matters in <code>pg_hba.conf</code>, so make sure that if you do add a
  839. new line, it is inserted before:</p>
  840. <pre><code>host all all ::1/128 ident
  841. </code></pre>
  842. <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>
  843. <p>Synapse will refuse to set up a new database if it has the wrong values of
  844. <code>COLLATE</code> and <code>CTYPE</code> set. Synapse will also refuse to start an existing database with incorrect values
  845. of <code>COLLATE</code> and <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the
  846. <code>database</code> section of the config, is set to true. Using different locales can cause issues if the locale library is updated from
  847. underneath the database, or if a different version of the locale is used on any
  848. replicas.</p>
  849. <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
  850. the correct locale parameter (as shown above). It is also possible to change the
  851. parameters on a live database and run a <code>REINDEX</code> on the entire database,
  852. however extreme care must be taken to avoid database corruption.</p>
  853. <p>Note that the above may fail with an error about duplicate rows if corruption
  854. has already occurred, and such duplicate rows will need to be manually removed.</p>
  855. <h3 id="fixing-inconsistent-sequences-error"><a class="header" href="#fixing-inconsistent-sequences-error">Fixing inconsistent sequences error</a></h3>
  856. <p>Synapse uses Postgres sequences to generate IDs for various tables. A sequence
  857. and associated table can get out of sync if, for example, Synapse has been
  858. downgraded and then upgraded again.</p>
  859. <p>To fix the issue shut down Synapse (including any and all workers) and run the
  860. SQL command included in the error message. Once done Synapse should start
  861. successfully.</p>
  862. <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>
  863. <p>It is recommended to put a reverse proxy such as
  864. <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">nginx</a>,
  865. <a href="https://httpd.apache.org/docs/current/mod/mod_proxy_http.html">Apache</a>,
  866. <a href="https://caddyserver.com/docs/quick-starts/reverse-proxy">Caddy</a>,
  867. <a href="https://www.haproxy.org/">HAProxy</a> or
  868. <a href="https://man.openbsd.org/relayd.8">relayd</a> in front of Synapse. One advantage
  869. of doing so is that it means that you can expose the default https port
  870. (443) to Matrix clients without needing to run Synapse with root
  871. privileges.</p>
  872. <p>You should configure your reverse proxy to forward requests to <code>/_matrix</code> or
  873. <code>/_synapse/client</code> to Synapse, and have it set the <code>X-Forwarded-For</code> and
  874. <code>X-Forwarded-Proto</code> request headers.</p>
  875. <p>You should remember that Matrix clients and other Matrix servers do not
  876. necessarily need to connect to your server via the same server name or
  877. port. Indeed, clients will use port 443 by default, whereas servers default to
  878. port 8448. Where these are different, we refer to the 'client port' and the
  879. 'federation port'. See <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
  880. specification</a>
  881. for more details of the algorithm used for federation connections, and
  882. <a href="delegate.html">Delegation</a> for instructions on setting up delegation.</p>
  883. <p><strong>NOTE</strong>: Your reverse proxy must not <code>canonicalise</code> or <code>normalise</code>
  884. the requested URI in any way (for example, by decoding <code>%xx</code> escapes).
  885. Beware that Apache <em>will</em> canonicalise URIs unless you specify
  886. <code>nocanon</code>.</p>
  887. <p>Let's assume that we expect clients to connect to our server at
  888. <code>https://matrix.example.com</code>, and other servers to connect at
  889. <code>https://example.com:8448</code>. The following sections detail the configuration of
  890. the reverse proxy and the homeserver.</p>
  891. <h2 id="homeserver-configuration"><a class="header" href="#homeserver-configuration">Homeserver Configuration</a></h2>
  892. <p>The HTTP configuration will need to be updated for Synapse to correctly record
  893. client IP addresses and generate redirect URLs while behind a reverse proxy. </p>
  894. <p>In <code>homeserver.yaml</code> set <code>x_forwarded: true</code> in the port 8008 section and
  895. consider setting <code>bind_addresses: ['127.0.0.1']</code> so that the server only
  896. listens to traffic on localhost. (Do not change <code>bind_addresses</code> to <code>127.0.0.1</code>
  897. when using a containerized Synapse, as that will prevent it from responding
  898. to proxied traffic.)</p>
  899. <p>Optionally, you can also set
  900. <a href="./usage/configuration/config_documentation.html#listeners"><code>request_id_header</code></a>
  901. so that the server extracts and re-uses the same request ID format that the
  902. reverse proxy is using.</p>
  903. <h2 id="reverse-proxy-configuration-examples"><a class="header" href="#reverse-proxy-configuration-examples">Reverse-proxy configuration examples</a></h2>
  904. <p><strong>NOTE</strong>: You only need one of these.</p>
  905. <h3 id="nginx"><a class="header" href="#nginx">nginx</a></h3>
  906. <pre><code class="language-nginx">server {
  907. listen 443 ssl http2;
  908. listen [::]:443 ssl http2;
  909. # For the federation port
  910. listen 8448 ssl http2 default_server;
  911. listen [::]:8448 ssl http2 default_server;
  912. server_name matrix.example.com;
  913. location ~ ^(/_matrix|/_synapse/client) {
  914. # note: do not add a path (even a single /) after the port in `proxy_pass`,
  915. # otherwise nginx will canonicalise the URI and cause signature verification
  916. # errors.
  917. proxy_pass http://localhost:8008;
  918. proxy_set_header X-Forwarded-For $remote_addr;
  919. proxy_set_header X-Forwarded-Proto $scheme;
  920. proxy_set_header Host $host;
  921. # Nginx by default only allows file uploads up to 1M in size
  922. # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
  923. client_max_body_size 50M;
  924. # Synapse responses may be chunked, which is an HTTP/1.1 feature.
  925. proxy_http_version 1.1;
  926. }
  927. }
  928. </code></pre>
  929. <h3 id="caddy-v2"><a class="header" href="#caddy-v2">Caddy v2</a></h3>
  930. <pre><code>matrix.example.com {
  931. reverse_proxy /_matrix/* localhost:8008
  932. reverse_proxy /_synapse/client/* localhost:8008
  933. }
  934. example.com:8448 {
  935. reverse_proxy localhost:8008
  936. }
  937. </code></pre>
  938. <p><a href="delegate.html">Delegation</a> example:</p>
  939. <pre><code>example.com {
  940. header /.well-known/matrix/* Content-Type application/json
  941. header /.well-known/matrix/* Access-Control-Allow-Origin *
  942. respond /.well-known/matrix/server `{&quot;m.server&quot;: &quot;matrix.example.com:443&quot;}`
  943. 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;}}`
  944. }
  945. matrix.example.com {
  946. reverse_proxy /_matrix/* localhost:8008
  947. reverse_proxy /_synapse/client/* localhost:8008
  948. }
  949. </code></pre>
  950. <h3 id="apache"><a class="header" href="#apache">Apache</a></h3>
  951. <pre><code class="language-apache">&lt;VirtualHost *:443&gt;
  952. SSLEngine on
  953. ServerName matrix.example.com
  954. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  955. AllowEncodedSlashes NoDecode
  956. ProxyPreserveHost on
  957. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  958. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  959. ProxyPass /_synapse/client http://127.0.0.1:8008/_synapse/client nocanon
  960. ProxyPassReverse /_synapse/client http://127.0.0.1:8008/_synapse/client
  961. &lt;/VirtualHost&gt;
  962. &lt;VirtualHost *:8448&gt;
  963. SSLEngine on
  964. ServerName example.com
  965. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  966. AllowEncodedSlashes NoDecode
  967. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  968. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  969. &lt;/VirtualHost&gt;
  970. </code></pre>
  971. <p><strong>NOTE</strong>: ensure the <code>nocanon</code> options are included.</p>
  972. <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>
  973. <pre><code class="language-apache">&lt;IfModule security2_module&gt;
  974. SecRuleEngine off
  975. &lt;/IfModule&gt;
  976. </code></pre>
  977. <p><strong>NOTE 3</strong>: Missing <code>ProxyPreserveHost on</code> can lead to a redirect loop.</p>
  978. <h3 id="haproxy"><a class="header" href="#haproxy">HAProxy</a></h3>
  979. <pre><code>frontend https
  980. bind *:443,[::]:443 ssl crt /etc/ssl/haproxy/ strict-sni alpn h2,http/1.1
  981. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  982. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  983. http-request set-header X-Forwarded-For %[src]
  984. # Matrix client traffic
  985. acl matrix-host hdr(host) -i matrix.example.com matrix.example.com:443
  986. acl matrix-path path_beg /_matrix
  987. acl matrix-path path_beg /_synapse/client
  988. use_backend matrix if matrix-host matrix-path
  989. frontend matrix-federation
  990. bind *:8448,[::]:8448 ssl crt /etc/ssl/haproxy/synapse.pem alpn h2,http/1.1
  991. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  992. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  993. http-request set-header X-Forwarded-For %[src]
  994. default_backend matrix
  995. backend matrix
  996. server matrix 127.0.0.1:8008
  997. </code></pre>
  998. <p><a href="delegate.html">Delegation</a> example:</p>
  999. <pre><code>frontend https
  1000. acl matrix-well-known-client-path path /.well-known/matrix/client
  1001. acl matrix-well-known-server-path path /.well-known/matrix/server
  1002. use_backend matrix-well-known-client if matrix-well-known-client-path
  1003. use_backend matrix-well-known-server if matrix-well-known-server-path
  1004. backend matrix-well-known-client
  1005. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  1006. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  1007. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  1008. 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;}}'
  1009. backend matrix-well-known-server
  1010. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  1011. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  1012. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  1013. http-request return status 200 content-type application/json string '{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}'
  1014. </code></pre>
  1015. <h3 id="relayd"><a class="header" href="#relayd">Relayd</a></h3>
  1016. <pre><code>table &lt;webserver&gt; { 127.0.0.1 }
  1017. table &lt;matrixserver&gt; { 127.0.0.1 }
  1018. http protocol &quot;https&quot; {
  1019. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1020. tls keypair &quot;example.com&quot;
  1021. match header set &quot;X-Forwarded-For&quot; value &quot;$REMOTE_ADDR&quot;
  1022. match header set &quot;X-Forwarded-Proto&quot; value &quot;https&quot;
  1023. # set CORS header for .well-known/matrix/server, .well-known/matrix/client
  1024. # httpd does not support setting headers, so do it here
  1025. match request path &quot;/.well-known/matrix/*&quot; tag &quot;matrix-cors&quot;
  1026. match response tagged &quot;matrix-cors&quot; header set &quot;Access-Control-Allow-Origin&quot; value &quot;*&quot;
  1027. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1028. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1029. # pass on non-matrix traffic to webserver
  1030. pass forward to &lt;webserver&gt;
  1031. }
  1032. relay &quot;https_traffic&quot; {
  1033. listen on egress port 443 tls
  1034. protocol &quot;https&quot;
  1035. forward to &lt;matrixserver&gt; port 8008 check tcp
  1036. forward to &lt;webserver&gt; port 8080 check tcp
  1037. }
  1038. http protocol &quot;matrix&quot; {
  1039. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1040. tls keypair &quot;example.com&quot;
  1041. block
  1042. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1043. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1044. }
  1045. relay &quot;matrix_federation&quot; {
  1046. listen on egress port 8448 tls
  1047. protocol &quot;matrix&quot;
  1048. forward to &lt;matrixserver&gt; port 8008 check tcp
  1049. }
  1050. </code></pre>
  1051. <h2 id="health-check-endpoint"><a class="header" href="#health-check-endpoint">Health check endpoint</a></h2>
  1052. <p>Synapse exposes a health check endpoint for use by reverse proxies.
  1053. Each configured HTTP listener has a <code>/health</code> endpoint which always returns
  1054. 200 OK (and doesn't get logged).</p>
  1055. <h2 id="synapse-administration-endpoints"><a class="header" href="#synapse-administration-endpoints">Synapse administration endpoints</a></h2>
  1056. <p>Endpoints for administering your Synapse instance are placed under
  1057. <code>/_synapse/admin</code>. These require authentication through an access token of an
  1058. admin user. However as access to these endpoints grants the caller a lot of power,
  1059. we do not recommend exposing them to the public internet without good reason.</p>
  1060. <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>
  1061. <p>You can use Synapse with a forward or outbound proxy. An example of when
  1062. this is necessary is in corporate environments behind a DMZ (demilitarized zone).
  1063. Synapse supports routing outbound HTTP(S) requests via a proxy. Only HTTP(S)
  1064. proxy is supported, not SOCKS proxy or anything else.</p>
  1065. <h2 id="configure"><a class="header" href="#configure">Configure</a></h2>
  1066. <p>The <code>http_proxy</code>, <code>https_proxy</code>, <code>no_proxy</code> environment variables are used to
  1067. specify proxy settings. The environment variable is not case sensitive.</p>
  1068. <ul>
  1069. <li><code>http_proxy</code>: Proxy server to use for HTTP requests.</li>
  1070. <li><code>https_proxy</code>: Proxy server to use for HTTPS requests.</li>
  1071. <li><code>no_proxy</code>: Comma-separated list of hosts, IP addresses, or IP ranges in CIDR
  1072. format which should not use the proxy. Synapse will directly connect to these hosts.</li>
  1073. </ul>
  1074. <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>
  1075. <ul>
  1076. <li>
  1077. <p>Supported schemes are <code>http://</code> and <code>https://</code>. The default scheme is <code>http://</code>
  1078. for compatibility reasons; it is recommended to set a scheme. If scheme is set
  1079. to <code>https://</code> the connection uses TLS between Synapse and the proxy.</p>
  1080. <p><strong>NOTE</strong>: Synapse validates the certificates. If the certificate is not
  1081. valid, then the connection is dropped.</p>
  1082. </li>
  1083. <li>
  1084. <p>Default port if not given is <code>1080</code>.</p>
  1085. </li>
  1086. <li>
  1087. <p>Username and password are optional and will be used to authenticate against
  1088. the proxy.</p>
  1089. </li>
  1090. </ul>
  1091. <p><strong>Examples</strong></p>
  1092. <ul>
  1093. <li>HTTP_PROXY=http://USERNAME:PASSWORD@10.0.1.1:8080/</li>
  1094. <li>HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.example.com:8080/</li>
  1095. <li>NO_PROXY=master.hostname.example.com,10.1.0.0/16,172.30.0.0/16</li>
  1096. </ul>
  1097. <p><strong>NOTE</strong>:
  1098. Synapse does not apply the IP blacklist to connections through the proxy (since
  1099. the DNS resolution is done by the proxy). It is expected that the proxy or firewall
  1100. will apply blacklisting of IP addresses.</p>
  1101. <h2 id="connection-types"><a class="header" href="#connection-types">Connection types</a></h2>
  1102. <p>The proxy will be <strong>used</strong> for:</p>
  1103. <ul>
  1104. <li>push</li>
  1105. <li>url previews</li>
  1106. <li>phone-home stats</li>
  1107. <li>recaptcha validation</li>
  1108. <li>CAS auth validation</li>
  1109. <li>OpenID Connect</li>
  1110. <li>Outbound federation</li>
  1111. <li>Federation (checking public key revocation)</li>
  1112. <li>Fetching public keys of other servers</li>
  1113. <li>Downloading remote media</li>
  1114. </ul>
  1115. <p>It will <strong>not be used</strong> for:</p>
  1116. <ul>
  1117. <li>Application Services</li>
  1118. <li>Identity servers</li>
  1119. <li>In worker configurations
  1120. <ul>
  1121. <li>connections between workers</li>
  1122. <li>connections from workers to Redis</li>
  1123. </ul>
  1124. </li>
  1125. </ul>
  1126. <h2 id="troubleshooting-1"><a class="header" href="#troubleshooting-1">Troubleshooting</a></h2>
  1127. <p>If a proxy server is used with TLS (HTTPS) and no connections are established,
  1128. it is most likely due to the proxy's certificates. To test this, the validation
  1129. in Synapse can be deactivated.</p>
  1130. <p><strong>NOTE</strong>: This has an impact on security and is for testing purposes only!</p>
  1131. <p>To deactivate the certificate validation, the following setting must be added to
  1132. your <a href="setup/../usage/configuration/homeserver_sample_config.html">homserver.yaml</a>.</p>
  1133. <pre><code class="language-yaml">use_insecure_ssl_client_just_for_testing_do_not_use: true
  1134. </code></pre>
  1135. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-1"><a class="header" href="#overview-1">Overview</a></h1>
  1136. <p>This document explains how to enable VoIP relaying on your homeserver with
  1137. TURN.</p>
  1138. <p>The synapse Matrix homeserver supports integration with TURN server via the
  1139. <a href="https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00">TURN server REST API</a>. This
  1140. allows the homeserver to generate credentials that are valid for use on the
  1141. TURN server through the use of a secret shared between the homeserver and the
  1142. TURN server.</p>
  1143. <p>This documentation provides two TURN server configuration examples:</p>
  1144. <ul>
  1145. <li><a href="setup/turn/coturn.html">coturn</a></li>
  1146. <li><a href="setup/turn/eturnal.html">eturnal</a></li>
  1147. </ul>
  1148. <h2 id="requirements"><a class="header" href="#requirements">Requirements</a></h2>
  1149. <p>For TURN relaying to work, the TURN service must be hosted on a server/endpoint with a public IP.</p>
  1150. <p>Hosting TURN behind NAT requires port forwaring and for the NAT gateway to have a public IP.
  1151. However, even with appropriate configuration, NAT is known to cause issues and to often not work.</p>
  1152. <p>Afterwards, the homeserver needs some further configuration.</p>
  1153. <h2 id="synapse-setup"><a class="header" href="#synapse-setup">Synapse setup</a></h2>
  1154. <p>Your homeserver configuration file needs the following extra keys:</p>
  1155. <ol>
  1156. <li><a href="usage/configuration/config_documentation.html#turn_uris"><code>turn_uris</code></a></li>
  1157. <li><a href="usage/configuration/config_documentation.html#turn_shared_secret"><code>turn_shared_secret</code></a></li>
  1158. <li><a href="usage/configuration/config_documentation.html#turn_user_lifetime"><code>turn_user_lifetime</code></a></li>
  1159. <li><a href="usage/configuration/config_documentation.html#turn_allow_guests"><code>turn_allow_guests</code></a></li>
  1160. </ol>
  1161. <p>As an example, here is the relevant section of the config file for <code>matrix.org</code>. The
  1162. <code>turn_uris</code> are appropriate for TURN servers listening on the default ports, with no TLS.</p>
  1163. <pre><code>turn_uris: [ &quot;turn:turn.matrix.org?transport=udp&quot;, &quot;turn:turn.matrix.org?transport=tcp&quot; ]
  1164. turn_shared_secret: &quot;n0t4ctuAllymatr1Xd0TorgSshar3d5ecret4obvIousreAsons&quot;
  1165. turn_user_lifetime: 86400000
  1166. turn_allow_guests: true
  1167. </code></pre>
  1168. <p>After updating the homeserver configuration, you must restart synapse:</p>
  1169. <ul>
  1170. <li>If you use synctl:
  1171. <pre><code class="language-sh"># Depending on how Synapse is installed, synctl may already be on
  1172. # your PATH. If not, you may need to activate a virtual environment.
  1173. synctl restart
  1174. </code></pre>
  1175. </li>
  1176. <li>If you use systemd:
  1177. <pre><code class="language-sh">systemctl restart matrix-synapse.service
  1178. </code></pre>
  1179. </li>
  1180. </ul>
  1181. <p>... and then reload any clients (or wait an hour for them to refresh their
  1182. settings).</p>
  1183. <h2 id="troubleshooting-2"><a class="header" href="#troubleshooting-2">Troubleshooting</a></h2>
  1184. <p>The normal symptoms of a misconfigured TURN server are that calls between
  1185. devices on different networks ring, but get stuck at &quot;call
  1186. connecting&quot;. Unfortunately, troubleshooting this can be tricky.</p>
  1187. <p>Here are a few things to try:</p>
  1188. <ul>
  1189. <li>
  1190. <p>Check that you have opened your firewall to allow TCP and UDP traffic to the
  1191. TURN ports (normally 3478 and 5349).</p>
  1192. </li>
  1193. <li>
  1194. <p>Check that you have opened your firewall to allow UDP traffic to the UDP
  1195. relay ports (49152-65535 by default).</p>
  1196. </li>
  1197. <li>
  1198. <p>Try disabling TLS/DTLS listeners and enable only its (unencrypted)
  1199. TCP/UDP listeners. (This will only leave signaling traffic unencrypted;
  1200. voice &amp; video WebRTC traffic is always encrypted.)</p>
  1201. </li>
  1202. <li>
  1203. <p>Some WebRTC implementations (notably, that of Google Chrome) appear to get
  1204. confused by TURN servers which are reachable over IPv6 (this appears to be
  1205. an unexpected side-effect of its handling of multiple IP addresses as
  1206. defined by
  1207. <a href="https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12"><code>draft-ietf-rtcweb-ip-handling</code></a>).</p>
  1208. <p>Try removing any AAAA records for your TURN server, so that it is only
  1209. reachable over IPv4.</p>
  1210. </li>
  1211. <li>
  1212. <p>If your TURN server is behind NAT:</p>
  1213. <ul>
  1214. <li>
  1215. <p>double-check that your NAT gateway is correctly forwarding all TURN
  1216. ports (normally 3478 &amp; 5349 for TCP &amp; UDP TURN traffic, and 49152-65535 for the UDP
  1217. relay) to the NAT-internal address of your TURN server. If advertising
  1218. both IPv4 and IPv6 external addresses via the <code>external-ip</code> option, ensure
  1219. that the NAT is forwarding both IPv4 and IPv6 traffic to the IPv4 and IPv6
  1220. internal addresses of your TURN server. When in doubt, remove AAAA records
  1221. for your TURN server and specify only an IPv4 address as your <code>external-ip</code>.</p>
  1222. </li>
  1223. <li>
  1224. <p>ensure that your TURN server uses the NAT gateway as its default route.</p>
  1225. </li>
  1226. </ul>
  1227. </li>
  1228. <li>
  1229. <p>Enable more verbose logging, in <code>coturn</code> via the <code>verbose</code> setting:</p>
  1230. <pre><code>verbose
  1231. </code></pre>
  1232. <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>
  1233. <pre><code class="language-yaml"> ## Logging configuration:
  1234. log_level: debug
  1235. </code></pre>
  1236. <p>... and then see if there are any clues in its logs.</p>
  1237. </li>
  1238. <li>
  1239. <p>If you are using a browser-based client under Chrome, check
  1240. <code>chrome://webrtc-internals/</code> for insights into the internals of the
  1241. negotiation. On Firefox, check the &quot;Connection Log&quot; on <code>about:webrtc</code>.</p>
  1242. <p>(Understanding the output is beyond the scope of this document!)</p>
  1243. </li>
  1244. <li>
  1245. <p>You can test your Matrix homeserver TURN setup with <a href="https://test.voip.librepush.net/">https://test.voip.librepush.net/</a>.
  1246. Note that this test is not fully reliable yet, so don't be discouraged if
  1247. the test fails.
  1248. <a href="https://github.com/matrix-org/voip-tester">Here</a> is the github repo of the
  1249. source of the tester, where you can file bug reports.</p>
  1250. </li>
  1251. <li>
  1252. <p>There is a WebRTC test tool at
  1253. <a href="https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/">https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/</a>. To
  1254. use it, you will need a username/password for your TURN server. You can
  1255. either:</p>
  1256. <ul>
  1257. <li>
  1258. <p>look for the <code>GET /_matrix/client/r0/voip/turnServer</code> request made by a
  1259. matrix client to your homeserver in your browser's network inspector. In
  1260. the response you should see <code>username</code> and <code>password</code>. Or:</p>
  1261. </li>
  1262. <li>
  1263. <p>Use the following shell commands for <code>coturn</code>:</p>
  1264. <pre><code class="language-sh">secret=staticAuthSecretHere
  1265. u=$((`date +%s` + 3600)):test
  1266. p=$(echo -n $u | openssl dgst -hmac $secret -sha1 -binary | base64)
  1267. echo -e &quot;username: $u\npassword: $p&quot;
  1268. </code></pre>
  1269. <p>or for <code>eturnal</code></p>
  1270. <pre><code class="language-sh">eturnalctl credentials
  1271. </code></pre>
  1272. </li>
  1273. <li>
  1274. <p>Or (<strong>coturn only</strong>): Temporarily configure <code>coturn</code> to accept a static
  1275. username/password. To do this, comment out <code>use-auth-secret</code> and
  1276. <code>static-auth-secret</code> and add the following:</p>
  1277. <pre><code>lt-cred-mech
  1278. user=username:password
  1279. </code></pre>
  1280. <p><strong>Note</strong>: these settings will not take effect unless <code>use-auth-secret</code>
  1281. and <code>static-auth-secret</code> are disabled.</p>
  1282. <p>Restart coturn after changing the configuration file.</p>
  1283. <p>Remember to restore the original settings to go back to testing with
  1284. Matrix clients!</p>
  1285. </li>
  1286. </ul>
  1287. <p>If the TURN server is working correctly, you should see at least one <code>relay</code>
  1288. entry in the results.</p>
  1289. </li>
  1290. </ul>
  1291. <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>
  1292. <p>The following sections describe how to install <a href="https://github.com/coturn/coturn">coturn</a> (which implements the TURN REST API).</p>
  1293. <h2 id="coturn-setup"><a class="header" href="#coturn-setup"><code>coturn</code> setup</a></h2>
  1294. <h3 id="initial-installation"><a class="header" href="#initial-installation">Initial installation</a></h3>
  1295. <p>The TURN daemon <code>coturn</code> is available from a variety of sources such as native package managers, or installation from source.</p>
  1296. <h4 id="debian-and-ubuntu-based-distributions"><a class="header" href="#debian-and-ubuntu-based-distributions">Debian and Ubuntu based distributions</a></h4>
  1297. <p>Just install the debian package:</p>
  1298. <pre><code class="language-sh">sudo apt install coturn
  1299. </code></pre>
  1300. <p>This will install and start a systemd service called <code>coturn</code>.</p>
  1301. <h4 id="source-installation"><a class="header" href="#source-installation">Source installation</a></h4>
  1302. <ol>
  1303. <li>
  1304. <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>
  1305. </li>
  1306. <li>
  1307. <p>Configure it:</p>
  1308. <pre><code class="language-sh">./configure
  1309. </code></pre>
  1310. <p>You may need to install <code>libevent2</code>: if so, you should do so in
  1311. the way recommended by your operating system. You can ignore
  1312. warnings about lack of database support: a database is unnecessary
  1313. for this purpose.</p>
  1314. </li>
  1315. <li>
  1316. <p>Build and install it:</p>
  1317. <pre><code class="language-sh">make
  1318. sudo make install
  1319. </code></pre>
  1320. </li>
  1321. </ol>
  1322. <h3 id="configuration"><a class="header" href="#configuration">Configuration</a></h3>
  1323. <ol>
  1324. <li>
  1325. <p>Create or edit the config file in <code>/etc/turnserver.conf</code>. The relevant
  1326. lines, with example values, are:</p>
  1327. <pre><code>use-auth-secret
  1328. static-auth-secret=[your secret key here]
  1329. realm=turn.myserver.org
  1330. </code></pre>
  1331. <p>See <code>turnserver.conf</code> for explanations of the options. One way to generate
  1332. the <code>static-auth-secret</code> is with <code>pwgen</code>:</p>
  1333. <pre><code class="language-sh">pwgen -s 64 1
  1334. </code></pre>
  1335. <p>A <code>realm</code> must be specified, but its value is somewhat arbitrary. (It is
  1336. sent to clients as part of the authentication flow.) It is conventional to
  1337. set it to be your server name.</p>
  1338. </li>
  1339. <li>
  1340. <p>You will most likely want to configure <code>coturn</code> to write logs somewhere. The
  1341. easiest way is normally to send them to the syslog:</p>
  1342. <pre><code class="language-sh">syslog
  1343. </code></pre>
  1344. <p>(in which case, the logs will be available via <code>journalctl -u coturn</code> on a
  1345. systemd system). Alternatively, <code>coturn</code> can be configured to write to a
  1346. logfile - check the example config file supplied with <code>coturn</code>.</p>
  1347. </li>
  1348. <li>
  1349. <p>Consider your security settings. TURN lets users request a relay which will
  1350. connect to arbitrary IP addresses and ports. The following configuration is
  1351. suggested as a minimum starting point:</p>
  1352. <pre><code># VoIP traffic is all UDP. There is no reason to let users connect to arbitrary TCP endpoints via the relay.
  1353. no-tcp-relay
  1354. # don't let the relay ever try to connect to private IP address ranges within your network (if any)
  1355. # given the turn server is likely behind your firewall, remember to include any privileged public IPs too.
  1356. denied-peer-ip=10.0.0.0-10.255.255.255
  1357. denied-peer-ip=192.168.0.0-192.168.255.255
  1358. denied-peer-ip=172.16.0.0-172.31.255.255
  1359. # recommended additional local peers to block, to mitigate external access to internal services.
  1360. # https://www.rtcsec.com/article/slack-webrtc-turn-compromise-and-bug-bounty/#how-to-fix-an-open-turn-relay-to-address-this-vulnerability
  1361. no-multicast-peers
  1362. denied-peer-ip=0.0.0.0-0.255.255.255
  1363. denied-peer-ip=100.64.0.0-100.127.255.255
  1364. denied-peer-ip=127.0.0.0-127.255.255.255
  1365. denied-peer-ip=169.254.0.0-169.254.255.255
  1366. denied-peer-ip=192.0.0.0-192.0.0.255
  1367. denied-peer-ip=192.0.2.0-192.0.2.255
  1368. denied-peer-ip=192.88.99.0-192.88.99.255
  1369. denied-peer-ip=198.18.0.0-198.19.255.255
  1370. denied-peer-ip=198.51.100.0-198.51.100.255
  1371. denied-peer-ip=203.0.113.0-203.0.113.255
  1372. denied-peer-ip=240.0.0.0-255.255.255.255
  1373. # special case the turn server itself so that client-&gt;TURN-&gt;TURN-&gt;client flows work
  1374. # this should be one of the turn server's listening IPs
  1375. allowed-peer-ip=10.0.0.1
  1376. # consider whether you want to limit the quota of relayed streams per user (or total) to avoid risk of DoS.
  1377. user-quota=12 # 4 streams per video call, so 12 streams = 3 simultaneous relayed calls per user.
  1378. total-quota=1200
  1379. </code></pre>
  1380. </li>
  1381. <li>
  1382. <p>Also consider supporting TLS/DTLS. To do this, add the following settings
  1383. to <code>turnserver.conf</code>:</p>
  1384. <pre><code># TLS certificates, including intermediate certs.
  1385. # For Let's Encrypt certificates, use `fullchain.pem` here.
  1386. cert=/path/to/fullchain.pem
  1387. # TLS private key file
  1388. pkey=/path/to/privkey.pem
  1389. # Ensure the configuration lines that disable TLS/DTLS are commented-out or removed
  1390. #no-tls
  1391. #no-dtls
  1392. </code></pre>
  1393. <p>In this case, replace the <code>turn:</code> schemes in the <code>turn_uris</code> settings below
  1394. with <code>turns:</code>.</p>
  1395. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1396. basic installation and got it working.</p>
  1397. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1398. not work with any Matrix client that uses Chromium's WebRTC library. This
  1399. currently includes Element Android &amp; iOS; for more details, see their
  1400. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1401. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1402. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1403. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1404. </li>
  1405. <li>
  1406. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1407. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1408. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1409. for the UDP relay.)</p>
  1410. </li>
  1411. <li>
  1412. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1413. publicly-reachable IP address. You must configure <code>coturn</code> to advertise that
  1414. address to connecting clients:</p>
  1415. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1416. </code></pre>
  1417. <p>You may optionally limit the TURN server to listen only on the local
  1418. address that is mapped by NAT to the external address:</p>
  1419. <pre><code>listening-ip=INTERNAL_TURNSERVER_IPv4_ADDRESS
  1420. </code></pre>
  1421. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1422. configure <code>coturn</code> to advertise each available address:</p>
  1423. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1424. external-ip=EXTERNAL_NAT_IPv6_ADDRESS
  1425. </code></pre>
  1426. <p>When advertising an external IPv6 address, ensure that the firewall and
  1427. network settings of the system running your TURN server are configured to
  1428. accept IPv6 traffic, and that the TURN server is listening on the local
  1429. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1430. </li>
  1431. <li>
  1432. <p>(Re)start the turn server:</p>
  1433. <ul>
  1434. <li>
  1435. <p>If you used the Debian package (or have set up a systemd unit yourself):</p>
  1436. <pre><code class="language-sh">sudo systemctl restart coturn
  1437. </code></pre>
  1438. </li>
  1439. <li>
  1440. <p>If you built from source:</p>
  1441. <pre><code class="language-sh">/usr/local/bin/turnserver -o
  1442. </code></pre>
  1443. </li>
  1444. </ul>
  1445. </li>
  1446. </ol>
  1447. <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>
  1448. <p>The following sections describe how to install <a href="https://github.com/processone/eturnal">eturnal</a>
  1449. (which implements the TURN REST API).</p>
  1450. <h2 id="eturnal-setup"><a class="header" href="#eturnal-setup"><code>eturnal</code> setup</a></h2>
  1451. <h3 id="initial-installation-1"><a class="header" href="#initial-installation-1">Initial installation</a></h3>
  1452. <p>The <code>eturnal</code> TURN server implementation is available from a variety of sources
  1453. such as native package managers, binary packages, installation from source or
  1454. <a href="https://eturnal.net/documentation/code/docker.html">container image</a>. They are
  1455. all described <a href="https://github.com/processone/eturnal#installation">here</a>.</p>
  1456. <p>Quick-Test instructions in a <a href="https://github.com/processone/eturnal/blob/master/QUICK-TEST.md">Linux Shell</a>
  1457. or with <a href="https://github.com/processone/eturnal/blob/master/docker-k8s/QUICK-TEST.md">Docker</a>
  1458. are available as well.</p>
  1459. <h3 id="configuration-1"><a class="header" href="#configuration-1">Configuration</a></h3>
  1460. <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>
  1461. here: <code>/etc/eturnal.yml</code> (and, if not found there, there is a backup file here:
  1462. <code>/opt/eturnal/etc/eturnal.yml</code>). It uses the (indentation-sensitive!) <a href="https://en.wikipedia.org/wiki/YAML">YAML</a>
  1463. format. The file contains further explanations.</p>
  1464. <p>Here are some hints how to configure eturnal on your <a href="https://github.com/processone/eturnal#configuration">host machine</a>
  1465. or when using e.g. <a href="https://eturnal.net/documentation/code/docker.html">Docker</a>.
  1466. You may also further deep dive into the <a href="https://eturnal.net/documentation/">reference documentation</a>.</p>
  1467. <p><code>eturnal</code> runs out of the box with the default configuration. To enable TURN and
  1468. to integrate it with your homeserver, some aspects in <code>eturnal</code>'s default configuration file
  1469. must be edited:</p>
  1470. <ol>
  1471. <li>
  1472. <p>Homeserver's <a href="setup/turn/../../usage/configuration/config_documentation.html#turn_shared_secret"><code>turn_shared_secret</code></a>
  1473. and eturnal's shared <code>secret</code> for authentication</p>
  1474. <p>Both need to have the same value. Uncomment and adjust this line in <code>eturnal</code>'s
  1475. configuration file:</p>
  1476. <pre><code class="language-yaml">secret: &quot;long-and-cryptic&quot; # Shared secret, CHANGE THIS.
  1477. </code></pre>
  1478. <p>One way to generate a <code>secret</code> is with <code>pwgen</code>:</p>
  1479. <pre><code class="language-sh">pwgen -s 64 1
  1480. </code></pre>
  1481. </li>
  1482. <li>
  1483. <p>Public IP address</p>
  1484. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1485. publicly-reachable IP address. <code>eturnal</code> tries to autodetect the public IP address,
  1486. however, it may also be configured by uncommenting and adjusting this line, so
  1487. <code>eturnal</code> advertises that address to connecting clients:</p>
  1488. <pre><code class="language-yaml">relay_ipv4_addr: &quot;203.0.113.4&quot; # The server's public IPv4 address.
  1489. </code></pre>
  1490. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1491. configure <code>eturnal</code> to advertise each available address:</p>
  1492. <pre><code class="language-yaml">relay_ipv4_addr: &quot;203.0.113.4&quot; # The server's public IPv4 address.
  1493. relay_ipv6_addr: &quot;2001:db8::4&quot; # The server's public IPv6 address (optional).
  1494. </code></pre>
  1495. <p>When advertising an external IPv6 address, ensure that the firewall and
  1496. network settings of the system running your TURN server are configured to
  1497. accept IPv6 traffic, and that the TURN server is listening on the local
  1498. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1499. </li>
  1500. <li>
  1501. <p>Logging</p>
  1502. <p>If <code>eturnal</code> was started by systemd, log files are written into the
  1503. <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>
  1504. instead, the <code>log_dir</code> option can be set to <code>stdout</code> in the configuration file.</p>
  1505. </li>
  1506. <li>
  1507. <p>Security considerations</p>
  1508. <p>Consider your security settings. TURN lets users request a relay which will
  1509. connect to arbitrary IP addresses and ports. The following configuration is
  1510. suggested as a minimum starting point, <a href="https://eturnal.net/documentation/#blacklist">see also the official documentation</a>:</p>
  1511. <pre><code class="language-yaml">## Reject TURN relaying from/to the following addresses/networks:
  1512. blacklist: # This is the default blacklist.
  1513. - &quot;127.0.0.0/8&quot; # IPv4 loopback.
  1514. - &quot;::1&quot; # IPv6 loopback.
  1515. - recommended # Expands to a number of networks recommended to be
  1516. # blocked, but includes private networks. Those
  1517. # would have to be 'whitelist'ed if eturnal serves
  1518. # local clients/peers within such networks.
  1519. </code></pre>
  1520. <p>To whitelist IP addresses or specific (private) networks, you need to <strong>add</strong> a
  1521. whitelist part into the configuration file, e.g.:</p>
  1522. <pre><code class="language-yaml">whitelist:
  1523. - &quot;192.168.0.0/16&quot;
  1524. - &quot;203.0.113.113&quot;
  1525. - &quot;2001:db8::/64&quot;
  1526. </code></pre>
  1527. <p>The more specific, the better.</p>
  1528. </li>
  1529. <li>
  1530. <p>TURNS (TURN via TLS/DTLS)</p>
  1531. <p>Also consider supporting TLS/DTLS. To do this, adjust the following settings
  1532. in the <code>eturnal.yml</code> configuration file (TLS parts should not be commented anymore):</p>
  1533. <pre><code class="language-yaml">listen:
  1534. - ip: &quot;::&quot;
  1535. port: 3478
  1536. transport: udp
  1537. - ip: &quot;::&quot;
  1538. port: 3478
  1539. transport: tcp
  1540. - ip: &quot;::&quot;
  1541. port: 5349
  1542. transport: tls
  1543. ## TLS certificate/key files (must be readable by 'eturnal' user!):
  1544. tls_crt_file: /etc/eturnal/tls/crt.pem
  1545. tls_key_file: /etc/eturnal/tls/key.pem
  1546. </code></pre>
  1547. <p>In this case, replace the <code>turn:</code> schemes in homeserver's <code>turn_uris</code> settings
  1548. with <code>turns:</code>. More is described <a href="setup/turn/../../usage/configuration/config_documentation.html#turn_uris">here</a>.</p>
  1549. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1550. basic installation and got it working.</p>
  1551. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1552. not work with any Matrix client that uses Chromium's WebRTC library. This
  1553. currently includes Element Android &amp; iOS; for more details, see their
  1554. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1555. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1556. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1557. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1558. </li>
  1559. <li>
  1560. <p>Firewall</p>
  1561. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1562. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1563. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1564. for the UDP relay.)</p>
  1565. </li>
  1566. <li>
  1567. <p>Reload/ restarting <code>eturnal</code></p>
  1568. <p>Changes in the configuration file require <code>eturnal</code> to reload/ restart, this
  1569. can be achieved by:</p>
  1570. <pre><code class="language-sh">eturnalctl reload
  1571. </code></pre>
  1572. <p><code>eturnal</code> performs a configuration check before actually reloading/ restarting
  1573. and provides hints, if something is not correctly configured.</p>
  1574. </li>
  1575. </ol>
  1576. <h3 id="eturnalctl-opterations-script"><a class="header" href="#eturnalctl-opterations-script">eturnalctl opterations script</a></h3>
  1577. <p><code>eturnal</code> offers a handy <a href="https://eturnal.net/documentation/#Operation">operations script</a>
  1578. which can be called e.g. to check, whether the service is up, to restart the service,
  1579. to query how many active sessions exist, to change logging behaviour and so on.</p>
  1580. <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>
  1581. <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>
  1582. <p>In the following documentation, we use the term <code>server_name</code> to refer to that setting
  1583. in your homeserver configuration file. It appears at the ends of user ids, and tells
  1584. other homeservers where they can find your server.</p>
  1585. <p>By default, other homeservers will expect to be able to reach yours via
  1586. your <code>server_name</code>, on port 8448. For example, if you set your <code>server_name</code>
  1587. to <code>example.com</code> (so that your user names look like <code>@user:example.com</code>),
  1588. other servers will try to connect to yours at <code>https://example.com:8448/</code>.</p>
  1589. <p>Delegation is a Matrix feature allowing a homeserver admin to retain a
  1590. <code>server_name</code> of <code>example.com</code> so that user IDs, room aliases, etc continue
  1591. to look like <code>*:example.com</code>, whilst having federation traffic routed
  1592. to a different server and/or port (e.g. <code>synapse.example.com:443</code>).</p>
  1593. <h2 id="well-known-delegation"><a class="header" href="#well-known-delegation">.well-known delegation</a></h2>
  1594. <p>To use this method, you need to be able to configure the server at
  1595. <code>https://&lt;server_name&gt;</code> to serve a file at
  1596. <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>. There are two ways to do this, shown below.</p>
  1597. <p>Note that the <code>.well-known</code> file is hosted on the default port for <code>https</code> (port 443).</p>
  1598. <h3 id="external-server"><a class="header" href="#external-server">External server</a></h3>
  1599. <p>For maximum flexibility, you need to configure an external server such as nginx, Apache
  1600. or HAProxy to serve the <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> file. Setting
  1601. up such a server is out of the scope of this documentation, but note that it is often
  1602. possible to configure your <a href="reverse_proxy.html">reverse proxy</a> for this.</p>
  1603. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> should be configured
  1604. return a JSON structure containing the key <code>m.server</code> like this:</p>
  1605. <pre><code class="language-json">{
  1606. &quot;m.server&quot;: &quot;&lt;synapse.server.name&gt;[:&lt;yourport&gt;]&quot;
  1607. }
  1608. </code></pre>
  1609. <p>In our example (where we want federation traffic to be routed to
  1610. <code>https://synapse.example.com</code>, on port 443), this would mean that
  1611. <code>https://example.com/.well-known/matrix/server</code> should return:</p>
  1612. <pre><code class="language-json">{
  1613. &quot;m.server&quot;: &quot;synapse.example.com:443&quot;
  1614. }
  1615. </code></pre>
  1616. <p>Note, specifying a port is optional. If no port is specified, then it defaults
  1617. to 8448.</p>
  1618. <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>
  1619. <p>If you are able to set up your domain so that <code>https://&lt;server_name&gt;</code> is routed to
  1620. Synapse (i.e., the only change needed is to direct federation traffic to port 443
  1621. instead of port 8448), then it is possible to configure Synapse to serve a suitable
  1622. <code>.well-known/matrix/server</code> file. To do so, add the following to your <code>homeserver.yaml</code>
  1623. file:</p>
  1624. <pre><code class="language-yaml">serve_server_wellknown: true
  1625. </code></pre>
  1626. <p><strong>Note</strong>: this <em>only</em> works if <code>https://&lt;server_name&gt;</code> is routed to Synapse, so is
  1627. generally not suitable if Synapse is hosted at a subdomain such as
  1628. <code>https://synapse.example.com</code>.</p>
  1629. <h2 id="srv-dns-record-delegation"><a class="header" href="#srv-dns-record-delegation">SRV DNS record delegation</a></h2>
  1630. <p>It is also possible to do delegation using a SRV DNS record. However, that is generally
  1631. not recommended, as it can be difficult to configure the TLS certificates correctly in
  1632. this case, and it offers little advantage over <code>.well-known</code> delegation.</p>
  1633. <p>Please keep in mind that server delegation is a function of server-server communication,
  1634. and as such using SRV DNS records will not cover use cases involving client-server comms.
  1635. This means setting global client settings (such as a Jitsi endpoint, or disabling
  1636. creating new rooms as encrypted by default, etc) will still require that you serve a file
  1637. from the <code>https://&lt;server_name&gt;/.well-known/</code> endpoints defined in the spec! If you are
  1638. considering using SRV DNS delegation to avoid serving files from this endpoint, consider
  1639. the impact that you will not be able to change those client-based default values globally,
  1640. and will be relegated to the featureset of the configuration of each individual client.</p>
  1641. <p>However, if you really need it, you can find some documentation on what such a
  1642. 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
  1643. specification</a>.</p>
  1644. <h2 id="delegation-faq"><a class="header" href="#delegation-faq">Delegation FAQ</a></h2>
  1645. <h3 id="when-do-i-need-delegation"><a class="header" href="#when-do-i-need-delegation">When do I need delegation?</a></h3>
  1646. <p>If your homeserver's APIs are accessible on the default federation port (8448)
  1647. and the domain your <code>server_name</code> points to, you do not need any delegation.</p>
  1648. <p>For instance, if you registered <code>example.com</code> and pointed its DNS A record at a
  1649. fresh server, you could install Synapse on that host, giving it a <code>server_name</code>
  1650. of <code>example.com</code>, and once a reverse proxy has been set up to proxy all requests
  1651. sent to the port <code>8448</code> and serve TLS certificates for <code>example.com</code>, you
  1652. wouldn't need any delegation set up.</p>
  1653. <p><strong>However</strong>, if your homeserver's APIs aren't accessible on port 8448 and on the
  1654. domain <code>server_name</code> points to, you will need to let other servers know how to
  1655. find it using delegation.</p>
  1656. <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>
  1657. <p>Generally, using a reverse proxy for both the federation and client traffic is a good
  1658. idea, since it saves handling TLS traffic in Synapse. See
  1659. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a
  1660. reverse proxy.</p>
  1661. <div style="break-before: page; page-break-before: always;"></div><h1 id="upgrading-synapse"><a class="header" href="#upgrading-synapse">Upgrading Synapse</a></h1>
  1662. <p>Before upgrading check if any special steps are required to upgrade from
  1663. the version you currently have installed to the current version of
  1664. Synapse. The extra instructions that may be required are listed later in
  1665. this document.</p>
  1666. <ul>
  1667. <li>
  1668. <p>Check that your versions of Python and PostgreSQL are still
  1669. supported.</p>
  1670. <p>Synapse follows upstream lifecycles for <a href="https://endoflife.date/python">Python</a> and
  1671. <a href="https://endoflife.date/postgresql">PostgreSQL</a>, and removes support for versions
  1672. which are no longer maintained.</p>
  1673. <p>The website <a href="https://endoflife.date">https://endoflife.date</a> also offers convenient
  1674. summaries.</p>
  1675. </li>
  1676. <li>
  1677. <p>If Synapse was installed using <a href="setup/installation.html#prebuilt-packages">prebuilt packages</a>,
  1678. you will need to follow the normal process for upgrading those packages.</p>
  1679. </li>
  1680. <li>
  1681. <p>If Synapse was installed using pip then upgrade to the latest
  1682. version by running:</p>
  1683. <pre><code class="language-bash">pip install --upgrade matrix-synapse
  1684. </code></pre>
  1685. </li>
  1686. <li>
  1687. <p>If Synapse was installed from source, then:</p>
  1688. <ol>
  1689. <li>
  1690. <p>Obtain the latest version of the source code. Git users can run
  1691. <code>git pull</code> to do this.</p>
  1692. </li>
  1693. <li>
  1694. <p>If you're running Synapse in a virtualenv, make sure to activate it before
  1695. upgrading. For example, if Synapse is installed in a virtualenv in <code>~/synapse/env</code> then
  1696. run:</p>
  1697. <pre><code class="language-bash">source ~/synapse/env/bin/activate
  1698. pip install --upgrade .
  1699. </code></pre>
  1700. <p>Include any relevant extras between square brackets, e.g. <code>pip install --upgrade &quot;.[postgres,oidc]&quot;</code>.</p>
  1701. </li>
  1702. <li>
  1703. <p>If you're using <code>poetry</code> to manage a Synapse installation, run:</p>
  1704. <pre><code class="language-bash">poetry install
  1705. </code></pre>
  1706. <p>Include any relevant extras with <code>--extras</code>, e.g. <code>poetry install --extras postgres --extras oidc</code>.
  1707. It's probably easiest to run <code>poetry install --extras all</code>.</p>
  1708. </li>
  1709. <li>
  1710. <p>Restart Synapse:</p>
  1711. <pre><code class="language-bash">synctl restart
  1712. </code></pre>
  1713. </li>
  1714. </ol>
  1715. </li>
  1716. </ul>
  1717. <p>To check whether your update was successful, you can check the running
  1718. server version with:</p>
  1719. <pre><code class="language-bash"># you may need to replace 'localhost:8008' if synapse is not configured
  1720. # to listen on port 8008.
  1721. curl http://localhost:8008/_synapse/admin/v1/server_version
  1722. </code></pre>
  1723. <h2 id="rolling-back-to-older-versions"><a class="header" href="#rolling-back-to-older-versions">Rolling back to older versions</a></h2>
  1724. <p>Rolling back to previous releases can be difficult, due to database
  1725. schema changes between releases. Where we have been able to test the
  1726. rollback process, this will be noted below.</p>
  1727. <p>In general, you will need to undo any changes made during the upgrade
  1728. process, for example:</p>
  1729. <ul>
  1730. <li>
  1731. <p>pip:</p>
  1732. <pre><code class="language-bash">source env/bin/activate
  1733. # replace `1.3.0` accordingly:
  1734. pip install matrix-synapse==1.3.0
  1735. </code></pre>
  1736. </li>
  1737. <li>
  1738. <p>Debian:</p>
  1739. <pre><code class="language-bash"># replace `1.3.0` and `stretch` accordingly:
  1740. wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1741. dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1742. </code></pre>
  1743. </li>
  1744. </ul>
  1745. <h1 id="upgrading-to-v1890"><a class="header" href="#upgrading-to-v1890">Upgrading to v1.89.0</a></h1>
  1746. <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>
  1747. <p>Application services can no longer call <code>/register</code> with a <code>user</code> property to create new users.
  1748. The standard <code>username</code> property should be used instead. See the
  1749. <a href="https://spec.matrix.org/v1.7/application-service-api/#server-admin-style-permissions">Application Service specification</a>
  1750. for more information.</p>
  1751. <h1 id="upgrading-to-v1880"><a class="header" href="#upgrading-to-v1880">Upgrading to v1.88.0</a></h1>
  1752. <h2 id="minimum-supported-python-version"><a class="header" href="#minimum-supported-python-version">Minimum supported Python version</a></h2>
  1753. <p>The minimum supported Python version has been increased from v3.7 to v3.8.
  1754. You will need Python 3.8 to run Synapse v1.88.0 (due out July 18th, 2023).</p>
  1755. <p>If you use current versions of the Matrix.org-distributed Debian
  1756. packages or Docker images, no action is required.</p>
  1757. <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>
  1758. <p>As mentioned previously in <a href="upgrade.html#upgrading-to-v1840">Upgrading to v1.84.0</a>, the following deprecated settings
  1759. are being removed in this release of Synapse:</p>
  1760. <ul>
  1761. <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>
  1762. <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>
  1763. <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>
  1764. </ul>
  1765. <p>Please ensure that you have migrated to using <code>main</code> on your shared configuration's <code>instance_map</code>
  1766. (or create one if necessary). This is required if you have <em><strong>any</strong></em> workers at all;
  1767. administrators of single-process (monolith) installations don't need to do anything.</p>
  1768. <p>For an illustrative example, please see <a href="upgrade.html#upgrading-to-v1840">Upgrading to v1.84.0</a> below.</p>
  1769. <h1 id="upgrading-to-v1860"><a class="header" href="#upgrading-to-v1860">Upgrading to v1.86.0</a></h1>
  1770. <h2 id="minimum-supported-rust-version"><a class="header" href="#minimum-supported-rust-version">Minimum supported Rust version</a></h2>
  1771. <p>The minimum supported Rust version has been increased from v1.58.1 to v1.60.0.
  1772. Users building from source will need to ensure their <code>rustc</code> version is up to
  1773. date.</p>
  1774. <h1 id="upgrading-to-v1850"><a class="header" href="#upgrading-to-v1850">Upgrading to v1.85.0</a></h1>
  1775. <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>
  1776. <p>Application services should ensure they call the <code>/register</code> endpoint with a
  1777. <code>username</code> property. The legacy <code>user</code> property is considered deprecated and
  1778. should no longer be included.</p>
  1779. <p>A future version of Synapse (v1.88.0 or later) will remove support for legacy
  1780. application service login.</p>
  1781. <h1 id="upgrading-to-v1840"><a class="header" href="#upgrading-to-v1840">Upgrading to v1.84.0</a></h1>
  1782. <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>
  1783. <p>When using workers,</p>
  1784. <ul>
  1785. <li><code>worker_replication_host</code></li>
  1786. <li><code>worker_replication_http_port</code></li>
  1787. <li><code>worker_replication_http_tls</code></li>
  1788. </ul>
  1789. <p>should now be removed from individual worker YAML configurations and the main process should instead be added to the <code>instance_map</code>
  1790. in the shared YAML configuration, using the name <code>main</code>.</p>
  1791. <p>The old <code>worker_replication_*</code> settings are now considered deprecated and are expected to be removed in Synapse v1.88.0.</p>
  1792. <h3 id="example-change"><a class="header" href="#example-change">Example change</a></h3>
  1793. <h4 id="before"><a class="header" href="#before">Before:</a></h4>
  1794. <p>Shared YAML</p>
  1795. <pre><code class="language-yaml">instance_map:
  1796. generic_worker1:
  1797. host: localhost
  1798. port: 5678
  1799. tls: false
  1800. </code></pre>
  1801. <p>Worker YAML</p>
  1802. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  1803. worker_name: generic_worker1
  1804. worker_replication_host: localhost
  1805. worker_replication_http_port: 3456
  1806. worker_replication_http_tls: false
  1807. worker_listeners:
  1808. - type: http
  1809. port: 1234
  1810. resources:
  1811. - names: [client, federation]
  1812. - type: http
  1813. port: 5678
  1814. resources:
  1815. - names: [replication]
  1816. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  1817. </code></pre>
  1818. <h4 id="after"><a class="header" href="#after">After:</a></h4>
  1819. <p>Shared YAML</p>
  1820. <pre><code class="language-yaml">instance_map:
  1821. main:
  1822. host: localhost
  1823. port: 3456
  1824. tls: false
  1825. generic_worker1:
  1826. host: localhost
  1827. port: 5678
  1828. tls: false
  1829. </code></pre>
  1830. <p>Worker YAML</p>
  1831. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  1832. worker_name: generic_worker1
  1833. worker_listeners:
  1834. - type: http
  1835. port: 1234
  1836. resources:
  1837. - names: [client, federation]
  1838. - type: http
  1839. port: 5678
  1840. resources:
  1841. - names: [replication]
  1842. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  1843. </code></pre>
  1844. <p>Notes: </p>
  1845. <ul>
  1846. <li><code>tls</code> is optional but mirrors the functionality of <code>worker_replication_http_tls</code></li>
  1847. </ul>
  1848. <h1 id="upgrading-to-v1810"><a class="header" href="#upgrading-to-v1810">Upgrading to v1.81.0</a></h1>
  1849. <h2 id="application-service-path--authentication-deprecations"><a class="header" href="#application-service-path--authentication-deprecations">Application service path &amp; authentication deprecations</a></h2>
  1850. <p>Synapse now attempts the versioned appservice paths before falling back to the
  1851. <a href="https://spec.matrix.org/v1.6/application-service-api/#legacy-routes">legacy paths</a>.
  1852. Usage of the legacy routes should be considered deprecated.</p>
  1853. <p>Additionally, Synapse has supported sending the application service access token
  1854. via <a href="https://spec.matrix.org/v1.6/application-service-api/#authorization">the <code>Authorization</code> header</a>
  1855. since v1.70.0. For backwards compatibility it is <em>also</em> sent as the <code>access_token</code>
  1856. query parameter. This is insecure and should be considered deprecated.</p>
  1857. <p>A future version of Synapse (v1.88.0 or later) will remove support for legacy
  1858. application service routes and query parameter authorization.</p>
  1859. <h1 id="upgrading-to-v1800"><a class="header" href="#upgrading-to-v1800">Upgrading to v1.80.0</a></h1>
  1860. <h2 id="reporting-events-error-code-change"><a class="header" href="#reporting-events-error-code-change">Reporting events error code change</a></h2>
  1861. <p>Before this update, the
  1862. <a href="https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3roomsroomidreporteventid"><code>POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}</code></a>
  1863. endpoint would return a <code>403</code> if a user attempted to report an event that they did not have access to.
  1864. This endpoint will now return a <code>404</code> in this case instead.</p>
  1865. <p>Clients that implement event reporting should check that their error handling code will handle this
  1866. change.</p>
  1867. <h1 id="upgrading-to-v1790"><a class="header" href="#upgrading-to-v1790">Upgrading to v1.79.0</a></h1>
  1868. <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>
  1869. <p>Synapse v1.79.0 deprecates the
  1870. <a href="modules/third_party_rules_callbacks.html#on_threepid_bind"><code>on_threepid_bind</code></a>
  1871. &quot;third-party rules&quot; Synapse module callback method in favour of a new module method,
  1872. <a href="modules/third_party_rules_callbacks.html#on_add_user_third_party_identifier"><code>on_add_user_third_party_identifier</code></a>.
  1873. <code>on_threepid_bind</code> will be removed in a future version of Synapse. You should check whether any Synapse
  1874. modules in use in your deployment are making use of <code>on_threepid_bind</code>, and update them where possible.</p>
  1875. <p>The arguments and functionality of the new method are the same.</p>
  1876. <p>The justification behind the name change is that the old method's name, <code>on_threepid_bind</code>, was
  1877. misleading. A user is considered to &quot;bind&quot; their third-party ID to their Matrix ID only if they
  1878. do so via an <a href="https://spec.matrix.org/latest/identity-service-api/">identity server</a>
  1879. (so that users on other homeservers may find them). But this method was not called in that case -
  1880. it was only called when a user added a third-party identifier on the local homeserver.</p>
  1881. <p>Module developers may also be interested in the related
  1882. <a href="modules/third_party_rules_callbacks.html#on_remove_user_third_party_identifier"><code>on_remove_user_third_party_identifier</code></a>
  1883. module callback method that was also added in Synapse v1.79.0. This new method is called when a
  1884. user removes a third-party identifier from their account.</p>
  1885. <h1 id="upgrading-to-v1780"><a class="header" href="#upgrading-to-v1780">Upgrading to v1.78.0</a></h1>
  1886. <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>
  1887. <p>Synapse 1.78.0 replaces the <code>/_synapse/admin/v1/media/&lt;server_name&gt;/delete</code>
  1888. admin API with an identical endpoint at <code>/_synapse/admin/v1/media/delete</code>. Please
  1889. update your tooling to use the new endpoint. The deprecated version will be removed
  1890. in a future release.</p>
  1891. <h1 id="upgrading-to-v1760"><a class="header" href="#upgrading-to-v1760">Upgrading to v1.76.0</a></h1>
  1892. <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>
  1893. <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>
  1894. <p>Server admins can opt out of this feature for the time being by setting</p>
  1895. <pre><code class="language-yaml">experimental:
  1896. faster_joins: false
  1897. </code></pre>
  1898. <p>in their server config.</p>
  1899. <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>
  1900. <p>Synapse has changed the format of the account data and devices replication
  1901. streams (between workers). This is a forwards- and backwards-incompatible
  1902. change: v1.75 workers cannot process account data replicated by v1.76 workers,
  1903. and vice versa.</p>
  1904. <p>Once all workers are upgraded to v1.76 (or downgraded to v1.75), account data
  1905. and device replication will resume as normal.</p>
  1906. <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>
  1907. <p>The minimum supported version of Poetry is now 1.3.2 (previously 1.2.0, <a href="upgrade.html#upgrading-to-v1670">since
  1908. Synapse 1.67</a>). If you have used <code>poetry install</code> to
  1909. install Synapse from a source checkout, you should upgrade poetry: see its
  1910. <a href="https://python-poetry.org/docs/#installation">installation instructions</a>.
  1911. For all other installation methods, no acction is required.</p>
  1912. <h1 id="upgrading-to-v1740"><a class="header" href="#upgrading-to-v1740">Upgrading to v1.74.0</a></h1>
  1913. <h2 id="unicode-support-in-user-search"><a class="header" href="#unicode-support-in-user-search">Unicode support in user search</a></h2>
  1914. <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>
  1915. <p>If you want to take advantage of this feature you need to install PyICU,
  1916. the ICU native dependency and its development headers
  1917. so that PyICU can build since no prebuilt wheels are available.</p>
  1918. <p>You can follow <a href="https://pypi.org/project/PyICU/">the PyICU documentation</a> to do so,
  1919. and then do <code>pip install matrix-synapse[user-search]</code> for a PyPI install.</p>
  1920. <p>Docker images and Debian packages need nothing specific as they already
  1921. include or specify ICU as an explicit dependency.</p>
  1922. <h2 id="user-directory-rebuild"><a class="header" href="#user-directory-rebuild">User directory rebuild</a></h2>
  1923. <p>Synapse 1.74 queues a background update
  1924. <a href="https://github.com/matrix-org/synapse/pull/14643">to rebuild the user directory</a>,
  1925. in order to fix missing or erroneous entries.</p>
  1926. <p>When this update begins, the user directory will be cleared out and rebuilt from
  1927. scratch. User directory lookups will be incomplete until the rebuild completes.
  1928. Admins can monitor the rebuild's progress by using the
  1929. <a href="usage/administration/admin_api/background_updates.html#status">Background update Admin API</a>.</p>
  1930. <h1 id="upgrading-to-v1730"><a class="header" href="#upgrading-to-v1730">Upgrading to v1.73.0</a></h1>
  1931. <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>
  1932. <p>Synapse v1.69.0 included the deprecation of legacy Prometheus metric names
  1933. and offered an option to disable them.
  1934. Synapse v1.71.0 disabled legacy Prometheus metric names by default.</p>
  1935. <p>This version, v1.73.0, removes those legacy Prometheus metric names entirely.
  1936. This also means that the <code>enable_legacy_metrics</code> configuration option has been
  1937. removed; it will no longer be possible to re-enable the legacy metric names.</p>
  1938. <p>If you use metrics and have not yet updated your Grafana dashboard(s),
  1939. Prometheus console(s) or alerting rule(s), please consider doing so when upgrading
  1940. to this version.
  1941. Note that the included Grafana dashboard was updated in v1.72.0 to correct some
  1942. metric names which were missed when legacy metrics were disabled by default.</p>
  1943. <p>See <a href="upgrade.html#deprecation-of-legacy-prometheus-metric-names">v1.69.0: Deprecation of legacy Prometheus metric names</a>
  1944. for more context.</p>
  1945. <h1 id="upgrading-to-v1720"><a class="header" href="#upgrading-to-v1720">Upgrading to v1.72.0</a></h1>
  1946. <h2 id="dropping-support-for-postgresql-10"><a class="header" href="#dropping-support-for-postgresql-10">Dropping support for PostgreSQL 10</a></h2>
  1947. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>, we've dropped
  1948. support for PostgreSQL 10, as it is no longer supported upstream.</p>
  1949. <p>This release of Synapse requires PostgreSQL 11+.</p>
  1950. <h1 id="upgrading-to-v1710"><a class="header" href="#upgrading-to-v1710">Upgrading to v1.71.0</a></h1>
  1951. <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>
  1952. <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>
  1953. <p>Modules relying on it can instead use the <code>create_login_token</code> method.</p>
  1954. <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>
  1955. <p>To align with spec (changed in
  1956. <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3905">MSC3905</a>), Synapse now
  1957. only considers local users to be interesting. In other words, the <code>users</code> namespace
  1958. regex is only be applied against local users of the homeserver.</p>
  1959. <p>Please note, this probably doesn't affect the expected behavior of your application
  1960. service, since an interesting local user in a room still means all messages in the room
  1961. (from local or remote users) will still be considered interesting. And matching a room
  1962. with the <code>rooms</code> or <code>aliases</code> namespace regex will still consider all events sent in the
  1963. room to be interesting to the application service.</p>
  1964. <p>If one of your application service's <code>users</code> regex was intending to match a remote user,
  1965. this will no longer match as you expect. The behavioral mismatch between matching all
  1966. local users and some remote users is why the spec was changed/clarified and this
  1967. caveat is no longer supported.</p>
  1968. <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>
  1969. <p>Synapse v1.71.0 disables legacy Prometheus metric names by default.
  1970. For administrators that still rely on them and have not yet had chance to update their
  1971. uses of the metrics, it's still possible to specify <code>enable_legacy_metrics: true</code> in
  1972. the configuration to re-enable them temporarily.</p>
  1973. <p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and at that point,
  1974. it will no longer be possible to re-enable them.</p>
  1975. <p>If you do not use metrics or you have already updated your Grafana dashboard(s),
  1976. Prometheus console(s) and alerting rule(s), there is no action needed.</p>
  1977. <p>See <a href="upgrade.html#deprecation-of-legacy-prometheus-metric-names">v1.69.0: Deprecation of legacy Prometheus metric names</a>.</p>
  1978. <h1 id="upgrading-to-v1690"><a class="header" href="#upgrading-to-v1690">Upgrading to v1.69.0</a></h1>
  1979. <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>
  1980. <p>Synapse now includes information indicating if a receipt applies to a thread when
  1981. replicating it to other workers. This is a forwards- and backwards-incompatible
  1982. change: v1.68 and workers cannot process receipts replicated by v1.69 workers, and
  1983. vice versa.</p>
  1984. <p>Once all workers are upgraded to v1.69 (or downgraded to v1.68), receipts
  1985. replication will resume as normal.</p>
  1986. <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>
  1987. <p>In current versions of Synapse, some Prometheus metrics are emitted under two different names,
  1988. with one of the names being older but non-compliant with OpenMetrics and Prometheus conventions
  1989. and one of the names being newer but compliant.</p>
  1990. <p>Synapse v1.71.0 will turn the old metric names off <em>by default</em>.
  1991. For administrators that still rely on them and have not had chance to update their
  1992. uses of the metrics, it's possible to specify <code>enable_legacy_metrics: true</code> in
  1993. the configuration to re-enable them temporarily.</p>
  1994. <p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and it will no longer
  1995. be possible to re-enable them.</p>
  1996. <p>The Grafana dashboard, Prometheus recording rules and Prometheus Consoles included
  1997. in the <code>contrib</code> directory in the Synapse repository have been updated to no longer
  1998. rely on the legacy names. These can be used on a current version of Synapse
  1999. because current versions of Synapse emit both old and new names.</p>
  2000. <p>You may need to update your alerting rules or any other rules that depend on
  2001. the names of Prometheus metrics.
  2002. If you want to test your changes before legacy names are disabled by default,
  2003. you may specify <code>enable_legacy_metrics: false</code> in your homeserver configuration.</p>
  2004. <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>
  2005. <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>
  2006. <p>The following method of the module API has been deprecated, and is scheduled to
  2007. be remove in v1.71.0:</p>
  2008. <pre><code class="language-python">def generate_short_term_login_token(
  2009. self,
  2010. user_id: str,
  2011. duration_in_ms: int = (2 * 60 * 1000),
  2012. auth_provider_id: str = &quot;&quot;,
  2013. auth_provider_session_id: Optional[str] = None,
  2014. ) -&gt; str:
  2015. ...
  2016. </code></pre>
  2017. <p>It has been replaced by an asynchronous equivalent:</p>
  2018. <pre><code class="language-python">async def create_login_token(
  2019. self,
  2020. user_id: str,
  2021. duration_in_ms: int = (2 * 60 * 1000),
  2022. auth_provider_id: Optional[str] = None,
  2023. auth_provider_session_id: Optional[str] = None,
  2024. ) -&gt; str:
  2025. ...
  2026. </code></pre>
  2027. <p>Synapse will log a warning when a module uses the deprecated method, to help
  2028. administrators find modules using it.</p>
  2029. <h1 id="upgrading-to-v1680"><a class="header" href="#upgrading-to-v1680">Upgrading to v1.68.0</a></h1>
  2030. <p>Two changes announced in the upgrade notes for v1.67.0 have now landed in v1.68.0.</p>
  2031. <h2 id="sqlite-version-requirement"><a class="header" href="#sqlite-version-requirement">SQLite version requirement</a></h2>
  2032. <p>Synapse now requires a SQLite version of 3.27.0 or higher if SQLite is configured as
  2033. Synapse's database.</p>
  2034. <p>Installations using</p>
  2035. <ul>
  2036. <li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
  2037. <li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
  2038. <li>a PostgreSQL database</li>
  2039. </ul>
  2040. <p>are not affected.</p>
  2041. <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>
  2042. <p>Building from a source checkout of Synapse now requires a recent Rust compiler
  2043. (currently Rust 1.58.1, but see also the
  2044. <a href="https://matrix-org.github.io/synapse/latest/deprecation_policy.html">Platform Dependency Policy</a>).</p>
  2045. <p>Installations using</p>
  2046. <ul>
  2047. <li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
  2048. <li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
  2049. <li>PyPI wheels via <code>pip install matrix-synapse</code> (on supported platforms and architectures)</li>
  2050. </ul>
  2051. <p>will not be affected.</p>
  2052. <h1 id="upgrading-to-v1670"><a class="header" href="#upgrading-to-v1670">Upgrading to v1.67.0</a></h1>
  2053. <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>
  2054. <p>Redis support was added in v1.13.0 with it becoming the recommended method in
  2055. v1.18.0. It replaced the old direct TCP connections (which was deprecated as of
  2056. v1.18.0) to the main process. With Redis, rather than all the workers connecting
  2057. to the main process, all the workers and the main process connect to Redis,
  2058. which relays replication commands between processes. This can give a significant
  2059. CPU saving on the main process and is a prerequisite for upcoming
  2060. performance improvements.</p>
  2061. <p>To migrate to Redis add the <a href="./workers.html#shared-configuration"><code>redis</code> config</a>,
  2062. and remove the TCP <code>replication</code> listener from config of the master and
  2063. <code>worker_replication_port</code> from worker config. Note that a HTTP listener with a
  2064. <code>replication</code> resource is still required.</p>
  2065. <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>
  2066. <p>The minimum supported version of poetry is now 1.2. This should only affect
  2067. those installing from a source checkout.</p>
  2068. <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>
  2069. <p>From the next major release (v1.68.0) installing Synapse from a source checkout
  2070. will require a recent Rust compiler. Those using packages or
  2071. <code>pip install matrix-synapse</code> will not be affected.</p>
  2072. <p>The simplest way of installing Rust is via <a href="https://rustup.rs/">rustup.rs</a></p>
  2073. <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>
  2074. <p>From the next major release (v1.68.0) Synapse will require SQLite 3.27.0 or
  2075. higher. Synapse v1.67.0 will be the last major release supporting SQLite
  2076. versions 3.22 to 3.26.</p>
  2077. <p>Those using Docker images or Debian packages from Matrix.org will not be
  2078. affected. If you have installed from source, you should check the version of
  2079. SQLite used by Python with:</p>
  2080. <pre><code class="language-shell">python -c &quot;import sqlite3; print(sqlite3.sqlite_version)&quot;
  2081. </code></pre>
  2082. <p>If this is too old, refer to your distribution for advice on upgrading.</p>
  2083. <h1 id="upgrading-to-v1660"><a class="header" href="#upgrading-to-v1660">Upgrading to v1.66.0</a></h1>
  2084. <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>
  2085. <p>As of this version, Synapse no longer allows the tasks of verifying email address
  2086. ownership, and password reset confirmation, to be delegated to an identity server.
  2087. This removal was previously planned for Synapse 1.64.0, but was
  2088. <a href="https://github.com/matrix-org/synapse/issues/13421">delayed</a> until now to give
  2089. homeserver administrators more notice of the change.</p>
  2090. <p>To continue to allow users to add email addresses to their homeserver accounts,
  2091. and perform password resets, make sure that Synapse is configured with a working
  2092. email server in the <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email"><code>email</code> configuration
  2093. section</a>
  2094. (including, at a minimum, a <code>notif_from</code> setting.)</p>
  2095. <p>Specifying an <code>email</code> setting under <code>account_threepid_delegates</code> will now cause
  2096. an error at startup.</p>
  2097. <h1 id="upgrading-to-v1640"><a class="header" href="#upgrading-to-v1640">Upgrading to v1.64.0</a></h1>
  2098. <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>
  2099. <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>
  2100. <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.
  2101. <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email">Consult the configuration documentation for more information.</a></p>
  2102. <p>The option that will be removed is <code>account_threepid_delegates.email</code>.</p>
  2103. <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>
  2104. <p>Synapse now includes a flag indicating if an event is an outlier when
  2105. replicating it to other workers. This is a forwards- and backwards-incompatible
  2106. change: v1.63 and workers cannot process events replicated by v1.64 workers, and
  2107. vice versa.</p>
  2108. <p>Once all workers are upgraded to v1.64 (or downgraded to v1.63), event
  2109. replication will resume as normal.</p>
  2110. <h2 id="frozendict-release"><a class="header" href="#frozendict-release">frozendict release</a></h2>
  2111. <p><a href="https://github.com/Marco-Sulla/python-frozendict/releases/tag/v2.3.3">frozendict 2.3.3</a>
  2112. has recently been released, which fixes a memory leak that occurs during <code>/sync</code>
  2113. requests. We advise server administrators who installed Synapse via pip to upgrade
  2114. frozendict with <code>pip install --upgrade frozendict</code>. The Docker image
  2115. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> already
  2116. include the updated library.</p>
  2117. <h1 id="upgrading-to-v1620"><a class="header" href="#upgrading-to-v1620">Upgrading to v1.62.0</a></h1>
  2118. <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>
  2119. <p>As a followup to changes in v1.60.0, the following spam-checker callbacks have changed signature:</p>
  2120. <ul>
  2121. <li><code>user_may_join_room</code></li>
  2122. <li><code>user_may_invite</code></li>
  2123. <li><code>user_may_send_3pid_invite</code></li>
  2124. <li><code>user_may_create_room</code></li>
  2125. <li><code>user_may_create_room_alias</code></li>
  2126. <li><code>user_may_publish_room</code></li>
  2127. <li><code>check_media_file_for_spam</code></li>
  2128. </ul>
  2129. <p>For each of these methods, the previous callback signature has been deprecated.</p>
  2130. <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>
  2131. <p>For instance, if your module implements <code>user_may_join_room</code> as follows:</p>
  2132. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  2133. if ...:
  2134. # Request is spam
  2135. return False
  2136. # Request is not spam
  2137. return True
  2138. </code></pre>
  2139. <p>you should rewrite it as follows:</p>
  2140. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  2141. if ...:
  2142. # Request is spam, mark it as forbidden (you may use some more precise error
  2143. # code if it is useful).
  2144. return synapse.module_api.errors.Codes.FORBIDDEN
  2145. # Request is not spam, mark it as such.
  2146. return synapse.module_api.NOT_SPAM
  2147. </code></pre>
  2148. <h1 id="upgrading-to-v1610"><a class="header" href="#upgrading-to-v1610">Upgrading to v1.61.0</a></h1>
  2149. <h2 id="removal-of-deprecated-communitygroups"><a class="header" href="#removal-of-deprecated-communitygroups">Removal of deprecated community/groups</a></h2>
  2150. <p>This release of Synapse will remove deprecated community/groups from codebase.</p>
  2151. <h3 id="worker-endpoints"><a class="header" href="#worker-endpoints">Worker endpoints</a></h3>
  2152. <p>For those who have deployed workers, following worker endpoints will no longer
  2153. exist and they can be removed from the reverse proxy configuration:</p>
  2154. <ul>
  2155. <li><code>^/_matrix/federation/v1/get_groups_publicised$</code></li>
  2156. <li><code>^/_matrix/client/(r0|v3|unstable)/joined_groups$</code></li>
  2157. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups$</code></li>
  2158. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups/</code></li>
  2159. <li><code>^/_matrix/federation/v1/groups/</code></li>
  2160. <li><code>^/_matrix/client/(r0|v3|unstable)/groups/</code></li>
  2161. </ul>
  2162. <h1 id="upgrading-to-v1600"><a class="header" href="#upgrading-to-v1600">Upgrading to v1.60.0</a></h1>
  2163. <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>
  2164. <p>This release of Synapse will add a unique index to the <code>state_group_edges</code> table, in order
  2165. to prevent accidentally introducing duplicate information (for example, because a database
  2166. backup was restored multiple times).</p>
  2167. <p>Duplicate rows being present in this table could cause drastic performance problems; see
  2168. <a href="https://github.com/matrix-org/synapse/issues/11779">issue 11779</a> for more details.</p>
  2169. <p>If your Synapse database already has had duplicate rows introduced into this table,
  2170. this could fail, with either of these errors:</p>
  2171. <p><strong>On Postgres:</strong></p>
  2172. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  2173. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  2174. ...
  2175. psycopg2.errors.UniqueViolation: could not create unique index &quot;state_group_edges_unique_idx&quot;
  2176. DETAIL: Key (state_group, prev_state_group)=(2, 1) is duplicated.
  2177. </code></pre>
  2178. <p>(The numbers may be different.)</p>
  2179. <p><strong>On SQLite:</strong></p>
  2180. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  2181. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  2182. ...
  2183. sqlite3.IntegrityError: UNIQUE constraint failed: state_group_edges.state_group, state_group_edges.prev_state_group
  2184. </code></pre>
  2185. <details>
  2186. <summary><b>Expand this section for steps to resolve this problem</b></summary>
  2187. <h3 id="on-postgres"><a class="header" href="#on-postgres">On Postgres</a></h3>
  2188. <p>Connect to your database with <code>psql</code>.</p>
  2189. <pre><code class="language-sql">BEGIN;
  2190. DELETE FROM state_group_edges WHERE (ctid, state_group, prev_state_group) IN (
  2191. SELECT row_id, state_group, prev_state_group
  2192. FROM (
  2193. SELECT
  2194. ctid AS row_id,
  2195. MIN(ctid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  2196. state_group,
  2197. prev_state_group
  2198. FROM state_group_edges
  2199. ) AS t1
  2200. WHERE row_id &lt;&gt; min_row_id
  2201. );
  2202. COMMIT;
  2203. </code></pre>
  2204. <h3 id="on-sqlite"><a class="header" href="#on-sqlite">On SQLite</a></h3>
  2205. <p>At the command-line, use <code>sqlite3 path/to/your-homeserver-database.db</code>:</p>
  2206. <pre><code class="language-sql">BEGIN;
  2207. DELETE FROM state_group_edges WHERE (rowid, state_group, prev_state_group) IN (
  2208. SELECT row_id, state_group, prev_state_group
  2209. FROM (
  2210. SELECT
  2211. rowid AS row_id,
  2212. MIN(rowid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  2213. state_group,
  2214. prev_state_group
  2215. FROM state_group_edges
  2216. )
  2217. WHERE row_id &lt;&gt; min_row_id
  2218. );
  2219. COMMIT;
  2220. </code></pre>
  2221. <h3 id="for-more-details"><a class="header" href="#for-more-details">For more details</a></h3>
  2222. <p><a href="https://github.com/matrix-org/synapse/issues/11779#issuecomment-1131545970">This comment on issue 11779</a>
  2223. has queries that can be used to check a database for this problem in advance.</p>
  2224. </details>
  2225. <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>
  2226. <p>The previous signature has been deprecated.</p>
  2227. <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>
  2228. <p>This is part of an ongoing refactoring of the SpamChecker API to make it less ambiguous and more powerful.</p>
  2229. <p>If your module implements <code>check_event_for_spam</code> as follows:</p>
  2230. <pre><code class="language-python">async def check_event_for_spam(event):
  2231. if ...:
  2232. # Event is spam
  2233. return True
  2234. # Event is not spam
  2235. return False
  2236. </code></pre>
  2237. <p>you should rewrite it as follows:</p>
  2238. <pre><code class="language-python">async def check_event_for_spam(event):
  2239. if ...:
  2240. # Event is spam, mark it as forbidden (you may use some more precise error
  2241. # code if it is useful).
  2242. return synapse.module_api.errors.Codes.FORBIDDEN
  2243. # Event is not spam, mark it as such.
  2244. return synapse.module_api.NOT_SPAM
  2245. </code></pre>
  2246. <h1 id="upgrading-to-v1590"><a class="header" href="#upgrading-to-v1590">Upgrading to v1.59.0</a></h1>
  2247. <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>
  2248. <p>The names of user devices are no longer visible to users on other homeservers by default.
  2249. Device IDs are unaffected, as these are necessary to facilitate end-to-end encryption.</p>
  2250. <p>To re-enable this functionality, set the
  2251. <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>
  2252. homeserver config option to <code>true</code>.</p>
  2253. <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>
  2254. <p>The <code>synapse.app.appservice</code> worker application type allowed you to configure a
  2255. single worker to use to notify application services of new events, as long
  2256. as this functionality was disabled on the main process with <code>notify_appservices: False</code>.
  2257. Further, the <code>synapse.app.user_dir</code> worker application type allowed you to configure
  2258. a single worker to be responsible for updating the user directory, as long as this
  2259. was disabled on the main process with <code>update_user_directory: False</code>.</p>
  2260. <p>To unify Synapse's worker types, the <code>synapse.app.appservice</code> worker application
  2261. type and the <code>notify_appservices</code> configuration option have been deprecated.
  2262. The <code>synapse.app.user_dir</code> worker application type and <code>update_user_directory</code>
  2263. configuration option have also been deprecated.</p>
  2264. <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>
  2265. worker application type is used and that the <code>notify_appservices_from_worker</code> and/or
  2266. <code>update_user_directory_from_worker</code> options are set to the name of a worker.</p>
  2267. <p>For the time being, the old options can be used alongside the new options to make
  2268. it easier to transition between the two configurations, however please note that:</p>
  2269. <ul>
  2270. <li>the options must not contradict each other (otherwise Synapse won't start); and</li>
  2271. <li>the <code>notify_appservices</code> and <code>update_user_directory</code> options will be removed in a future release of Synapse.</li>
  2272. </ul>
  2273. <p>Please see the <a href="workers.html#notifying-application-services"><em>Notifying Application Services</em></a> and
  2274. <a href="workers.html#updating-the-user-directory"><em>Updating the User Directory</em></a> sections of the worker
  2275. documentation for more information.</p>
  2276. <h1 id="upgrading-to-v1580"><a class="header" href="#upgrading-to-v1580">Upgrading to v1.58.0</a></h1>
  2277. <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>
  2278. <p>The non-standard groups/communities feature in Synapse has been disabled by default
  2279. and will be removed in Synapse v1.61.0.</p>
  2280. <h1 id="upgrading-to-v1570"><a class="header" href="#upgrading-to-v1570">Upgrading to v1.57.0</a></h1>
  2281. <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>
  2282. <p>Synapse v1.57.0 includes a <a href="https://github.com/matrix-org/synapse/pull/12209">change</a> to the
  2283. way transaction IDs are managed for application services. If your deployment uses a dedicated
  2284. worker for application service traffic, <strong>it must be stopped</strong> when the database is upgraded
  2285. (which normally happens when the main process is upgraded), to ensure the change is made safely
  2286. without any risk of reusing transaction IDs.</p>
  2287. <p>Deployments which do not use separate worker processes can be upgraded as normal. Similarly,
  2288. deployments where no application services are in use can be upgraded as normal.</p>
  2289. <details>
  2290. <summary><b>Recovering from an incorrect upgrade</b></summary>
  2291. <p>If the database schema is upgraded <em>without</em> stopping the worker responsible
  2292. for AS traffic, then the following error may be given when attempting to start
  2293. a Synapse worker or master process:</p>
  2294. <pre><code>**********************************************************************************
  2295. Error during initialisation:
  2296. Postgres sequence 'application_services_txn_id_seq' is inconsistent with associated
  2297. table 'application_services_txns'. This can happen if Synapse has been downgraded and
  2298. then upgraded again, or due to a bad migration.
  2299. To fix this error, shut down Synapse (including any and all workers)
  2300. and run the following SQL:
  2301. SELECT setval('application_services_txn_id_seq', (
  2302. SELECT GREATEST(MAX(txn_id), 0) FROM application_services_txns
  2303. ));
  2304. See docs/postgres.md for more information.
  2305. There may be more information in the logs.
  2306. **********************************************************************************
  2307. </code></pre>
  2308. <p>This error may also be seen if Synapse is <em>downgraded</em> to an earlier version,
  2309. and then upgraded again to v1.57.0 or later.</p>
  2310. <p>In either case:</p>
  2311. <ol>
  2312. <li>Ensure that the worker responsible for AS traffic is stopped.</li>
  2313. <li>Run the SQL command given in the error message via <code>psql</code>.</li>
  2314. </ol>
  2315. <p>Synapse should then start correctly.</p>
  2316. </details>
  2317. <h1 id="upgrading-to-v1560"><a class="header" href="#upgrading-to-v1560">Upgrading to v1.56.0</a></h1>
  2318. <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>
  2319. <p>Synapse will refuse to start if registration is enabled without email, captcha, or token-based verification unless the new config
  2320. flag <code>enable_registration_without_verification</code> is set to &quot;true&quot;.</p>
  2321. <h2 id="groupscommunities-feature-has-been-deprecated"><a class="header" href="#groupscommunities-feature-has-been-deprecated">Groups/communities feature has been deprecated</a></h2>
  2322. <p>The non-standard groups/communities feature in Synapse has been deprecated and will
  2323. be disabled by default in Synapse v1.58.0.</p>
  2324. <p>You can test disabling it by adding the following to your homeserver configuration:</p>
  2325. <pre><code class="language-yaml">experimental_features:
  2326. groups_enabled: false
  2327. </code></pre>
  2328. <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>
  2329. <p>Synapse now refuses to start when using PostgreSQL with non-<code>C</code> values for <code>COLLATE</code> and
  2330. <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the database section of
  2331. 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>
  2332. for more information and instructions on how to fix a database with incorrect values.</p>
  2333. <h1 id="upgrading-to-v1550"><a class="header" href="#upgrading-to-v1550">Upgrading to v1.55.0</a></h1>
  2334. <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>
  2335. <p>The <code>synctl</code> script
  2336. <a href="https://github.com/matrix-org/synapse/pull/12140">has been made</a> an
  2337. <a href="https://packaging.python.org/en/latest/specifications/entry-points/">entry point</a>
  2338. and no longer exists at the root of Synapse's source tree. If you wish to use
  2339. <code>synctl</code> to manage your homeserver, you should invoke <code>synctl</code> directly, e.g.
  2340. <code>synctl start</code> instead of <code>./synctl start</code> or <code>/path/to/synctl start</code>.</p>
  2341. <p>You will need to ensure <code>synctl</code> is on your <code>PATH</code>.</p>
  2342. <ul>
  2343. <li>This is automatically the case when using
  2344. <a href="https://packages.matrix.org/debian/">Debian packages</a> or
  2345. <a href="https://hub.docker.com/r/matrixdotorg/synapse">docker images</a>
  2346. provided by Matrix.org.</li>
  2347. <li>When installing from a wheel, sdist, or PyPI, a <code>synctl</code> executable is added
  2348. to your Python installation's <code>bin</code>. This should be on your <code>PATH</code>
  2349. automatically, though you might need to activate a virtual environment
  2350. depending on how you installed Synapse.</li>
  2351. </ul>
  2352. <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>
  2353. <p>Synapse v1.55.0 drops support for Mjolnir 1.3.1 and earlier.
  2354. If you use the Mjolnir module to moderate your homeserver,
  2355. please upgrade Mjolnir to version 1.3.2 or later before upgrading Synapse.</p>
  2356. <h1 id="upgrading-to-v1540"><a class="header" href="#upgrading-to-v1540">Upgrading to v1.54.0</a></h1>
  2357. <h2 id="legacy-structured-logging-configuration-removal"><a class="header" href="#legacy-structured-logging-configuration-removal">Legacy structured logging configuration removal</a></h2>
  2358. <p>This release removes support for the <code>structured: true</code> logging configuration
  2359. which was deprecated in Synapse v1.23.0. If your logging configuration contains
  2360. <code>structured: true</code> then it should be modified based on the
  2361. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  2362. <h1 id="upgrading-to-v1530"><a class="header" href="#upgrading-to-v1530">Upgrading to v1.53.0</a></h1>
  2363. <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>
  2364. <p>Per the deprecation notice in Synapse v1.51.0, listeners of type <code>webclient</code>
  2365. are no longer supported and configuring them is a now a configuration error.</p>
  2366. <p>Configuring a non-HTTP(S) <code>web_client_location</code> configuration is is now a
  2367. configuration error. Since the <code>webclient</code> listener is no longer supported, this
  2368. setting only applies to the root path <code>/</code> of Synapse's web server and no longer
  2369. the <code>/_matrix/client/</code> path.</p>
  2370. <h2 id="stablisation-of-msc3231"><a class="header" href="#stablisation-of-msc3231">Stablisation of MSC3231</a></h2>
  2371. <p>The unstable validity-check endpoint for the
  2372. <a href="https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity">Registration Tokens</a>
  2373. feature has been stabilised and moved from:</p>
  2374. <p><code>/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity</code></p>
  2375. <p>to:</p>
  2376. <p><code>/_matrix/client/v1/register/m.login.registration_token/validity</code></p>
  2377. <p>Please update any relevant reverse proxy or firewall configurations appropriately.</p>
  2378. <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>
  2379. <p>Formerly, entries in the cache were not evicted regardless of whether they were accessed after storing.
  2380. This behavior has now changed. By default entries in the cache are now evicted after 30m of not being accessed.
  2381. To change the default behavior, go to the <code>caches</code> section of the config and change the <code>expire_caches</code> and
  2382. <code>cache_entry_ttl</code> flags as necessary. Please note that these flags replace the <code>expiry_time</code> flag in the config.
  2383. The <code>expiry_time</code> flag will still continue to work, but it has been deprecated and will be removed in the future.</p>
  2384. <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>
  2385. <p>The <code>capabilities</code> of MSC3283 from the REST API <code>/_matrix/client/r0/capabilities</code>
  2386. becomes stable.</p>
  2387. <p>The old <code>capabilities</code></p>
  2388. <ul>
  2389. <li><code>org.matrix.msc3283.set_displayname</code>,</li>
  2390. <li><code>org.matrix.msc3283.set_avatar_url</code> and</li>
  2391. <li><code>org.matrix.msc3283.3pid_changes</code></li>
  2392. </ul>
  2393. <p>are deprecated and scheduled to be removed in Synapse v1.54.0.</p>
  2394. <p>The new <code>capabilities</code></p>
  2395. <ul>
  2396. <li><code>m.set_displayname</code>,</li>
  2397. <li><code>m.set_avatar_url</code> and</li>
  2398. <li><code>m.3pid_changes</code></li>
  2399. </ul>
  2400. <p>are now active by default.</p>
  2401. <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>
  2402. <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>,
  2403. the deprecated <code>user_may_create_room_with_invites</code> module callback has been removed.</p>
  2404. <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>
  2405. 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>
  2406. 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>
  2407. 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>
  2408. <h1 id="upgrading-to-v1520"><a class="header" href="#upgrading-to-v1520">Upgrading to v1.52.0</a></h1>
  2409. <h2 id="twisted-security-release"><a class="header" href="#twisted-security-release">Twisted security release</a></h2>
  2410. <p>Note that <a href="https://github.com/twisted/twisted/releases/tag/twisted-22.1.0">Twisted 22.1.0</a>
  2411. has recently been released, which fixes a <a href="https://github.com/twisted/twisted/security/advisories/GHSA-92x2-jw7w-xvvx">security issue</a>
  2412. within the Twisted library. We do not believe Synapse is affected by this vulnerability,
  2413. though we advise server administrators who installed Synapse via pip to upgrade Twisted
  2414. with <code>pip install --upgrade Twisted treq</code> as a matter of good practice. The Docker image
  2415. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> are using the
  2416. updated library.</p>
  2417. <h1 id="upgrading-to-v1510"><a class="header" href="#upgrading-to-v1510">Upgrading to v1.51.0</a></h1>
  2418. <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>
  2419. <p>Listeners of type <code>webclient</code> are deprecated and scheduled to be removed in
  2420. Synapse v1.53.0.</p>
  2421. <p>Similarly, a non-HTTP(S) <code>web_client_location</code> configuration is deprecated and
  2422. will become a configuration error in Synapse v1.53.0.</p>
  2423. <h1 id="upgrading-to-v1500"><a class="header" href="#upgrading-to-v1500">Upgrading to v1.50.0</a></h1>
  2424. <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>
  2425. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2426. we've dropped support for Python 3.6 and PostgreSQL 9.6, as they are no
  2427. longer supported upstream.</p>
  2428. <p>This release of Synapse requires Python 3.7+ and PostgreSQL 10+.</p>
  2429. <h1 id="upgrading-to-v1470"><a class="header" href="#upgrading-to-v1470">Upgrading to v1.47.0</a></h1>
  2430. <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>
  2431. <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>
  2432. (released on 2021-05-17) and have now been removed:</p>
  2433. <ul>
  2434. <li><code>POST /_synapse/admin/v1/&lt;room_id&gt;/delete</code></li>
  2435. </ul>
  2436. <p>Any scripts still using the above APIs should be converted to use the
  2437. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  2438. <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>
  2439. <p>The <code>user_may_create_room_with_invites</code> is deprecated and will be removed in a future
  2440. version of Synapse. Modules implementing this callback can instead implement
  2441. <a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
  2442. 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>
  2443. module API method to infer whether the invite is happening in the context of creating a
  2444. room.</p>
  2445. <p>We plan to remove this callback in January 2022.</p>
  2446. <h1 id="upgrading-to-v1450"><a class="header" href="#upgrading-to-v1450">Upgrading to v1.45.0</a></h1>
  2447. <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>
  2448. <p>Media storage provider modules that read from the Synapse configuration object (i.e. that
  2449. read the value of <code>hs.config.[...]</code>) now need to specify the configuration section they're
  2450. reading from. This means that if a module reads the value of e.g. <code>hs.config.media_store_path</code>,
  2451. it needs to replace it with <code>hs.config.media.media_store_path</code>.</p>
  2452. <h1 id="upgrading-to-v1440"><a class="header" href="#upgrading-to-v1440">Upgrading to v1.44.0</a></h1>
  2453. <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>
  2454. <p>The <code>url_cache/</code> and <code>url_cache_thumbnails/</code> directories in the media store are
  2455. no longer mirrored to storage providers. These two directories can be safely
  2456. deleted from any configured storage providers to reclaim space.</p>
  2457. <h1 id="upgrading-to-v1430"><a class="header" href="#upgrading-to-v1430">Upgrading to v1.43.0</a></h1>
  2458. <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>
  2459. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#available-worker-applications">available worker applications documentation</a>
  2460. has been updated to reflect that calls to the <code>/spaces</code>, <code>/hierarchy</code>, and
  2461. <code>/summary</code> endpoints can now be routed to workers for both client API and
  2462. federation requests.</p>
  2463. <h1 id="upgrading-to-v1420"><a class="header" href="#upgrading-to-v1420">Upgrading to v1.42.0</a></h1>
  2464. <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>
  2465. <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>
  2466. (released on 2021-01-13) and have now been removed:</p>
  2467. <ul>
  2468. <li><code>POST /_synapse/admin/v1/purge_room</code></li>
  2469. <li><code>POST /_synapse/admin/v1/shutdown_room/&lt;room_id&gt;</code></li>
  2470. </ul>
  2471. <p>Any scripts still using the above APIs should be converted to use the
  2472. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  2473. <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>
  2474. <p>This may affect you if you make use of custom HTML templates for the
  2475. <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
  2476. <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>
  2477. <p>The template is now provided an <code>error</code> variable if the authentication
  2478. process failed. See the default templates linked above for an example.</p>
  2479. <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>
  2480. <p>Users will stop receiving message updates via email for addresses that were
  2481. once, but not still, linked to their account.</p>
  2482. <h1 id="upgrading-to-v1410"><a class="header" href="#upgrading-to-v1410">Upgrading to v1.41.0</a></h1>
  2483. <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>
  2484. <p>Since Synapse 1.6.0 (2019-11-26) you can set a proxy for outbound HTTP requests via
  2485. http_proxy/https_proxy environment variables. This proxy was set for:</p>
  2486. <ul>
  2487. <li>push</li>
  2488. <li>url previews</li>
  2489. <li>phone-home stats</li>
  2490. <li>recaptcha validation</li>
  2491. <li>CAS auth validation</li>
  2492. <li>OpenID Connect</li>
  2493. <li>Federation (checking public key revocation)</li>
  2494. </ul>
  2495. <p>In this version we have added support for outbound requests for:</p>
  2496. <ul>
  2497. <li>Outbound federation</li>
  2498. <li>Downloading remote media</li>
  2499. <li>Fetching public keys of other servers</li>
  2500. </ul>
  2501. <p>These requests use the same proxy configuration. If you have a proxy configuration we
  2502. recommend to verify the configuration. It may be necessary to adjust the <code>no_proxy</code>
  2503. environment variable.</p>
  2504. <p>See <a href="setup/forward_proxy.html">using a forward proxy with Synapse documentation</a> for
  2505. details.</p>
  2506. <h2 id="deprecation-of-template_dir"><a class="header" href="#deprecation-of-template_dir">Deprecation of <code>template_dir</code></a></h2>
  2507. <p>The <code>template_dir</code> settings in the <code>sso</code>, <code>account_validity</code> and <code>email</code> sections of the
  2508. configuration file are now deprecated. Server admins should use the new
  2509. <code>templates.custom_template_directory</code> setting in the configuration file and use one single
  2510. custom template directory for all aforementioned features. Template file names remain
  2511. unchanged. See <a href="https://matrix-org.github.io/synapse/latest/templates.html">the related documentation</a>
  2512. for more information and examples.</p>
  2513. <p>We plan to remove support for these settings in October 2021.</p>
  2514. <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>
  2515. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#synapseappmedia_repository">media repository worker documentation</a>
  2516. has been updated to reflect that calls to <code>/_synapse/admin/v1/users/{userId}/media</code>
  2517. must now be handled by media repository workers. This is due to the new <code>DELETE</code> method
  2518. of this endpoint modifying the media store.</p>
  2519. <h1 id="upgrading-to-v1390"><a class="header" href="#upgrading-to-v1390">Upgrading to v1.39.0</a></h1>
  2520. <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>
  2521. <p>The current third-party rules module interface is deprecated in favour of the new generic
  2522. modules system introduced in Synapse v1.37.0. Authors of third-party rules modules can refer
  2523. to <a href="modules/porting_legacy_module.html">this documentation</a>
  2524. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this documentation</a>
  2525. to update their configuration once the modules they are using have been updated.</p>
  2526. <p>We plan to remove support for the current third-party rules interface in September 2021.</p>
  2527. <h1 id="upgrading-to-v1380"><a class="header" href="#upgrading-to-v1380">Upgrading to v1.38.0</a></h1>
  2528. <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>
  2529. <p>This release includes a database schema update which requires re-indexing one of
  2530. the larger tables in the database, <code>events</code>. This could result in increased
  2531. disk I/O for several hours or days after upgrading while the migration
  2532. completes. Furthermore, because we have to keep the old indexes until the new
  2533. indexes are ready, it could result in a significant, temporary, increase in
  2534. disk space.</p>
  2535. <p>To get a rough idea of the disk space required, check the current size of one
  2536. of the indexes. For example, from a <code>psql</code> shell, run the following sql:</p>
  2537. <pre><code class="language-sql">SELECT pg_size_pretty(pg_relation_size('events_order_room'));
  2538. </code></pre>
  2539. <p>We need to rebuild <strong>four</strong> indexes, so you will need to multiply this result
  2540. by four to give an estimate of the disk space required. For example, on one
  2541. particular server:</p>
  2542. <pre><code>synapse=# select pg_size_pretty(pg_relation_size('events_order_room'));
  2543. pg_size_pretty
  2544. ----------------
  2545. 288 MB
  2546. (1 row)
  2547. </code></pre>
  2548. <p>On this server, it would be wise to ensure that at least 1152MB are free.</p>
  2549. <p>The additional disk space will be freed once the migration completes.</p>
  2550. <p>SQLite databases are unaffected by this change.</p>
  2551. <h1 id="upgrading-to-v1370"><a class="header" href="#upgrading-to-v1370">Upgrading to v1.37.0</a></h1>
  2552. <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>
  2553. <p>The current spam checker interface is deprecated in favour of a new generic modules system.
  2554. Authors of spam checker modules can refer to [this
  2555. documentation](modules/porting_legacy_module.md
  2556. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this
  2557. documentation</a>
  2558. to update their configuration once the modules they are using have been updated.</p>
  2559. <p>We plan to remove support for the current spam checker interface in August 2021.</p>
  2560. <p>More module interfaces will be ported over to this new generic system in future versions
  2561. of Synapse.</p>
  2562. <h1 id="upgrading-to-v1340"><a class="header" href="#upgrading-to-v1340">Upgrading to v1.34.0</a></h1>
  2563. <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>
  2564. <p>The <code>room_invite_state_types</code> configuration setting has been deprecated
  2565. 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
  2566. file</a>.</p>
  2567. <p>If you have set <code>room_invite_state_types</code> to the default value you
  2568. should simply remove it from your configuration file. The default value
  2569. used to be:</p>
  2570. <pre><code class="language-yaml">room_invite_state_types:
  2571. - &quot;m.room.join_rules&quot;
  2572. - &quot;m.room.canonical_alias&quot;
  2573. - &quot;m.room.avatar&quot;
  2574. - &quot;m.room.encryption&quot;
  2575. - &quot;m.room.name&quot;
  2576. </code></pre>
  2577. <p>If you have customised this value, you should remove
  2578. <code>room_invite_state_types</code> and configure <code>room_prejoin_state</code> instead.</p>
  2579. <h1 id="upgrading-to-v1330"><a class="header" href="#upgrading-to-v1330">Upgrading to v1.33.0</a></h1>
  2580. <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>
  2581. <p>This may affect you if you have enabled the account validity feature,
  2582. and have made use of a custom HTML template specified by the
  2583. <code>account_validity.template_dir</code> or
  2584. <code>account_validity.account_renewed_html_path</code> Synapse config options.</p>
  2585. <p>The template can now accept an <code>expiration_ts</code> variable, which
  2586. represents the unix timestamp in milliseconds for the future date of
  2587. 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
  2588. template</a>
  2589. for an example of usage.</p>
  2590. <p>ALso note that a new HTML template, <code>account_previously_renewed.html</code>,
  2591. has been added. This is is shown to users when they attempt to renew
  2592. their account with a valid renewal token that has already been used
  2593. before. The default template contents can been found
  2594. <a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_previously_renewed.html">here</a>,
  2595. and can also accept an <code>expiration_ts</code> variable. This template replaces
  2596. the error message users would previously see upon attempting to use a
  2597. valid renewal token more than once.</p>
  2598. <h1 id="upgrading-to-v1320"><a class="header" href="#upgrading-to-v1320">Upgrading to v1.32.0</a></h1>
  2599. <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>
  2600. <p>This release introduces <a href="https://github.com/matrix-org/synapse/issues/9853">a
  2601. regression</a> that can
  2602. overwhelm connected Prometheus instances. This issue is not present in
  2603. Synapse v1.32.0rc1.</p>
  2604. <p>If you have been affected, please downgrade to 1.31.0. You then may need
  2605. to remove excess writeahead logs in order for Prometheus to recover.
  2606. Instructions for doing so are provided
  2607. <a href="https://github.com/matrix-org/synapse/pull/9854#issuecomment-823472183">here</a>.</p>
  2608. <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>
  2609. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2610. we've dropped support for Python 3.5 and PostgreSQL 9.5, as they are no
  2611. longer supported upstream.</p>
  2612. <p>This release of Synapse requires Python 3.6+ and PostgresSQL 9.6+ or
  2613. SQLite 3.22+.</p>
  2614. <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>
  2615. <p>The deprecated v1 &quot;list accounts&quot; admin API
  2616. (<code>GET /_synapse/admin/v1/users/&lt;user_id&gt;</code>) has been removed in this
  2617. version.</p>
  2618. <p>The <a href="admin_api/user_admin_api.html#list-accounts">v2 list accounts API</a>
  2619. has been available since Synapse 1.7.0 (2019-12-13), and is accessible
  2620. under <code>GET /_synapse/admin/v2/users</code>.</p>
  2621. <p>The deprecation of the old endpoint was announced with Synapse 1.28.0
  2622. (released on 2021-02-25).</p>
  2623. <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>
  2624. <p>In compliance with the <a href="https://matrix.org/docs/spec/application_service/r0.1.2#server-admin-style-permissions">Application Service
  2625. spec</a>,
  2626. Application Services are now required to use the
  2627. <code>m.login.application_service</code> type when registering users via the
  2628. <code>/_matrix/client/r0/register</code> endpoint. This behaviour was deprecated in
  2629. Synapse v1.30.0.</p>
  2630. <p>Please ensure your Application Services are up to date.</p>
  2631. <h1 id="upgrading-to-v1290"><a class="header" href="#upgrading-to-v1290">Upgrading to v1.29.0</a></h1>
  2632. <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>
  2633. <p>When using Synapse with a reverse proxy (in particular, when using the
  2634. <code>x_forwarded</code> option on an HTTP listener), Synapse now
  2635. expects to receive an <code>X-Forwarded-Proto</code> header on incoming
  2636. HTTP requests. If it is not set, Synapse will log a warning on each
  2637. received request.</p>
  2638. <p>To avoid the warning, administrators using a reverse proxy should ensure
  2639. that the reverse proxy sets <code>X-Forwarded-Proto</code> header to
  2640. <code>https</code> or <code>http</code> to indicate the protocol used
  2641. by the client.</p>
  2642. <p>Synapse also requires the <code>Host</code> header to be preserved.</p>
  2643. <p>See the <a href="reverse_proxy.html">reverse proxy documentation</a>, where the
  2644. example configurations have been updated to show how to set these
  2645. headers.</p>
  2646. <p>(Users of <a href="https://caddyserver.com/">Caddy</a> are unaffected, since we
  2647. believe it sets <code>X-Forwarded-Proto</code> by default.)</p>
  2648. <h1 id="upgrading-to-v1270"><a class="header" href="#upgrading-to-v1270">Upgrading to v1.27.0</a></h1>
  2649. <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>
  2650. <p>This version changes the URI used for callbacks from OAuth2 and SAML2
  2651. identity providers:</p>
  2652. <ul>
  2653. <li>
  2654. <p>If your server is configured for single sign-on via an OpenID
  2655. Connect or OAuth2 identity provider, you will need to add
  2656. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> to the list
  2657. of permitted &quot;redirect URIs&quot; at the identity provider.</p>
  2658. <p>See the <a href="openid.html">OpenID docs</a> for more information on setting
  2659. up OpenID Connect.</p>
  2660. </li>
  2661. <li>
  2662. <p>If your server is configured for single sign-on via a SAML2 identity
  2663. provider, you will need to add
  2664. <code>[synapse public baseurl]/_synapse/client/saml2/authn_response</code> as a
  2665. permitted &quot;ACS location&quot; (also known as &quot;allowed callback URLs&quot;)
  2666. at the identity provider.</p>
  2667. <p>The &quot;Issuer&quot; in the &quot;AuthnRequest&quot; to the SAML2 identity
  2668. provider is also updated to
  2669. <code>[synapse public baseurl]/_synapse/client/saml2/metadata.xml</code>. If
  2670. your SAML2 identity provider uses this property to validate or
  2671. otherwise identify Synapse, its configuration will need to be
  2672. updated to use the new URL. Alternatively you could create a new,
  2673. separate &quot;EntityDescriptor&quot; in your SAML2 identity provider with
  2674. the new URLs and leave the URLs in the existing &quot;EntityDescriptor&quot;
  2675. as they were.</p>
  2676. </li>
  2677. </ul>
  2678. <h2 id="changes-to-html-templates"><a class="header" href="#changes-to-html-templates">Changes to HTML templates</a></h2>
  2679. <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
  2680. autoescape</a>
  2681. enabled for files ending in <code>.html</code>, <code>.htm</code>, and <code>.xml</code>. If you have
  2682. customised these templates and see issues when viewing them you might
  2683. need to update them. It is expected that most configurations will need
  2684. no changes.</p>
  2685. <p>If you have customised the templates <em>names</em> for these templates, it is
  2686. recommended to verify they end in <code>.html</code> to ensure autoescape is
  2687. enabled.</p>
  2688. <p>The above applies to the following templates:</p>
  2689. <ul>
  2690. <li><code>add_threepid.html</code></li>
  2691. <li><code>add_threepid_failure.html</code></li>
  2692. <li><code>add_threepid_success.html</code></li>
  2693. <li><code>notice_expiry.html</code></li>
  2694. <li><code>notice_expiry.html</code></li>
  2695. <li><code>notif_mail.html</code> (which, by default, includes <code>room.html</code> and
  2696. <code>notif.html</code>)</li>
  2697. <li><code>password_reset.html</code></li>
  2698. <li><code>password_reset_confirmation.html</code></li>
  2699. <li><code>password_reset_failure.html</code></li>
  2700. <li><code>password_reset_success.html</code></li>
  2701. <li><code>registration.html</code></li>
  2702. <li><code>registration_failure.html</code></li>
  2703. <li><code>registration_success.html</code></li>
  2704. <li><code>sso_account_deactivated.html</code></li>
  2705. <li><code>sso_auth_bad_user.html</code></li>
  2706. <li><code>sso_auth_confirm.html</code></li>
  2707. <li><code>sso_auth_success.html</code></li>
  2708. <li><code>sso_error.html</code></li>
  2709. <li><code>sso_login_idp_picker.html</code></li>
  2710. <li><code>sso_redirect_confirm.html</code></li>
  2711. </ul>
  2712. <h1 id="upgrading-to-v1260"><a class="header" href="#upgrading-to-v1260">Upgrading to v1.26.0</a></h1>
  2713. <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>
  2714. <p>v1.26.0 includes a lot of large changes. If something problematic
  2715. occurs, you may want to roll-back to a previous version of Synapse.
  2716. Because v1.26.0 also includes a new database schema version, reverting
  2717. that version is also required alongside the generic rollback
  2718. instructions mentioned above. In short, to roll back to v1.25.0 you need
  2719. to:</p>
  2720. <ol>
  2721. <li>
  2722. <p>Stop the server</p>
  2723. </li>
  2724. <li>
  2725. <p>Decrease the schema version in the database:</p>
  2726. <pre><code class="language-sql">UPDATE schema_version SET version = 58;
  2727. </code></pre>
  2728. </li>
  2729. <li>
  2730. <p>Delete the ignored users &amp; chain cover data:</p>
  2731. <pre><code class="language-sql">DROP TABLE IF EXISTS ignored_users;
  2732. UPDATE rooms SET has_auth_chain_index = false;
  2733. </code></pre>
  2734. <p>For PostgreSQL run:</p>
  2735. <pre><code class="language-sql">TRUNCATE event_auth_chain_links;
  2736. TRUNCATE event_auth_chains;
  2737. </code></pre>
  2738. <p>For SQLite run:</p>
  2739. <pre><code class="language-sql">DELETE FROM event_auth_chain_links;
  2740. DELETE FROM event_auth_chains;
  2741. </code></pre>
  2742. </li>
  2743. <li>
  2744. <p>Mark the deltas as not run (so they will re-run on upgrade).</p>
  2745. <pre><code class="language-sql">DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/01ignored_user.py&quot;;
  2746. DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/06chain_cover_index.sql&quot;;
  2747. </code></pre>
  2748. </li>
  2749. <li>
  2750. <p>Downgrade Synapse by following the instructions for your
  2751. installation method in the &quot;Rolling back to older versions&quot;
  2752. section above.</p>
  2753. </li>
  2754. </ol>
  2755. <h1 id="upgrading-to-v1250"><a class="header" href="#upgrading-to-v1250">Upgrading to v1.25.0</a></h1>
  2756. <h2 id="last-release-supporting-python-35"><a class="header" href="#last-release-supporting-python-35">Last release supporting Python 3.5</a></h2>
  2757. <p>This is the last release of Synapse which guarantees support with Python
  2758. 3.5, which passed its upstream End of Life date several months ago.</p>
  2759. <p>We will attempt to maintain support through March 2021, but without
  2760. guarantees.</p>
  2761. <p>In the future, Synapse will follow upstream schedules for ending support
  2762. of older versions of Python and PostgreSQL. Please upgrade to at least
  2763. Python 3.6 and PostgreSQL 9.6 as soon as possible.</p>
  2764. <h2 id="blacklisting-ip-ranges"><a class="header" href="#blacklisting-ip-ranges">Blacklisting IP ranges</a></h2>
  2765. <p>Synapse v1.25.0 includes new settings, <code>ip_range_blacklist</code> and
  2766. <code>ip_range_whitelist</code>, for controlling outgoing requests from Synapse for
  2767. federation, identity servers, push, and for checking key validity for
  2768. third-party invite events. The previous setting,
  2769. <code>federation_ip_range_blacklist</code>, is deprecated. The new
  2770. <code>ip_range_blacklist</code> defaults to private IP ranges if it is not defined.</p>
  2771. <p>If you have never customised <code>federation_ip_range_blacklist</code> it is
  2772. recommended that you remove that setting.</p>
  2773. <p>If you have customised <code>federation_ip_range_blacklist</code> you should update
  2774. the setting name to <code>ip_range_blacklist</code>.</p>
  2775. <p>If you have a custom push server that is reached via private IP space
  2776. you may need to customise <code>ip_range_blacklist</code> or <code>ip_range_whitelist</code>.</p>
  2777. <h1 id="upgrading-to-v1240"><a class="header" href="#upgrading-to-v1240">Upgrading to v1.24.0</a></h1>
  2778. <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>
  2779. <p>This release allows the OpenID Connect mapping provider to perform
  2780. normalisation of the localpart of the Matrix ID. This allows for the
  2781. mapping provider to specify different algorithms, instead of the
  2782. <a href="https://matrix.org/docs/spec/appendices#mapping-from-other-character-sets">default
  2783. way</a>.</p>
  2784. <p>If your Synapse configuration uses a custom mapping provider
  2785. (<code>oidc_config.user_mapping_provider.module</code> is specified and
  2786. not equal to
  2787. <code>synapse.handlers.oidc_handler.JinjaOidcMappingProvider</code>)
  2788. then you <em>must</em> ensure that <code>map_user_attributes</code> of the
  2789. mapping provider performs some normalisation of the
  2790. <code>localpart</code> returned. To match previous behaviour you can
  2791. use the <code>map_username_to_mxid_localpart</code> function provided
  2792. by Synapse. An example is shown below:</p>
  2793. <pre><code class="language-python">from synapse.types import map_username_to_mxid_localpart
  2794. class MyMappingProvider:
  2795. def map_user_attributes(self, userinfo, token):
  2796. # ... your custom logic ...
  2797. sso_user_id = ...
  2798. localpart = map_username_to_mxid_localpart(sso_user_id)
  2799. return {&quot;localpart&quot;: localpart}
  2800. </code></pre>
  2801. <h2 id="removal-historical-synapse-admin-api"><a class="header" href="#removal-historical-synapse-admin-api">Removal historical Synapse Admin API</a></h2>
  2802. <p>Historically, the Synapse Admin API has been accessible under:</p>
  2803. <ul>
  2804. <li><code>/_matrix/client/api/v1/admin</code></li>
  2805. <li><code>/_matrix/client/unstable/admin</code></li>
  2806. <li><code>/_matrix/client/r0/admin</code></li>
  2807. <li><code>/_synapse/admin/v1</code></li>
  2808. </ul>
  2809. <p>The endpoints with <code>/_matrix/client/*</code> prefixes have been removed as of
  2810. v1.24.0. The Admin API is now only accessible under:</p>
  2811. <ul>
  2812. <li><code>/_synapse/admin/v1</code></li>
  2813. </ul>
  2814. <p>The only exception is the <code>/admin/whois</code> endpoint, which is
  2815. <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
  2816. API</a>.</p>
  2817. <p>The deprecation of the old endpoints was announced with Synapse 1.20.0
  2818. (released on 2020-09-22) and makes it easier for homeserver admins to
  2819. lock down external access to the Admin API endpoints.</p>
  2820. <h1 id="upgrading-to-v1230"><a class="header" href="#upgrading-to-v1230">Upgrading to v1.23.0</a></h1>
  2821. <h2 id="structured-logging-configuration-breaking-changes"><a class="header" href="#structured-logging-configuration-breaking-changes">Structured logging configuration breaking changes</a></h2>
  2822. <p>This release deprecates use of the <code>structured: true</code> logging
  2823. configuration for structured logging. If your logging configuration
  2824. contains <code>structured: true</code> then it should be modified based on the
  2825. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  2826. <p>The <code>structured</code> and <code>drains</code> logging options are now deprecated and
  2827. should be replaced by standard logging configuration of <code>handlers</code> and
  2828. <code>formatters</code>.</p>
  2829. <p>A future will release of Synapse will make using <code>structured: true</code> an
  2830. error.</p>
  2831. <h1 id="upgrading-to-v1220"><a class="header" href="#upgrading-to-v1220">Upgrading to v1.22.0</a></h1>
  2832. <h2 id="thirdpartyeventrules-breaking-changes"><a class="header" href="#thirdpartyeventrules-breaking-changes">ThirdPartyEventRules breaking changes</a></h2>
  2833. <p>This release introduces a backwards-incompatible change to modules
  2834. making use of <code>ThirdPartyEventRules</code> in Synapse. If you make use of a
  2835. module defined under the <code>third_party_event_rules</code> config option, please
  2836. make sure it is updated to handle the below change:</p>
  2837. <p>The <code>http_client</code> argument is no longer passed to modules as they are
  2838. initialised. Instead, modules are expected to make use of the
  2839. <code>http_client</code> property on the <code>ModuleApi</code> class. Modules are now passed
  2840. a <code>module_api</code> argument during initialisation, which is an instance of
  2841. <code>ModuleApi</code>. <code>ModuleApi</code> instances have a <code>http_client</code> property which
  2842. acts the same as the <code>http_client</code> argument previously passed to
  2843. <code>ThirdPartyEventRules</code> modules.</p>
  2844. <h1 id="upgrading-to-v1210"><a class="header" href="#upgrading-to-v1210">Upgrading to v1.21.0</a></h1>
  2845. <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>
  2846. <p>The <a href="reverse_proxy.html">reverse proxy documentation</a>
  2847. has been updated to include reverse proxy directives for
  2848. <code>/_synapse/client/*</code> endpoints. As the user password reset flow now uses
  2849. endpoints under this prefix, <strong>you must update your reverse proxy
  2850. configurations for user password reset to work</strong>.</p>
  2851. <p>Additionally, note that the <a href="workers.html">Synapse worker documentation</a> has been updated to</p>
  2852. <p>: state that the <code>/_synapse/client/password_reset/email/submit_token</code>
  2853. endpoint can be handled</p>
  2854. <p>by all workers. If you make use of Synapse's worker feature, please
  2855. update your reverse proxy configuration to reflect this change.</p>
  2856. <h2 id="new-html-templates"><a class="header" href="#new-html-templates">New HTML templates</a></h2>
  2857. <p>A new HTML template,
  2858. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/res/templates/password_reset_confirmation.html">password_reset_confirmation.html</a>,
  2859. has been added to the <code>synapse/res/templates</code> directory. If you are
  2860. using a custom template directory, you may want to copy the template
  2861. over and modify it.</p>
  2862. <p>Note that as of v1.20.0, templates do not need to be included in custom
  2863. template directories for Synapse to start. The default templates will be
  2864. used if a custom template cannot be found.</p>
  2865. <p>This page will appear to the user after clicking a password reset link
  2866. that has been emailed to them.</p>
  2867. <p>To complete password reset, the page must include a way to make a
  2868. <code>POST</code> request to
  2869. <code>/_synapse/client/password_reset/{medium}/submit_token</code> with the query
  2870. parameters from the original link, presented as a URL-encoded form. See
  2871. the file itself for more details.</p>
  2872. <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>
  2873. <p>The <code>saml_error.html</code> template was removed from Synapse and replaced
  2874. with the <code>sso_error.html</code> template. If your Synapse is configured to use
  2875. SAML and a custom <code>sso_redirect_confirm_template_dir</code> configuration then
  2876. any customisations of the <code>saml_error.html</code> template will need to be
  2877. merged into the <code>sso_error.html</code> template. These templates are similar,
  2878. but the parameters are slightly different:</p>
  2879. <ul>
  2880. <li>The <code>msg</code> parameter should be renamed to <code>error_description</code>.</li>
  2881. <li>There is no longer a <code>code</code> parameter for the response code.</li>
  2882. <li>A string <code>error</code> parameter is available that includes a short hint
  2883. of why a user is seeing the error page.</li>
  2884. </ul>
  2885. <h1 id="upgrading-to-v1180"><a class="header" href="#upgrading-to-v1180">Upgrading to v1.18.0</a></h1>
  2886. <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>
  2887. <p>From 10th August 2020, we will no longer publish Docker images with the
  2888. <code>-py3</code> tag suffix. The images tagged with the
  2889. <code>-py3</code> suffix have been identical to the non-suffixed tags
  2890. since release 0.99.0, and the suffix is obsolete.</p>
  2891. <p>On 10th August, we will remove the <code>latest-py3</code> tag.
  2892. Existing per-release tags (such as <code>v1.18.0-py3</code> will not
  2893. be removed, but no new <code>-py3</code> tags will be added.</p>
  2894. <p>Scripts relying on the <code>-py3</code> suffix will need to be
  2895. updated.</p>
  2896. <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>
  2897. <p>When setting up worker processes, we now recommend the use of a Redis
  2898. server for replication. <strong>The old direct TCP connection method is
  2899. deprecated and will be removed in a future release.</strong> See
  2900. the <a href="https://matrix-org.github.io/synapse/v1.66/workers.html">worker documentation</a> for more details.</p>
  2901. <h1 id="upgrading-to-v1140"><a class="header" href="#upgrading-to-v1140">Upgrading to v1.14.0</a></h1>
  2902. <p>This version includes a database update which is run as part of the
  2903. upgrade, and which may take a couple of minutes in the case of a large
  2904. server. Synapse will not respond to HTTP requests while this update is
  2905. taking place.</p>
  2906. <h1 id="upgrading-to-v1130"><a class="header" href="#upgrading-to-v1130">Upgrading to v1.13.0</a></h1>
  2907. <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>
  2908. <p>A bug was introduced in Synapse 1.4.0 which could cause the room
  2909. directory to be incomplete or empty if Synapse was upgraded directly
  2910. from v1.2.1 or earlier, to versions between v1.4.0 and v1.12.x.</p>
  2911. <p>This will <em>not</em> be a problem for Synapse installations which were:</p>
  2912. <p>: - created at v1.4.0 or later,
  2913. - upgraded via v1.3.x, or
  2914. - upgraded straight from v1.2.1 or earlier to v1.13.0 or later.</p>
  2915. <p>If completeness of the room directory is a concern, installations which
  2916. are affected can be repaired as follows:</p>
  2917. <ol>
  2918. <li>
  2919. <p>Run the following sql from a <code>psql</code> or
  2920. <code>sqlite3</code> console:</p>
  2921. <pre><code class="language-sql">INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2922. ('populate_stats_process_rooms', '{}', 'current_state_events_membership');
  2923. INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2924. ('populate_stats_process_users', '{}', 'populate_stats_process_rooms');
  2925. </code></pre>
  2926. </li>
  2927. <li>
  2928. <p>Restart synapse.</p>
  2929. </li>
  2930. </ol>
  2931. <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>
  2932. <p>New templates (<code>sso_auth_confirm.html</code>, <code>sso_auth_success.html</code>, and
  2933. <code>sso_account_deactivated.html</code>) were added to Synapse. If your Synapse
  2934. is configured to use SSO and a custom
  2935. <code>sso_redirect_confirm_template_dir</code> configuration then these templates
  2936. will need to be copied from
  2937. <a href="https://github.com/matrix-org/synapse/tree/develop/synapse/res/templates"><code>synapse/res/templates</code></a> into that directory.</p>
  2938. <h2 id="synapse-sso-plugins-method-deprecation"><a class="header" href="#synapse-sso-plugins-method-deprecation">Synapse SSO Plugins Method Deprecation</a></h2>
  2939. <p>Plugins using the <code>complete_sso_login</code> method of
  2940. <code>synapse.module_api.ModuleApi</code> should update to using the async/await
  2941. version <code>complete_sso_login_async</code> which includes additional checks. The
  2942. non-async version is considered deprecated.</p>
  2943. <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>
  2944. <p>v1.13.0 includes a lot of large changes. If something problematic
  2945. occurs, you may want to roll-back to a previous version of Synapse.
  2946. Because v1.13.0 also includes a new database schema version, reverting
  2947. that version is also required alongside the generic rollback
  2948. instructions mentioned above. In short, to roll back to v1.12.4 you need
  2949. to:</p>
  2950. <ol>
  2951. <li>
  2952. <p>Stop the server</p>
  2953. </li>
  2954. <li>
  2955. <p>Decrease the schema version in the database:</p>
  2956. <pre><code class="language-sql">UPDATE schema_version SET version = 57;
  2957. </code></pre>
  2958. </li>
  2959. <li>
  2960. <p>Downgrade Synapse by following the instructions for your
  2961. installation method in the &quot;Rolling back to older versions&quot;
  2962. section above.</p>
  2963. </li>
  2964. </ol>
  2965. <h1 id="upgrading-to-v1120"><a class="header" href="#upgrading-to-v1120">Upgrading to v1.12.0</a></h1>
  2966. <p>This version includes a database update which is run as part of the
  2967. upgrade, and which may take some time (several hours in the case of a
  2968. large server). Synapse will not respond to HTTP requests while this
  2969. update is taking place.</p>
  2970. <p>This is only likely to be a problem in the case of a server which is
  2971. participating in many rooms.</p>
  2972. <ol start="0">
  2973. <li>
  2974. <p>As with all upgrades, it is recommended that you have a recent
  2975. backup of your database which can be used for recovery in the event
  2976. of any problems.</p>
  2977. </li>
  2978. <li>
  2979. <p>As an initial check to see if you will be affected, you can try
  2980. running the following query from the <code>psql</code> or
  2981. <code>sqlite3</code> console. It is safe to run it while Synapse is
  2982. still running.</p>
  2983. <pre><code class="language-sql">SELECT MAX(q.v) FROM (
  2984. SELECT (
  2985. SELECT ej.json AS v
  2986. FROM state_events se INNER JOIN event_json ej USING (event_id)
  2987. WHERE se.room_id=rooms.room_id AND se.type='m.room.create' AND se.state_key=''
  2988. LIMIT 1
  2989. ) FROM rooms WHERE rooms.room_version IS NULL
  2990. ) q;
  2991. </code></pre>
  2992. <p>This query will take about the same amount of time as the upgrade
  2993. process: ie, if it takes 5 minutes, then it is likely that Synapse
  2994. will be unresponsive for 5 minutes during the upgrade.</p>
  2995. <p>If you consider an outage of this duration to be acceptable, no
  2996. further action is necessary and you can simply start Synapse 1.12.0.</p>
  2997. <p>If you would prefer to reduce the downtime, continue with the steps
  2998. below.</p>
  2999. </li>
  3000. <li>
  3001. <p>The easiest workaround for this issue is to manually create a new
  3002. index before upgrading. On PostgreSQL, his can be done as follows:</p>
  3003. <pre><code class="language-sql">CREATE INDEX CONCURRENTLY tmp_upgrade_1_12_0_index
  3004. ON state_events(room_id) WHERE type = 'm.room.create';
  3005. </code></pre>
  3006. <p>The above query may take some time, but is also safe to run while
  3007. Synapse is running.</p>
  3008. <p>We assume that no SQLite users have databases large enough to be
  3009. affected. If you <em>are</em> affected, you can run a similar query,
  3010. omitting the <code>CONCURRENTLY</code> keyword. Note however that this
  3011. operation may in itself cause Synapse to stop running for some time.
  3012. Synapse admins are reminded that <a href="postgres.html">SQLite is not recommended for use
  3013. outside a test environment</a>.</p>
  3014. </li>
  3015. <li>
  3016. <p>Once the index has been created, the <code>SELECT</code> query in step 1 above
  3017. should complete quickly. It is therefore safe to upgrade to Synapse
  3018. 1.12.0.</p>
  3019. </li>
  3020. <li>
  3021. <p>Once Synapse 1.12.0 has successfully started and is responding to
  3022. HTTP requests, the temporary index can be removed:</p>
  3023. <pre><code class="language-sql">DROP INDEX tmp_upgrade_1_12_0_index;
  3024. </code></pre>
  3025. </li>
  3026. </ol>
  3027. <h1 id="upgrading-to-v1100"><a class="header" href="#upgrading-to-v1100">Upgrading to v1.10.0</a></h1>
  3028. <p>Synapse will now log a warning on start up if used with a PostgreSQL
  3029. database that has a non-recommended locale set.</p>
  3030. <p>See <a href="postgres.html">Postgres</a> for details.</p>
  3031. <h1 id="upgrading-to-v180"><a class="header" href="#upgrading-to-v180">Upgrading to v1.8.0</a></h1>
  3032. <p>Specifying a <code>log_file</code> config option will now cause Synapse to refuse
  3033. to start, and should be replaced by with the <code>log_config</code> option.
  3034. Support for the <code>log_file</code> option was removed in v1.3.0 and has since
  3035. had no effect.</p>
  3036. <h1 id="upgrading-to-v170"><a class="header" href="#upgrading-to-v170">Upgrading to v1.7.0</a></h1>
  3037. <p>In an attempt to configure Synapse in a privacy preserving way, the
  3038. default behaviours of <code>allow_public_rooms_without_auth</code> and
  3039. <code>allow_public_rooms_over_federation</code> have been inverted. This means that
  3040. by default, only authenticated users querying the Client/Server API will
  3041. be able to query the room directory, and relatedly that the server will
  3042. not share room directory information with other servers over federation.</p>
  3043. <p>If your installation does not explicitly set these settings one way or
  3044. the other and you want either setting to be <code>true</code> then it will
  3045. necessary to update your homeserver configuration file accordingly.</p>
  3046. <p>For more details on the surrounding context see our
  3047. <a href="https://matrix.org/blog/2019/11/09/avoiding-unwelcome-visitors-on-private-matrix-servers">explainer</a>.</p>
  3048. <h1 id="upgrading-to-v150"><a class="header" href="#upgrading-to-v150">Upgrading to v1.5.0</a></h1>
  3049. <p>This release includes a database migration which may take several
  3050. minutes to complete if there are a large number (more than a million or
  3051. so) of entries in the <code>devices</code> table. This is only likely to a be a
  3052. problem on very large installations.</p>
  3053. <h1 id="upgrading-to-v140"><a class="header" href="#upgrading-to-v140">Upgrading to v1.4.0</a></h1>
  3054. <h2 id="new-custom-templates"><a class="header" href="#new-custom-templates">New custom templates</a></h2>
  3055. <p>If you have configured a custom template directory with the
  3056. <code>email.template_dir</code> option, be aware that there are new templates
  3057. regarding registration and threepid management (see below) that must be
  3058. included.</p>
  3059. <ul>
  3060. <li><code>registration.html</code> and <code>registration.txt</code></li>
  3061. <li><code>registration_success.html</code> and <code>registration_failure.html</code></li>
  3062. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code></li>
  3063. <li><code>add_threepid_failure.html</code> and <code>add_threepid_success.html</code></li>
  3064. </ul>
  3065. <p>Synapse will expect these files to exist inside the configured template
  3066. directory, and <strong>will fail to start</strong> if they are absent. To view the
  3067. default templates, see
  3068. <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">synapse/res/templates</a>.</p>
  3069. <h2 id="3pid-verification-changes"><a class="header" href="#3pid-verification-changes">3pid verification changes</a></h2>
  3070. <p><strong>Note: As of this release, users will be unable to add phone numbers or
  3071. email addresses to their accounts, without changes to the Synapse
  3072. configuration. This includes adding an email address during
  3073. registration.</strong></p>
  3074. <p>It is possible for a user to associate an email address or phone number
  3075. with their account, for a number of reasons:</p>
  3076. <ul>
  3077. <li>for use when logging in, as an alternative to the user id.</li>
  3078. <li>in the case of email, as an alternative contact to help with account
  3079. recovery.</li>
  3080. <li>in the case of email, to receive notifications of missed messages.</li>
  3081. </ul>
  3082. <p>Before an email address or phone number can be added to a user's
  3083. account, or before such an address is used to carry out a
  3084. password-reset, Synapse must confirm the operation with the owner of the
  3085. email address or phone number. It does this by sending an email or text
  3086. giving the user a link or token to confirm receipt. This process is
  3087. known as '3pid verification'. ('3pid', or 'threepid', stands for
  3088. third-party identifier, and we use it to refer to external identifiers
  3089. such as email addresses and phone numbers.)</p>
  3090. <p>Previous versions of Synapse delegated the task of 3pid verification to
  3091. an identity server by default. In most cases this server is <code>vector.im</code>
  3092. or <code>matrix.org</code>.</p>
  3093. <p>In Synapse 1.4.0, for security and privacy reasons, the homeserver will
  3094. no longer delegate this task to an identity server by default. Instead,
  3095. the server administrator will need to explicitly decide how they would
  3096. like the verification messages to be sent.</p>
  3097. <p>In the medium term, the <code>vector.im</code> and <code>matrix.org</code> identity servers
  3098. will disable support for delegated 3pid verification entirely. However,
  3099. in order to ease the transition, they will retain the capability for a
  3100. limited period. Delegated email verification will be disabled on Monday
  3101. 2nd December 2019 (giving roughly 2 months notice). Disabling delegated
  3102. SMS verification will follow some time after that once SMS verification
  3103. support lands in Synapse.</p>
  3104. <p>Once delegated 3pid verification support has been disabled in the
  3105. <code>vector.im</code> and <code>matrix.org</code> identity servers, all Synapse versions that
  3106. depend on those instances will be unable to verify email and phone
  3107. numbers through them. There are no imminent plans to remove delegated
  3108. 3pid verification from Sydent generally. (Sydent is the identity server
  3109. project that backs the <code>vector.im</code> and <code>matrix.org</code> instances).</p>
  3110. <h3 id="email-1"><a class="header" href="#email-1">Email</a></h3>
  3111. <p>Following upgrade, to continue verifying email (e.g. as part of the
  3112. registration process), admins can either:-</p>
  3113. <ul>
  3114. <li>Configure Synapse to use an email server.</li>
  3115. <li>Run or choose an identity server which allows delegated email
  3116. verification and delegate to it.</li>
  3117. </ul>
  3118. <h4 id="configure-smtp-in-synapse"><a class="header" href="#configure-smtp-in-synapse">Configure SMTP in Synapse</a></h4>
  3119. <p>To configure an SMTP server for Synapse, modify the configuration
  3120. section headed <code>email</code>, and be sure to have at least the
  3121. <code>smtp_host, smtp_port</code> and <code>notif_from</code> fields filled out.</p>
  3122. <p>You may also need to set <code>smtp_user</code>, <code>smtp_pass</code>, and
  3123. <code>require_transport_security</code>.</p>
  3124. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  3125. for more details on these settings.</p>
  3126. <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>
  3127. <p>Some admins will wish to continue using email verification as part of
  3128. the registration process, but will not immediately have an appropriate
  3129. SMTP server at hand.</p>
  3130. <p>To this end, we will continue to support email verification delegation
  3131. via the <code>vector.im</code> and <code>matrix.org</code> identity servers for two months.
  3132. Support for delegated email verification will be disabled on Monday 2nd
  3133. December.</p>
  3134. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  3135. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  3136. server</a>) to handle
  3137. sending confirmation messages via email and SMS.</p>
  3138. <p>So to delegate email verification, in <code>homeserver.yaml</code>, set
  3139. <code>account_threepid_delegates.email</code> to the base URL of an identity
  3140. server. For example:</p>
  3141. <pre><code class="language-yaml">account_threepid_delegates:
  3142. email: https://example.com # Delegate email sending to example.com
  3143. </code></pre>
  3144. <p>Note that <code>account_threepid_delegates.email</code> replaces the deprecated
  3145. <code>email.trust_identity_server_for_password_resets</code>: if
  3146. <code>email.trust_identity_server_for_password_resets</code> is set to <code>true</code>, and
  3147. <code>account_threepid_delegates.email</code> is not set, then the first entry in
  3148. <code>trusted_third_party_id_servers</code> will be used as the
  3149. <code>account_threepid_delegate</code> for email. This is to ensure compatibility
  3150. with existing Synapse installs that set up external server handling for
  3151. these tasks before v1.4.0. If
  3152. <code>email.trust_identity_server_for_password_resets</code> is <code>true</code> and no
  3153. trusted identity server domains are configured, Synapse will report an
  3154. error and refuse to start.</p>
  3155. <p>If <code>email.trust_identity_server_for_password_resets</code> is <code>false</code> or
  3156. absent and no <code>email</code> delegate is configured in
  3157. <code>account_threepid_delegates</code>, then Synapse will send email verification
  3158. messages itself, using the configured SMTP server (see above). that
  3159. type.</p>
  3160. <h3 id="phone-numbers"><a class="header" href="#phone-numbers">Phone numbers</a></h3>
  3161. <p>Synapse does not support phone-number verification itself, so the only
  3162. way to maintain the ability for users to add phone numbers to their
  3163. accounts will be by continuing to delegate phone number verification to
  3164. the <code>matrix.org</code> and <code>vector.im</code> identity servers (or another identity
  3165. server that supports SMS sending).</p>
  3166. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  3167. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  3168. server</a>) to handle
  3169. sending confirmation messages via email and SMS.</p>
  3170. <p>So to delegate phone number verification, in <code>homeserver.yaml</code>, set
  3171. <code>account_threepid_delegates.msisdn</code> to the base URL of an identity
  3172. server. For example:</p>
  3173. <pre><code class="language-yaml">account_threepid_delegates:
  3174. msisdn: https://example.com # Delegate sms sending to example.com
  3175. </code></pre>
  3176. <p>The <code>matrix.org</code> and <code>vector.im</code> identity servers will continue to
  3177. support delegated phone number verification via SMS until such time as
  3178. it is possible for admins to configure their servers to perform phone
  3179. number verification directly. More details will follow in a future
  3180. release.</p>
  3181. <h2 id="rolling-back-to-v131"><a class="header" href="#rolling-back-to-v131">Rolling back to v1.3.1</a></h2>
  3182. <p>If you encounter problems with v1.4.0, it should be possible to roll
  3183. back to v1.3.1, subject to the following:</p>
  3184. <ul>
  3185. <li>
  3186. <p>The 'room statistics' engine was heavily reworked in this release
  3187. (see <a href="https://github.com/matrix-org/synapse/pull/5971">#5971</a>),
  3188. including significant changes to the database schema, which are not
  3189. easily reverted. This will cause the room statistics engine to stop
  3190. updating when you downgrade.</p>
  3191. <p>The room statistics are essentially unused in v1.3.1 (in future
  3192. versions of Synapse, they will be used to populate the room
  3193. directory), so there should be no loss of functionality. However,
  3194. the statistics engine will write errors to the logs, which can be
  3195. avoided by setting the following in <code>homeserver.yaml</code>:</p>
  3196. <pre><code class="language-yaml">stats:
  3197. enabled: false
  3198. </code></pre>
  3199. <p>Don't forget to re-enable it when you upgrade again, in preparation
  3200. for its use in the room directory!</p>
  3201. </li>
  3202. </ul>
  3203. <h1 id="upgrading-to-v120"><a class="header" href="#upgrading-to-v120">Upgrading to v1.2.0</a></h1>
  3204. <p>Some counter metrics have been renamed, with the old names deprecated.
  3205. See <a href="metrics-howto.html#renaming-of-metrics--deprecation-of-old-names-in-12">the metrics
  3206. documentation</a>
  3207. for details.</p>
  3208. <h1 id="upgrading-to-v110"><a class="header" href="#upgrading-to-v110">Upgrading to v1.1.0</a></h1>
  3209. <p>Synapse v1.1.0 removes support for older Python and PostgreSQL versions,
  3210. as outlined in <a href="https://matrix.org/blog/2019/04/08/synapse-deprecating-postgres-9-4-and-python-2-x">our deprecation
  3211. notice</a>.</p>
  3212. <h2 id="minimum-python-version"><a class="header" href="#minimum-python-version">Minimum Python Version</a></h2>
  3213. <p>Synapse v1.1.0 has a minimum Python requirement of Python 3.5. Python
  3214. 3.6 or Python 3.7 are recommended as they have improved internal string
  3215. handling, significantly reducing memory usage.</p>
  3216. <p>If you use current versions of the Matrix.org-distributed Debian
  3217. packages or Docker images, action is not required.</p>
  3218. <p>If you install Synapse in a Python virtual environment, please see
  3219. &quot;Upgrading to v0.34.0&quot; for notes on setting up a new virtualenv under
  3220. Python 3.</p>
  3221. <h2 id="minimum-postgresql-version"><a class="header" href="#minimum-postgresql-version">Minimum PostgreSQL Version</a></h2>
  3222. <p>If using PostgreSQL under Synapse, you will need to use PostgreSQL 9.5
  3223. or above. Please see the <a href="https://www.postgresql.org/docs/11/upgrading.html">PostgreSQL
  3224. documentation</a> for
  3225. more details on upgrading your database.</p>
  3226. <h1 id="upgrading-to-v10"><a class="header" href="#upgrading-to-v10">Upgrading to v1.0</a></h1>
  3227. <h2 id="validation-of-tls-certificates"><a class="header" href="#validation-of-tls-certificates">Validation of TLS certificates</a></h2>
  3228. <p>Synapse v1.0 is the first release to enforce validation of TLS
  3229. certificates for the federation API. It is therefore essential that your
  3230. certificates are correctly configured.</p>
  3231. <p>Note, v1.0 installations will also no longer be able to federate with
  3232. servers that have not correctly configured their certificates.</p>
  3233. <p>In rare cases, it may be desirable to disable certificate checking: for
  3234. example, it might be essential to be able to federate with a given
  3235. legacy server in a closed federation. This can be done in one of two
  3236. ways:-</p>
  3237. <ul>
  3238. <li>Configure the global switch <code>federation_verify_certificates</code> to
  3239. <code>false</code>.</li>
  3240. <li>Configure a whitelist of server domains to trust via
  3241. <code>federation_certificate_verification_whitelist</code>.</li>
  3242. </ul>
  3243. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  3244. for more details on these settings.</p>
  3245. <h2 id="email-2"><a class="header" href="#email-2">Email</a></h2>
  3246. <p>When a user requests a password reset, Synapse will send an email to the
  3247. user to confirm the request.</p>
  3248. <p>Previous versions of Synapse delegated the job of sending this email to
  3249. an identity server. If the identity server was somehow malicious or
  3250. became compromised, it would be theoretically possible to hijack an
  3251. account through this means.</p>
  3252. <p>Therefore, by default, Synapse v1.0 will send the confirmation email
  3253. itself. If Synapse is not configured with an SMTP server, password reset
  3254. via email will be disabled.</p>
  3255. <p>To configure an SMTP server for Synapse, modify the configuration
  3256. section headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>,
  3257. <code>smtp_port</code> and <code>notif_from</code> fields filled out. You may also need to set
  3258. <code>smtp_user</code>, <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  3259. <p>If you are absolutely certain that you wish to continue using an
  3260. identity server for password resets, set
  3261. <code>trust_identity_server_for_password_resets</code> to <code>true</code>.</p>
  3262. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  3263. for more details on these settings.</p>
  3264. <h2 id="new-email-templates"><a class="header" href="#new-email-templates">New email templates</a></h2>
  3265. <p>Some new templates have been added to the default template directory for the purpose of
  3266. the homeserver sending its own password reset emails. If you have configured a
  3267. custom <code>template_dir</code> in your Synapse config, these files will need to be added.</p>
  3268. <p><code>password_reset.html</code> and <code>password_reset.txt</code> are HTML and plain text
  3269. templates respectively that contain the contents of what will be emailed
  3270. to the user upon attempting to reset their password via email.
  3271. <code>password_reset_success.html</code> and <code>password_reset_failure.html</code> are HTML
  3272. files that the content of which (assuming no redirect URL is set) will
  3273. be shown to the user after they attempt to click the link in the email
  3274. sent to them.</p>
  3275. <h1 id="upgrading-to-v0990"><a class="header" href="#upgrading-to-v0990">Upgrading to v0.99.0</a></h1>
  3276. <p>Please be aware that, before Synapse v1.0 is released around March 2019,
  3277. you will need to replace any self-signed certificates with those
  3278. verified by a root CA. Information on how to do so can be found at the
  3279. ACME docs.</p>
  3280. <h1 id="upgrading-to-v0340"><a class="header" href="#upgrading-to-v0340">Upgrading to v0.34.0</a></h1>
  3281. <ol>
  3282. <li>
  3283. <p>This release is the first to fully support Python 3. Synapse will
  3284. now run on Python versions 3.5, or 3.6 (as well as 2.7). We
  3285. recommend switching to Python 3, as it has been shown to give
  3286. performance improvements.</p>
  3287. <p>For users who have installed Synapse into a virtualenv, we recommend
  3288. doing this by creating a new virtualenv. For example:</p>
  3289. <pre><code class="language-sh">virtualenv -p python3 ~/synapse/env3
  3290. source ~/synapse/env3/bin/activate
  3291. pip install matrix-synapse
  3292. </code></pre>
  3293. <p>You can then start synapse as normal, having activated the new
  3294. virtualenv:</p>
  3295. <pre><code class="language-sh">cd ~/synapse
  3296. source env3/bin/activate
  3297. synctl start
  3298. </code></pre>
  3299. <p>Users who have installed from distribution packages should see the
  3300. relevant package documentation. See below for notes on Debian
  3301. packages.</p>
  3302. <ul>
  3303. <li>
  3304. <p>When upgrading to Python 3, you <strong>must</strong> make sure that your log
  3305. files are configured as UTF-8, by adding <code>encoding: utf8</code> to the
  3306. <code>RotatingFileHandler</code> configuration (if you have one) in your
  3307. <code>&lt;server&gt;.log.config</code> file. For example, if your <code>log.config</code>
  3308. file contains:</p>
  3309. <pre><code class="language-yaml">handlers:
  3310. file:
  3311. class: logging.handlers.RotatingFileHandler
  3312. formatter: precise
  3313. filename: homeserver.log
  3314. maxBytes: 104857600
  3315. backupCount: 10
  3316. filters: [context]
  3317. console:
  3318. class: logging.StreamHandler
  3319. formatter: precise
  3320. filters: [context]
  3321. </code></pre>
  3322. <p>Then you should update this to be:</p>
  3323. <pre><code class="language-yaml">handlers:
  3324. file:
  3325. class: logging.handlers.RotatingFileHandler
  3326. formatter: precise
  3327. filename: homeserver.log
  3328. maxBytes: 104857600
  3329. backupCount: 10
  3330. filters: [context]
  3331. encoding: utf8
  3332. console:
  3333. class: logging.StreamHandler
  3334. formatter: precise
  3335. filters: [context]
  3336. </code></pre>
  3337. <p>There is no need to revert this change if downgrading to
  3338. Python 2.</p>
  3339. </li>
  3340. </ul>
  3341. <p>We are also making available Debian packages which will run Synapse
  3342. on Python 3. You can switch to these packages with
  3343. <code>apt-get install matrix-synapse-py3</code>, however, please read
  3344. <a href="https://github.com/matrix-org/synapse/blob/release-v0.34.0/debian/NEWS">debian/NEWS</a>
  3345. before doing so. The existing <code>matrix-synapse</code> packages will
  3346. continue to use Python 2 for the time being.</p>
  3347. </li>
  3348. <li>
  3349. <p>This release removes the <code>riot.im</code> from the default list of trusted
  3350. identity servers.</p>
  3351. <p>If <code>riot.im</code> is in your homeserver's list of
  3352. <code>trusted_third_party_id_servers</code>, you should remove it. It was added
  3353. in case a hypothetical future identity server was put there. If you
  3354. don't remove it, users may be unable to deactivate their accounts.</p>
  3355. </li>
  3356. <li>
  3357. <p>This release no longer installs the (unmaintained) Matrix Console
  3358. web client as part of the default installation. It is possible to
  3359. re-enable it by installing it separately and setting the
  3360. <code>web_client_location</code> config option, but please consider switching
  3361. to another client.</p>
  3362. </li>
  3363. </ol>
  3364. <h1 id="upgrading-to-v0337"><a class="header" href="#upgrading-to-v0337">Upgrading to v0.33.7</a></h1>
  3365. <p>This release removes the example email notification templates from
  3366. <code>res/templates</code> (they are now internal to the python package). This
  3367. should only affect you if you (a) deploy your Synapse instance from a
  3368. git checkout or a github snapshot URL, and (b) have email notifications
  3369. enabled.</p>
  3370. <p>If you have email notifications enabled, you should ensure that
  3371. <code>email.template_dir</code> is either configured to point at a directory where
  3372. you have installed customised templates, or leave it unset to use the
  3373. default templates.</p>
  3374. <h1 id="upgrading-to-v0273"><a class="header" href="#upgrading-to-v0273">Upgrading to v0.27.3</a></h1>
  3375. <p>This release expands the anonymous usage stats sent if the opt-in
  3376. <code>report_stats</code> configuration is set to <code>true</code>. We now capture RSS memory
  3377. and cpu use at a very coarse level. This requires administrators to
  3378. install the optional <code>psutil</code> python module.</p>
  3379. <p>We would appreciate it if you could assist by ensuring this module is
  3380. available and <code>report_stats</code> is enabled. This will let us see if
  3381. performance changes to synapse are having an impact to the general
  3382. community.</p>
  3383. <h1 id="upgrading-to-v0150"><a class="header" href="#upgrading-to-v0150">Upgrading to v0.15.0</a></h1>
  3384. <p>If you want to use the new URL previewing API
  3385. (<code>/_matrix/media/r0/preview_url</code>) then you have to explicitly enable it
  3386. in the config and update your dependencies dependencies. See README.rst
  3387. for details.</p>
  3388. <h1 id="upgrading-to-v0110"><a class="header" href="#upgrading-to-v0110">Upgrading to v0.11.0</a></h1>
  3389. <p>This release includes the option to send anonymous usage stats to
  3390. matrix.org, and requires that administrators explictly opt in or out by
  3391. setting the <code>report_stats</code> option to either <code>true</code> or <code>false</code>.</p>
  3392. <p>We would really appreciate it if you could help our project out by
  3393. reporting anonymized usage statistics from your homeserver. Only very
  3394. basic aggregate data (e.g. number of users) will be reported, but it
  3395. helps us to track the growth of the Matrix community, and helps us to
  3396. make Matrix a success, as well as to convince other networks that they
  3397. should peer with us.</p>
  3398. <h1 id="upgrading-to-v090"><a class="header" href="#upgrading-to-v090">Upgrading to v0.9.0</a></h1>
  3399. <p>Application services have had a breaking API change in this version.</p>
  3400. <p>They can no longer register themselves with a home server using the AS
  3401. HTTP API. This decision was made because a compromised application
  3402. service with free reign to register any regex in effect grants full
  3403. read/write access to the home server if a regex of <code>.*</code> is used. An
  3404. attack where a compromised AS re-registers itself with <code>.*</code> was deemed
  3405. too big of a security risk to ignore, and so the ability to register
  3406. with the HS remotely has been removed.</p>
  3407. <p>It has been replaced by specifying a list of application service
  3408. registrations in <code>homeserver.yaml</code>:</p>
  3409. <pre><code class="language-yaml">app_service_config_files: [&quot;registration-01.yaml&quot;, &quot;registration-02.yaml&quot;]
  3410. </code></pre>
  3411. <p>Where <code>registration-01.yaml</code> looks like:</p>
  3412. <pre><code class="language-yaml">url: &lt;String&gt; # e.g. &quot;https://my.application.service.com&quot;
  3413. as_token: &lt;String&gt;
  3414. hs_token: &lt;String&gt;
  3415. sender_localpart: &lt;String&gt; # This is a new field which denotes the user_id localpart when using the AS token
  3416. namespaces:
  3417. users:
  3418. - exclusive: &lt;Boolean&gt;
  3419. regex: &lt;String&gt; # e.g. &quot;@prefix_.*&quot;
  3420. aliases:
  3421. - exclusive: &lt;Boolean&gt;
  3422. regex: &lt;String&gt;
  3423. rooms:
  3424. - exclusive: &lt;Boolean&gt;
  3425. regex: &lt;String&gt;
  3426. </code></pre>
  3427. <h1 id="upgrading-to-v080"><a class="header" href="#upgrading-to-v080">Upgrading to v0.8.0</a></h1>
  3428. <p>Servers which use captchas will need to add their public key to:</p>
  3429. <pre><code>static/client/register/register_config.js
  3430. window.matrixRegistrationConfig = {
  3431. recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  3432. };
  3433. </code></pre>
  3434. <p>This is required in order to support registration fallback (typically
  3435. used on mobile devices).</p>
  3436. <h1 id="upgrading-to-v070"><a class="header" href="#upgrading-to-v070">Upgrading to v0.7.0</a></h1>
  3437. <p>New dependencies are:</p>
  3438. <ul>
  3439. <li>pydenticon</li>
  3440. <li>simplejson</li>
  3441. <li>syutil</li>
  3442. <li>matrix-angular-sdk</li>
  3443. </ul>
  3444. <p>To pull in these dependencies in a virtual env, run:</p>
  3445. <pre><code>python synapse/python_dependencies.py | xargs -n 1 pip install
  3446. </code></pre>
  3447. <h1 id="upgrading-to-v060"><a class="header" href="#upgrading-to-v060">Upgrading to v0.6.0</a></h1>
  3448. <p>To pull in new dependencies, run:</p>
  3449. <pre><code>python setup.py develop --user
  3450. </code></pre>
  3451. <p>This update includes a change to the database schema. To upgrade you
  3452. first need to upgrade the database by running:</p>
  3453. <pre><code>python scripts/upgrade_db_to_v0.6.0.py &lt;db&gt; &lt;server_name&gt; &lt;signing_key&gt;
  3454. </code></pre>
  3455. <p>Where <code>&lt;db&gt;</code> is the location of the database,
  3456. <code>&lt;server_name&gt;</code> is the server name as specified in the
  3457. synapse configuration, and <code>&lt;signing_key&gt;</code> is the location
  3458. of the signing key as specified in the synapse configuration.</p>
  3459. <p>This may take some time to complete. Failures of signatures and content
  3460. hashes can safely be ignored.</p>
  3461. <h1 id="upgrading-to-v051"><a class="header" href="#upgrading-to-v051">Upgrading to v0.5.1</a></h1>
  3462. <p>Depending on precisely when you installed v0.5.0 you may have ended up
  3463. with a stale release of the reference matrix webclient installed as a
  3464. python module. To uninstall it and ensure you are depending on the
  3465. latest module, please run:</p>
  3466. <pre><code>$ pip uninstall syweb
  3467. </code></pre>
  3468. <h1 id="upgrading-to-v050"><a class="header" href="#upgrading-to-v050">Upgrading to v0.5.0</a></h1>
  3469. <p>The webclient has been split out into a seperate repository/pacakage in
  3470. this release. Before you restart your homeserver you will need to pull
  3471. in the webclient package by running:</p>
  3472. <pre><code>python setup.py develop --user
  3473. </code></pre>
  3474. <p>This release completely changes the database schema and so requires
  3475. upgrading it before starting the new version of the homeserver.</p>
  3476. <p>The script &quot;database-prepare-for-0.5.0.sh&quot; should be used to upgrade
  3477. the database. This will save all user information, such as logins and
  3478. profiles, but will otherwise purge the database. This includes messages,
  3479. which rooms the home server was a member of and room alias mappings.</p>
  3480. <p>If you would like to keep your history, please take a copy of your
  3481. database file and ask for help in #matrix:matrix.org. The upgrade
  3482. process is, unfortunately, non trivial and requires human intervention
  3483. to resolve any resulting conflicts during the upgrade process.</p>
  3484. <p>Before running the command the homeserver should be first completely
  3485. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3486. <blockquote>
  3487. <p>./scripts/database-prepare-for-0.5.0.sh &quot;homeserver.db&quot;</p>
  3488. </blockquote>
  3489. <p>Once this has successfully completed it will be safe to restart the
  3490. homeserver. You may notice that the homeserver takes a few seconds
  3491. longer to restart than usual as it reinitializes the database.</p>
  3492. <p>On startup of the new version, users can either rejoin remote rooms
  3493. using room aliases or by being reinvited. Alternatively, if any other
  3494. homeserver sends a message to a room that the homeserver was previously
  3495. in the local HS will automatically rejoin the room.</p>
  3496. <h1 id="upgrading-to-v040"><a class="header" href="#upgrading-to-v040">Upgrading to v0.4.0</a></h1>
  3497. <p>This release needs an updated syutil version. Run:</p>
  3498. <pre><code>python setup.py develop
  3499. </code></pre>
  3500. <p>You will also need to upgrade your configuration as the signing key
  3501. format has changed. Run:</p>
  3502. <pre><code>python -m synapse.app.homeserver --config-path &lt;CONFIG&gt; --generate-config
  3503. </code></pre>
  3504. <h1 id="upgrading-to-v030"><a class="header" href="#upgrading-to-v030">Upgrading to v0.3.0</a></h1>
  3505. <p>This registration API now closely matches the login API. This introduces
  3506. a bit more backwards and forwards between the HS and the client, but
  3507. this improves the overall flexibility of the API. You can now GET on
  3508. /register to retrieve a list of valid registration flows. Upon choosing
  3509. one, they are submitted in the same way as login, e.g:</p>
  3510. <pre><code>{
  3511. type: m.login.password,
  3512. user: foo,
  3513. password: bar
  3514. }
  3515. </code></pre>
  3516. <p>The default HS supports 2 flows, with and without Identity Server email
  3517. authentication. Enabling captcha on the HS will add in an extra step to
  3518. all flows: <code>m.login.recaptcha</code> which must be completed before you can
  3519. transition to the next stage. There is a new login type:
  3520. <code>m.login.email.identity</code> which contains the <code>threepidCreds</code> key which
  3521. were previously sent in the original register request. For more
  3522. information on this, see the specification.</p>
  3523. <h2 id="web-client"><a class="header" href="#web-client">Web Client</a></h2>
  3524. <p>The VoIP specification has changed between v0.2.0 and v0.3.0. Users
  3525. should refresh any browser tabs to get the latest web client code. Users
  3526. on v0.2.0 of the web client will not be able to call those on v0.3.0 and
  3527. vice versa.</p>
  3528. <h1 id="upgrading-to-v020"><a class="header" href="#upgrading-to-v020">Upgrading to v0.2.0</a></h1>
  3529. <p>The home server now requires setting up of SSL config before it can run.
  3530. To automatically generate default config use:</p>
  3531. <pre><code>$ python synapse/app/homeserver.py \
  3532. --server-name machine.my.domain.name \
  3533. --bind-port 8448 \
  3534. --config-path homeserver.config \
  3535. --generate-config
  3536. </code></pre>
  3537. <p>This config can be edited if desired, for example to specify a different
  3538. SSL certificate to use. Once done you can run the home server using:</p>
  3539. <pre><code>$ python synapse/app/homeserver.py --config-path homeserver.config
  3540. </code></pre>
  3541. <p>See the README.rst for more information.</p>
  3542. <p>Also note that some config options have been renamed, including:</p>
  3543. <ul>
  3544. <li>&quot;host&quot; to &quot;server-name&quot;</li>
  3545. <li>&quot;database&quot; to &quot;database-path&quot;</li>
  3546. <li>&quot;port&quot; to &quot;bind-port&quot; and &quot;unsecure-port&quot;</li>
  3547. </ul>
  3548. <h1 id="upgrading-to-v001"><a class="header" href="#upgrading-to-v001">Upgrading to v0.0.1</a></h1>
  3549. <p>This release completely changes the database schema and so requires
  3550. upgrading it before starting the new version of the homeserver.</p>
  3551. <p>The script &quot;database-prepare-for-0.0.1.sh&quot; should be used to upgrade
  3552. the database. This will save all user information, such as logins and
  3553. profiles, but will otherwise purge the database. This includes messages,
  3554. which rooms the home server was a member of and room alias mappings.</p>
  3555. <p>Before running the command the homeserver should be first completely
  3556. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3557. <blockquote>
  3558. <p>./scripts/database-prepare-for-0.0.1.sh &quot;homeserver.db&quot;</p>
  3559. </blockquote>
  3560. <p>Once this has successfully completed it will be safe to restart the
  3561. homeserver. You may notice that the homeserver takes a few seconds
  3562. longer to restart than usual as it reinitializes the database.</p>
  3563. <p>On startup of the new version, users can either rejoin remote rooms
  3564. using room aliases or by being reinvited. Alternatively, if any other
  3565. homeserver sends a message to a room that the homeserver was previously
  3566. in the local HS will automatically rejoin the room.</p>
  3567. <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>
  3568. <p>Federation is the process by which users on different servers can participate
  3569. in the same room. For this to work, those other servers must be able to contact
  3570. yours to send messages.</p>
  3571. <p>The <code>server_name</code> configured in the Synapse configuration file (often
  3572. <code>homeserver.yaml</code>) defines how resources (users, rooms, etc.) will be
  3573. identified (eg: <code>@user:example.com</code>, <code>#room:example.com</code>). By default,
  3574. it is also the domain that other servers will use to try to reach your
  3575. server (via port 8448). This is easy to set up and will work provided
  3576. you set the <code>server_name</code> to match your machine's public DNS hostname.</p>
  3577. <p>For this default configuration to work, you will need to listen for TLS
  3578. connections on port 8448. The preferred way to do that is by using a
  3579. reverse proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions
  3580. on how to correctly set one up.</p>
  3581. <p>In some cases you might not want to run Synapse on the machine that has
  3582. the <code>server_name</code> as its public DNS hostname, or you might want federation
  3583. traffic to use a different port than 8448. For example, you might want to
  3584. have your user names look like <code>@user:example.com</code>, but you want to run
  3585. Synapse on <code>synapse.example.com</code> on port 443. This can be done using
  3586. delegation, which allows an admin to control where federation traffic should
  3587. be sent. See <a href="delegate.html">the delegation documentation</a> for instructions on how to set this up.</p>
  3588. <p>Once federation has been configured, you should be able to join a room over
  3589. federation. A good place to start is <code>#synapse:matrix.org</code> - a room for
  3590. Synapse admins.</p>
  3591. <h2 id="troubleshooting-3"><a class="header" href="#troubleshooting-3">Troubleshooting</a></h2>
  3592. <p>You can use the <a href="https://matrix.org/federationtester">federation tester</a>
  3593. to check if your homeserver is configured correctly. Alternatively try the
  3594. <a href="https://matrix.org/federationtester/api/report?server_name=DOMAIN">JSON API used by the federation tester</a>.
  3595. Note that you'll have to modify this URL to replace <code>DOMAIN</code> with your
  3596. <code>server_name</code>. Hitting the API directly provides extra detail.</p>
  3597. <p>The typical failure mode for federation is that when the server tries to join
  3598. a room, it is rejected with &quot;401: Unauthorized&quot;. Generally this means that other
  3599. servers in the room could not access yours. (Joining a room over federation is
  3600. a complicated dance which requires connections in both directions).</p>
  3601. <p>Another common problem is that people on other servers can't join rooms that
  3602. you invite them to. This can be caused by an incorrectly-configured reverse
  3603. proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions on how
  3604. to correctly configure a reverse proxy.</p>
  3605. <h3 id="known-issues"><a class="header" href="#known-issues">Known issues</a></h3>
  3606. <p><strong>HTTP <code>308 Permanent Redirect</code> redirects are not followed</strong>: Due to missing features
  3607. in the HTTP library used by Synapse, 308 redirects are currently not followed by
  3608. federating servers, which can cause <code>M_UNKNOWN</code> or <code>401 Unauthorized</code> errors. This
  3609. may affect users who are redirecting apex-to-www (e.g. <code>example.com</code> -&gt; <code>www.example.com</code>),
  3610. and especially users of the Kubernetes <em>Nginx Ingress</em> module, which uses 308 redirect
  3611. codes by default. For those Kubernetes users, <a href="https://stackoverflow.com/a/52617528/5096871">this Stackoverflow post</a>
  3612. might be helpful. For other users, switching to a <code>301 Moved Permanently</code> code may be
  3613. an option. 308 redirect codes will be supported properly in a future
  3614. release of Synapse.</p>
  3615. <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>
  3616. <p>If you want to get up and running quickly with a trio of homeservers in a
  3617. private federation, there is a script in the <code>demo</code> directory. This is mainly
  3618. useful just for development purposes. See
  3619. <a href="https://matrix-org.github.io/synapse/develop/development/demo.html">demo scripts</a>.</p>
  3620. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuration-2"><a class="header" href="#configuration-2">Configuration</a></h1>
  3621. <p>This section contains information on tweaking Synapse via the various options in the configuration file. A configuration
  3622. file should have been generated when you <a href="usage/configuration/../../setup/installation.html">installed Synapse</a>.</p>
  3623. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuring-synapse"><a class="header" href="#configuring-synapse">Configuring Synapse</a></h1>
  3624. <p>This is intended as a guide to the Synapse configuration. The behavior of a Synapse instance can be modified
  3625. through the many configuration settings documented here — each config option is explained,
  3626. including what the default is, how to change the default and what sort of behaviour the setting governs.
  3627. Also included is an example configuration for each setting. If you don't want to spend a lot of time
  3628. thinking about options, the config as generated sets sensible defaults for all values. Do note however that the
  3629. database defaults to SQLite, which is not recommended for production usage. You can read more on this subject
  3630. <a href="usage/configuration/../../setup/installation.html#using-postgresql">here</a>.</p>
  3631. <h2 id="config-conventions"><a class="header" href="#config-conventions">Config Conventions</a></h2>
  3632. <p>Configuration options that take a time period can be set using a number
  3633. followed by a letter. Letters have the following meanings:</p>
  3634. <ul>
  3635. <li><code>s</code> = second</li>
  3636. <li><code>m</code> = minute</li>
  3637. <li><code>h</code> = hour</li>
  3638. <li><code>d</code> = day</li>
  3639. <li><code>w</code> = week</li>
  3640. <li><code>y</code> = year</li>
  3641. </ul>
  3642. <p>For example, setting <code>redaction_retention_period: 5m</code> would remove redacted
  3643. messages from the database after 5 minutes, rather than 5 months.</p>
  3644. <p>In addition, configuration options referring to size use the following suffixes:</p>
  3645. <ul>
  3646. <li><code>M</code> = MiB, or 1,048,576 bytes</li>
  3647. <li><code>K</code> = KiB, or 1024 bytes</li>
  3648. </ul>
  3649. <p>For example, setting <code>max_avatar_size: 10M</code> means that Synapse will not accept files larger than 10,485,760 bytes
  3650. for a user avatar.</p>
  3651. <h3 id="yaml"><a class="header" href="#yaml">YAML</a></h3>
  3652. <p>The configuration file is a <a href="https://yaml.org/">YAML</a> file, which means that certain syntax rules
  3653. apply if you want your config file to be read properly. A few helpful things to know:</p>
  3654. <ul>
  3655. <li>
  3656. <p><code>#</code> before any option in the config will comment out that setting and either a default (if available) will
  3657. be applied or Synapse will ignore the setting. Thus, in example #1 below, the setting will be read and
  3658. applied, but in example #2 the setting will not be read and a default will be applied.</p>
  3659. <p>Example #1:</p>
  3660. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3661. </code></pre>
  3662. <p>Example #2:</p>
  3663. <pre><code class="language-yaml">#pid_file: DATADIR/homeserver.pid
  3664. </code></pre>
  3665. </li>
  3666. <li>
  3667. <p>Indentation matters! The indentation before a setting
  3668. will determine whether a given setting is read as part of another
  3669. setting, or considered on its own. Thus, in example #1, the <code>enabled</code> setting
  3670. is read as a sub-option of the <code>presence</code> setting, and will be properly applied.</p>
  3671. <p>However, the lack of indentation before the <code>enabled</code> setting in example #2 means
  3672. that when reading the config, Synapse will consider both <code>presence</code> and <code>enabled</code> as
  3673. different settings. In this case, <code>presence</code> has no value, and thus a default applied, and <code>enabled</code>
  3674. is an option that Synapse doesn't recognize and thus ignores.</p>
  3675. <p>Example #1:</p>
  3676. <pre><code class="language-yaml">presence:
  3677. enabled: false
  3678. </code></pre>
  3679. <p>Example #2:</p>
  3680. <pre><code class="language-yaml">presence:
  3681. enabled: false
  3682. </code></pre>
  3683. <p>In this manual, all top-level settings (ones with no indentation) are identified
  3684. at the beginning of their section (i.e. &quot;### <code>example_setting</code>&quot;) and
  3685. the sub-options, if any, are identified and listed in the body of the section.
  3686. In addition, each setting has an example of its usage, with the proper indentation
  3687. shown.</p>
  3688. </li>
  3689. </ul>
  3690. <h2 id="modules"><a class="header" href="#modules">Modules</a></h2>
  3691. <p>Server admins can expand Synapse's functionality with external modules.</p>
  3692. <p>See <a href="usage/configuration/../../modules/index.html">here</a> for more
  3693. documentation on how to configure or create custom modules for Synapse.</p>
  3694. <hr />
  3695. <h3 id="modules-1"><a class="header" href="#modules-1"><code>modules</code></a></h3>
  3696. <p>Use the <code>module</code> sub-option to add modules under this option to extend functionality.
  3697. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  3698. for the <code>module</code>.</p>
  3699. <p>Defaults to none.</p>
  3700. <p>Example configuration:</p>
  3701. <pre><code class="language-yaml">modules:
  3702. - module: my_super_module.MySuperClass
  3703. config:
  3704. do_thing: true
  3705. - module: my_other_super_module.SomeClass
  3706. config: {}
  3707. </code></pre>
  3708. <hr />
  3709. <h2 id="server"><a class="header" href="#server">Server</a></h2>
  3710. <p>Define your homeserver name and other base options.</p>
  3711. <hr />
  3712. <h3 id="server_name"><a class="header" href="#server_name"><code>server_name</code></a></h3>
  3713. <p>This sets the public-facing domain of the server.</p>
  3714. <p>The <code>server_name</code> name will appear at the end of usernames and room addresses
  3715. created on your server. For example if the <code>server_name</code> was example.com,
  3716. usernames on your server would be in the format <code>@user:example.com</code></p>
  3717. <p>In most cases you should avoid using a matrix specific subdomain such as
  3718. matrix.example.com or synapse.example.com as the <code>server_name</code> for the same
  3719. reasons you wouldn't use user@email.example.com as your email address.
  3720. See <a href="usage/configuration/../../delegate.html">here</a>
  3721. for information on how to host Synapse on a subdomain while preserving
  3722. a clean <code>server_name</code>.</p>
  3723. <p>The <code>server_name</code> cannot be changed later so it is important to
  3724. configure this correctly before you start Synapse. It should be all
  3725. lowercase and may contain an explicit port.</p>
  3726. <p>There is no default for this option.</p>
  3727. <p>Example configuration #1:</p>
  3728. <pre><code class="language-yaml">server_name: matrix.org
  3729. </code></pre>
  3730. <p>Example configuration #2:</p>
  3731. <pre><code class="language-yaml">server_name: localhost:8080
  3732. </code></pre>
  3733. <hr />
  3734. <h3 id="pid_file"><a class="header" href="#pid_file"><code>pid_file</code></a></h3>
  3735. <p>When running Synapse as a daemon, the file to store the pid in. Defaults to none.</p>
  3736. <p>Example configuration:</p>
  3737. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3738. </code></pre>
  3739. <hr />
  3740. <h3 id="web_client_location"><a class="header" href="#web_client_location"><code>web_client_location</code></a></h3>
  3741. <p>The absolute URL to the web client which <code>/</code> will redirect to. Defaults to none.</p>
  3742. <p>Example configuration:</p>
  3743. <pre><code class="language-yaml">web_client_location: https://riot.example.com/
  3744. </code></pre>
  3745. <hr />
  3746. <h3 id="public_baseurl"><a class="header" href="#public_baseurl"><code>public_baseurl</code></a></h3>
  3747. <p>The public-facing base URL that clients use to access this Homeserver (not
  3748. including _matrix/...). This is the same URL a user might enter into the
  3749. 'Custom Homeserver URL' field on their client. If you use Synapse with a
  3750. reverse proxy, this should be the URL to reach Synapse via the proxy.
  3751. Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
  3752. <a href="usage/configuration/config_documentation.html#listeners">'listeners'</a> below).</p>
  3753. <p>Defaults to <code>https://&lt;server_name&gt;/</code>.</p>
  3754. <p>Example configuration:</p>
  3755. <pre><code class="language-yaml">public_baseurl: https://example.com/
  3756. </code></pre>
  3757. <hr />
  3758. <h3 id="serve_server_wellknown"><a class="header" href="#serve_server_wellknown"><code>serve_server_wellknown</code></a></h3>
  3759. <p>By default, other servers will try to reach our server on port 8448, which can
  3760. be inconvenient in some environments.</p>
  3761. <p>Provided <code>https://&lt;server_name&gt;/</code> on port 443 is routed to Synapse, this
  3762. option configures Synapse to serve a file at <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>.
  3763. This will tell other servers to send traffic to port 443 instead.</p>
  3764. <p>This option currently defaults to false.</p>
  3765. <p>See <a href="usage/configuration/../../delegate.html">Delegation of incoming federation traffic</a> for more
  3766. information.</p>
  3767. <p>Example configuration:</p>
  3768. <pre><code class="language-yaml">serve_server_wellknown: true
  3769. </code></pre>
  3770. <hr />
  3771. <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>
  3772. <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>.
  3773. 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>
  3774. <p>If this option is provided, it parses the given yaml to json and
  3775. serves it on <code>/.well-known/matrix/client</code> endpoint
  3776. alongside the standard properties.</p>
  3777. <p><em>Added in Synapse 1.62.0.</em></p>
  3778. <p>Example configuration:</p>
  3779. <pre><code class="language-yaml">extra_well_known_client_content :
  3780. option1: value1
  3781. option2: value2
  3782. </code></pre>
  3783. <hr />
  3784. <h3 id="soft_file_limit"><a class="header" href="#soft_file_limit"><code>soft_file_limit</code></a></h3>
  3785. <p>Set the soft limit on the number of file descriptors synapse can use.
  3786. Zero is used to indicate synapse should set the soft limit to the hard limit.
  3787. Defaults to 0.</p>
  3788. <p>Example configuration:</p>
  3789. <pre><code class="language-yaml">soft_file_limit: 3
  3790. </code></pre>
  3791. <hr />
  3792. <h3 id="presence"><a class="header" href="#presence"><code>presence</code></a></h3>
  3793. <p>Presence tracking allows users to see the state (e.g online/offline)
  3794. of other local and remote users. Set the <code>enabled</code> sub-option to false to
  3795. disable presence tracking on this homeserver. Defaults to true.
  3796. This option replaces the previous top-level 'use_presence' option.</p>
  3797. <p>Example configuration:</p>
  3798. <pre><code class="language-yaml">presence:
  3799. enabled: false
  3800. </code></pre>
  3801. <hr />
  3802. <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>
  3803. <p>Whether to require authentication to retrieve profile data (avatars, display names) of other
  3804. users through the client API. Defaults to false. Note that profile data is also available
  3805. via the federation API, unless <code>allow_profile_lookup_over_federation</code> is set to false.</p>
  3806. <p>Example configuration:</p>
  3807. <pre><code class="language-yaml">require_auth_for_profile_requests: true
  3808. </code></pre>
  3809. <hr />
  3810. <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>
  3811. <p>Use this option to require a user to share a room with another user in order
  3812. to retrieve their profile information. Only checked on Client-Server
  3813. requests. Profile requests from other servers should be checked by the
  3814. requesting server. Defaults to false.</p>
  3815. <p>Example configuration:</p>
  3816. <pre><code class="language-yaml">limit_profile_requests_to_users_who_share_rooms: true
  3817. </code></pre>
  3818. <hr />
  3819. <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>
  3820. <p>Use this option to prevent a user's profile data from being retrieved and
  3821. displayed in a room until they have joined it. By default, a user's
  3822. profile data is included in an invite event, regardless of the values
  3823. of the above two settings, and whether or not the users share a server.
  3824. Defaults to true.</p>
  3825. <p>Example configuration:</p>
  3826. <pre><code class="language-yaml">include_profile_data_on_invite: false
  3827. </code></pre>
  3828. <hr />
  3829. <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>
  3830. <p>If set to true, removes the need for authentication to access the server's
  3831. public rooms directory through the client API, meaning that anyone can
  3832. query the room directory. Defaults to false.</p>
  3833. <p>Example configuration:</p>
  3834. <pre><code class="language-yaml">allow_public_rooms_without_auth: true
  3835. </code></pre>
  3836. <hr />
  3837. <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>
  3838. <p>If set to true, allows any other homeserver to fetch the server's public
  3839. rooms directory via federation. Defaults to false.</p>
  3840. <p>Example configuration:</p>
  3841. <pre><code class="language-yaml">allow_public_rooms_over_federation: true
  3842. </code></pre>
  3843. <hr />
  3844. <h3 id="default_room_version"><a class="header" href="#default_room_version"><code>default_room_version</code></a></h3>
  3845. <p>The default room version for newly created rooms on this server.</p>
  3846. <p>Known room versions are listed <a href="https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions">here</a></p>
  3847. <p>For example, for room version 1, <code>default_room_version</code> should be set
  3848. to &quot;1&quot;.</p>
  3849. <p>Currently defaults to <a href="https://spec.matrix.org/v1.5/rooms/v10/">&quot;10&quot;</a>.</p>
  3850. <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>
  3851. <p>Example configuration:</p>
  3852. <pre><code class="language-yaml">default_room_version: &quot;8&quot;
  3853. </code></pre>
  3854. <hr />
  3855. <h3 id="gc_thresholds"><a class="header" href="#gc_thresholds"><code>gc_thresholds</code></a></h3>
  3856. <p>The garbage collection threshold parameters to pass to <code>gc.set_threshold</code>, if defined.
  3857. Defaults to none.</p>
  3858. <p>Example configuration:</p>
  3859. <pre><code class="language-yaml">gc_thresholds: [700, 10, 10]
  3860. </code></pre>
  3861. <hr />
  3862. <h3 id="gc_min_interval"><a class="header" href="#gc_min_interval"><code>gc_min_interval</code></a></h3>
  3863. <p>The minimum time in seconds between each GC for a generation, regardless of
  3864. the GC thresholds. This ensures that we don't do GC too frequently. A value of <code>[1s, 10s, 30s]</code>
  3865. indicates that a second must pass between consecutive generation 0 GCs, etc.</p>
  3866. <p>Defaults to <code>[1s, 10s, 30s]</code>.</p>
  3867. <p>Example configuration:</p>
  3868. <pre><code class="language-yaml">gc_min_interval: [0.5s, 30s, 1m]
  3869. </code></pre>
  3870. <hr />
  3871. <h3 id="filter_timeline_limit"><a class="header" href="#filter_timeline_limit"><code>filter_timeline_limit</code></a></h3>
  3872. <p>Set the limit on the returned events in the timeline in the get
  3873. and sync operations. Defaults to 100. A value of -1 means no upper limit.</p>
  3874. <p>Example configuration:</p>
  3875. <pre><code class="language-yaml">filter_timeline_limit: 5000
  3876. </code></pre>
  3877. <hr />
  3878. <h3 id="block_non_admin_invites"><a class="header" href="#block_non_admin_invites"><code>block_non_admin_invites</code></a></h3>
  3879. <p>Whether room invites to users on this server should be blocked
  3880. (except those sent by local server admins). Defaults to false.</p>
  3881. <p>Example configuration:</p>
  3882. <pre><code class="language-yaml">block_non_admin_invites: true
  3883. </code></pre>
  3884. <hr />
  3885. <h3 id="enable_search"><a class="header" href="#enable_search"><code>enable_search</code></a></h3>
  3886. <p>If set to false, new messages will not be indexed for searching and users
  3887. will receive errors when searching for messages. Defaults to true.</p>
  3888. <p>Example configuration:</p>
  3889. <pre><code class="language-yaml">enable_search: false
  3890. </code></pre>
  3891. <hr />
  3892. <h3 id="ip_range_blacklist"><a class="header" href="#ip_range_blacklist"><code>ip_range_blacklist</code></a></h3>
  3893. <p>This option prevents outgoing requests from being sent to the specified blacklisted IP address
  3894. CIDR ranges. If this option is not specified then it defaults to private IP
  3895. address ranges (see the example below).</p>
  3896. <p>The blacklist applies to the outbound requests for federation, identity servers,
  3897. push servers, and for checking key validity for third-party invite events.</p>
  3898. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  3899. listed here, since they correspond to unroutable addresses.)</p>
  3900. <p>This option replaces <code>federation_ip_range_blacklist</code> in Synapse v1.25.0.</p>
  3901. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  3902. <p>Example configuration:</p>
  3903. <pre><code class="language-yaml">ip_range_blacklist:
  3904. - '127.0.0.0/8'
  3905. - '10.0.0.0/8'
  3906. - '172.16.0.0/12'
  3907. - '192.168.0.0/16'
  3908. - '100.64.0.0/10'
  3909. - '192.0.0.0/24'
  3910. - '169.254.0.0/16'
  3911. - '192.88.99.0/24'
  3912. - '198.18.0.0/15'
  3913. - '192.0.2.0/24'
  3914. - '198.51.100.0/24'
  3915. - '203.0.113.0/24'
  3916. - '224.0.0.0/4'
  3917. - '::1/128'
  3918. - 'fe80::/10'
  3919. - 'fc00::/7'
  3920. - '2001:db8::/32'
  3921. - 'ff00::/8'
  3922. - 'fec0::/10'
  3923. </code></pre>
  3924. <hr />
  3925. <h3 id="ip_range_whitelist"><a class="header" href="#ip_range_whitelist"><code>ip_range_whitelist</code></a></h3>
  3926. <p>List of IP address CIDR ranges that should be allowed for federation,
  3927. identity servers, push servers, and for checking key validity for
  3928. third-party invite events. This is useful for specifying exceptions to
  3929. wide-ranging blacklisted target IP ranges - e.g. for communication with
  3930. a push server only visible in your network.</p>
  3931. <p>This whitelist overrides <code>ip_range_blacklist</code> and defaults to an empty
  3932. list.</p>
  3933. <p>Example configuration:</p>
  3934. <pre><code class="language-yaml">ip_range_whitelist:
  3935. - '192.168.1.1'
  3936. </code></pre>
  3937. <hr />
  3938. <h3 id="listeners"><a class="header" href="#listeners"><code>listeners</code></a></h3>
  3939. <p>List of ports that Synapse should listen on, their purpose and their
  3940. configuration.</p>
  3941. <p>Sub-options for each listener include:</p>
  3942. <ul>
  3943. <li>
  3944. <p><code>port</code>: the TCP port to bind to.</p>
  3945. </li>
  3946. <li>
  3947. <p><code>tag</code>: An alias for the port in the logger name. If set the tag is logged instead
  3948. of the port. Default to <code>None</code>, is optional and only valid for listener with <code>type: http</code>.
  3949. See the docs <a href="usage/configuration/../administration/request_log.html">request log format</a>.</p>
  3950. </li>
  3951. <li>
  3952. <p><code>bind_addresses</code>: a list of local addresses to listen on. The default is
  3953. 'all local interfaces'.</p>
  3954. </li>
  3955. <li>
  3956. <p><code>type</code>: the type of listener. Normally <code>http</code>, but other valid options are:</p>
  3957. <ul>
  3958. <li>
  3959. <p><code>manhole</code>: (see the docs <a href="usage/configuration/../../manhole.html">here</a>),</p>
  3960. </li>
  3961. <li>
  3962. <p><code>metrics</code>: (see the docs <a href="usage/configuration/../../metrics-howto.html">here</a>),</p>
  3963. </li>
  3964. </ul>
  3965. </li>
  3966. <li>
  3967. <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>
  3968. </li>
  3969. <li>
  3970. <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
  3971. behind a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
  3972. </li>
  3973. <li>
  3974. <p><code>request_id_header</code>: The header extracted from each incoming request that is
  3975. used as the basis for the request ID. The request ID is used in
  3976. <a href="usage/configuration/../administration/request_log.html#request-log-format">logs</a> and tracing to
  3977. correlate and match up requests. When unset, Synapse will automatically
  3978. generate sequential request IDs. This option is useful when Synapse is behind
  3979. a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
  3980. <p><em>Added in Synapse 1.68.0.</em></p>
  3981. </li>
  3982. <li>
  3983. <p><code>resources</code>: Only valid for an 'http' listener. A list of resources to host
  3984. on this port. Sub-options for each resource are:</p>
  3985. <ul>
  3986. <li>
  3987. <p><code>names</code>: a list of names of HTTP resources. See below for a list of valid resource names.</p>
  3988. </li>
  3989. <li>
  3990. <p><code>compress</code>: set to true to enable gzip compression on HTTP bodies for this resource. This is currently only supported with the
  3991. <code>client</code>, <code>consent</code>, <code>metrics</code> and <code>federation</code> resources.</p>
  3992. </li>
  3993. </ul>
  3994. </li>
  3995. <li>
  3996. <p><code>additional_resources</code>: Only valid for an 'http' listener. A map of
  3997. additional endpoints which should be loaded via dynamic modules.</p>
  3998. </li>
  3999. </ul>
  4000. <p>Unix socket support (<em>Added in Synapse 1.89.0</em>):</p>
  4001. <ul>
  4002. <li><code>path</code>: A path and filename for a Unix socket. Make sure it is located in a
  4003. directory with read and write permissions, and that it already exists (the directory
  4004. will not be created). Defaults to <code>None</code>.
  4005. <ul>
  4006. <li><strong>Note</strong>: The use of both <code>path</code> and <code>port</code> options for the same <code>listener</code> is not
  4007. compatible.</li>
  4008. <li>The <code>x_forwarded</code> option defaults to true when using Unix sockets and can be omitted.</li>
  4009. <li>Other options that would not make sense to use with a UNIX socket, such as
  4010. <code>bind_addresses</code> and <code>tls</code> will be ignored and can be removed.</li>
  4011. </ul>
  4012. </li>
  4013. <li><code>mode</code>: The file permissions to set on the UNIX socket. Defaults to <code>666</code></li>
  4014. <li><strong>Note:</strong> Must be set as <code>type: http</code> (does not support <code>metrics</code> and <code>manhole</code>).
  4015. Also make sure that <code>metrics</code> is not included in <code>resources</code> -&gt; <code>names</code></li>
  4016. </ul>
  4017. <p>Valid resource names are:</p>
  4018. <ul>
  4019. <li>
  4020. <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>
  4021. </li>
  4022. <li>
  4023. <p><code>consent</code>: user consent forms (/_matrix/consent). See <a href="usage/configuration/../../consent_tracking.html">here</a> for more.</p>
  4024. </li>
  4025. <li>
  4026. <p><code>federation</code>: the server-server API (/_matrix/federation). Also implies <code>media</code>, <code>keys</code>, <code>openid</code></p>
  4027. </li>
  4028. <li>
  4029. <p><code>keys</code>: the key discovery API (/_matrix/key).</p>
  4030. </li>
  4031. <li>
  4032. <p><code>media</code>: the media API (/_matrix/media).</p>
  4033. </li>
  4034. <li>
  4035. <p><code>metrics</code>: the metrics interface. See <a href="usage/configuration/../../metrics-howto.html">here</a>. (Not compatible with Unix sockets)</p>
  4036. </li>
  4037. <li>
  4038. <p><code>openid</code>: OpenID authentication. See <a href="usage/configuration/../../openid.html">here</a>.</p>
  4039. </li>
  4040. <li>
  4041. <p><code>replication</code>: the HTTP replication API (/_synapse/replication). See <a href="usage/configuration/../../workers.html">here</a>.</p>
  4042. </li>
  4043. <li>
  4044. <p><code>static</code>: static resources under synapse/static (/_matrix/static). (Mostly useful for 'fallback authentication'.)</p>
  4045. </li>
  4046. <li>
  4047. <p><code>health</code>: the <a href="usage/configuration/../../reverse_proxy.html#health-check-endpoint">health check endpoint</a>. This endpoint
  4048. is by default active for all other resources and does not have to be activated separately.
  4049. This is only useful if you want to use the health endpoint explicitly on a dedicated port or
  4050. for <a href="usage/configuration/../../workers.html">workers</a> and containers without listener e.g.
  4051. <a href="usage/configuration/../../workers.html#notifying-application-services">application services</a>.</p>
  4052. </li>
  4053. </ul>
  4054. <p>Example configuration #1:</p>
  4055. <pre><code class="language-yaml">listeners:
  4056. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  4057. #
  4058. # (Note that you will also need to give Synapse a TLS key and certificate: see the TLS section
  4059. # below.)
  4060. #
  4061. - port: 8448
  4062. type: http
  4063. tls: true
  4064. resources:
  4065. - names: [client, federation]
  4066. </code></pre>
  4067. <p>Example configuration #2:</p>
  4068. <pre><code class="language-yaml">listeners:
  4069. # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  4070. # that unwraps TLS.
  4071. #
  4072. # If you plan to use a reverse proxy, please see
  4073. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  4074. #
  4075. - port: 8008
  4076. tls: false
  4077. type: http
  4078. x_forwarded: true
  4079. bind_addresses: ['::1', '127.0.0.1']
  4080. resources:
  4081. - names: [client, federation]
  4082. compress: false
  4083. # example additional_resources:
  4084. additional_resources:
  4085. &quot;/_matrix/my/custom/endpoint&quot;:
  4086. module: my_module.CustomRequestHandler
  4087. config: {}
  4088. # Turn on the twisted ssh manhole service on localhost on the given
  4089. # port.
  4090. - port: 9000
  4091. bind_addresses: ['::1', '127.0.0.1']
  4092. type: manhole
  4093. </code></pre>
  4094. <p>Example configuration #3:</p>
  4095. <pre><code class="language-yaml">listeners:
  4096. # Unix socket listener: Ideal for Synapse deployments behind a reverse proxy, offering
  4097. # lightweight interprocess communication without TCP/IP overhead, avoid port
  4098. # conflicts, and providing enhanced security through system file permissions.
  4099. #
  4100. # Note that x_forwarded will default to true, when using a UNIX socket. Please see
  4101. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  4102. #
  4103. - path: /var/run/synapse/main_public.sock
  4104. type: http
  4105. resources:
  4106. - names: [client, federation]
  4107. </code></pre>
  4108. <hr />
  4109. <h3 id="manhole_settings"><a class="header" href="#manhole_settings"><code>manhole_settings</code></a></h3>
  4110. <p>Connection settings for the manhole. You can find more information
  4111. on the manhole <a href="usage/configuration/../../manhole.html">here</a>. Manhole sub-options include:</p>
  4112. <ul>
  4113. <li><code>username</code> : the username for the manhole. This defaults to 'matrix'.</li>
  4114. <li><code>password</code>: The password for the manhole. This defaults to 'rabbithole'.</li>
  4115. <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.
  4116. If these are left unset, then hardcoded and non-secret keys are used,
  4117. which could allow traffic to be intercepted if sent over a public network.</li>
  4118. </ul>
  4119. <p>Example configuration:</p>
  4120. <pre><code class="language-yaml">manhole_settings:
  4121. username: manhole
  4122. password: mypassword
  4123. ssh_priv_key_path: CONFDIR/id_rsa
  4124. ssh_pub_key_path: CONFDIR/id_rsa.pub
  4125. </code></pre>
  4126. <hr />
  4127. <h3 id="dummy_events_threshold"><a class="header" href="#dummy_events_threshold"><code>dummy_events_threshold</code></a></h3>
  4128. <p>Forward extremities can build up in a room due to networking delays between
  4129. homeservers. Once this happens in a large room, calculation of the state of
  4130. that room can become quite expensive. To mitigate this, once the number of
  4131. forward extremities reaches a given threshold, Synapse will send an
  4132. <code>org.matrix.dummy_event</code> event, which will reduce the forward extremities
  4133. in the room.</p>
  4134. <p>This setting defines the threshold (i.e. number of forward extremities in the room) at which dummy events are sent.
  4135. The default value is 10.</p>
  4136. <p>Example configuration:</p>
  4137. <pre><code class="language-yaml">dummy_events_threshold: 5
  4138. </code></pre>
  4139. <hr />
  4140. <h3 id="delete_stale_devices_after"><a class="header" href="#delete_stale_devices_after"><code>delete_stale_devices_after</code></a></h3>
  4141. <p>An optional duration. If set, Synapse will run a daily background task to log out and
  4142. delete any device that hasn't been accessed for more than the specified amount of time.</p>
  4143. <p>Defaults to no duration, which means devices are never pruned.</p>
  4144. <p><strong>Note:</strong> This task will always run on the main process, regardless of the value of
  4145. <code>run_background_tasks_on</code>. This is due to workers currently not having the ability to
  4146. delete devices.</p>
  4147. <p>Example configuration:</p>
  4148. <pre><code class="language-yaml">delete_stale_devices_after: 1y
  4149. </code></pre>
  4150. <hr />
  4151. <h3 id="email-3"><a class="header" href="#email-3"><code>email</code></a></h3>
  4152. <p>Configuration for sending emails from Synapse.</p>
  4153. <p>Server admins can configure custom templates for email content. See
  4154. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  4155. <p>This setting has the following sub-options:</p>
  4156. <ul>
  4157. <li>
  4158. <p><code>smtp_host</code>: The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.</p>
  4159. </li>
  4160. <li>
  4161. <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>
  4162. <p><em>Changed in Synapse 1.64.0:</em> the default port is now aware of <code>force_tls</code>.</p>
  4163. </li>
  4164. <li>
  4165. <p><code>smtp_user</code> and <code>smtp_pass</code>: Username/password for authentication to the SMTP server. By default, no
  4166. authentication is attempted.</p>
  4167. </li>
  4168. <li>
  4169. <p><code>force_tls</code>: By default, Synapse connects over plain text and then optionally upgrades
  4170. to TLS via STARTTLS. If this option is set to true, TLS is used from the start (Implicit TLS),
  4171. and the option <code>require_transport_security</code> is ignored.
  4172. It is recommended to enable this if supported by your mail server.</p>
  4173. <p><em>New in Synapse 1.64.0.</em></p>
  4174. </li>
  4175. <li>
  4176. <p><code>require_transport_security</code>: Set to true to require TLS transport security for SMTP.
  4177. By default, Synapse will connect over plain text, and will then switch to
  4178. TLS via STARTTLS <em>if the SMTP server supports it</em>. If this option is set,
  4179. Synapse will refuse to connect unless the server supports STARTTLS.</p>
  4180. </li>
  4181. <li>
  4182. <p><code>enable_tls</code>: By default, if the server supports TLS, it will be used, and the server
  4183. must present a certificate that is valid for 'smtp_host'. If this option
  4184. is set to false, TLS will not be used.</p>
  4185. </li>
  4186. <li>
  4187. <p><code>notif_from</code>: defines the &quot;From&quot; address to use when sending emails.
  4188. It must be set if email sending is enabled. The placeholder '%(app)s' will be replaced by the application name,
  4189. which is normally set in <code>app_name</code>, but may be overridden by the
  4190. Matrix client application. Note that the placeholder must be written '%(app)s', including the
  4191. trailing 's'.</p>
  4192. </li>
  4193. <li>
  4194. <p><code>app_name</code>: <code>app_name</code> defines the default value for '%(app)s' in <code>notif_from</code> and email
  4195. subjects. It defaults to 'Matrix'.</p>
  4196. </li>
  4197. <li>
  4198. <p><code>enable_notifs</code>: Set to true to enable sending emails for messages that the user
  4199. has missed. Disabled by default.</p>
  4200. </li>
  4201. <li>
  4202. <p><code>notif_for_new_users</code>: Set to false to disable automatic subscription to email
  4203. notifications for new users. Enabled by default.</p>
  4204. </li>
  4205. <li>
  4206. <p><code>client_base_url</code>: Custom URL for client links within the email notifications. By default
  4207. links will be based on &quot;https://matrix.to&quot;. (This setting used to be called <code>riot_base_url</code>;
  4208. the old name is still supported for backwards-compatibility but is now deprecated.)</p>
  4209. </li>
  4210. <li>
  4211. <p><code>validation_token_lifetime</code>: Configures the time that a validation email will expire after sending.
  4212. Defaults to 1h.</p>
  4213. </li>
  4214. <li>
  4215. <p><code>invite_client_location</code>: The web client location to direct users to during an invite. This is passed
  4216. to the identity server as the <code>org.matrix.web_client_location</code> key. Defaults
  4217. to unset, giving no guidance to the identity server.</p>
  4218. </li>
  4219. <li>
  4220. <p><code>subjects</code>: Subjects to use when sending emails from Synapse. The placeholder '%(app)s' will
  4221. be replaced with the value of the <code>app_name</code> setting, or by a value dictated by the Matrix client application.
  4222. In addition, each subject can use the following placeholders: '%(person)s', which will be replaced by the displayname
  4223. 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
  4224. message(s) have been sent to, e.g. &quot;My super room&quot;. In addition, emails related to account administration will
  4225. can use the '%(server_name)s' placeholder, which will be replaced by the value of the
  4226. <code>server_name</code> setting in your Synapse configuration.</p>
  4227. <p>Here is a list of subjects for notification emails that can be set:</p>
  4228. <ul>
  4229. <li><code>message_from_person_in_room</code>: Subject to use to notify about one message from one or more user(s) in a
  4230. 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>
  4231. <li><code>message_from_person</code>: Subject to use to notify about one message from one or more user(s) in a
  4232. room which doesn't have a name. Defaults to &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;</li>
  4233. <li><code>messages_from_person</code>: Subject to use to notify about multiple messages from one or more users in
  4234. a room which doesn't have a name. Defaults to &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;</li>
  4235. <li><code>messages_in_room</code>: Subject to use to notify about multiple messages in a room which has a
  4236. name. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;</li>
  4237. <li><code>messages_in_room_and_others</code>: Subject to use to notify about multiple messages in multiple rooms.
  4238. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;</li>
  4239. <li><code>messages_from_person_and_others</code>: Subject to use to notify about multiple messages from multiple persons in
  4240. multiple rooms. This is similar to the setting above except it's used when
  4241. the room in which the notification was triggered has no name. Defaults to
  4242. &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;</li>
  4243. <li><code>invite_from_person_to_room</code>: Subject to use to notify about an invite to a room which has a name.
  4244. Defaults to &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;</li>
  4245. <li><code>invite_from_person</code>: Subject to use to notify about an invite to a room which doesn't have a
  4246. name. Defaults to &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;</li>
  4247. <li><code>password_reset</code>: Subject to use when sending a password reset email. Defaults to &quot;[%(server_name)s] Password reset&quot;</li>
  4248. <li><code>email_validation</code>: Subject to use when sending a verification email to assert an address's
  4249. ownership. Defaults to &quot;[%(server_name)s] Validate your email&quot;</li>
  4250. </ul>
  4251. </li>
  4252. </ul>
  4253. <p>Example configuration:</p>
  4254. <pre><code class="language-yaml">email:
  4255. smtp_host: mail.server
  4256. smtp_port: 587
  4257. smtp_user: &quot;exampleusername&quot;
  4258. smtp_pass: &quot;examplepassword&quot;
  4259. force_tls: true
  4260. require_transport_security: true
  4261. enable_tls: false
  4262. notif_from: &quot;Your Friendly %(app)s homeserver &lt;noreply@example.com&gt;&quot;
  4263. app_name: my_branded_matrix_server
  4264. enable_notifs: true
  4265. notif_for_new_users: false
  4266. client_base_url: &quot;http://localhost/riot&quot;
  4267. validation_token_lifetime: 15m
  4268. invite_client_location: https://app.element.io
  4269. subjects:
  4270. message_from_person_in_room: &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;
  4271. message_from_person: &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;
  4272. messages_from_person: &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;
  4273. messages_in_room: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;
  4274. messages_in_room_and_others: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;
  4275. messages_from_person_and_others: &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;
  4276. invite_from_person_to_room: &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;
  4277. invite_from_person: &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;
  4278. password_reset: &quot;[%(server_name)s] Password reset&quot;
  4279. email_validation: &quot;[%(server_name)s] Validate your email&quot;
  4280. </code></pre>
  4281. <h2 id="homeserver-blocking"><a class="header" href="#homeserver-blocking">Homeserver blocking</a></h2>
  4282. <p>Useful options for Synapse admins.</p>
  4283. <hr />
  4284. <h3 id="admin_contact"><a class="header" href="#admin_contact"><code>admin_contact</code></a></h3>
  4285. <p>How to reach the server admin, used in <code>ResourceLimitError</code>. Defaults to none.</p>
  4286. <p>Example configuration:</p>
  4287. <pre><code class="language-yaml">admin_contact: 'mailto:admin@server.com'
  4288. </code></pre>
  4289. <hr />
  4290. <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>
  4291. <p>Blocks users from connecting to the homeserver and provides a human-readable reason
  4292. why the connection was blocked. Defaults to false.</p>
  4293. <p>Example configuration:</p>
  4294. <pre><code class="language-yaml">hs_disabled: true
  4295. hs_disabled_message: 'Reason for why the HS is blocked'
  4296. </code></pre>
  4297. <hr />
  4298. <h3 id="limit_usage_by_mau"><a class="header" href="#limit_usage_by_mau"><code>limit_usage_by_mau</code></a></h3>
  4299. <p>This option disables/enables monthly active user blocking. Used in cases where the admin or
  4300. server owner wants to limit to the number of monthly active users. When enabled and a limit is
  4301. reached the server returns a <code>ResourceLimitError</code> with error type <code>Codes.RESOURCE_LIMIT_EXCEEDED</code>.
  4302. Defaults to false. If this is enabled, a value for <code>max_mau_value</code> must also be set.</p>
  4303. <p>See <a href="usage/configuration/../administration/monthly_active_users.html">Monthly Active Users</a> for details on how to configure MAU.</p>
  4304. <p>Example configuration:</p>
  4305. <pre><code class="language-yaml">limit_usage_by_mau: true
  4306. </code></pre>
  4307. <hr />
  4308. <h3 id="max_mau_value"><a class="header" href="#max_mau_value"><code>max_mau_value</code></a></h3>
  4309. <p>This option sets the hard limit of monthly active users above which the server will start
  4310. blocking user actions if <code>limit_usage_by_mau</code> is enabled. Defaults to 0.</p>
  4311. <p>Example configuration:</p>
  4312. <pre><code class="language-yaml">max_mau_value: 50
  4313. </code></pre>
  4314. <hr />
  4315. <h3 id="mau_trial_days"><a class="header" href="#mau_trial_days"><code>mau_trial_days</code></a></h3>
  4316. <p>The option <code>mau_trial_days</code> is a means to add a grace period for active users. It
  4317. means that users must be active for the specified number of days before they
  4318. can be considered active and guards against the case where lots of users
  4319. sign up in a short space of time never to return after their initial
  4320. session. Defaults to 0.</p>
  4321. <p>Example configuration:</p>
  4322. <pre><code class="language-yaml">mau_trial_days: 5
  4323. </code></pre>
  4324. <hr />
  4325. <h3 id="mau_appservice_trial_days"><a class="header" href="#mau_appservice_trial_days"><code>mau_appservice_trial_days</code></a></h3>
  4326. <p>The option <code>mau_appservice_trial_days</code> is similar to <code>mau_trial_days</code>, but applies a different
  4327. trial number if the user was registered by an appservice. A value
  4328. of 0 means no trial days are applied. Appservices not listed in this dictionary
  4329. use the value of <code>mau_trial_days</code> instead.</p>
  4330. <p>Example configuration:</p>
  4331. <pre><code class="language-yaml">mau_appservice_trial_days:
  4332. my_appservice_id: 3
  4333. another_appservice_id: 6
  4334. </code></pre>
  4335. <hr />
  4336. <h3 id="mau_limit_alerting"><a class="header" href="#mau_limit_alerting"><code>mau_limit_alerting</code></a></h3>
  4337. <p>The option <code>mau_limit_alerting</code> is a means of limiting client-side alerting
  4338. should the mau limit be reached. This is useful for small instances
  4339. where the admin has 5 mau seats (say) for 5 specific people and no
  4340. interest increasing the mau limit further. Defaults to true, which
  4341. means that alerting is enabled.</p>
  4342. <p>Example configuration:</p>
  4343. <pre><code class="language-yaml">mau_limit_alerting: false
  4344. </code></pre>
  4345. <hr />
  4346. <h3 id="mau_stats_only"><a class="header" href="#mau_stats_only"><code>mau_stats_only</code></a></h3>
  4347. <p>If enabled, the metrics for the number of monthly active users will
  4348. be populated, however no one will be limited based on these numbers. If <code>limit_usage_by_mau</code>
  4349. is true, this is implied to be true. Defaults to false.</p>
  4350. <p>Example configuration:</p>
  4351. <pre><code class="language-yaml">mau_stats_only: true
  4352. </code></pre>
  4353. <hr />
  4354. <h3 id="mau_limit_reserved_threepids"><a class="header" href="#mau_limit_reserved_threepids"><code>mau_limit_reserved_threepids</code></a></h3>
  4355. <p>Sometimes the server admin will want to ensure certain accounts are
  4356. never blocked by mau checking. These accounts are specified by this option.
  4357. Defaults to none. Add accounts by specifying the <code>medium</code> and <code>address</code> of the
  4358. reserved threepid (3rd party identifier).</p>
  4359. <p>Example configuration:</p>
  4360. <pre><code class="language-yaml">mau_limit_reserved_threepids:
  4361. - medium: 'email'
  4362. address: 'reserved_user@example.com'
  4363. </code></pre>
  4364. <hr />
  4365. <h3 id="server_context"><a class="header" href="#server_context"><code>server_context</code></a></h3>
  4366. <p>This option is used by phonehome stats to group together related servers.
  4367. Defaults to none.</p>
  4368. <p>Example configuration:</p>
  4369. <pre><code class="language-yaml">server_context: context
  4370. </code></pre>
  4371. <hr />
  4372. <h3 id="limit_remote_rooms"><a class="header" href="#limit_remote_rooms"><code>limit_remote_rooms</code></a></h3>
  4373. <p>When this option is enabled, the room &quot;complexity&quot; will be checked before a user
  4374. joins a new remote room. If it is above the complexity limit, the server will
  4375. disallow joining, or will instantly leave. This is useful for homeservers that are
  4376. resource-constrained. Options for this setting include:</p>
  4377. <ul>
  4378. <li><code>enabled</code>: whether this check is enabled. Defaults to false.</li>
  4379. <li><code>complexity</code>: the limit above which rooms cannot be joined. The default is 1.0.</li>
  4380. <li><code>complexity_error</code>: override the error which is returned when the room is too complex with a
  4381. custom message.</li>
  4382. <li><code>admins_can_join</code>: allow server admins to join complex rooms. Default is false.</li>
  4383. </ul>
  4384. <p>Room complexity is an arbitrary measure based on factors such as the number of
  4385. users in the room.</p>
  4386. <p>Example configuration:</p>
  4387. <pre><code class="language-yaml">limit_remote_rooms:
  4388. enabled: true
  4389. complexity: 0.5
  4390. complexity_error: &quot;I can't let you do that, Dave.&quot;
  4391. admins_can_join: true
  4392. </code></pre>
  4393. <hr />
  4394. <h3 id="require_membership_for_aliases"><a class="header" href="#require_membership_for_aliases"><code>require_membership_for_aliases</code></a></h3>
  4395. <p>Whether to require a user to be in the room to add an alias to it.
  4396. Defaults to true.</p>
  4397. <p>Example configuration:</p>
  4398. <pre><code class="language-yaml">require_membership_for_aliases: false
  4399. </code></pre>
  4400. <hr />
  4401. <h3 id="allow_per_room_profiles"><a class="header" href="#allow_per_room_profiles"><code>allow_per_room_profiles</code></a></h3>
  4402. <p>Whether to allow per-room membership profiles through the sending of membership
  4403. events with profile information that differs from the target's global profile.
  4404. Defaults to true.</p>
  4405. <p>Example configuration:</p>
  4406. <pre><code class="language-yaml">allow_per_room_profiles: false
  4407. </code></pre>
  4408. <hr />
  4409. <h3 id="max_avatar_size"><a class="header" href="#max_avatar_size"><code>max_avatar_size</code></a></h3>
  4410. <p>The largest permissible file size in bytes for a user avatar. Defaults to no restriction.
  4411. Use M for MB and K for KB.</p>
  4412. <p>Note that user avatar changes will not work if this is set without using Synapse's media repository.</p>
  4413. <p>Example configuration:</p>
  4414. <pre><code class="language-yaml">max_avatar_size: 10M
  4415. </code></pre>
  4416. <hr />
  4417. <h3 id="allowed_avatar_mimetypes"><a class="header" href="#allowed_avatar_mimetypes"><code>allowed_avatar_mimetypes</code></a></h3>
  4418. <p>The MIME types allowed for user avatars. Defaults to no restriction.</p>
  4419. <p>Note that user avatar changes will not work if this is set without
  4420. using Synapse's media repository.</p>
  4421. <p>Example configuration:</p>
  4422. <pre><code class="language-yaml">allowed_avatar_mimetypes: [&quot;image/png&quot;, &quot;image/jpeg&quot;, &quot;image/gif&quot;]
  4423. </code></pre>
  4424. <hr />
  4425. <h3 id="redaction_retention_period"><a class="header" href="#redaction_retention_period"><code>redaction_retention_period</code></a></h3>
  4426. <p>How long to keep redacted events in unredacted form in the database. After
  4427. this period redacted events get replaced with their redacted form in the DB.</p>
  4428. <p>Synapse will check whether the rentention period has concluded for redacted
  4429. events every 5 minutes. Thus, even if this option is set to <code>0</code>, Synapse may
  4430. still take up to 5 minutes to purge redacted events from the database.</p>
  4431. <p>Defaults to <code>7d</code>. Set to <code>null</code> to disable.</p>
  4432. <p>Example configuration:</p>
  4433. <pre><code class="language-yaml">redaction_retention_period: 28d
  4434. </code></pre>
  4435. <hr />
  4436. <h3 id="user_ips_max_age"><a class="header" href="#user_ips_max_age"><code>user_ips_max_age</code></a></h3>
  4437. <p>How long to track users' last seen time and IPs in the database.</p>
  4438. <p>Defaults to <code>28d</code>. Set to <code>null</code> to disable clearing out of old rows.</p>
  4439. <p>Example configuration:</p>
  4440. <pre><code class="language-yaml">user_ips_max_age: 14d
  4441. </code></pre>
  4442. <hr />
  4443. <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>
  4444. <p>Inhibits the <code>/requestToken</code> endpoints from returning an error that might leak
  4445. information about whether an e-mail address is in use or not on this
  4446. homeserver. Defaults to false.
  4447. Note that for some endpoints the error situation is the e-mail already being
  4448. used, and for others the error is entering the e-mail being unused.
  4449. If this option is enabled, instead of returning an error, these endpoints will
  4450. act as if no error happened and return a fake session ID ('sid') to clients.</p>
  4451. <p>Example configuration:</p>
  4452. <pre><code class="language-yaml">request_token_inhibit_3pid_errors: true
  4453. </code></pre>
  4454. <hr />
  4455. <h3 id="next_link_domain_whitelist"><a class="header" href="#next_link_domain_whitelist"><code>next_link_domain_whitelist</code></a></h3>
  4456. <p>A list of domains that the domain portion of <code>next_link</code> parameters
  4457. must match.</p>
  4458. <p>This parameter is optionally provided by clients while requesting
  4459. validation of an email or phone number, and maps to a link that
  4460. users will be automatically redirected to after validation
  4461. succeeds. Clients can make use this parameter to aid the validation
  4462. process.</p>
  4463. <p>The whitelist is applied whether the homeserver or an identity server is handling validation.</p>
  4464. <p>The default value is no whitelist functionality; all domains are
  4465. allowed. Setting this value to an empty list will instead disallow
  4466. all domains.</p>
  4467. <p>Example configuration:</p>
  4468. <pre><code class="language-yaml">next_link_domain_whitelist: [&quot;matrix.org&quot;]
  4469. </code></pre>
  4470. <hr />
  4471. <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>
  4472. <p>These options define templates to use when generating email or HTML page contents.
  4473. The <code>custom_template_directory</code> determines which directory Synapse will try to
  4474. find template files in to use to generate email or HTML page contents.
  4475. If not set, or a file is not found within the template directory, a default
  4476. template from within the Synapse package will be used.</p>
  4477. <p>See <a href="usage/configuration/../../templates.html">here</a> for more
  4478. information about using custom templates.</p>
  4479. <p>Example configuration:</p>
  4480. <pre><code class="language-yaml">templates:
  4481. custom_template_directory: /path/to/custom/templates/
  4482. </code></pre>
  4483. <hr />
  4484. <h3 id="retention"><a class="header" href="#retention"><code>retention</code></a></h3>
  4485. <p>This option and the associated options determine message retention policy at the
  4486. server level.</p>
  4487. <p>Room admins and mods can define a retention period for their rooms using the
  4488. <code>m.room.retention</code> state event, and server admins can cap this period by setting
  4489. the <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> config options.</p>
  4490. <p>If this feature is enabled, Synapse will regularly look for and purge events
  4491. which are older than the room's maximum retention period. Synapse will also
  4492. filter events received over federation so that events that should have been
  4493. purged are ignored and not stored again.</p>
  4494. <p>The message retention policies feature is disabled by default. Please be advised
  4495. that enabling this feature carries some risk. There are known bugs with the implementation
  4496. which can cause database corruption. Setting retention to delete older history
  4497. is less risky than deleting newer history but in general caution is advised when enabling this
  4498. experimental feature. You can read more about this feature <a href="usage/configuration/../../message_retention_policies.html">here</a>.</p>
  4499. <p>This setting has the following sub-options:</p>
  4500. <ul>
  4501. <li>
  4502. <p><code>default_policy</code>: Default retention policy. If set, Synapse will apply it to rooms that lack the
  4503. 'm.room.retention' state event. This option is further specified by the
  4504. <code>min_lifetime</code> and <code>max_lifetime</code> sub-options associated with it. Note that the
  4505. value of <code>min_lifetime</code> doesn't matter much because Synapse doesn't take it into account yet.</p>
  4506. </li>
  4507. <li>
  4508. <p><code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code>: Retention policy limits. If
  4509. set, and the state of a room contains a <code>m.room.retention</code> event in its state
  4510. which contains a <code>min_lifetime</code> or a <code>max_lifetime</code> that's out of these bounds,
  4511. Synapse will cap the room's policy to these limits when running purge jobs.</p>
  4512. </li>
  4513. <li>
  4514. <p><code>purge_jobs</code> and the associated <code>shortest_max_lifetime</code> and <code>longest_max_lifetime</code> sub-options:
  4515. Server admins can define the settings of the background jobs purging the
  4516. events whose lifetime has expired under the <code>purge_jobs</code> section.</p>
  4517. <p>If no configuration is provided for this option, a single job will be set up to delete
  4518. expired events in every room daily.</p>
  4519. <p>Each job's configuration defines which range of message lifetimes the job
  4520. takes care of. For example, if <code>shortest_max_lifetime</code> is '2d' and
  4521. <code>longest_max_lifetime</code> is '3d', the job will handle purging expired events in
  4522. rooms whose state defines a <code>max_lifetime</code> that's both higher than 2 days, and
  4523. lower than or equal to 3 days. Both the minimum and the maximum value of a
  4524. range are optional, e.g. a job with no <code>shortest_max_lifetime</code> and a
  4525. <code>longest_max_lifetime</code> of '3d' will handle every room with a retention policy
  4526. whose <code>max_lifetime</code> is lower than or equal to three days.</p>
  4527. <p>The rationale for this per-job configuration is that some rooms might have a
  4528. retention policy with a low <code>max_lifetime</code>, where history needs to be purged
  4529. of outdated messages on a more frequent basis than for the rest of the rooms
  4530. (e.g. every 12h), but not want that purge to be performed by a job that's
  4531. iterating over every room it knows, which could be heavy on the server.</p>
  4532. <p>If any purge job is configured, it is strongly recommended to have at least
  4533. a single job with neither <code>shortest_max_lifetime</code> nor <code>longest_max_lifetime</code>
  4534. set, or one job without <code>shortest_max_lifetime</code> and one job without
  4535. <code>longest_max_lifetime</code> set. Otherwise some rooms might be ignored, even if
  4536. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> are set, because capping a
  4537. room's policy to these values is done after the policies are retrieved from
  4538. Synapse's database (which is done using the range specified in a purge job's
  4539. configuration).</p>
  4540. </li>
  4541. </ul>
  4542. <p>Example configuration:</p>
  4543. <pre><code class="language-yaml">retention:
  4544. enabled: true
  4545. default_policy:
  4546. min_lifetime: 1d
  4547. max_lifetime: 1y
  4548. allowed_lifetime_min: 1d
  4549. allowed_lifetime_max: 1y
  4550. purge_jobs:
  4551. - longest_max_lifetime: 3d
  4552. interval: 12h
  4553. - shortest_max_lifetime: 3d
  4554. interval: 1d
  4555. </code></pre>
  4556. <hr />
  4557. <h2 id="tls"><a class="header" href="#tls">TLS</a></h2>
  4558. <p>Options related to TLS.</p>
  4559. <hr />
  4560. <h3 id="tls_certificate_path"><a class="header" href="#tls_certificate_path"><code>tls_certificate_path</code></a></h3>
  4561. <p>This option specifies a PEM-encoded X509 certificate for TLS.
  4562. This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  4563. certificate, signed by a recognised Certificate Authority. Defaults to none.</p>
  4564. <p>Be sure to use a <code>.pem</code> file that includes the full certificate chain including
  4565. any intermediate certificates (for instance, if using certbot, use
  4566. <code>fullchain.pem</code> as your certificate, not <code>cert.pem</code>).</p>
  4567. <p>Example configuration:</p>
  4568. <pre><code class="language-yaml">tls_certificate_path: &quot;CONFDIR/SERVERNAME.tls.crt&quot;
  4569. </code></pre>
  4570. <hr />
  4571. <h3 id="tls_private_key_path"><a class="header" href="#tls_private_key_path"><code>tls_private_key_path</code></a></h3>
  4572. <p>PEM-encoded private key for TLS. Defaults to none.</p>
  4573. <p>Example configuration:</p>
  4574. <pre><code class="language-yaml">tls_private_key_path: &quot;CONFDIR/SERVERNAME.tls.key&quot;
  4575. </code></pre>
  4576. <hr />
  4577. <h3 id="federation_verify_certificates"><a class="header" href="#federation_verify_certificates"><code>federation_verify_certificates</code></a></h3>
  4578. <p>Whether to verify TLS server certificates for outbound federation requests.</p>
  4579. <p>Defaults to true. To disable certificate verification, set the option to false.</p>
  4580. <p>Example configuration:</p>
  4581. <pre><code class="language-yaml">federation_verify_certificates: false
  4582. </code></pre>
  4583. <hr />
  4584. <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>
  4585. <p>The minimum TLS version that will be used for outbound federation requests.</p>
  4586. <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
  4587. that setting this value higher than <code>1.2</code> will prevent federation to most
  4588. of the public Matrix network: only configure it to <code>1.3</code> if you have an
  4589. entirely private federation setup and you can ensure TLS 1.3 support.</p>
  4590. <p>Example configuration:</p>
  4591. <pre><code class="language-yaml">federation_client_minimum_tls_version: 1.2
  4592. </code></pre>
  4593. <hr />
  4594. <h3 id="federation_certificate_verification_whitelist"><a class="header" href="#federation_certificate_verification_whitelist"><code>federation_certificate_verification_whitelist</code></a></h3>
  4595. <p>Skip federation certificate verification on a given whitelist
  4596. of domains.</p>
  4597. <p>This setting should only be used in very specific cases, such as
  4598. federation over Tor hidden services and similar. For private networks
  4599. of homeservers, you likely want to use a private CA instead.</p>
  4600. <p>Only effective if <code>federation_verify_certificates</code> is <code>true</code>.</p>
  4601. <p>Example configuration:</p>
  4602. <pre><code class="language-yaml">federation_certificate_verification_whitelist:
  4603. - lon.example.com
  4604. - &quot;*.domain.com&quot;
  4605. - &quot;*.onion&quot;
  4606. </code></pre>
  4607. <hr />
  4608. <h3 id="federation_custom_ca_list"><a class="header" href="#federation_custom_ca_list"><code>federation_custom_ca_list</code></a></h3>
  4609. <p>List of custom certificate authorities for federation traffic.</p>
  4610. <p>This setting should only normally be used within a private network of
  4611. homeservers.</p>
  4612. <p>Note that this list will replace those that are provided by your
  4613. operating environment. Certificates must be in PEM format.</p>
  4614. <p>Example configuration:</p>
  4615. <pre><code class="language-yaml">federation_custom_ca_list:
  4616. - myCA1.pem
  4617. - myCA2.pem
  4618. - myCA3.pem
  4619. </code></pre>
  4620. <hr />
  4621. <h2 id="federation"><a class="header" href="#federation">Federation</a></h2>
  4622. <p>Options related to federation.</p>
  4623. <hr />
  4624. <h3 id="federation_domain_whitelist"><a class="header" href="#federation_domain_whitelist"><code>federation_domain_whitelist</code></a></h3>
  4625. <p>Restrict federation to the given whitelist of domains.
  4626. N.B. we recommend also firewalling your federation listener to limit
  4627. inbound federation traffic as early as possible, rather than relying
  4628. purely on this application-layer restriction. If not specified, the
  4629. default is to whitelist everything.</p>
  4630. <p>Example configuration:</p>
  4631. <pre><code class="language-yaml">federation_domain_whitelist:
  4632. - lon.example.com
  4633. - nyc.example.com
  4634. - syd.example.com
  4635. </code></pre>
  4636. <hr />
  4637. <h3 id="federation_metrics_domains"><a class="header" href="#federation_metrics_domains"><code>federation_metrics_domains</code></a></h3>
  4638. <p>Report prometheus metrics on the age of PDUs being sent to and received from
  4639. the given domains. This can be used to give an idea of &quot;delay&quot; on inbound
  4640. and outbound federation, though be aware that any delay can be due to problems
  4641. at either end or with the intermediate network.</p>
  4642. <p>By default, no domains are monitored in this way.</p>
  4643. <p>Example configuration:</p>
  4644. <pre><code class="language-yaml">federation_metrics_domains:
  4645. - matrix.org
  4646. - example.com
  4647. </code></pre>
  4648. <hr />
  4649. <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>
  4650. <p>Set to false to disable profile lookup over federation. By default, the
  4651. Federation API allows other homeservers to obtain profile data of any user
  4652. on this homeserver.</p>
  4653. <p>Example configuration:</p>
  4654. <pre><code class="language-yaml">allow_profile_lookup_over_federation: false
  4655. </code></pre>
  4656. <hr />
  4657. <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>
  4658. <p>Set this option to true to allow device display name lookup over federation. By default, the
  4659. Federation API prevents other homeservers from obtaining the display names of any user devices
  4660. on this homeserver.</p>
  4661. <p>Example configuration:</p>
  4662. <pre><code class="language-yaml">allow_device_name_lookup_over_federation: true
  4663. </code></pre>
  4664. <hr />
  4665. <h3 id="federation-1"><a class="header" href="#federation-1"><code>federation</code></a></h3>
  4666. <p>The federation section defines some sub-options related to federation.</p>
  4667. <p>The following options are related to configuring timeout and retry logic for one request,
  4668. independently of the others.
  4669. Short retry algorithm is used when something or someone will wait for the request to have an
  4670. answer, while long retry is used for requests that happen in the background,
  4671. like sending a federation transaction.</p>
  4672. <ul>
  4673. <li><code>client_timeout</code>: timeout for the federation requests. Default to 60s.</li>
  4674. <li><code>max_short_retry_delay</code>: maximum delay to be used for the short retry algo. Default to 2s.</li>
  4675. <li><code>max_long_retry_delay</code>: maximum delay to be used for the short retry algo. Default to 60s.</li>
  4676. <li><code>max_short_retries</code>: maximum number of retries for the short retry algo. Default to 3 attempts.</li>
  4677. <li><code>max_long_retries</code>: maximum number of retries for the long retry algo. Default to 10 attempts.</li>
  4678. </ul>
  4679. <p>Example configuration:</p>
  4680. <pre><code class="language-yaml">federation:
  4681. client_timeout: 180s
  4682. max_short_retry_delay: 7s
  4683. max_long_retry_delay: 100s
  4684. max_short_retries: 5
  4685. max_long_retries: 20
  4686. </code></pre>
  4687. <hr />
  4688. <h2 id="caching"><a class="header" href="#caching">Caching</a></h2>
  4689. <p>Options related to caching.</p>
  4690. <hr />
  4691. <h3 id="event_cache_size"><a class="header" href="#event_cache_size"><code>event_cache_size</code></a></h3>
  4692. <p>The number of events to cache in memory. Defaults to 10K. Like other caches,
  4693. this is affected by <code>caches.global_factor</code> (see below).</p>
  4694. <p>Note that this option is not part of the <code>caches</code> section.</p>
  4695. <p>Example configuration:</p>
  4696. <pre><code class="language-yaml">event_cache_size: 15K
  4697. </code></pre>
  4698. <hr />
  4699. <h3 id="caches-and-associated-values"><a class="header" href="#caches-and-associated-values"><code>caches</code> and associated values</a></h3>
  4700. <p>A cache 'factor' is a multiplier that can be applied to each of
  4701. Synapse's caches in order to increase or decrease the maximum
  4702. number of entries that can be stored.</p>
  4703. <p><code>caches</code> can be configured through the following sub-options:</p>
  4704. <ul>
  4705. <li>
  4706. <p><code>global_factor</code>: Controls the global cache factor, which is the default cache factor
  4707. for all caches if a specific factor for that cache is not otherwise
  4708. set.</p>
  4709. <p>This can also be set by the <code>SYNAPSE_CACHE_FACTOR</code> environment
  4710. variable. Setting by environment variable takes priority over
  4711. setting through the config file.</p>
  4712. <p>Defaults to 0.5, which will halve the size of all caches.</p>
  4713. </li>
  4714. <li>
  4715. <p><code>per_cache_factors</code>: A dictionary of cache name to cache factor for that individual
  4716. cache. Overrides the global cache factor for a given cache.</p>
  4717. <p>These can also be set through environment variables comprised
  4718. of <code>SYNAPSE_CACHE_FACTOR_</code> + the name of the cache in capital
  4719. letters and underscores. Setting by environment variable
  4720. takes priority over setting through the config file.
  4721. Ex. <code>SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0</code></p>
  4722. <p>Some caches have '*' and other characters that are not
  4723. alphanumeric or underscores. These caches can be named with or
  4724. without the special characters stripped. For example, to specify
  4725. the cache factor for <code>*stateGroupCache*</code> via an environment
  4726. variable would be <code>SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0</code>.</p>
  4727. </li>
  4728. <li>
  4729. <p><code>expire_caches</code>: Controls whether cache entries are evicted after a specified time
  4730. period. Defaults to true. Set to false to disable this feature. Note that never expiring
  4731. caches may result in excessive memory usage.</p>
  4732. </li>
  4733. <li>
  4734. <p><code>cache_entry_ttl</code>: If <code>expire_caches</code> is enabled, this flag controls how long an entry can
  4735. be in a cache without having been accessed before being evicted.
  4736. Defaults to 30m.</p>
  4737. </li>
  4738. <li>
  4739. <p><code>sync_response_cache_duration</code>: Controls how long the results of a /sync request are
  4740. cached for after a successful response is returned. A higher duration can help clients
  4741. with intermittent connections, at the cost of higher memory usage.
  4742. A value of zero means that sync responses are not cached.
  4743. Defaults to 2m.</p>
  4744. <p><em>Changed in Synapse 1.62.0</em>: The default was changed from 0 to 2m.</p>
  4745. </li>
  4746. <li>
  4747. <p><code>cache_autotuning</code> and its sub-options <code>max_cache_memory_usage</code>, <code>target_cache_memory_usage</code>, and
  4748. <code>min_cache_ttl</code> work in conjunction with each other to maintain a balance between cache memory
  4749. 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>
  4750. to utilize this option, and all three of the options must be specified for this feature to work. This option
  4751. defaults to off, enable it by providing values for the sub-options listed below. Please note that the feature will not work
  4752. and may cause unstable behavior (such as excessive emptying of caches or exceptions) if all of the values are not provided.
  4753. 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
  4754. durations.</p>
  4755. <ul>
  4756. <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.
  4757. They will continue to be evicted until the memory usage drops below the <code>target_memory_usage</code>, set in
  4758. the setting below, or until the <code>min_cache_ttl</code> is hit. There is no default value for this option.</li>
  4759. <li><code>target_cache_memory_usage</code> sets a rough target for the desired memory usage of the caches. There is no default value
  4760. for this option.</li>
  4761. <li><code>min_cache_ttl</code> sets a limit under which newer cache entries are not evicted and is only applied when
  4762. caches are actively being evicted/<code>max_cache_memory_usage</code> has been exceeded. This is to protect hot caches
  4763. from being emptied while Synapse is evicting due to memory. There is no default value for this option.</li>
  4764. </ul>
  4765. </li>
  4766. </ul>
  4767. <p>Example configuration:</p>
  4768. <pre><code class="language-yaml">event_cache_size: 15K
  4769. caches:
  4770. global_factor: 1.0
  4771. per_cache_factors:
  4772. get_users_who_share_room_with_user: 2.0
  4773. sync_response_cache_duration: 2m
  4774. cache_autotuning:
  4775. max_cache_memory_usage: 1024M
  4776. target_cache_memory_usage: 758M
  4777. min_cache_ttl: 5m
  4778. </code></pre>
  4779. <h3 id="reloading-cache-factors"><a class="header" href="#reloading-cache-factors">Reloading cache factors</a></h3>
  4780. <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
  4781. <a href="https://en.wikipedia.org/wiki/SIGHUP"><code>SIGHUP</code></a> signal to Synapse using e.g.</p>
  4782. <pre><code class="language-commandline">kill -HUP [PID_OF_SYNAPSE_PROCESS]
  4783. </code></pre>
  4784. <p>If you are running multiple workers, you must individually update the worker
  4785. config file and send this signal to each worker process.</p>
  4786. <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>
  4787. file in Synapse's <code>contrib</code> directory, you can send a <code>SIGHUP</code> signal by using
  4788. <code>systemctl reload matrix-synapse</code>.</p>
  4789. <hr />
  4790. <h2 id="database"><a class="header" href="#database">Database</a></h2>
  4791. <p>Config options related to database settings.</p>
  4792. <hr />
  4793. <h3 id="database-1"><a class="header" href="#database-1"><code>database</code></a></h3>
  4794. <p>The <code>database</code> setting defines the database that synapse uses to store all of
  4795. its data.</p>
  4796. <p>Associated sub-options:</p>
  4797. <ul>
  4798. <li>
  4799. <p><code>name</code>: this option specifies the database engine to use: either <code>sqlite3</code> (for SQLite)
  4800. or <code>psycopg2</code> (for PostgreSQL). If no name is specified Synapse will default to SQLite.</p>
  4801. </li>
  4802. <li>
  4803. <p><code>txn_limit</code> gives the maximum number of transactions to run per connection
  4804. before reconnecting. Defaults to 0, which means no limit.</p>
  4805. </li>
  4806. <li>
  4807. <p><code>allow_unsafe_locale</code> is an option specific to Postgres. Under the default behavior, Synapse will refuse to
  4808. start if the postgres db is set to a non-C locale. You can override this behavior (which is <em>not</em> recommended)
  4809. by setting <code>allow_unsafe_locale</code> to true. Note that doing so may corrupt your database. You can find more information
  4810. <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>
  4811. </li>
  4812. <li>
  4813. <p><code>args</code> gives options which are passed through to the database engine,
  4814. except for options starting with <code>cp_</code>, which are used to configure the Twisted
  4815. connection pool. For a reference to valid arguments, see:</p>
  4816. <ul>
  4817. <li>for <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3.connect">sqlite</a></li>
  4818. <li>for <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">postgres</a></li>
  4819. <li>for <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__">the connection pool</a></li>
  4820. </ul>
  4821. </li>
  4822. </ul>
  4823. <p>For more information on using Synapse with Postgres,
  4824. see <a href="usage/configuration/../../postgres.html">here</a>.</p>
  4825. <p>Example SQLite configuration:</p>
  4826. <pre><code class="language-yaml">database:
  4827. name: sqlite3
  4828. args:
  4829. database: /path/to/homeserver.db
  4830. </code></pre>
  4831. <p>Example Postgres configuration:</p>
  4832. <pre><code class="language-yaml">database:
  4833. name: psycopg2
  4834. txn_limit: 10000
  4835. args:
  4836. user: synapse_user
  4837. password: secretpassword
  4838. database: synapse
  4839. host: localhost
  4840. port: 5432
  4841. cp_min: 5
  4842. cp_max: 10
  4843. </code></pre>
  4844. <hr />
  4845. <h3 id="databases"><a class="header" href="#databases"><code>databases</code></a></h3>
  4846. <p>The <code>databases</code> option allows specifying a mapping between certain database tables and
  4847. database host details, spreading the load of a single Synapse instance across multiple
  4848. database backends. This is often referred to as &quot;database sharding&quot;. This option is only
  4849. supported for PostgreSQL database backends.</p>
  4850. <p><strong>Important note:</strong> This is a supported option, but is not currently used in production by the
  4851. Matrix.org Foundation. Proceed with caution and always make backups.</p>
  4852. <p><code>databases</code> is a dictionary of arbitrarily-named database entries. Each entry is equivalent
  4853. to the value of the <code>database</code> homeserver config option (see above), with the addition of
  4854. a <code>data_stores</code> key. <code>data_stores</code> is an array of strings that specifies the data store(s)
  4855. (a defined label for a set of tables) that should be stored on the associated database
  4856. backend entry.</p>
  4857. <p>The currently defined values for <code>data_stores</code> are:</p>
  4858. <ul>
  4859. <li>
  4860. <p><code>&quot;state&quot;</code>: Database that relates to state groups will be stored in this database.</p>
  4861. <p>Specifically, that means the following tables:</p>
  4862. <ul>
  4863. <li><code>state_groups</code></li>
  4864. <li><code>state_group_edges</code></li>
  4865. <li><code>state_groups_state</code></li>
  4866. </ul>
  4867. <p>And the following sequences:</p>
  4868. <ul>
  4869. <li><code>state_groups_seq_id</code></li>
  4870. </ul>
  4871. </li>
  4872. <li>
  4873. <p><code>&quot;main&quot;</code>: All other database tables and sequences.</p>
  4874. </li>
  4875. </ul>
  4876. <p>All databases will end up with additional tables used for tracking database schema migrations
  4877. and any pending background updates. Synapse will create these automatically on startup when checking for
  4878. and/or performing database schema migrations.</p>
  4879. <p>To migrate an existing database configuration (e.g. all tables on a single database) to a different
  4880. configuration (e.g. the &quot;main&quot; data store on one database, and &quot;state&quot; on another), do the following:</p>
  4881. <ol>
  4882. <li>
  4883. <p>Take a backup of your existing database. Things can and do go wrong and database corruption is no joke!</p>
  4884. </li>
  4885. <li>
  4886. <p>Ensure all pending database migrations have been applied and background updates have run. The simplest
  4887. way to do this is to use the <code>update_synapse_database</code> script supplied with your Synapse installation.</p>
  4888. <pre><code class="language-sh">update_synapse_database --database-config homeserver.yaml --run-background-updates
  4889. </code></pre>
  4890. </li>
  4891. <li>
  4892. <p>Copy over the necessary tables and sequences from one database to the other. Tables relating to database
  4893. migrations, schemas, schema versions and background updates should <strong>not</strong> be copied.</p>
  4894. <p>As an example, say that you'd like to split out the &quot;state&quot; data store from an existing database which
  4895. currently contains all data stores.</p>
  4896. <p>Simply copy the tables and sequences defined above for the &quot;state&quot; datastore from the existing database
  4897. to the secondary database. As noted above, additional tables will be created in the secondary database
  4898. when Synapse is started.</p>
  4899. </li>
  4900. <li>
  4901. <p>Modify/create the <code>databases</code> option in your <code>homeserver.yaml</code> to match the desired database configuration.</p>
  4902. </li>
  4903. <li>
  4904. <p>Start Synapse. Check that it starts up successfully and that things generally seem to be working.</p>
  4905. </li>
  4906. <li>
  4907. <p>Drop the old tables that were copied in step 3.</p>
  4908. </li>
  4909. </ol>
  4910. <p>Only one of the options <code>database</code> or <code>databases</code> may be specified in your config, but not both.</p>
  4911. <p>Example configuration:</p>
  4912. <pre><code class="language-yaml">databases:
  4913. basement_box:
  4914. name: psycopg2
  4915. txn_limit: 10000
  4916. data_stores: [&quot;main&quot;]
  4917. args:
  4918. user: synapse_user
  4919. password: secretpassword
  4920. database: synapse_main
  4921. host: localhost
  4922. port: 5432
  4923. cp_min: 5
  4924. cp_max: 10
  4925. my_other_database:
  4926. name: psycopg2
  4927. txn_limit: 10000
  4928. data_stores: [&quot;state&quot;]
  4929. args:
  4930. user: synapse_user
  4931. password: secretpassword
  4932. database: synapse_state
  4933. host: localhost
  4934. port: 5432
  4935. cp_min: 5
  4936. cp_max: 10
  4937. </code></pre>
  4938. <hr />
  4939. <h2 id="logging"><a class="header" href="#logging">Logging</a></h2>
  4940. <p>Config options related to logging.</p>
  4941. <hr />
  4942. <h3 id="log_config"><a class="header" href="#log_config"><code>log_config</code></a></h3>
  4943. <p>This option specifies a yaml python logging config file as described
  4944. <a href="https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema">here</a>.</p>
  4945. <p>Example configuration:</p>
  4946. <pre><code class="language-yaml">log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  4947. </code></pre>
  4948. <hr />
  4949. <h2 id="ratelimiting"><a class="header" href="#ratelimiting">Ratelimiting</a></h2>
  4950. <p>Options related to ratelimiting in Synapse.</p>
  4951. <p>Each ratelimiting configuration is made of two parameters:</p>
  4952. <ul>
  4953. <li><code>per_second</code>: number of requests a client can send per second.</li>
  4954. <li><code>burst_count</code>: number of requests a client can send before being throttled.</li>
  4955. </ul>
  4956. <hr />
  4957. <h3 id="rc_message"><a class="header" href="#rc_message"><code>rc_message</code></a></h3>
  4958. <p>Ratelimiting settings for client messaging.</p>
  4959. <p>This is a ratelimiting option for messages that ratelimits sending based on the account the client
  4960. is using. It defaults to: <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  4961. <p>Example configuration:</p>
  4962. <pre><code class="language-yaml">rc_message:
  4963. per_second: 0.5
  4964. burst_count: 15
  4965. </code></pre>
  4966. <hr />
  4967. <h3 id="rc_registration"><a class="header" href="#rc_registration"><code>rc_registration</code></a></h3>
  4968. <p>This option ratelimits registration requests based on the client's IP address.
  4969. It defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  4970. <p>Example configuration:</p>
  4971. <pre><code class="language-yaml">rc_registration:
  4972. per_second: 0.15
  4973. burst_count: 2
  4974. </code></pre>
  4975. <hr />
  4976. <h3 id="rc_registration_token_validity"><a class="header" href="#rc_registration_token_validity"><code>rc_registration_token_validity</code></a></h3>
  4977. <p>This option checks the validity of registration tokens that ratelimits requests based on
  4978. the client's IP address.
  4979. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 5</code>.</p>
  4980. <p>Example configuration:</p>
  4981. <pre><code class="language-yaml">rc_registration_token_validity:
  4982. per_second: 0.3
  4983. burst_count: 6
  4984. </code></pre>
  4985. <hr />
  4986. <h3 id="rc_login"><a class="header" href="#rc_login"><code>rc_login</code></a></h3>
  4987. <p>This option specifies several limits for login:</p>
  4988. <ul>
  4989. <li>
  4990. <p><code>address</code> ratelimits login requests based on the client's IP
  4991. address. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  4992. </li>
  4993. <li>
  4994. <p><code>account</code> ratelimits login requests based on the account the
  4995. client is attempting to log into. Defaults to <code>per_second: 0.003</code>,
  4996. <code>burst_count: 5</code>.</p>
  4997. </li>
  4998. <li>
  4999. <p><code>failed_attempts</code> ratelimits login requests based on the account the
  5000. client is attempting to log into, based on the amount of failed login
  5001. attempts for this account. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  5002. </li>
  5003. </ul>
  5004. <p>Example configuration:</p>
  5005. <pre><code class="language-yaml">rc_login:
  5006. address:
  5007. per_second: 0.15
  5008. burst_count: 5
  5009. account:
  5010. per_second: 0.18
  5011. burst_count: 4
  5012. failed_attempts:
  5013. per_second: 0.19
  5014. burst_count: 7
  5015. </code></pre>
  5016. <hr />
  5017. <h3 id="rc_admin_redaction"><a class="header" href="#rc_admin_redaction"><code>rc_admin_redaction</code></a></h3>
  5018. <p>This option sets ratelimiting redactions by room admins. If this is not explicitly
  5019. set then it uses the same ratelimiting as per <code>rc_message</code>. This is useful
  5020. to allow room admins to deal with abuse quickly.</p>
  5021. <p>Example configuration:</p>
  5022. <pre><code class="language-yaml">rc_admin_redaction:
  5023. per_second: 1
  5024. burst_count: 50
  5025. </code></pre>
  5026. <hr />
  5027. <h3 id="rc_joins"><a class="header" href="#rc_joins"><code>rc_joins</code></a></h3>
  5028. <p>This option allows for ratelimiting number of rooms a user can join. This setting has the following sub-options:</p>
  5029. <ul>
  5030. <li>
  5031. <p><code>local</code>: ratelimits when users are joining rooms the server is already in.
  5032. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 10</code>.</p>
  5033. </li>
  5034. <li>
  5035. <p><code>remote</code>: ratelimits when users are trying to join rooms not on the server (which
  5036. can be more computationally expensive than restricting locally). Defaults to
  5037. <code>per_second: 0.01</code>, <code>burst_count: 10</code></p>
  5038. </li>
  5039. </ul>
  5040. <p>Example configuration:</p>
  5041. <pre><code class="language-yaml">rc_joins:
  5042. local:
  5043. per_second: 0.2
  5044. burst_count: 15
  5045. remote:
  5046. per_second: 0.03
  5047. burst_count: 12
  5048. </code></pre>
  5049. <hr />
  5050. <h3 id="rc_joins_per_room"><a class="header" href="#rc_joins_per_room"><code>rc_joins_per_room</code></a></h3>
  5051. <p>This option allows admins to ratelimit joins to a room based on the number of recent
  5052. joins (local or remote) to that room. It is intended to mitigate mass-join spam
  5053. waves which target multiple homeservers.</p>
  5054. <p>By default, one join is permitted to a room every second, with an accumulating
  5055. buffer of up to ten instantaneous joins.</p>
  5056. <p>Example configuration (default values):</p>
  5057. <pre><code class="language-yaml">rc_joins_per_room:
  5058. per_second: 1
  5059. burst_count: 10
  5060. </code></pre>
  5061. <p><em>Added in Synapse 1.64.0.</em></p>
  5062. <hr />
  5063. <h3 id="rc_3pid_validation"><a class="header" href="#rc_3pid_validation"><code>rc_3pid_validation</code></a></h3>
  5064. <p>This option ratelimits how often a user or IP can attempt to validate a 3PID.
  5065. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  5066. <p>Example configuration:</p>
  5067. <pre><code class="language-yaml">rc_3pid_validation:
  5068. per_second: 0.003
  5069. burst_count: 5
  5070. </code></pre>
  5071. <hr />
  5072. <h3 id="rc_invites"><a class="header" href="#rc_invites"><code>rc_invites</code></a></h3>
  5073. <p>This option sets ratelimiting how often invites can be sent in a room or to a
  5074. specific user. <code>per_room</code> defaults to <code>per_second: 0.3</code>, <code>burst_count: 10</code> and
  5075. <code>per_user</code> defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  5076. <p>Client requests that invite user(s) when <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3createroom">creating a
  5077. room</a>
  5078. will count against the <code>rc_invites.per_room</code> limit, whereas
  5079. client requests to <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite">invite a single user to a
  5080. room</a>
  5081. will count against both the <code>rc_invites.per_user</code> and <code>rc_invites.per_room</code> limits.</p>
  5082. <p>Federation requests to invite a user will count against the <code>rc_invites.per_user</code>
  5083. limit only, as Synapse presumes ratelimiting by room will be done by the sending server.</p>
  5084. <p>The <code>rc_invites.per_user</code> limit applies to the <em>receiver</em> of the invite, rather than the
  5085. sender, meaning that a <code>rc_invite.per_user.burst_count</code> of 5 mandates that a single user
  5086. cannot <em>receive</em> more than a burst of 5 invites at a time.</p>
  5087. <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>
  5088. <p><em>Changed in version 1.63:</em> added the <code>per_issuer</code> limit.</p>
  5089. <p>Example configuration:</p>
  5090. <pre><code class="language-yaml">rc_invites:
  5091. per_room:
  5092. per_second: 0.5
  5093. burst_count: 5
  5094. per_user:
  5095. per_second: 0.004
  5096. burst_count: 3
  5097. per_issuer:
  5098. per_second: 0.5
  5099. burst_count: 5
  5100. </code></pre>
  5101. <hr />
  5102. <h3 id="rc_third_party_invite"><a class="header" href="#rc_third_party_invite"><code>rc_third_party_invite</code></a></h3>
  5103. <p>This option ratelimits 3PID invites (i.e. invites sent to a third-party ID
  5104. such as an email address or a phone number) based on the account that's
  5105. sending the invite. Defaults to <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  5106. <p>Example configuration:</p>
  5107. <pre><code class="language-yaml">rc_third_party_invite:
  5108. per_second: 0.2
  5109. burst_count: 10
  5110. </code></pre>
  5111. <hr />
  5112. <h3 id="rc_federation"><a class="header" href="#rc_federation"><code>rc_federation</code></a></h3>
  5113. <p>Defines limits on federation requests.</p>
  5114. <p>The <code>rc_federation</code> configuration has the following sub-options:</p>
  5115. <ul>
  5116. <li><code>window_size</code>: window size in milliseconds. Defaults to 1000.</li>
  5117. <li><code>sleep_limit</code>: number of federation requests from a single server in
  5118. a window before the server will delay processing the request. Defaults to 10.</li>
  5119. <li><code>sleep_delay</code>: duration in milliseconds to delay processing events
  5120. from remote servers by if they go over the sleep limit. Defaults to 500.</li>
  5121. <li><code>reject_limit</code>: maximum number of concurrent federation requests
  5122. allowed from a single server. Defaults to 50.</li>
  5123. <li><code>concurrent</code>: number of federation requests to concurrently process
  5124. from a single server. Defaults to 3.</li>
  5125. </ul>
  5126. <p>Example configuration:</p>
  5127. <pre><code class="language-yaml">rc_federation:
  5128. window_size: 750
  5129. sleep_limit: 15
  5130. sleep_delay: 400
  5131. reject_limit: 40
  5132. concurrent: 5
  5133. </code></pre>
  5134. <hr />
  5135. <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>
  5136. <p>Sets outgoing federation transaction frequency for sending read-receipts,
  5137. per-room.</p>
  5138. <p>If we end up trying to send out more read-receipts, they will get buffered up
  5139. into fewer transactions. Defaults to 50.</p>
  5140. <p>Example configuration:</p>
  5141. <pre><code class="language-yaml">federation_rr_transactions_per_room_per_second: 40
  5142. </code></pre>
  5143. <hr />
  5144. <h2 id="media-store"><a class="header" href="#media-store">Media Store</a></h2>
  5145. <p>Config options related to Synapse's media store.</p>
  5146. <hr />
  5147. <h3 id="enable_media_repo"><a class="header" href="#enable_media_repo"><code>enable_media_repo</code></a></h3>
  5148. <p>Enable the media store service in the Synapse master. Defaults to true.
  5149. Set to false if you are using a separate media store worker.</p>
  5150. <p>Example configuration:</p>
  5151. <pre><code class="language-yaml">enable_media_repo: false
  5152. </code></pre>
  5153. <hr />
  5154. <h3 id="media_store_path"><a class="header" href="#media_store_path"><code>media_store_path</code></a></h3>
  5155. <p>Directory where uploaded images and attachments are stored.</p>
  5156. <p>Example configuration:</p>
  5157. <pre><code class="language-yaml">media_store_path: &quot;DATADIR/media_store&quot;
  5158. </code></pre>
  5159. <hr />
  5160. <h3 id="media_storage_providers"><a class="header" href="#media_storage_providers"><code>media_storage_providers</code></a></h3>
  5161. <p>Media storage providers allow media to be stored in different
  5162. locations. Defaults to none. Associated sub-options are:</p>
  5163. <ul>
  5164. <li><code>module</code>: type of resource, e.g. <code>file_system</code>.</li>
  5165. <li><code>store_local</code>: whether to store newly uploaded local files</li>
  5166. <li><code>store_remote</code>: whether to store newly downloaded local files</li>
  5167. <li><code>store_synchronous</code>: whether to wait for successful storage for local uploads</li>
  5168. <li><code>config</code>: sets a path to the resource through the <code>directory</code> option</li>
  5169. </ul>
  5170. <p>Example configuration:</p>
  5171. <pre><code class="language-yaml">media_storage_providers:
  5172. - module: file_system
  5173. store_local: false
  5174. store_remote: false
  5175. store_synchronous: false
  5176. config:
  5177. directory: /mnt/some/other/directory
  5178. </code></pre>
  5179. <hr />
  5180. <h3 id="max_upload_size"><a class="header" href="#max_upload_size"><code>max_upload_size</code></a></h3>
  5181. <p>The largest allowed upload size in bytes.</p>
  5182. <p>If you are using a reverse proxy you may also need to set this value in
  5183. your reverse proxy's config. Defaults to 50M. Notably Nginx has a small max body size by default.
  5184. See <a href="usage/configuration/../../reverse_proxy.html">here</a> for more on using a reverse proxy with Synapse.</p>
  5185. <p>Example configuration:</p>
  5186. <pre><code class="language-yaml">max_upload_size: 60M
  5187. </code></pre>
  5188. <hr />
  5189. <h3 id="max_image_pixels"><a class="header" href="#max_image_pixels"><code>max_image_pixels</code></a></h3>
  5190. <p>Maximum number of pixels that will be thumbnailed. Defaults to 32M.</p>
  5191. <p>Example configuration:</p>
  5192. <pre><code class="language-yaml">max_image_pixels: 35M
  5193. </code></pre>
  5194. <hr />
  5195. <h3 id="prevent_media_downloads_from"><a class="header" href="#prevent_media_downloads_from"><code>prevent_media_downloads_from</code></a></h3>
  5196. <p>A list of domains to never download media from. Media from these
  5197. domains that is already downloaded will not be deleted, but will be
  5198. inaccessible to users. This option does not affect admin APIs trying
  5199. to download/operate on media.</p>
  5200. <p>This will not prevent the listed domains from accessing media themselves.
  5201. It simply prevents users on this server from downloading media originating
  5202. from the listed servers.</p>
  5203. <p>This will have no effect on media originating from the local server.
  5204. This only affects media downloaded from other Matrix servers, to
  5205. 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>
  5206. <p>Defaults to an empty list (nothing blocked).</p>
  5207. <p>Example configuration:</p>
  5208. <pre><code class="language-yaml">prevent_media_downloads_from:
  5209. - evil.example.org
  5210. - evil2.example.org
  5211. </code></pre>
  5212. <hr />
  5213. <h3 id="dynamic_thumbnails"><a class="header" href="#dynamic_thumbnails"><code>dynamic_thumbnails</code></a></h3>
  5214. <p>Whether to generate new thumbnails on the fly to precisely match
  5215. the resolution requested by the client. If true then whenever
  5216. a new resolution is requested by the client the server will
  5217. generate a new thumbnail. If false the server will pick a thumbnail
  5218. from a precalculated list. Defaults to false.</p>
  5219. <p>Example configuration:</p>
  5220. <pre><code class="language-yaml">dynamic_thumbnails: true
  5221. </code></pre>
  5222. <hr />
  5223. <h3 id="thumbnail_sizes"><a class="header" href="#thumbnail_sizes"><code>thumbnail_sizes</code></a></h3>
  5224. <p>List of thumbnails to precalculate when an image is uploaded. Associated sub-options are:</p>
  5225. <ul>
  5226. <li><code>width</code></li>
  5227. <li><code>height</code></li>
  5228. <li><code>method</code>: i.e. <code>crop</code>, <code>scale</code>, etc.</li>
  5229. </ul>
  5230. <p>Example configuration:</p>
  5231. <pre><code class="language-yaml">thumbnail_sizes:
  5232. - width: 32
  5233. height: 32
  5234. method: crop
  5235. - width: 96
  5236. height: 96
  5237. method: crop
  5238. - width: 320
  5239. height: 240
  5240. method: scale
  5241. - width: 640
  5242. height: 480
  5243. method: scale
  5244. - width: 800
  5245. height: 600
  5246. method: scale
  5247. </code></pre>
  5248. <hr />
  5249. <h3 id="media_retention"><a class="header" href="#media_retention"><code>media_retention</code></a></h3>
  5250. <p>Controls whether local media and entries in the remote media cache
  5251. (media that is downloaded from other homeservers) should be removed
  5252. under certain conditions, typically for the purpose of saving space.</p>
  5253. <p>Purging media files will be the carried out by the media worker
  5254. (that is, the worker that has the <code>enable_media_repo</code> homeserver config
  5255. option set to 'true'). This may be the main process.</p>
  5256. <p>The <code>media_retention.local_media_lifetime</code> and
  5257. <code>media_retention.remote_media_lifetime</code> config options control whether
  5258. media will be purged if it has not been accessed in a given amount of
  5259. time. Note that media is 'accessed' when loaded in a room in a client, or
  5260. otherwise downloaded by a local or remote user. If the media has never
  5261. been accessed, the media's creation time is used instead. Both thumbnails
  5262. and the original media will be removed. If either of these options are unset,
  5263. then media of that type will not be purged.</p>
  5264. <p>Local or cached remote media that has been
  5265. <a href="usage/configuration/../../admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantined</a>
  5266. will not be deleted. Similarly, local media that has been marked as
  5267. <a href="usage/configuration/../../admin_api/media_admin_api.html#protecting-media-from-being-quarantined">protected from quarantine</a>
  5268. will not be deleted.</p>
  5269. <p>Example configuration:</p>
  5270. <pre><code class="language-yaml">media_retention:
  5271. local_media_lifetime: 90d
  5272. remote_media_lifetime: 14d
  5273. </code></pre>
  5274. <hr />
  5275. <h3 id="url_preview_enabled"><a class="header" href="#url_preview_enabled"><code>url_preview_enabled</code></a></h3>
  5276. <p>This setting determines whether the preview URL API is enabled.
  5277. It is disabled by default. Set to true to enable. If enabled you must specify a
  5278. <code>url_preview_ip_range_blacklist</code> blacklist.</p>
  5279. <p>Example configuration:</p>
  5280. <pre><code class="language-yaml">url_preview_enabled: true
  5281. </code></pre>
  5282. <hr />
  5283. <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>
  5284. <p>List of IP address CIDR ranges that the URL preview spider is denied
  5285. from accessing. There are no defaults: you must explicitly
  5286. specify a list for URL previewing to work. You should specify any
  5287. internal services in your network that you do not want synapse to try
  5288. to connect to, otherwise anyone in any Matrix room could cause your
  5289. synapse to issue arbitrary GET requests to your internal services,
  5290. causing serious security issues.</p>
  5291. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  5292. listed here, since they correspond to unroutable addresses.)</p>
  5293. <p>This must be specified if <code>url_preview_enabled</code> is set. It is recommended that
  5294. you use the following example list as a starting point.</p>
  5295. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  5296. <p>Example configuration:</p>
  5297. <pre><code class="language-yaml">url_preview_ip_range_blacklist:
  5298. - '127.0.0.0/8'
  5299. - '10.0.0.0/8'
  5300. - '172.16.0.0/12'
  5301. - '192.168.0.0/16'
  5302. - '100.64.0.0/10'
  5303. - '192.0.0.0/24'
  5304. - '169.254.0.0/16'
  5305. - '192.88.99.0/24'
  5306. - '198.18.0.0/15'
  5307. - '192.0.2.0/24'
  5308. - '198.51.100.0/24'
  5309. - '203.0.113.0/24'
  5310. - '224.0.0.0/4'
  5311. - '::1/128'
  5312. - 'fe80::/10'
  5313. - 'fc00::/7'
  5314. - '2001:db8::/32'
  5315. - 'ff00::/8'
  5316. - 'fec0::/10'
  5317. </code></pre>
  5318. <hr />
  5319. <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>
  5320. <p>This option sets a list of IP address CIDR ranges that the URL preview spider is allowed
  5321. to access even if they are specified in <code>url_preview_ip_range_blacklist</code>.
  5322. This is useful for specifying exceptions to wide-ranging blacklisted
  5323. target IP ranges - e.g. for enabling URL previews for a specific private
  5324. website only visible in your network. Defaults to none.</p>
  5325. <p>Example configuration:</p>
  5326. <pre><code class="language-yaml">url_preview_ip_range_whitelist:
  5327. - '192.168.1.1'
  5328. </code></pre>
  5329. <hr />
  5330. <h3 id="url_preview_url_blacklist"><a class="header" href="#url_preview_url_blacklist"><code>url_preview_url_blacklist</code></a></h3>
  5331. <p>Optional list of URL matches that the URL preview spider is
  5332. denied from accessing. You should use <code>url_preview_ip_range_blacklist</code>
  5333. in preference to this, otherwise someone could define a public DNS
  5334. entry that points to a private IP address and circumvent the blacklist.
  5335. This is more useful if you know there is an entire shape of URL that
  5336. you know that will never want synapse to try to spider.</p>
  5337. <p>Each list entry is a dictionary of url component attributes as returned
  5338. by urlparse.urlsplit as applied to the absolute form of the URL. See
  5339. <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit">here</a> for more
  5340. information. Some examples are:</p>
  5341. <ul>
  5342. <li><code>username</code></li>
  5343. <li><code>netloc</code></li>
  5344. <li><code>scheme</code></li>
  5345. <li><code>path</code></li>
  5346. </ul>
  5347. <p>The values of the dictionary are treated as a filename match pattern
  5348. applied to that component of URLs, unless they start with a ^ in which
  5349. case they are treated as a regular expression match. If all the
  5350. specified component matches for a given list item succeed, the URL is
  5351. blacklisted.</p>
  5352. <p>Example configuration:</p>
  5353. <pre><code class="language-yaml">url_preview_url_blacklist:
  5354. # blacklist any URL with a username in its URI
  5355. - username: '*'
  5356. # blacklist all *.google.com URLs
  5357. - netloc: 'google.com'
  5358. - netloc: '*.google.com'
  5359. # blacklist all plain HTTP URLs
  5360. - scheme: 'http'
  5361. # blacklist http(s)://www.acme.com/foo
  5362. - netloc: 'www.acme.com'
  5363. path: '/foo'
  5364. # blacklist any URL with a literal IPv4 address
  5365. - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  5366. </code></pre>
  5367. <hr />
  5368. <h3 id="max_spider_size"><a class="header" href="#max_spider_size"><code>max_spider_size</code></a></h3>
  5369. <p>The largest allowed URL preview spidering size in bytes. Defaults to 10M.</p>
  5370. <p>Example configuration:</p>
  5371. <pre><code class="language-yaml">max_spider_size: 8M
  5372. </code></pre>
  5373. <hr />
  5374. <h3 id="url_preview_accept_language"><a class="header" href="#url_preview_accept_language"><code>url_preview_accept_language</code></a></h3>
  5375. <p>A list of values for the Accept-Language HTTP header used when
  5376. downloading webpages during URL preview generation. This allows
  5377. Synapse to specify the preferred languages that URL previews should
  5378. be in when communicating with remote servers.</p>
  5379. <p>Each value is a IETF language tag; a 2-3 letter identifier for a
  5380. language, optionally followed by subtags separated by '-', specifying
  5381. a country or region variant.</p>
  5382. <p>Multiple values can be provided, and a weight can be added to each by
  5383. using quality value syntax (;q=). '*' translates to any language.</p>
  5384. <p>Defaults to &quot;en&quot;.</p>
  5385. <p>Example configuration:</p>
  5386. <pre><code class="language-yaml"> url_preview_accept_language:
  5387. - 'en-UK'
  5388. - 'en-US;q=0.9'
  5389. - 'fr;q=0.8'
  5390. - '*;q=0.7'
  5391. </code></pre>
  5392. <hr />
  5393. <h3 id="oembed"><a class="header" href="#oembed"><code>oembed</code></a></h3>
  5394. <p>oEmbed allows for easier embedding content from a website. It can be
  5395. used for generating URLs previews of services which support it. A default list of oEmbed providers
  5396. is included with Synapse. Set <code>disable_default_providers</code> to true to disable using
  5397. these default oEmbed URLs. Use <code>additional_providers</code> to specify additional files with oEmbed configuration (each
  5398. should be in the form of providers.json). By default this list is empty.</p>
  5399. <p>Example configuration:</p>
  5400. <pre><code class="language-yaml">oembed:
  5401. disable_default_providers: true
  5402. additional_providers:
  5403. - oembed/my_providers.json
  5404. </code></pre>
  5405. <hr />
  5406. <h2 id="captcha"><a class="header" href="#captcha">Captcha</a></h2>
  5407. <p>See <a href="usage/configuration/../../CAPTCHA_SETUP.html">here</a> for full details on setting up captcha.</p>
  5408. <hr />
  5409. <h3 id="recaptcha_public_key"><a class="header" href="#recaptcha_public_key"><code>recaptcha_public_key</code></a></h3>
  5410. <p>This homeserver's ReCAPTCHA public key. Must be specified if
  5411. <a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is enabled.</p>
  5412. <p>Example configuration:</p>
  5413. <pre><code class="language-yaml">recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  5414. </code></pre>
  5415. <hr />
  5416. <h3 id="recaptcha_private_key"><a class="header" href="#recaptcha_private_key"><code>recaptcha_private_key</code></a></h3>
  5417. <p>This homeserver's ReCAPTCHA private key. Must be specified if
  5418. <a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is
  5419. enabled.</p>
  5420. <p>Example configuration:</p>
  5421. <pre><code class="language-yaml">recaptcha_private_key: &quot;YOUR_PRIVATE_KEY&quot;
  5422. </code></pre>
  5423. <hr />
  5424. <h3 id="enable_registration_captcha"><a class="header" href="#enable_registration_captcha"><code>enable_registration_captcha</code></a></h3>
  5425. <p>Set to <code>true</code> to require users to complete a CAPTCHA test when registering an account.
  5426. Requires a valid ReCaptcha public/private key.
  5427. Defaults to <code>false</code>.</p>
  5428. <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>
  5429. <p>Example configuration:</p>
  5430. <pre><code class="language-yaml">enable_registration_captcha: true
  5431. </code></pre>
  5432. <hr />
  5433. <h3 id="recaptcha_siteverify_api"><a class="header" href="#recaptcha_siteverify_api"><code>recaptcha_siteverify_api</code></a></h3>
  5434. <p>The API endpoint to use for verifying <code>m.login.recaptcha</code> responses.
  5435. Defaults to <code>https://www.recaptcha.net/recaptcha/api/siteverify</code>.</p>
  5436. <p>Example configuration:</p>
  5437. <pre><code class="language-yaml">recaptcha_siteverify_api: &quot;https://my.recaptcha.site&quot;
  5438. </code></pre>
  5439. <hr />
  5440. <h2 id="turn"><a class="header" href="#turn">TURN</a></h2>
  5441. <p>Options related to adding a TURN server to Synapse.</p>
  5442. <hr />
  5443. <h3 id="turn_uris"><a class="header" href="#turn_uris"><code>turn_uris</code></a></h3>
  5444. <p>The public URIs of the TURN server to give to clients.</p>
  5445. <p>Example configuration:</p>
  5446. <pre><code class="language-yaml">turn_uris: [turn:example.org]
  5447. </code></pre>
  5448. <hr />
  5449. <h3 id="turn_shared_secret"><a class="header" href="#turn_shared_secret"><code>turn_shared_secret</code></a></h3>
  5450. <p>The shared secret used to compute passwords for the TURN server.</p>
  5451. <p>Example configuration:</p>
  5452. <pre><code class="language-yaml">turn_shared_secret: &quot;YOUR_SHARED_SECRET&quot;
  5453. </code></pre>
  5454. <hr />
  5455. <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>
  5456. <p>The Username and password if the TURN server needs them and does not use a token.</p>
  5457. <p>Example configuration:</p>
  5458. <pre><code class="language-yaml">turn_username: &quot;TURNSERVER_USERNAME&quot;
  5459. turn_password: &quot;TURNSERVER_PASSWORD&quot;
  5460. </code></pre>
  5461. <hr />
  5462. <h3 id="turn_user_lifetime"><a class="header" href="#turn_user_lifetime"><code>turn_user_lifetime</code></a></h3>
  5463. <p>How long generated TURN credentials last. Defaults to 1h.</p>
  5464. <p>Example configuration:</p>
  5465. <pre><code class="language-yaml">turn_user_lifetime: 2h
  5466. </code></pre>
  5467. <hr />
  5468. <h3 id="turn_allow_guests"><a class="header" href="#turn_allow_guests"><code>turn_allow_guests</code></a></h3>
  5469. <p>Whether guests should be allowed to use the TURN server. This defaults to true, otherwise
  5470. VoIP will be unreliable for guests. However, it does introduce a slight security risk as
  5471. it allows users to connect to arbitrary endpoints without having first signed up for a valid account (e.g. by passing a CAPTCHA).</p>
  5472. <p>Example configuration:</p>
  5473. <pre><code class="language-yaml">turn_allow_guests: false
  5474. </code></pre>
  5475. <hr />
  5476. <h2 id="registration"><a class="header" href="#registration">Registration</a></h2>
  5477. <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>
  5478. <hr />
  5479. <h3 id="enable_registration"><a class="header" href="#enable_registration"><code>enable_registration</code></a></h3>
  5480. <p>Enable registration for new users. Defaults to <code>false</code>.</p>
  5481. <p>It is highly recommended that if you enable registration, you set one or more
  5482. or the following options, to avoid abuse of your server by &quot;bots&quot;:</p>
  5483. <ul>
  5484. <li><a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a></li>
  5485. <li><a href="usage/configuration/config_documentation.html#registrations_require_3pid"><code>registrations_require_3pid</code></a></li>
  5486. <li><a href="usage/configuration/config_documentation.html#registration_requires_token"><code>registration_requires_token</code></a></li>
  5487. </ul>
  5488. <p>(In order to enable registration without any verification, you must also set
  5489. <a href="usage/configuration/config_documentation.html#enable_registration_without_verification"><code>enable_registration_without_verification</code></a>.)</p>
  5490. <p>Note that even if this setting is disabled, new accounts can still be created
  5491. via the admin API if
  5492. <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a> is set.</p>
  5493. <p>Example configuration:</p>
  5494. <pre><code class="language-yaml">enable_registration: true
  5495. </code></pre>
  5496. <hr />
  5497. <h3 id="enable_registration_without_verification"><a class="header" href="#enable_registration_without_verification"><code>enable_registration_without_verification</code></a></h3>
  5498. <p>Enable registration without email or captcha verification. Note: this option is <em>not</em> recommended,
  5499. as registration without verification is a known vector for spam and abuse. Defaults to <code>false</code>. Has no effect
  5500. unless <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is also enabled.</p>
  5501. <p>Example configuration:</p>
  5502. <pre><code class="language-yaml">enable_registration_without_verification: true
  5503. </code></pre>
  5504. <hr />
  5505. <h3 id="registrations_require_3pid"><a class="header" href="#registrations_require_3pid"><code>registrations_require_3pid</code></a></h3>
  5506. <p>If this is set, users must provide all of the specified types of 3PID when registering an account.</p>
  5507. <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>
  5508. <p>Example configuration:</p>
  5509. <pre><code class="language-yaml">registrations_require_3pid:
  5510. - email
  5511. - msisdn
  5512. </code></pre>
  5513. <hr />
  5514. <h3 id="disable_msisdn_registration"><a class="header" href="#disable_msisdn_registration"><code>disable_msisdn_registration</code></a></h3>
  5515. <p>Explicitly disable asking for MSISDNs from the registration
  5516. flow (overrides <code>registrations_require_3pid</code> if MSISDNs are set as required).</p>
  5517. <p>Example configuration:</p>
  5518. <pre><code class="language-yaml">disable_msisdn_registration: true
  5519. </code></pre>
  5520. <hr />
  5521. <h3 id="allowed_local_3pids"><a class="header" href="#allowed_local_3pids"><code>allowed_local_3pids</code></a></h3>
  5522. <p>Mandate that users are only allowed to associate certain formats of
  5523. 3PIDs with accounts on this server, as specified by the <code>medium</code> and <code>pattern</code> sub-options.</p>
  5524. <p>Example configuration:</p>
  5525. <pre><code class="language-yaml">allowed_local_3pids:
  5526. - medium: email
  5527. pattern: '^[^@]+@matrix\.org$'
  5528. - medium: email
  5529. pattern: '^[^@]+@vector\.im$'
  5530. - medium: msisdn
  5531. pattern: '\+44'
  5532. </code></pre>
  5533. <hr />
  5534. <h3 id="enable_3pid_lookup"><a class="header" href="#enable_3pid_lookup"><code>enable_3pid_lookup</code></a></h3>
  5535. <p>Enable 3PIDs lookup requests to identity servers from this server. Defaults to true.</p>
  5536. <p>Example configuration:</p>
  5537. <pre><code class="language-yaml">enable_3pid_lookup: false
  5538. </code></pre>
  5539. <hr />
  5540. <h3 id="registration_requires_token"><a class="header" href="#registration_requires_token"><code>registration_requires_token</code></a></h3>
  5541. <p>Require users to submit a token during registration.
  5542. Tokens can be managed using the admin <a href="usage/configuration/../administration/admin_api/registration_tokens.html">API</a>.
  5543. Disabling this option will not delete any tokens previously generated.
  5544. Defaults to <code>false</code>. Set to <code>true</code> to enable.</p>
  5545. <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>
  5546. <p>Example configuration:</p>
  5547. <pre><code class="language-yaml">registration_requires_token: true
  5548. </code></pre>
  5549. <hr />
  5550. <h3 id="registration_shared_secret"><a class="header" href="#registration_shared_secret"><code>registration_shared_secret</code></a></h3>
  5551. <p>If set, allows registration of standard or admin accounts by anyone who has the
  5552. shared secret, even if <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is not
  5553. set.</p>
  5554. <p>This is primarily intended for use with the <code>register_new_matrix_user</code> script
  5555. (see <a href="usage/configuration/../../setup/installation.html#registering-a-user">Registering a user</a>);
  5556. however, the interface is <a href="usage/configuration/../../admin_api/register_api.html">documented</a>.</p>
  5557. <p>See also <a href="usage/configuration/config_documentation.html#registration_shared_secret_path"><code>registration_shared_secret_path</code></a>.</p>
  5558. <p>Example configuration:</p>
  5559. <pre><code class="language-yaml">registration_shared_secret: &lt;PRIVATE STRING&gt;
  5560. </code></pre>
  5561. <hr />
  5562. <h3 id="registration_shared_secret_path"><a class="header" href="#registration_shared_secret_path"><code>registration_shared_secret_path</code></a></h3>
  5563. <p>An alternative to <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>:
  5564. allows the shared secret to be specified in an external file.</p>
  5565. <p>The file should be a plain text file, containing only the shared secret.</p>
  5566. <p>If this file does not exist, Synapse will create a new shared
  5567. secret on startup and store it in this file.</p>
  5568. <p>Example configuration:</p>
  5569. <pre><code class="language-yaml">registration_shared_secret_path: /path/to/secrets/file
  5570. </code></pre>
  5571. <p><em>Added in Synapse 1.67.0.</em></p>
  5572. <hr />
  5573. <h3 id="bcrypt_rounds"><a class="header" href="#bcrypt_rounds"><code>bcrypt_rounds</code></a></h3>
  5574. <p>Set the number of bcrypt rounds used to generate password hash.
  5575. Larger numbers increase the work factor needed to generate the hash.
  5576. The default number is 12 (which equates to 2^12 rounds).
  5577. N.B. that increasing this will exponentially increase the time required
  5578. to register or login - e.g. 24 =&gt; 2^24 rounds which will take &gt;20 mins.
  5579. Example configuration:</p>
  5580. <pre><code class="language-yaml">bcrypt_rounds: 14
  5581. </code></pre>
  5582. <hr />
  5583. <h3 id="allow_guest_access"><a class="header" href="#allow_guest_access"><code>allow_guest_access</code></a></h3>
  5584. <p>Allows users to register as guests without a password/email/etc, and
  5585. participate in rooms hosted on this server which have been made
  5586. accessible to anonymous users. Defaults to false.</p>
  5587. <p>Example configuration:</p>
  5588. <pre><code class="language-yaml">allow_guest_access: true
  5589. </code></pre>
  5590. <hr />
  5591. <h3 id="default_identity_server"><a class="header" href="#default_identity_server"><code>default_identity_server</code></a></h3>
  5592. <p>The identity server which we suggest that clients should use when users log
  5593. in on this server.</p>
  5594. <p>(By default, no suggestion is made, so it is left up to the client.
  5595. This setting is ignored unless <code>public_baseurl</code> is also explicitly set.)</p>
  5596. <p>Example configuration:</p>
  5597. <pre><code class="language-yaml">default_identity_server: https://matrix.org
  5598. </code></pre>
  5599. <hr />
  5600. <h3 id="account_threepid_delegates"><a class="header" href="#account_threepid_delegates"><code>account_threepid_delegates</code></a></h3>
  5601. <p>Delegate verification of phone numbers to an identity server.</p>
  5602. <p>When a user wishes to add a phone number to their account, we need to verify that they
  5603. actually own that phone number, which requires sending them a text message (SMS).
  5604. Currently Synapse does not support sending those texts itself and instead delegates the
  5605. task to an identity server. The base URI for the identity server to be used is
  5606. specified by the <code>account_threepid_delegates.msisdn</code> option.</p>
  5607. <p>If this is left unspecified, Synapse will not allow users to add phone numbers to
  5608. their account.</p>
  5609. <p>(Servers handling the these requests must answer the <code>/requestToken</code> endpoints defined
  5610. by the Matrix Identity Service API
  5611. <a href="https://matrix.org/docs/spec/identity_service/latest">specification</a>.)</p>
  5612. <p><em>Deprecated in Synapse 1.64.0</em>: The <code>email</code> option is deprecated.</p>
  5613. <p><em>Removed in Synapse 1.66.0</em>: The <code>email</code> option has been removed.
  5614. If present, Synapse will report a configuration error on startup.</p>
  5615. <p>Example configuration:</p>
  5616. <pre><code class="language-yaml">account_threepid_delegates:
  5617. msisdn: http://localhost:8090 # Delegate SMS sending to this local process
  5618. </code></pre>
  5619. <hr />
  5620. <h3 id="enable_set_displayname"><a class="header" href="#enable_set_displayname"><code>enable_set_displayname</code></a></h3>
  5621. <p>Whether users are allowed to change their displayname after it has
  5622. been initially set. Useful when provisioning users based on the
  5623. contents of a third-party directory.</p>
  5624. <p>Does not apply to server administrators. Defaults to true.</p>
  5625. <p>Example configuration:</p>
  5626. <pre><code class="language-yaml">enable_set_displayname: false
  5627. </code></pre>
  5628. <hr />
  5629. <h3 id="enable_set_avatar_url"><a class="header" href="#enable_set_avatar_url"><code>enable_set_avatar_url</code></a></h3>
  5630. <p>Whether users are allowed to change their avatar after it has been
  5631. initially set. Useful when provisioning users based on the contents
  5632. of a third-party directory.</p>
  5633. <p>Does not apply to server administrators. Defaults to true.</p>
  5634. <p>Example configuration:</p>
  5635. <pre><code class="language-yaml">enable_set_avatar_url: false
  5636. </code></pre>
  5637. <hr />
  5638. <h3 id="enable_3pid_changes"><a class="header" href="#enable_3pid_changes"><code>enable_3pid_changes</code></a></h3>
  5639. <p>Whether users can change the third-party IDs associated with their accounts
  5640. (email address and msisdn).</p>
  5641. <p>Defaults to true.</p>
  5642. <p>Example configuration:</p>
  5643. <pre><code class="language-yaml">enable_3pid_changes: false
  5644. </code></pre>
  5645. <hr />
  5646. <h3 id="auto_join_rooms"><a class="header" href="#auto_join_rooms"><code>auto_join_rooms</code></a></h3>
  5647. <p>Users who register on this homeserver will automatically be joined
  5648. to the rooms listed under this option.</p>
  5649. <p>By default, any room aliases included in this list will be created
  5650. as a publicly joinable room when the first user registers for the
  5651. homeserver. If the room already exists, make certain it is a publicly joinable
  5652. room, i.e. the join rule of the room must be set to 'public'. You can find more options
  5653. relating to auto-joining rooms below.</p>
  5654. <p>As Spaces are just rooms under the hood, Space aliases may also be
  5655. used.</p>
  5656. <p>Example configuration:</p>
  5657. <pre><code class="language-yaml">auto_join_rooms:
  5658. - &quot;#exampleroom:example.com&quot;
  5659. - &quot;#anotherexampleroom:example.com&quot;
  5660. </code></pre>
  5661. <hr />
  5662. <h3 id="autocreate_auto_join_rooms"><a class="header" href="#autocreate_auto_join_rooms"><code>autocreate_auto_join_rooms</code></a></h3>
  5663. <p>Where <code>auto_join_rooms</code> are specified, setting this flag ensures that
  5664. the rooms exist by creating them when the first user on the
  5665. homeserver registers. This option will not create Spaces.</p>
  5666. <p>By default the auto-created rooms are publicly joinable from any federated
  5667. server. Use the <code>autocreate_auto_join_rooms_federated</code> and
  5668. <code>autocreate_auto_join_room_preset</code> settings to customise this behaviour.</p>
  5669. <p>Setting to false means that if the rooms are not manually created,
  5670. users cannot be auto-joined since they do not exist.</p>
  5671. <p>Defaults to true.</p>
  5672. <p>Example configuration:</p>
  5673. <pre><code class="language-yaml">autocreate_auto_join_rooms: false
  5674. </code></pre>
  5675. <hr />
  5676. <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>
  5677. <p>Whether the rooms listed in <code>auto_join_rooms</code> that are auto-created are available
  5678. via federation. Only has an effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  5679. <p>Note that whether a room is federated cannot be modified after
  5680. creation.</p>
  5681. <p>Defaults to true: the room will be joinable from other servers.
  5682. Set to false to prevent users from other homeservers from
  5683. joining these rooms.</p>
  5684. <p>Example configuration:</p>
  5685. <pre><code class="language-yaml">autocreate_auto_join_rooms_federated: false
  5686. </code></pre>
  5687. <hr />
  5688. <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>
  5689. <p>The room preset to use when auto-creating one of <code>auto_join_rooms</code>. Only has an
  5690. effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  5691. <p>Possible values for this option are:</p>
  5692. <ul>
  5693. <li>&quot;public_chat&quot;: the room is joinable by anyone, including
  5694. federated servers if <code>autocreate_auto_join_rooms_federated</code> is true (the default).</li>
  5695. <li>&quot;private_chat&quot;: an invitation is required to join these rooms.</li>
  5696. <li>&quot;trusted_private_chat&quot;: an invitation is required to join this room and the invitee is
  5697. assigned a power level of 100 upon joining the room.</li>
  5698. </ul>
  5699. <p>If a value of &quot;private_chat&quot; or &quot;trusted_private_chat&quot; is used then
  5700. <code>auto_join_mxid_localpart</code> must also be configured.</p>
  5701. <p>Defaults to &quot;public_chat&quot;.</p>
  5702. <p>Example configuration:</p>
  5703. <pre><code class="language-yaml">autocreate_auto_join_room_preset: private_chat
  5704. </code></pre>
  5705. <hr />
  5706. <h3 id="auto_join_mxid_localpart"><a class="header" href="#auto_join_mxid_localpart"><code>auto_join_mxid_localpart</code></a></h3>
  5707. <p>The local part of the user id which is used to create <code>auto_join_rooms</code> if
  5708. <code>autocreate_auto_join_rooms</code> is true. If this is not provided then the
  5709. initial user account that registers will be used to create the rooms.</p>
  5710. <p>The user id is also used to invite new users to any auto-join rooms which
  5711. are set to invite-only.</p>
  5712. <p>It <em>must</em> be configured if <code>autocreate_auto_join_room_preset</code> is set to
  5713. &quot;private_chat&quot; or &quot;trusted_private_chat&quot;.</p>
  5714. <p>Note that this must be specified in order for new users to be correctly
  5715. invited to any auto-join rooms which have been set to invite-only (either
  5716. at the time of creation or subsequently).</p>
  5717. <p>Note that, if the room already exists, this user must be joined and
  5718. have the appropriate permissions to invite new members.</p>
  5719. <p>Example configuration:</p>
  5720. <pre><code class="language-yaml">auto_join_mxid_localpart: system
  5721. </code></pre>
  5722. <hr />
  5723. <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>
  5724. <p>When <code>auto_join_rooms</code> is specified, setting this flag to false prevents
  5725. guest accounts from being automatically joined to the rooms.</p>
  5726. <p>Defaults to true.</p>
  5727. <p>Example configuration:</p>
  5728. <pre><code class="language-yaml">auto_join_rooms_for_guests: false
  5729. </code></pre>
  5730. <hr />
  5731. <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>
  5732. <p>Whether to inhibit errors raised when registering a new account if the user ID
  5733. already exists. If turned on, requests to <code>/register/available</code> will always
  5734. show a user ID as available, and Synapse won't raise an error when starting
  5735. a registration with a user ID that already exists. However, Synapse will still
  5736. raise an error if the registration completes and the username conflicts.</p>
  5737. <p>Defaults to false.</p>
  5738. <p>Example configuration:</p>
  5739. <pre><code class="language-yaml">inhibit_user_in_use_error: true
  5740. </code></pre>
  5741. <hr />
  5742. <h2 id="user-session-management"><a class="header" href="#user-session-management">User session management</a></h2>
  5743. <hr />
  5744. <h3 id="session_lifetime"><a class="header" href="#session_lifetime"><code>session_lifetime</code></a></h3>
  5745. <p>Time that a user's session remains valid for, after they log in.</p>
  5746. <p>Note that this is not currently compatible with guest logins.</p>
  5747. <p>Note also that this is calculated at login time: changes are not applied retrospectively to users who have already
  5748. logged in.</p>
  5749. <p>By default, this is infinite.</p>
  5750. <p>Example configuration:</p>
  5751. <pre><code class="language-yaml">session_lifetime: 24h
  5752. </code></pre>
  5753. <hr />
  5754. <h3 id="refresh_access_token_lifetime"><a class="header" href="#refresh_access_token_lifetime"><code>refresh_access_token_lifetime</code></a></h3>
  5755. <p>Time that an access token remains valid for, if the session is using refresh tokens.</p>
  5756. <p>For more information about refresh tokens, please see the <a href="usage/configuration/user_authentication/refresh_tokens.html">manual</a>.</p>
  5757. <p>Note that this only applies to clients which advertise support for refresh tokens.</p>
  5758. <p>Note also that this is calculated at login time and refresh time: changes are not applied to
  5759. existing sessions until they are refreshed.</p>
  5760. <p>By default, this is 5 minutes.</p>
  5761. <p>Example configuration:</p>
  5762. <pre><code class="language-yaml">refreshable_access_token_lifetime: 10m
  5763. </code></pre>
  5764. <hr />
  5765. <h3 id="refresh_token_lifetime-24h"><a class="header" href="#refresh_token_lifetime-24h"><code>refresh_token_lifetime: 24h</code></a></h3>
  5766. <p>Time that a refresh token remains valid for (provided that it is not
  5767. exchanged for another one first).
  5768. This option can be used to automatically log-out inactive sessions.
  5769. Please see the manual for more information.</p>
  5770. <p>Note also that this is calculated at login time and refresh time:
  5771. changes are not applied to existing sessions until they are refreshed.</p>
  5772. <p>By default, this is infinite.</p>
  5773. <p>Example configuration:</p>
  5774. <pre><code class="language-yaml">refresh_token_lifetime: 24h
  5775. </code></pre>
  5776. <hr />
  5777. <h3 id="nonrefreshable_access_token_lifetime"><a class="header" href="#nonrefreshable_access_token_lifetime"><code>nonrefreshable_access_token_lifetime</code></a></h3>
  5778. <p>Time that an access token remains valid for, if the session is NOT
  5779. using refresh tokens.</p>
  5780. <p>Please note that not all clients support refresh tokens, so setting
  5781. this to a short value may be inconvenient for some users who will
  5782. then be logged out frequently.</p>
  5783. <p>Note also that this is calculated at login time: changes are not applied
  5784. retrospectively to existing sessions for users that have already logged in.</p>
  5785. <p>By default, this is infinite.</p>
  5786. <p>Example configuration:</p>
  5787. <pre><code class="language-yaml">nonrefreshable_access_token_lifetime: 24h
  5788. </code></pre>
  5789. <hr />
  5790. <h3 id="ui_auth"><a class="header" href="#ui_auth"><code>ui_auth</code></a></h3>
  5791. <p>The amount of time to allow a user-interactive authentication session to be active.</p>
  5792. <p>This defaults to 0, meaning the user is queried for their credentials
  5793. before every action, but this can be overridden to allow a single
  5794. validation to be re-used. This weakens the protections afforded by
  5795. the user-interactive authentication process, by allowing for multiple
  5796. (and potentially different) operations to use the same validation session.</p>
  5797. <p>This is ignored for potentially &quot;dangerous&quot; operations (including
  5798. deactivating an account, modifying an account password, adding a 3PID,
  5799. and minting additional login tokens).</p>
  5800. <p>Use the <code>session_timeout</code> sub-option here to change the time allowed for credential validation.</p>
  5801. <p>Example configuration:</p>
  5802. <pre><code class="language-yaml">ui_auth:
  5803. session_timeout: &quot;15s&quot;
  5804. </code></pre>
  5805. <hr />
  5806. <h3 id="login_via_existing_session"><a class="header" href="#login_via_existing_session"><code>login_via_existing_session</code></a></h3>
  5807. <p>Matrix supports the ability of an existing session to mint a login token for
  5808. another client.</p>
  5809. <p>Synapse disables this by default as it has security ramifications -- a malicious
  5810. client could use the mechanism to spawn more than one session.</p>
  5811. <p>The duration of time the generated token is valid for can be configured with the
  5812. <code>token_timeout</code> sub-option.</p>
  5813. <p>User-interactive authentication is required when this is enabled unless the
  5814. <code>require_ui_auth</code> sub-option is set to <code>False</code>.</p>
  5815. <p>Example configuration:</p>
  5816. <pre><code class="language-yaml">login_via_existing_session:
  5817. enabled: true
  5818. require_ui_auth: false
  5819. token_timeout: &quot;5m&quot;
  5820. </code></pre>
  5821. <hr />
  5822. <h2 id="metrics"><a class="header" href="#metrics">Metrics</a></h2>
  5823. <p>Config options related to metrics.</p>
  5824. <hr />
  5825. <h3 id="enable_metrics"><a class="header" href="#enable_metrics"><code>enable_metrics</code></a></h3>
  5826. <p>Set to true to enable collection and rendering of performance metrics.
  5827. Defaults to false.</p>
  5828. <p>Example configuration:</p>
  5829. <pre><code class="language-yaml">enable_metrics: true
  5830. </code></pre>
  5831. <hr />
  5832. <h3 id="sentry"><a class="header" href="#sentry"><code>sentry</code></a></h3>
  5833. <p>Use this option to enable sentry integration. Provide the DSN assigned to you by sentry
  5834. with the <code>dsn</code> setting.</p>
  5835. <p>NOTE: While attempts are made to ensure that the logs don't contain
  5836. any sensitive information, this cannot be guaranteed. By enabling
  5837. this option the sentry server may therefore receive sensitive
  5838. information, and it in turn may then disseminate sensitive information
  5839. through insecure notification channels if so configured.</p>
  5840. <p>Example configuration:</p>
  5841. <pre><code class="language-yaml">sentry:
  5842. dsn: &quot;...&quot;
  5843. </code></pre>
  5844. <hr />
  5845. <h3 id="metrics_flags"><a class="header" href="#metrics_flags"><code>metrics_flags</code></a></h3>
  5846. <p>Flags to enable Prometheus metrics which are not suitable to be
  5847. enabled by default, either for performance reasons or limited use.
  5848. Currently the only option is <code>known_servers</code>, which publishes
  5849. <code>synapse_federation_known_servers</code>, a gauge of the number of
  5850. servers this homeserver knows about, including itself. May cause
  5851. performance problems on large homeservers.</p>
  5852. <p>Example configuration:</p>
  5853. <pre><code class="language-yaml">metrics_flags:
  5854. known_servers: true
  5855. </code></pre>
  5856. <hr />
  5857. <h3 id="report_stats"><a class="header" href="#report_stats"><code>report_stats</code></a></h3>
  5858. <p>Whether or not to report homeserver usage statistics. This is originally
  5859. set when generating the config. Set this option to true or false to change the current
  5860. behavior. See
  5861. <a href="usage/configuration/../administration/monitoring/reporting_homeserver_usage_statistics.html">Reporting Homeserver Usage Statistics</a>
  5862. for information on what data is reported.</p>
  5863. <p>Statistics will be reported 5 minutes after Synapse starts, and then every 3 hours
  5864. after that.</p>
  5865. <p>Example configuration:</p>
  5866. <pre><code class="language-yaml">report_stats: true
  5867. </code></pre>
  5868. <hr />
  5869. <h3 id="report_stats_endpoint"><a class="header" href="#report_stats_endpoint"><code>report_stats_endpoint</code></a></h3>
  5870. <p>The endpoint to report homeserver usage statistics to.
  5871. Defaults to https://matrix.org/report-usage-stats/push</p>
  5872. <p>Example configuration:</p>
  5873. <pre><code class="language-yaml">report_stats_endpoint: https://example.com/report-usage-stats/push
  5874. </code></pre>
  5875. <hr />
  5876. <h2 id="api-configuration"><a class="header" href="#api-configuration">API Configuration</a></h2>
  5877. <p>Config settings related to the client/server API</p>
  5878. <hr />
  5879. <h3 id="room_prejoin_state"><a class="header" href="#room_prejoin_state"><code>room_prejoin_state</code></a></h3>
  5880. <p>This setting controls the state that is shared with users upon receiving an
  5881. invite to a room, or in reply to a knock on a room. By default, the following
  5882. state events are shared with users:</p>
  5883. <ul>
  5884. <li><code>m.room.join_rules</code></li>
  5885. <li><code>m.room.canonical_alias</code></li>
  5886. <li><code>m.room.avatar</code></li>
  5887. <li><code>m.room.encryption</code></li>
  5888. <li><code>m.room.name</code></li>
  5889. <li><code>m.room.create</code></li>
  5890. <li><code>m.room.topic</code></li>
  5891. </ul>
  5892. <p>To change the default behavior, use the following sub-options:</p>
  5893. <ul>
  5894. <li>
  5895. <p><code>disable_default_event_types</code>: boolean. Set to <code>true</code> to disable the above
  5896. defaults. If this is enabled, only the event types listed in
  5897. <code>additional_event_types</code> are shared. Defaults to <code>false</code>.</p>
  5898. </li>
  5899. <li>
  5900. <p><code>additional_event_types</code>: A list of additional state events to include in the
  5901. events to be shared. By default, this list is empty (so only the default event
  5902. types are shared).</p>
  5903. <p>Each entry in this list should be either a single string or a list of two
  5904. strings.</p>
  5905. <ul>
  5906. <li>A standalone string <code>t</code> represents all events with type <code>t</code> (i.e.
  5907. with no restrictions on state keys).</li>
  5908. <li>A pair of strings <code>[t, s]</code> represents a single event with type <code>t</code> and
  5909. state key <code>s</code>. The same type can appear in two entries with different state
  5910. keys: in this situation, both state keys are included in prejoin state.</li>
  5911. </ul>
  5912. </li>
  5913. </ul>
  5914. <p>Example configuration:</p>
  5915. <pre><code class="language-yaml">room_prejoin_state:
  5916. disable_default_event_types: false
  5917. additional_event_types:
  5918. # Share all events of type `org.example.custom.event.typeA`
  5919. - org.example.custom.event.typeA
  5920. # Share only events of type `org.example.custom.event.typeB` whose
  5921. # state_key is &quot;foo&quot;
  5922. - [&quot;org.example.custom.event.typeB&quot;, &quot;foo&quot;]
  5923. # Share only events of type `org.example.custom.event.typeC` whose
  5924. # state_key is &quot;bar&quot; or &quot;baz&quot;
  5925. - [&quot;org.example.custom.event.typeC&quot;, &quot;bar&quot;]
  5926. - [&quot;org.example.custom.event.typeC&quot;, &quot;baz&quot;]
  5927. </code></pre>
  5928. <p><em>Changed in Synapse 1.74:</em> admins can filter the events in prejoin state based
  5929. on their state key.</p>
  5930. <hr />
  5931. <h3 id="track_puppeted_user_ips"><a class="header" href="#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a></h3>
  5932. <p>We record the IP address of clients used to access the API for various
  5933. reasons, including displaying it to the user in the &quot;Where you're signed in&quot;
  5934. dialog.</p>
  5935. <p>By default, when puppeting another user via the admin API, the client IP
  5936. address is recorded against the user who created the access token (ie, the
  5937. admin user), and <em>not</em> the puppeted user.</p>
  5938. <p>Set this option to true to also record the IP address against the puppeted
  5939. user. (This also means that the puppeted user will count as an &quot;active&quot; user
  5940. for the purpose of monthly active user tracking - see <code>limit_usage_by_mau</code> etc
  5941. above.)</p>
  5942. <p>Example configuration:</p>
  5943. <pre><code class="language-yaml">track_puppeted_user_ips: true
  5944. </code></pre>
  5945. <hr />
  5946. <h3 id="app_service_config_files"><a class="header" href="#app_service_config_files"><code>app_service_config_files</code></a></h3>
  5947. <p>A list of application service config files to use.</p>
  5948. <p>Example configuration:</p>
  5949. <pre><code class="language-yaml">app_service_config_files:
  5950. - app_service_1.yaml
  5951. - app_service_2.yaml
  5952. </code></pre>
  5953. <hr />
  5954. <h3 id="track_appservice_user_ips"><a class="header" href="#track_appservice_user_ips"><code>track_appservice_user_ips</code></a></h3>
  5955. <p>Defaults to false. Set to true to enable tracking of application service IP addresses.
  5956. Implicitly enables MAU tracking for application service users.</p>
  5957. <p>Example configuration:</p>
  5958. <pre><code class="language-yaml">track_appservice_user_ips: true
  5959. </code></pre>
  5960. <hr />
  5961. <h3 id="macaroon_secret_key"><a class="header" href="#macaroon_secret_key"><code>macaroon_secret_key</code></a></h3>
  5962. <p>A secret which is used to sign</p>
  5963. <ul>
  5964. <li>access token for guest users,</li>
  5965. <li>short-term login token used during SSO logins (OIDC or SAML2) and</li>
  5966. <li>token used for unsubscribing from email notifications.</li>
  5967. </ul>
  5968. <p>If none is specified, the <code>registration_shared_secret</code> is used, if one is given;
  5969. otherwise, a secret key is derived from the signing key.</p>
  5970. <p>Example configuration:</p>
  5971. <pre><code class="language-yaml">macaroon_secret_key: &lt;PRIVATE STRING&gt;
  5972. </code></pre>
  5973. <hr />
  5974. <h3 id="form_secret"><a class="header" href="#form_secret"><code>form_secret</code></a></h3>
  5975. <p>A secret which is used to calculate HMACs for form values, to stop
  5976. falsification of values. Must be specified for the User Consent
  5977. forms to work.</p>
  5978. <p>Example configuration:</p>
  5979. <pre><code class="language-yaml">form_secret: &lt;PRIVATE STRING&gt;
  5980. </code></pre>
  5981. <hr />
  5982. <h2 id="signing-keys"><a class="header" href="#signing-keys">Signing Keys</a></h2>
  5983. <p>Config options relating to signing keys</p>
  5984. <hr />
  5985. <h3 id="signing_key_path"><a class="header" href="#signing_key_path"><code>signing_key_path</code></a></h3>
  5986. <p>Path to the signing key to sign events and federation requests with.</p>
  5987. <p><em>New in Synapse 1.67</em>: If this file does not exist, Synapse will create a new signing
  5988. key on startup and store it in this file.</p>
  5989. <p>Example configuration:</p>
  5990. <pre><code class="language-yaml">signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  5991. </code></pre>
  5992. <hr />
  5993. <h3 id="old_signing_keys"><a class="header" href="#old_signing_keys"><code>old_signing_keys</code></a></h3>
  5994. <p>The keys that the server used to sign messages with but won't use
  5995. to sign new messages. For each key, <code>key</code> should be the base64-encoded public key, and
  5996. <code>expired_ts</code>should be the time (in milliseconds since the unix epoch) that
  5997. it was last used.</p>
  5998. <p>It is possible to build an entry from an old <code>signing.key</code> file using the
  5999. <code>export_signing_key</code> script which is provided with synapse.</p>
  6000. <p>Example configuration:</p>
  6001. <pre><code class="language-yaml">old_signing_keys:
  6002. &quot;ed25519:id&quot;: { key: &quot;base64string&quot;, expired_ts: 123456789123 }
  6003. </code></pre>
  6004. <hr />
  6005. <h3 id="key_refresh_interval"><a class="header" href="#key_refresh_interval"><code>key_refresh_interval</code></a></h3>
  6006. <p>How long key response published by this server is valid for.
  6007. Used to set the <code>valid_until_ts</code> in <code>/key/v2</code> APIs.
  6008. Determines how quickly servers will query to check which keys
  6009. are still valid. Defaults to 1d.</p>
  6010. <p>Example configuration:</p>
  6011. <pre><code class="language-yaml">key_refresh_interval: 2d
  6012. </code></pre>
  6013. <hr />
  6014. <h3 id="trusted_key_servers"><a class="header" href="#trusted_key_servers"><code>trusted_key_servers</code></a></h3>
  6015. <p>The trusted servers to download signing keys from.</p>
  6016. <p>When we need to fetch a signing key, each server is tried in parallel.</p>
  6017. <p>Normally, the connection to the key server is validated via TLS certificates.
  6018. Additional security can be provided by configuring a <code>verify key</code>, which
  6019. will make synapse check that the response is signed by that key.</p>
  6020. <p>This setting supercedes an older setting named <code>perspectives</code>. The old format
  6021. is still supported for backwards-compatibility, but it is deprecated.</p>
  6022. <p><code>trusted_key_servers</code> defaults to matrix.org, but using it will generate a
  6023. warning on start-up. To suppress this warning, set
  6024. <code>suppress_key_server_warning</code> to true.</p>
  6025. <p>If the use of a trusted key server has to be deactivated, e.g. in a private
  6026. federation or for privacy reasons, this can be realised by setting
  6027. an empty array (<code>trusted_key_servers: []</code>). Then Synapse will request the keys
  6028. directly from the server that owns the keys. If Synapse does not get keys directly
  6029. from the server, the events of this server will be rejected.</p>
  6030. <p>Options for each entry in the list include:</p>
  6031. <ul>
  6032. <li><code>server_name</code>: the name of the server. Required.</li>
  6033. <li><code>verify_keys</code>: an optional map from key id to base64-encoded public key.
  6034. If specified, we will check that the response is signed by at least
  6035. one of the given keys.</li>
  6036. <li><code>accept_keys_insecurely</code>: a boolean. Normally, if <code>verify_keys</code> is unset,
  6037. and <code>federation_verify_certificates</code> is not <code>true</code>, synapse will refuse
  6038. to start, because this would allow anyone who can spoof DNS responses
  6039. to masquerade as the trusted key server. If you know what you are doing
  6040. and are sure that your network environment provides a secure connection
  6041. to the key server, you can set this to <code>true</code> to override this behaviour.</li>
  6042. </ul>
  6043. <p>Example configuration #1:</p>
  6044. <pre><code class="language-yaml">trusted_key_servers:
  6045. - server_name: &quot;my_trusted_server.example.com&quot;
  6046. verify_keys:
  6047. &quot;ed25519:auto&quot;: &quot;abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr&quot;
  6048. - server_name: &quot;my_other_trusted_server.example.com&quot;
  6049. </code></pre>
  6050. <p>Example configuration #2:</p>
  6051. <pre><code class="language-yaml">trusted_key_servers:
  6052. - server_name: &quot;matrix.org&quot;
  6053. </code></pre>
  6054. <hr />
  6055. <h3 id="suppress_key_server_warning"><a class="header" href="#suppress_key_server_warning"><code>suppress_key_server_warning</code></a></h3>
  6056. <p>Set the following to true to disable the warning that is emitted when the
  6057. <code>trusted_key_servers</code> include 'matrix.org'. See above.</p>
  6058. <p>Example configuration:</p>
  6059. <pre><code class="language-yaml">suppress_key_server_warning: true
  6060. </code></pre>
  6061. <hr />
  6062. <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>
  6063. <p>The signing keys to use when acting as a trusted key server. If not specified
  6064. defaults to the server signing key.</p>
  6065. <p>Can contain multiple keys, one per line.</p>
  6066. <p>Example configuration:</p>
  6067. <pre><code class="language-yaml">key_server_signing_keys_path: &quot;key_server_signing_keys.key&quot;
  6068. </code></pre>
  6069. <hr />
  6070. <h2 id="single-sign-on-integration"><a class="header" href="#single-sign-on-integration">Single sign-on integration</a></h2>
  6071. <p>The following settings can be used to make Synapse use a single sign-on
  6072. provider for authentication, instead of its internal password database.</p>
  6073. <p>You will probably also want to set the following options to <code>false</code> to
  6074. disable the regular login/registration flows:</p>
  6075. <ul>
  6076. <li><a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a></li>
  6077. <li><a href="usage/configuration/config_documentation.html#password_config"><code>password_config.enabled</code></a></li>
  6078. </ul>
  6079. <hr />
  6080. <h3 id="saml2_config"><a class="header" href="#saml2_config"><code>saml2_config</code></a></h3>
  6081. <p>Enable SAML2 for registration and login. Uses pysaml2. To learn more about pysaml and
  6082. to find a full list options for configuring pysaml, read the docs <a href="https://pysaml2.readthedocs.io/en/latest/">here</a>.</p>
  6083. <p>At least one of <code>sp_config</code> or <code>config_path</code> must be set in this section to
  6084. enable SAML login. You can either put your entire pysaml config inline using the <code>sp_config</code>
  6085. option, or you can specify a path to a psyaml config file with the sub-option <code>config_path</code>.
  6086. This setting has the following sub-options:</p>
  6087. <ul>
  6088. <li><code>sp_config</code>: the configuration for the pysaml2 Service Provider. See pysaml2 docs for format of config.
  6089. Default values will be used for the <code>entityid</code> and <code>service</code> settings,
  6090. so it is not normally necessary to specify them unless you need to
  6091. override them. Here are a few useful sub-options for configuring pysaml:
  6092. <ul>
  6093. <li><code>metadata</code>: Point this to the IdP's metadata. You must provide either a local
  6094. file via the <code>local</code> attribute or (preferably) a URL via the
  6095. <code>remote</code> attribute.</li>
  6096. <li><code>accepted_time_diff: 3</code>: Allowed clock difference in seconds between the homeserver and IdP.
  6097. Defaults to 0.</li>
  6098. <li><code>service</code>: By default, the user has to go to our login page first. If you'd like
  6099. to allow IdP-initiated login, set <code>allow_unsolicited</code> to true under <code>sp</code> in the <code>service</code>
  6100. section.</li>
  6101. </ul>
  6102. </li>
  6103. <li><code>config_path</code>: specify a separate pysaml2 configuration file thusly:
  6104. <code>config_path: &quot;CONFDIR/sp_conf.py&quot;</code></li>
  6105. <li><code>saml_session_lifetime</code>: The lifetime of a SAML session. This defines how long a user has to
  6106. complete the authentication process, if <code>allow_unsolicited</code> is unset. The default is 15 minutes.</li>
  6107. <li><code>user_mapping_provider</code>: Using this option, an external module can be provided as a
  6108. custom solution to mapping attributes returned from a saml provider onto a matrix user. The
  6109. <code>user_mapping_provider</code> has the following attributes:
  6110. <ul>
  6111. <li><code>module</code>: The custom module's class.</li>
  6112. <li><code>config</code>: Custom configuration values for the module. Use the values provided in the
  6113. example if you are using the built-in user_mapping_provider, or provide your own
  6114. config values for a custom class if you are using one. This section will be passed as a Python
  6115. dictionary to the module's <code>parse_config</code> method. The built-in provider takes the following two
  6116. options:
  6117. <ul>
  6118. <li><code>mxid_source_attribute</code>: The SAML attribute (after mapping via the attribute maps) to use
  6119. to derive the Matrix ID from. It is 'uid' by default. Note: This used to be configured by the
  6120. <code>saml2_config.mxid_source_attribute option</code>. If that is still defined, its value will be used instead.</li>
  6121. <li><code>mxid_mapping</code>: The mapping system to use for mapping the saml attribute onto a
  6122. matrix ID. Options include: <code>hexencode</code> (which maps unpermitted characters to '=xx')
  6123. and <code>dotreplace</code> (which replaces unpermitted characters with '.').
  6124. The default is <code>hexencode</code>. Note: This used to be configured by the
  6125. <code>saml2_config.mxid_mapping option</code>. If that is still defined, its value will be used instead.</li>
  6126. </ul>
  6127. </li>
  6128. </ul>
  6129. </li>
  6130. <li><code>grandfathered_mxid_source_attribute</code>: In previous versions of synapse, the mapping from SAML attribute to
  6131. MXID was always calculated dynamically rather than stored in a table. For backwards- compatibility, we will look for <code>user_ids</code>
  6132. matching such a pattern before creating a new account. This setting controls the SAML attribute which will be used for this
  6133. backwards-compatibility lookup. Typically it should be 'uid', but if the attribute maps are changed, it may be necessary to change it.
  6134. The default is 'uid'.</li>
  6135. <li><code>attribute_requirements</code>: It is possible to configure Synapse to only allow logins if SAML attributes
  6136. match particular values. The requirements can be listed under
  6137. <code>attribute_requirements</code> as shown in the example. All of the listed attributes must
  6138. match for the login to be permitted.</li>
  6139. <li><code>idp_entityid</code>: If the metadata XML contains multiple IdP entities then the <code>idp_entityid</code>
  6140. option must be set to the entity to redirect users to.
  6141. Most deployments only have a single IdP entity and so should omit this option.</li>
  6142. </ul>
  6143. <p>Once SAML support is enabled, a metadata file will be exposed at
  6144. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/metadata.xml</code>, which you may be able to
  6145. use to configure your SAML IdP with. Alternatively, you can manually configure
  6146. the IdP to use an ACS location of
  6147. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/authn_response</code>.</p>
  6148. <p>Example configuration:</p>
  6149. <pre><code class="language-yaml">saml2_config:
  6150. sp_config:
  6151. metadata:
  6152. local: [&quot;saml2/idp.xml&quot;]
  6153. remote:
  6154. - url: https://our_idp/metadata.xml
  6155. accepted_time_diff: 3
  6156. service:
  6157. sp:
  6158. allow_unsolicited: true
  6159. # The examples below are just used to generate our metadata xml, and you
  6160. # may well not need them, depending on your setup. Alternatively you
  6161. # may need a whole lot more detail - see the pysaml2 docs!
  6162. description: [&quot;My awesome SP&quot;, &quot;en&quot;]
  6163. name: [&quot;Test SP&quot;, &quot;en&quot;]
  6164. ui_info:
  6165. display_name:
  6166. - lang: en
  6167. text: &quot;Display Name is the descriptive name of your service.&quot;
  6168. description:
  6169. - lang: en
  6170. text: &quot;Description should be a short paragraph explaining the purpose of the service.&quot;
  6171. information_url:
  6172. - lang: en
  6173. text: &quot;https://example.com/terms-of-service&quot;
  6174. privacy_statement_url:
  6175. - lang: en
  6176. text: &quot;https://example.com/privacy-policy&quot;
  6177. keywords:
  6178. - lang: en
  6179. text: [&quot;Matrix&quot;, &quot;Element&quot;]
  6180. logo:
  6181. - lang: en
  6182. text: &quot;https://example.com/logo.svg&quot;
  6183. width: &quot;200&quot;
  6184. height: &quot;80&quot;
  6185. organization:
  6186. name: Example com
  6187. display_name:
  6188. - [&quot;Example co&quot;, &quot;en&quot;]
  6189. url: &quot;http://example.com&quot;
  6190. contact_person:
  6191. - given_name: Bob
  6192. sur_name: &quot;the Sysadmin&quot;
  6193. email_address&quot;: [&quot;admin@example.com&quot;]
  6194. contact_type&quot;: technical
  6195. saml_session_lifetime: 5m
  6196. user_mapping_provider:
  6197. # Below options are intended for the built-in provider, they should be
  6198. # changed if using a custom module.
  6199. config:
  6200. mxid_source_attribute: displayName
  6201. mxid_mapping: dotreplace
  6202. grandfathered_mxid_source_attribute: upn
  6203. attribute_requirements:
  6204. - attribute: userGroup
  6205. value: &quot;staff&quot;
  6206. - attribute: department
  6207. value: &quot;sales&quot;
  6208. idp_entityid: 'https://our_idp/entityid'
  6209. </code></pre>
  6210. <hr />
  6211. <h3 id="oidc_providers"><a class="header" href="#oidc_providers"><code>oidc_providers</code></a></h3>
  6212. <p>List of OpenID Connect (OIDC) / OAuth 2.0 identity providers, for registration
  6213. and login. See <a href="usage/configuration/../../openid.html">here</a>
  6214. for information on how to configure these options.</p>
  6215. <p>For backwards compatibility, it is also possible to configure a single OIDC
  6216. provider via an <code>oidc_config</code> setting. This is now deprecated and admins are
  6217. advised to migrate to the <code>oidc_providers</code> format. (When doing that migration,
  6218. use <code>oidc</code> for the <code>idp_id</code> to ensure that existing users continue to be
  6219. recognised.)</p>
  6220. <p>Options for each entry include:</p>
  6221. <ul>
  6222. <li>
  6223. <p><code>idp_id</code>: a unique identifier for this identity provider. Used internally
  6224. by Synapse; should be a single word such as 'github'.
  6225. Note that, if this is changed, users authenticating via that provider
  6226. will no longer be recognised as the same user!
  6227. (Use &quot;oidc&quot; here if you are migrating from an old <code>oidc_config</code> configuration.)</p>
  6228. </li>
  6229. <li>
  6230. <p><code>idp_name</code>: A user-facing name for this identity provider, which is used to
  6231. offer the user a choice of login mechanisms.</p>
  6232. </li>
  6233. <li>
  6234. <p><code>idp_icon</code>: An optional icon for this identity provider, which is presented
  6235. by clients and Synapse's own IdP picker page. If given, must be an
  6236. MXC URI of the format mxc://<server-name>/<media-id>. (An easy way to
  6237. obtain such an MXC URI is to upload an image to an (unencrypted) room
  6238. and then copy the &quot;url&quot; from the source of the event.)</p>
  6239. </li>
  6240. <li>
  6241. <p><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
  6242. to style the login flow according to the identity provider in question.
  6243. See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</p>
  6244. </li>
  6245. <li>
  6246. <p><code>discover</code>: set to false to disable the use of the OIDC discovery mechanism
  6247. to discover endpoints. Defaults to true.</p>
  6248. </li>
  6249. <li>
  6250. <p><code>issuer</code>: Required. The OIDC issuer. Used to validate tokens and (if discovery
  6251. is enabled) to discover the provider's endpoints.</p>
  6252. </li>
  6253. <li>
  6254. <p><code>client_id</code>: Required. oauth2 client id to use.</p>
  6255. </li>
  6256. <li>
  6257. <p><code>client_secret</code>: oauth2 client secret to use. May be omitted if
  6258. <code>client_secret_jwt_key</code> is given, or if <code>client_auth_method</code> is 'none'.</p>
  6259. </li>
  6260. <li>
  6261. <p><code>client_secret_jwt_key</code>: Alternative to client_secret: details of a key used
  6262. to create a JSON Web Token to be used as an OAuth2 client secret. If
  6263. given, must be a dictionary with the following properties:</p>
  6264. <ul>
  6265. <li>
  6266. <p><code>key</code>: a pem-encoded signing key. Must be a suitable key for the
  6267. algorithm specified. Required unless <code>key_file</code> is given.</p>
  6268. </li>
  6269. <li>
  6270. <p><code>key_file</code>: the path to file containing a pem-encoded signing key file.
  6271. Required unless <code>key</code> is given.</p>
  6272. </li>
  6273. <li>
  6274. <p><code>jwt_header</code>: a dictionary giving properties to include in the JWT
  6275. header. Must include the key <code>alg</code>, giving the algorithm used to
  6276. sign the JWT, such as &quot;ES256&quot;, using the JWA identifiers in
  6277. RFC7518.</p>
  6278. </li>
  6279. <li>
  6280. <p><code>jwt_payload</code>: an optional dictionary giving properties to include in
  6281. the JWT payload. Normally this should include an <code>iss</code> key.</p>
  6282. </li>
  6283. </ul>
  6284. </li>
  6285. <li>
  6286. <p><code>client_auth_method</code>: auth method to use when exchanging the token. Valid
  6287. values are <code>client_secret_basic</code> (default), <code>client_secret_post</code> and
  6288. <code>none</code>.</p>
  6289. </li>
  6290. <li>
  6291. <p><code>pkce_method</code>: Whether to use proof key for code exchange when requesting
  6292. and exchanging the token. Valid values are: <code>auto</code>, <code>always</code>, or <code>never</code>. Defaults
  6293. to <code>auto</code>, which uses PKCE if supported during metadata discovery. Set to <code>always</code>
  6294. to force enable PKCE or <code>never</code> to force disable PKCE.</p>
  6295. </li>
  6296. <li>
  6297. <p><code>scopes</code>: list of scopes to request. This should normally include the &quot;openid&quot;
  6298. scope. Defaults to <code>[&quot;openid&quot;]</code>.</p>
  6299. </li>
  6300. <li>
  6301. <p><code>authorization_endpoint</code>: the oauth2 authorization endpoint. Required if
  6302. provider discovery is disabled.</p>
  6303. </li>
  6304. <li>
  6305. <p><code>token_endpoint</code>: the oauth2 token endpoint. Required if provider discovery is
  6306. disabled.</p>
  6307. </li>
  6308. <li>
  6309. <p><code>userinfo_endpoint</code>: the OIDC userinfo endpoint. Required if discovery is
  6310. disabled and the 'openid' scope is not requested.</p>
  6311. </li>
  6312. <li>
  6313. <p><code>jwks_uri</code>: URI where to fetch the JWKS. Required if discovery is disabled and
  6314. the 'openid' scope is used.</p>
  6315. </li>
  6316. <li>
  6317. <p><code>skip_verification</code>: set to 'true' to skip metadata verification. Use this if
  6318. you are connecting to a provider that is not OpenID Connect compliant.
  6319. Defaults to false. Avoid this in production.</p>
  6320. </li>
  6321. <li>
  6322. <p><code>user_profile_method</code>: Whether to fetch the user profile from the userinfo
  6323. endpoint, or to rely on the data returned in the id_token from the <code>token_endpoint</code>.
  6324. Valid values are: <code>auto</code> or <code>userinfo_endpoint</code>.
  6325. Defaults to <code>auto</code>, which uses the userinfo endpoint if <code>openid</code> is
  6326. not included in <code>scopes</code>. Set to <code>userinfo_endpoint</code> to always use the
  6327. userinfo endpoint.</p>
  6328. </li>
  6329. <li>
  6330. <p><code>allow_existing_users</code>: set to true to allow a user logging in via OIDC to
  6331. match a pre-existing account instead of failing. This could be used if
  6332. switching from password logins to OIDC. Defaults to false.</p>
  6333. </li>
  6334. <li>
  6335. <p><code>enable_registration</code>: set to 'false' to disable automatic registration of new
  6336. users. This allows the OIDC SSO flow to be limited to sign in only, rather than
  6337. automatically registering users that have a valid SSO login but do not have
  6338. a pre-registered account. Defaults to true.</p>
  6339. </li>
  6340. <li>
  6341. <p><code>user_mapping_provider</code>: Configuration for how attributes returned from a OIDC
  6342. provider are mapped onto a matrix user. This setting has the following
  6343. sub-properties:</p>
  6344. <ul>
  6345. <li>
  6346. <p><code>module</code>: The class name of a custom mapping module. Default is
  6347. <code>synapse.handlers.oidc.JinjaOidcMappingProvider</code>.
  6348. See <a href="usage/configuration/../../sso_mapping_providers.html#openid-mapping-providers">OpenID Mapping Providers</a>
  6349. for information on implementing a custom mapping provider.</p>
  6350. </li>
  6351. <li>
  6352. <p><code>config</code>: Configuration for the mapping provider module. This section will
  6353. be passed as a Python dictionary to the user mapping provider
  6354. module's <code>parse_config</code> method.</p>
  6355. <p>For the default provider, the following settings are available:</p>
  6356. <ul>
  6357. <li>
  6358. <p><code>subject_template</code>: Jinja2 template for a unique identifier for the user.
  6359. Defaults to <code>{{ user.sub }}</code>, which OpenID Connect compliant providers should provide.</p>
  6360. <p>This replaces and overrides <code>subject_claim</code>.</p>
  6361. </li>
  6362. <li>
  6363. <p><code>subject_claim</code>: name of the claim containing a unique identifier
  6364. for the user. Defaults to 'sub', which OpenID Connect
  6365. compliant providers should provide.</p>
  6366. <p><em>Deprecated in Synapse v1.75.0.</em></p>
  6367. </li>
  6368. <li>
  6369. <p><code>picture_template</code>: Jinja2 template for an url for the user's profile picture.
  6370. Defaults to <code>{{ user.picture }}</code>, which OpenID Connect compliant providers should
  6371. provide and has to refer to a direct image file such as PNG, JPEG, or GIF image file.</p>
  6372. <p>This replaces and overrides <code>picture_claim</code>.</p>
  6373. <p>Currently only supported in monolithic (single-process) server configurations
  6374. where the media repository runs within the Synapse process.</p>
  6375. </li>
  6376. <li>
  6377. <p><code>picture_claim</code>: name of the claim containing an url for the user's profile picture.
  6378. Defaults to 'picture', which OpenID Connect compliant providers should provide
  6379. and has to refer to a direct image file such as PNG, JPEG, or GIF image file.</p>
  6380. <p>Currently only supported in monolithic (single-process) server configurations
  6381. where the media repository runs within the Synapse process.</p>
  6382. <p><em>Deprecated in Synapse v1.75.0.</em></p>
  6383. </li>
  6384. <li>
  6385. <p><code>localpart_template</code>: Jinja2 template for the localpart of the MXID.
  6386. If this is not set, the user will be prompted to choose their
  6387. own username (see the documentation for the <code>sso_auth_account_details.html</code>
  6388. template). This template can use the <code>localpart_from_email</code> filter.</p>
  6389. </li>
  6390. <li>
  6391. <p><code>confirm_localpart</code>: Whether to prompt the user to validate (or
  6392. change) the generated localpart (see the documentation for the
  6393. 'sso_auth_account_details.html' template), instead of
  6394. registering the account right away.</p>
  6395. </li>
  6396. <li>
  6397. <p><code>display_name_template</code>: Jinja2 template for the display name to set
  6398. on first login. If unset, no displayname will be set.</p>
  6399. </li>
  6400. <li>
  6401. <p><code>email_template</code>: Jinja2 template for the email address of the user.
  6402. If unset, no email address will be added to the account.</p>
  6403. </li>
  6404. <li>
  6405. <p><code>extra_attributes</code>: a map of Jinja2 templates for extra attributes
  6406. to send back to the client during login. Note that these are non-standard and clients will ignore them
  6407. without modifications.</p>
  6408. </li>
  6409. </ul>
  6410. </li>
  6411. </ul>
  6412. <p>When rendering, the Jinja2 templates are given a 'user' variable,
  6413. which is set to the claims returned by the UserInfo Endpoint and/or
  6414. in the ID Token.</p>
  6415. </li>
  6416. <li>
  6417. <p><code>backchannel_logout_enabled</code>: set to <code>true</code> to process OIDC Back-Channel Logout notifications.
  6418. Those notifications are expected to be received on <code>/_synapse/client/oidc/backchannel_logout</code>.
  6419. Defaults to <code>false</code>.</p>
  6420. </li>
  6421. <li>
  6422. <p><code>backchannel_logout_ignore_sub</code>: by default, the OIDC Back-Channel Logout feature checks that the
  6423. <code>sub</code> claim matches the subject claim received during login. This check can be disabled by setting
  6424. this to <code>true</code>. Defaults to <code>false</code>.</p>
  6425. <p>You might want to disable this if the <code>subject_claim</code> returned by the mapping provider is not <code>sub</code>.</p>
  6426. </li>
  6427. </ul>
  6428. <p>It is possible to configure Synapse to only allow logins if certain attributes
  6429. match particular values in the OIDC userinfo. The requirements can be listed under
  6430. <code>attribute_requirements</code> as shown here:</p>
  6431. <pre><code class="language-yaml">attribute_requirements:
  6432. - attribute: family_name
  6433. value: &quot;Stephensson&quot;
  6434. - attribute: groups
  6435. value: &quot;admin&quot;
  6436. </code></pre>
  6437. <p>All of the listed attributes must match for the login to be permitted. Additional attributes can be added to
  6438. userinfo by expanding the <code>scopes</code> section of the OIDC config to retrieve
  6439. additional information from the OIDC provider.</p>
  6440. <p>If the OIDC claim is a list, then the attribute must match any value in the list.
  6441. Otherwise, it must exactly match the value of the claim. Using the example
  6442. above, the <code>family_name</code> claim MUST be &quot;Stephensson&quot;, but the <code>groups</code>
  6443. claim MUST contain &quot;admin&quot;.</p>
  6444. <p>Example configuration:</p>
  6445. <pre><code class="language-yaml">oidc_providers:
  6446. # Generic example
  6447. #
  6448. - idp_id: my_idp
  6449. idp_name: &quot;My OpenID provider&quot;
  6450. idp_icon: &quot;mxc://example.com/mediaid&quot;
  6451. discover: false
  6452. issuer: &quot;https://accounts.example.com/&quot;
  6453. client_id: &quot;provided-by-your-issuer&quot;
  6454. client_secret: &quot;provided-by-your-issuer&quot;
  6455. client_auth_method: client_secret_post
  6456. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6457. authorization_endpoint: &quot;https://accounts.example.com/oauth2/auth&quot;
  6458. token_endpoint: &quot;https://accounts.example.com/oauth2/token&quot;
  6459. userinfo_endpoint: &quot;https://accounts.example.com/userinfo&quot;
  6460. jwks_uri: &quot;https://accounts.example.com/.well-known/jwks.json&quot;
  6461. skip_verification: true
  6462. enable_registration: true
  6463. user_mapping_provider:
  6464. config:
  6465. subject_claim: &quot;id&quot;
  6466. localpart_template: &quot;{{ user.login }}&quot;
  6467. display_name_template: &quot;{{ user.name }}&quot;
  6468. email_template: &quot;{{ user.email }}&quot;
  6469. attribute_requirements:
  6470. - attribute: userGroup
  6471. value: &quot;synapseUsers&quot;
  6472. </code></pre>
  6473. <hr />
  6474. <h3 id="cas_config"><a class="header" href="#cas_config"><code>cas_config</code></a></h3>
  6475. <p>Enable Central Authentication Service (CAS) for registration and login.
  6476. Has the following sub-options:</p>
  6477. <ul>
  6478. <li><code>enabled</code>: Set this to true to enable authorization against a CAS server.
  6479. Defaults to false.</li>
  6480. <li><code>server_url</code>: The URL of the CAS authorization endpoint.</li>
  6481. <li><code>displayname_attribute</code>: The attribute of the CAS response to use as the display name.
  6482. If no name is given here, no displayname will be set.</li>
  6483. <li><code>required_attributes</code>: It is possible to configure Synapse to only allow logins if CAS attributes
  6484. match particular values. All of the keys given below must exist
  6485. and the values must match the given value. Alternately if the given value
  6486. is <code>None</code> then any value is allowed (the attribute just must exist).
  6487. All of the listed attributes must match for the login to be permitted.</li>
  6488. </ul>
  6489. <p>Example configuration:</p>
  6490. <pre><code class="language-yaml">cas_config:
  6491. enabled: true
  6492. server_url: &quot;https://cas-server.com&quot;
  6493. displayname_attribute: name
  6494. required_attributes:
  6495. userGroup: &quot;staff&quot;
  6496. department: None
  6497. </code></pre>
  6498. <hr />
  6499. <h3 id="sso"><a class="header" href="#sso"><code>sso</code></a></h3>
  6500. <p>Additional settings to use with single-sign on systems such as OpenID Connect,
  6501. SAML2 and CAS.</p>
  6502. <p>Server admins can configure custom templates for pages related to SSO. See
  6503. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  6504. <p>Options include:</p>
  6505. <ul>
  6506. <li><code>client_whitelist</code>: A list of client URLs which are whitelisted so that the user does not
  6507. have to confirm giving access to their account to the URL. Any client
  6508. whose URL starts with an entry in the following list will not be subject
  6509. to an additional confirmation step after the SSO login is completed.
  6510. WARNING: An entry such as &quot;https://my.client&quot; is insecure, because it
  6511. will also match &quot;https://my.client.evil.site&quot;, exposing your users to
  6512. phishing attacks from evil.site. To avoid this, include a slash after the
  6513. hostname: &quot;https://my.client/&quot;.
  6514. The login fallback page (used by clients that don't natively support the
  6515. required login flows) is whitelisted in addition to any URLs in this list.
  6516. By default, this list contains only the login fallback page.</li>
  6517. <li><code>update_profile_information</code>: Use this setting to keep a user's profile fields in sync with information from
  6518. the identity provider. Currently only syncing the displayname is supported. Fields
  6519. are checked on every SSO login, and are updated if necessary.
  6520. Note that enabling this option will override user profile information,
  6521. regardless of whether users have opted-out of syncing that
  6522. information when first signing in. Defaults to false.</li>
  6523. </ul>
  6524. <p>Example configuration:</p>
  6525. <pre><code class="language-yaml">sso:
  6526. client_whitelist:
  6527. - https://riot.im/develop
  6528. - https://my.custom.client/
  6529. update_profile_information: true
  6530. </code></pre>
  6531. <hr />
  6532. <h3 id="jwt_config"><a class="header" href="#jwt_config"><code>jwt_config</code></a></h3>
  6533. <p>JSON web token integration. The following settings can be used to make
  6534. Synapse JSON web tokens for authentication, instead of its internal
  6535. password database.</p>
  6536. <p>Each JSON Web Token needs to contain a &quot;sub&quot; (subject) claim, which is
  6537. used as the localpart of the mxid.</p>
  6538. <p>Additionally, the expiration time (&quot;exp&quot;), not before time (&quot;nbf&quot;),
  6539. and issued at (&quot;iat&quot;) claims are validated if present.</p>
  6540. <p>Note that this is a non-standard login type and client support is
  6541. expected to be non-existent.</p>
  6542. <p>See <a href="usage/configuration/../../jwt.html">here</a> for more.</p>
  6543. <p>Additional sub-options for this setting include:</p>
  6544. <ul>
  6545. <li><code>enabled</code>: Set to true to enable authorization using JSON web
  6546. tokens. Defaults to false.</li>
  6547. <li><code>secret</code>: This is either the private shared secret or the public key used to
  6548. decode the contents of the JSON web token. Required if <code>enabled</code> is set to true.</li>
  6549. <li><code>algorithm</code>: The algorithm used to sign (or HMAC) the JSON web token.
  6550. Supported algorithms are listed
  6551. <a href="https://docs.authlib.org/en/latest/specs/rfc7518.html">here (section JWS)</a>.
  6552. Required if <code>enabled</code> is set to true.</li>
  6553. <li><code>subject_claim</code>: Name of the claim containing a unique identifier for the user.
  6554. Optional, defaults to <code>sub</code>.</li>
  6555. <li><code>issuer</code>: The issuer to validate the &quot;iss&quot; claim against. Optional. If provided the
  6556. &quot;iss&quot; claim will be required and validated for all JSON web tokens.</li>
  6557. <li><code>audiences</code>: A list of audiences to validate the &quot;aud&quot; claim against. Optional.
  6558. If provided the &quot;aud&quot; claim will be required and validated for all JSON web tokens.
  6559. Note that if the &quot;aud&quot; claim is included in a JSON web token then
  6560. validation will fail without configuring audiences.</li>
  6561. </ul>
  6562. <p>Example configuration:</p>
  6563. <pre><code class="language-yaml">jwt_config:
  6564. enabled: true
  6565. secret: &quot;provided-by-your-issuer&quot;
  6566. algorithm: &quot;provided-by-your-issuer&quot;
  6567. subject_claim: &quot;name_of_claim&quot;
  6568. issuer: &quot;provided-by-your-issuer&quot;
  6569. audiences:
  6570. - &quot;provided-by-your-issuer&quot;
  6571. </code></pre>
  6572. <hr />
  6573. <h3 id="password_config"><a class="header" href="#password_config"><code>password_config</code></a></h3>
  6574. <p>Use this setting to enable password-based logins.</p>
  6575. <p>This setting has the following sub-options:</p>
  6576. <ul>
  6577. <li><code>enabled</code>: Defaults to true.
  6578. Set to false to disable password authentication.
  6579. Set to <code>only_for_reauth</code> to allow users with existing passwords to use them
  6580. to log in and reauthenticate, whilst preventing new users from setting passwords.</li>
  6581. <li><code>localdb_enabled</code>: Set to false to disable authentication against the local password
  6582. database. This is ignored if <code>enabled</code> is false, and is only useful
  6583. if you have other <code>password_providers</code>. Defaults to true.</li>
  6584. <li><code>pepper</code>: Set the value here to a secret random string for extra security.
  6585. DO NOT CHANGE THIS AFTER INITIAL SETUP!</li>
  6586. <li><code>policy</code>: Define and enforce a password policy, such as minimum lengths for passwords, etc.
  6587. Each parameter is optional. This is an implementation of MSC2000. Parameters are as follows:
  6588. <ul>
  6589. <li><code>enabled</code>: Defaults to false. Set to true to enable.</li>
  6590. <li><code>minimum_length</code>: Minimum accepted length for a password. Defaults to 0.</li>
  6591. <li><code>require_digit</code>: Whether a password must contain at least one digit.
  6592. Defaults to false.</li>
  6593. <li><code>require_symbol</code>: Whether a password must contain at least one symbol.
  6594. A symbol is any character that's not a number or a letter. Defaults to false.</li>
  6595. <li><code>require_lowercase</code>: Whether a password must contain at least one lowercase letter.
  6596. Defaults to false.</li>
  6597. <li><code>require_uppercase</code>: Whether a password must contain at least one uppercase letter.
  6598. Defaults to false.</li>
  6599. </ul>
  6600. </li>
  6601. </ul>
  6602. <p>Example configuration:</p>
  6603. <pre><code class="language-yaml">password_config:
  6604. enabled: false
  6605. localdb_enabled: false
  6606. pepper: &quot;EVEN_MORE_SECRET&quot;
  6607. policy:
  6608. enabled: true
  6609. minimum_length: 15
  6610. require_digit: true
  6611. require_symbol: true
  6612. require_lowercase: true
  6613. require_uppercase: true
  6614. </code></pre>
  6615. <hr />
  6616. <h2 id="push"><a class="header" href="#push">Push</a></h2>
  6617. <p>Configuration settings related to push notifications</p>
  6618. <hr />
  6619. <h3 id="push-1"><a class="header" href="#push-1"><code>push</code></a></h3>
  6620. <p>This setting defines options for push notifications.</p>
  6621. <p>This option has a number of sub-options. They are as follows:</p>
  6622. <ul>
  6623. <li><code>enabled</code>: Enables or disables push notification calculation. Note, disabling this will also
  6624. stop unread counts being calculated for rooms. This mode of operation is intended
  6625. for homeservers which may only have bots or appservice users connected, or are otherwise
  6626. not interested in push/unread counters. This is enabled by default.</li>
  6627. <li><code>include_content</code>: Clients requesting push notifications can either have the body of
  6628. the message sent in the notification poke along with other details
  6629. like the sender, or just the event ID and room ID (<code>event_id_only</code>).
  6630. If clients choose the to have the body sent, this option controls whether the
  6631. notification request includes the content of the event (other details
  6632. like the sender are still included). If <code>event_id_only</code> is enabled, it
  6633. has no effect.
  6634. For modern android devices the notification content will still appear
  6635. because it is loaded by the app. iPhone, however will send a
  6636. notification saying only that a message arrived and who it came from.
  6637. Defaults to true. Set to false to only include the event ID and room ID in push notification payloads.</li>
  6638. <li><code>group_unread_count_by_room: false</code>: When a push notification is received, an unread count is also sent.
  6639. This number can either be calculated as the number of unread messages for the user, or the number of <em>rooms</em> the
  6640. user has unread messages in. Defaults to true, meaning push clients will see the number of
  6641. rooms with unread messages in them. Set to false to instead send the number
  6642. of unread messages.</li>
  6643. <li><code>jitter_delay</code>: Delays push notifications by a random amount up to the given
  6644. duration. Useful for mitigating timing attacks. Optional, defaults to no
  6645. delay. <em>Added in Synapse 1.84.0.</em></li>
  6646. </ul>
  6647. <p>Example configuration:</p>
  6648. <pre><code class="language-yaml">push:
  6649. enabled: true
  6650. include_content: false
  6651. group_unread_count_by_room: false
  6652. jitter_delay: &quot;10s&quot;
  6653. </code></pre>
  6654. <hr />
  6655. <h2 id="rooms"><a class="header" href="#rooms">Rooms</a></h2>
  6656. <p>Config options relating to rooms.</p>
  6657. <hr />
  6658. <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>
  6659. <p>Controls whether locally-created rooms should be end-to-end encrypted by
  6660. default.</p>
  6661. <p>Possible options are &quot;all&quot;, &quot;invite&quot;, and &quot;off&quot;. They are defined as:</p>
  6662. <ul>
  6663. <li>&quot;all&quot;: any locally-created room</li>
  6664. <li>&quot;invite&quot;: any room created with the <code>private_chat</code> or <code>trusted_private_chat</code>
  6665. room creation presets</li>
  6666. <li>&quot;off&quot;: this option will take no effect</li>
  6667. </ul>
  6668. <p>The default value is &quot;off&quot;.</p>
  6669. <p>Note that this option will only affect rooms created after it is set. It
  6670. will also not affect rooms created by other servers.</p>
  6671. <p>Example configuration:</p>
  6672. <pre><code class="language-yaml">encryption_enabled_by_default_for_room_type: invite
  6673. </code></pre>
  6674. <hr />
  6675. <h3 id="user_directory"><a class="header" href="#user_directory"><code>user_directory</code></a></h3>
  6676. <p>This setting defines options related to the user directory.</p>
  6677. <p>This option has the following sub-options:</p>
  6678. <ul>
  6679. <li>
  6680. <p><code>enabled</code>: Defines whether users can search the user directory. If false then
  6681. empty responses are returned to all queries. Defaults to true.</p>
  6682. </li>
  6683. <li>
  6684. <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.
  6685. If false, search results will only contain users
  6686. visible in public rooms and users sharing a room with the requester.
  6687. Defaults to false.</p>
  6688. <p>NB. If you set this to true, and the last time the user_directory search
  6689. indexes were (re)built was before Synapse 1.44, you'll have to
  6690. rebuild the indexes in order to search through all known users.</p>
  6691. <p>These indexes are built the first time Synapse starts; admins can
  6692. manually trigger a rebuild via the API following the instructions
  6693. <a href="usage/configuration/../administration/admin_api/background_updates.html#run">for running background updates</a>,
  6694. set to true to return search results containing all known users, even if that
  6695. user does not share a room with the requester.</p>
  6696. </li>
  6697. <li>
  6698. <p><code>prefer_local_users</code>: Defines whether to prefer local users in search query results.
  6699. If set to true, local users are more likely to appear above remote users when searching the
  6700. user directory. Defaults to false.</p>
  6701. </li>
  6702. </ul>
  6703. <p>Example configuration:</p>
  6704. <pre><code class="language-yaml">user_directory:
  6705. enabled: false
  6706. search_all_users: true
  6707. prefer_local_users: true
  6708. </code></pre>
  6709. <hr />
  6710. <h3 id="user_consent"><a class="header" href="#user_consent"><code>user_consent</code></a></h3>
  6711. <p>For detailed instructions on user consent configuration, see <a href="usage/configuration/../../consent_tracking.html">here</a>.</p>
  6712. <p>Parts of this section are required if enabling the <code>consent</code> resource under
  6713. <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code></a>, in particular <code>template_dir</code> and <code>version</code>.</p>
  6714. <ul>
  6715. <li>
  6716. <p><code>template_dir</code>: gives the location of the templates for the HTML forms.
  6717. This directory should contain one subdirectory per language (eg, <code>en</code>, <code>fr</code>),
  6718. and each language directory should contain the policy document (named as
  6719. <version>.html) and a success page (success.html).</p>
  6720. </li>
  6721. <li>
  6722. <p><code>version</code>: specifies the 'current' version of the policy document. It defines
  6723. the version to be served by the consent resource if there is no 'v'
  6724. parameter.</p>
  6725. </li>
  6726. <li>
  6727. <p><code>server_notice_content</code>: if enabled, will send a user a &quot;Server Notice&quot;
  6728. asking them to consent to the privacy policy. The <a href="usage/configuration/config_documentation.html#server_notices"><code>server_notices</code> section</a>
  6729. must also be configured for this to work. Notices will <em>not</em> be sent to
  6730. guest users unless <code>send_server_notice_to_guests</code> is set to true.</p>
  6731. </li>
  6732. <li>
  6733. <p><code>block_events_error</code>, if set, will block any attempts to send events
  6734. until the user consents to the privacy policy. The value of the setting is
  6735. used as the text of the error.</p>
  6736. </li>
  6737. <li>
  6738. <p><code>require_at_registration</code>, if enabled, will add a step to the registration
  6739. process, similar to how captcha works. Users will be required to accept the
  6740. policy before their account is created.</p>
  6741. </li>
  6742. <li>
  6743. <p><code>policy_name</code> is the display name of the policy users will see when registering
  6744. for an account. Has no effect unless <code>require_at_registration</code> is enabled.
  6745. Defaults to &quot;Privacy Policy&quot;.</p>
  6746. </li>
  6747. </ul>
  6748. <p>Example configuration:</p>
  6749. <pre><code class="language-yaml">user_consent:
  6750. template_dir: res/templates/privacy
  6751. version: 1.0
  6752. server_notice_content:
  6753. msgtype: m.text
  6754. body: &gt;-
  6755. To continue using this homeserver you must review and agree to the
  6756. terms and conditions at %(consent_uri)s
  6757. send_server_notice_to_guests: true
  6758. block_events_error: &gt;-
  6759. To continue using this homeserver you must review and agree to the
  6760. terms and conditions at %(consent_uri)s
  6761. require_at_registration: false
  6762. policy_name: Privacy Policy
  6763. </code></pre>
  6764. <hr />
  6765. <h3 id="stats"><a class="header" href="#stats"><code>stats</code></a></h3>
  6766. <p>Settings for local room and user statistics collection. See <a href="usage/configuration/../../room_and_user_statistics.html">here</a>
  6767. for more.</p>
  6768. <ul>
  6769. <li><code>enabled</code>: Set to false to disable room and user statistics. Note that doing
  6770. so may cause certain features (such as the room directory) not to work
  6771. correctly. Defaults to true.</li>
  6772. </ul>
  6773. <p>Example configuration:</p>
  6774. <pre><code class="language-yaml">stats:
  6775. enabled: false
  6776. </code></pre>
  6777. <hr />
  6778. <h3 id="server_notices"><a class="header" href="#server_notices"><code>server_notices</code></a></h3>
  6779. <p>Use this setting to enable a room which can be used to send notices
  6780. from the server to users. It is a special room which users cannot leave; notices
  6781. in the room come from a special &quot;notices&quot; user id.</p>
  6782. <p>If you use this setting, you <em>must</em> define the <code>system_mxid_localpart</code>
  6783. sub-setting, which defines the id of the user which will be used to send the
  6784. notices.</p>
  6785. <p>Sub-options for this setting include:</p>
  6786. <ul>
  6787. <li><code>system_mxid_display_name</code>: set the display name of the &quot;notices&quot; user</li>
  6788. <li><code>system_mxid_avatar_url</code>: set the avatar for the &quot;notices&quot; user</li>
  6789. <li><code>room_name</code>: set the room name of the server notices room</li>
  6790. </ul>
  6791. <p>Example configuration:</p>
  6792. <pre><code class="language-yaml">server_notices:
  6793. system_mxid_localpart: notices
  6794. system_mxid_display_name: &quot;Server Notices&quot;
  6795. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  6796. room_name: &quot;Server Notices&quot;
  6797. </code></pre>
  6798. <hr />
  6799. <h3 id="enable_room_list_search"><a class="header" href="#enable_room_list_search"><code>enable_room_list_search</code></a></h3>
  6800. <p>Set to false to disable searching the public room list. When disabled
  6801. blocks searching local and remote room lists for local and remote
  6802. users by always returning an empty list for all queries. Defaults to true.</p>
  6803. <p>Example configuration:</p>
  6804. <pre><code class="language-yaml">enable_room_list_search: false
  6805. </code></pre>
  6806. <hr />
  6807. <h3 id="alias_creation_rules"><a class="header" href="#alias_creation_rules"><code>alias_creation_rules</code></a></h3>
  6808. <p>The <code>alias_creation_rules</code> option controls who is allowed to create aliases
  6809. on this server.</p>
  6810. <p>The format of this option is a list of rules that contain globs that
  6811. match against user_id, room_id and the new alias (fully qualified with
  6812. server name). The action in the first rule that matches is taken,
  6813. which can currently either be &quot;allow&quot; or &quot;deny&quot;.</p>
  6814. <p>Missing user_id/room_id/alias fields default to &quot;*&quot;.</p>
  6815. <p>If no rules match the request is denied. An empty list means no one
  6816. can create aliases.</p>
  6817. <p>Options for the rules include:</p>
  6818. <ul>
  6819. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  6820. <li><code>alias</code>: Matches against the alias being created. Defaults to &quot;*&quot;.</li>
  6821. <li><code>room_id</code>: Matches against the room ID the alias is being pointed at. Defaults to &quot;*&quot;</li>
  6822. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
  6823. </ul>
  6824. <p>Example configuration:</p>
  6825. <pre><code class="language-yaml">alias_creation_rules:
  6826. - user_id: &quot;bad_user&quot;
  6827. alias: &quot;spammy_alias&quot;
  6828. room_id: &quot;*&quot;
  6829. action: deny
  6830. </code></pre>
  6831. <hr />
  6832. <h3 id="room_list_publication_rules"><a class="header" href="#room_list_publication_rules"><code>room_list_publication_rules</code></a></h3>
  6833. <p>The <code>room_list_publication_rules</code> option controls who can publish and
  6834. which rooms can be published in the public room list.</p>
  6835. <p>The format of this option is the same as that for
  6836. <code>alias_creation_rules</code>.</p>
  6837. <p>If the room has one or more aliases associated with it, only one of
  6838. the aliases needs to match the alias rule. If there are no aliases
  6839. then only rules with <code>alias: *</code> match.</p>
  6840. <p>If no rules match the request is denied. An empty list means no one
  6841. can publish rooms.</p>
  6842. <p>Options for the rules include:</p>
  6843. <ul>
  6844. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  6845. <li><code>alias</code>: Matches against any current local or canonical aliases associated with the room. Defaults to &quot;*&quot;.</li>
  6846. <li><code>room_id</code>: Matches against the room ID being published. Defaults to &quot;*&quot;.</li>
  6847. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
  6848. </ul>
  6849. <p>Example configuration:</p>
  6850. <pre><code class="language-yaml">room_list_publication_rules:
  6851. - user_id: &quot;*&quot;
  6852. alias: &quot;*&quot;
  6853. room_id: &quot;*&quot;
  6854. action: allow
  6855. </code></pre>
  6856. <hr />
  6857. <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>
  6858. <p>The <code>default_power_level_content_override</code> option controls the default power
  6859. levels for rooms.</p>
  6860. <p>Useful if you know that your users need special permissions in rooms
  6861. that they create (e.g. to send particular types of state events without
  6862. needing an elevated power level). This takes the same shape as the
  6863. <code>power_level_content_override</code> parameter in the /createRoom API, but
  6864. is applied before that parameter.</p>
  6865. <p>Note that each key provided inside a preset (for example <code>events</code> in the example
  6866. below) will overwrite all existing defaults inside that key. So in the example
  6867. below, newly-created private_chat rooms will have no rules for any event types
  6868. except <code>com.example.foo</code>.</p>
  6869. <p>Example configuration:</p>
  6870. <pre><code class="language-yaml">default_power_level_content_override:
  6871. private_chat: { &quot;events&quot;: { &quot;com.example.foo&quot; : 0 } }
  6872. trusted_private_chat: null
  6873. public_chat: null
  6874. </code></pre>
  6875. <hr />
  6876. <h3 id="forget_rooms_on_leave"><a class="header" href="#forget_rooms_on_leave"><code>forget_rooms_on_leave</code></a></h3>
  6877. <p>Set to true to automatically forget rooms for users when they leave them, either
  6878. normally or via a kick or ban. Defaults to false.</p>
  6879. <p>Example configuration:</p>
  6880. <pre><code class="language-yaml">forget_rooms_on_leave: false
  6881. </code></pre>
  6882. <hr />
  6883. <h2 id="opentracing"><a class="header" href="#opentracing">Opentracing</a></h2>
  6884. <p>Configuration options related to Opentracing support.</p>
  6885. <hr />
  6886. <h3 id="opentracing-1"><a class="header" href="#opentracing-1"><code>opentracing</code></a></h3>
  6887. <p>These settings enable and configure opentracing, which implements distributed tracing.
  6888. This allows you to observe the causal chains of events across servers
  6889. including requests, key lookups etc., across any server running
  6890. synapse or any other services which support opentracing
  6891. (specifically those implemented with Jaeger).</p>
  6892. <p>Sub-options include:</p>
  6893. <ul>
  6894. <li><code>enabled</code>: whether tracing is enabled. Set to true to enable. Disabled by default.</li>
  6895. <li><code>homeserver_whitelist</code>: The list of homeservers we wish to send and receive span contexts and span baggage.
  6896. See <a href="usage/configuration/../../opentracing.html">here</a> for more.
  6897. This is a list of regexes which are matched against the <code>server_name</code> of the homeserver.
  6898. By default, it is empty, so no servers are matched.</li>
  6899. <li><code>force_tracing_for_users</code>: # A list of the matrix IDs of users whose requests will always be traced,
  6900. even if the tracing system would otherwise drop the traces due to probabilistic sampling.
  6901. By default, the list is empty.</li>
  6902. <li><code>jaeger_config</code>: Jaeger can be configured to sample traces at different rates.
  6903. All configuration options provided by Jaeger can be set here. Jaeger's configuration is
  6904. mostly related to trace sampling which is documented <a href="https://www.jaegertracing.io/docs/latest/sampling/">here</a>.</li>
  6905. </ul>
  6906. <p>Example configuration:</p>
  6907. <pre><code class="language-yaml">opentracing:
  6908. enabled: true
  6909. homeserver_whitelist:
  6910. - &quot;.*&quot;
  6911. force_tracing_for_users:
  6912. - &quot;@user1:server_name&quot;
  6913. - &quot;@user2:server_name&quot;
  6914. jaeger_config:
  6915. sampler:
  6916. type: const
  6917. param: 1
  6918. logging:
  6919. false
  6920. </code></pre>
  6921. <hr />
  6922. <h2 id="coordinating-workers"><a class="header" href="#coordinating-workers">Coordinating workers</a></h2>
  6923. <p>Configuration options related to workers which belong in the main config file
  6924. (usually called <code>homeserver.yaml</code>).
  6925. A Synapse deployment can scale horizontally by running multiple Synapse processes
  6926. called <em>workers</em>. Incoming requests are distributed between workers to handle higher
  6927. loads. Some workers are privileged and can accept requests from other workers.</p>
  6928. <p>As a result, the worker configuration is divided into two parts.</p>
  6929. <ol>
  6930. <li>The first part (in this section of the manual) defines which shardable tasks
  6931. are delegated to privileged workers. This allows unprivileged workers to make
  6932. requests to a privileged worker to act on their behalf.</li>
  6933. <li><a href="usage/configuration/config_documentation.html#individual-worker-configuration">The second part</a>
  6934. controls the behaviour of individual workers in isolation.</li>
  6935. </ol>
  6936. <p>For guidance on setting up workers, see the <a href="usage/configuration/../../workers.html">worker documentation</a>.</p>
  6937. <hr />
  6938. <h3 id="worker_replication_secret"><a class="header" href="#worker_replication_secret"><code>worker_replication_secret</code></a></h3>
  6939. <p>A shared secret used by the replication APIs on the main process to authenticate
  6940. HTTP requests from workers.</p>
  6941. <p>The default, this value is omitted (equivalently <code>null</code>), which means that
  6942. traffic between the workers and the main process is not authenticated.</p>
  6943. <p>Example configuration:</p>
  6944. <pre><code class="language-yaml">worker_replication_secret: &quot;secret_secret&quot;
  6945. </code></pre>
  6946. <hr />
  6947. <h3 id="start_pushers"><a class="header" href="#start_pushers"><code>start_pushers</code></a></h3>
  6948. <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>
  6949. <p>Controls sending of push notifications on the main process. Set to <code>false</code>
  6950. if using a <a href="usage/configuration/../../workers.html#synapseapppusher">pusher worker</a>. Defaults to <code>true</code>.</p>
  6951. <p>Example configuration:</p>
  6952. <pre><code class="language-yaml">start_pushers: false
  6953. </code></pre>
  6954. <hr />
  6955. <h3 id="pusher_instances"><a class="header" href="#pusher_instances"><code>pusher_instances</code></a></h3>
  6956. <p>It is possible to scale the processes that handle sending push notifications to <a href="https://github.com/matrix-org/sygnal">sygnal</a>
  6957. 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
  6958. a <code>pusher_instances</code> map. Doing so will remove handling of this function from the main
  6959. process. Multiple workers can be added to this map, in which case the work is balanced
  6960. across them. Ensure the main process and all pusher workers are restarted after changing
  6961. this option.</p>
  6962. <p>Example configuration for a single worker:</p>
  6963. <pre><code class="language-yaml">pusher_instances:
  6964. - pusher_worker1
  6965. </code></pre>
  6966. <p>And for multiple workers:</p>
  6967. <pre><code class="language-yaml">pusher_instances:
  6968. - pusher_worker1
  6969. - pusher_worker2
  6970. </code></pre>
  6971. <hr />
  6972. <h3 id="send_federation"><a class="header" href="#send_federation"><code>send_federation</code></a></h3>
  6973. <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>
  6974. <p>Controls sending of outbound federation transactions on the main process.
  6975. Set to <code>false</code> if using a <a href="usage/configuration/../../workers.html#synapseappfederation_sender">federation sender worker</a>.
  6976. Defaults to <code>true</code>.</p>
  6977. <p>Example configuration:</p>
  6978. <pre><code class="language-yaml">send_federation: false
  6979. </code></pre>
  6980. <hr />
  6981. <h3 id="federation_sender_instances"><a class="header" href="#federation_sender_instances"><code>federation_sender_instances</code></a></h3>
  6982. <p>It is possible to scale the processes that handle sending outbound federation requests
  6983. 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
  6984. a <code>federation_sender_instances</code> map. Doing so will remove handling of this function from
  6985. the main process. Multiple workers can be added to this map, in which case the work is
  6986. balanced across them.</p>
  6987. <p>This configuration setting must be shared between all workers handling federation
  6988. sending, and if changed all federation sender workers must be stopped at the same time
  6989. and then started, to ensure that all instances are running with the same config (otherwise
  6990. events may be dropped).</p>
  6991. <p>Example configuration for a single worker:</p>
  6992. <pre><code class="language-yaml">federation_sender_instances:
  6993. - federation_sender1
  6994. </code></pre>
  6995. <p>And for multiple workers:</p>
  6996. <pre><code class="language-yaml">federation_sender_instances:
  6997. - federation_sender1
  6998. - federation_sender2
  6999. </code></pre>
  7000. <hr />
  7001. <h3 id="instance_map"><a class="header" href="#instance_map"><code>instance_map</code></a></h3>
  7002. <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
  7003. replication listener of the worker, if configured, and to the main process. Each worker
  7004. declared under <a href="usage/configuration/../../workers.html#stream-writers"><code>stream_writers</code></a> and
  7005. <a href="usage/configuration/config_documentation.html#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a> needs a HTTP
  7006. replication listener, and that listener should be included in the <code>instance_map</code>. The
  7007. main process also needs an entry on the <code>instance_map</code>, and it should be listed under
  7008. <code>main</code> <strong>if even one other worker exists</strong>. Ensure the port matches with what is
  7009. declared inside the <code>listener</code> block for a <code>replication</code> listener.</p>
  7010. <p>Example configuration:</p>
  7011. <pre><code class="language-yaml">instance_map:
  7012. main:
  7013. host: localhost
  7014. port: 8030
  7015. worker1:
  7016. host: localhost
  7017. port: 8034
  7018. </code></pre>
  7019. <p>Example configuration(#2, for UNIX sockets):</p>
  7020. <pre><code class="language-yaml">instance_map:
  7021. main:
  7022. path: /var/run/synapse/main_replication.sock
  7023. worker1:
  7024. path: /var/run/synapse/worker1_replication.sock
  7025. </code></pre>
  7026. <hr />
  7027. <h3 id="stream_writers"><a class="header" href="#stream_writers"><code>stream_writers</code></a></h3>
  7028. <p>Experimental: When using workers you can define which workers should
  7029. handle writing to streams such as event persistence and typing notifications.
  7030. Any worker specified here must also be in the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>.</p>
  7031. <p>See the list of available streams in the
  7032. <a href="usage/configuration/../../workers.html#stream-writers">worker documentation</a>.</p>
  7033. <p>Example configuration:</p>
  7034. <pre><code class="language-yaml">stream_writers:
  7035. events: worker1
  7036. typing: worker1
  7037. </code></pre>
  7038. <hr />
  7039. <h3 id="outbound_federation_restricted_to"><a class="header" href="#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a></h3>
  7040. <p>When using workers, you can restrict outbound federation traffic to only go through a
  7041. specific subset of workers. Any worker specified here must also be in the
  7042. <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>.
  7043. <a href="usage/configuration/config_documentation.html#worker_replication_secret"><code>worker_replication_secret</code></a> must also be configured to
  7044. authorize inter-worker communication.</p>
  7045. <pre><code class="language-yaml">outbound_federation_restricted_to:
  7046. - federation_sender1
  7047. - federation_sender2
  7048. </code></pre>
  7049. <h2>Also see the <a href="usage/configuration/../../workers.html#restrict-outbound-federation-traffic-to-a-specific-set-of-workers">worker
  7050. documentation</a>
  7051. for more info.</h2>
  7052. <h3 id="run_background_tasks_on"><a class="header" href="#run_background_tasks_on"><code>run_background_tasks_on</code></a></h3>
  7053. <p>The <a href="usage/configuration/../../workers.html#background-tasks">worker</a> that is used to run
  7054. background tasks (e.g. cleaning up expired data). If not provided this
  7055. defaults to the main process.</p>
  7056. <p>Example configuration:</p>
  7057. <pre><code class="language-yaml">run_background_tasks_on: worker1
  7058. </code></pre>
  7059. <hr />
  7060. <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>
  7061. <p>The <a href="usage/configuration/../../workers.html#updating-the-user-directory">worker</a> that is used to
  7062. update the user directory. If not provided this defaults to the main process.</p>
  7063. <p>Example configuration:</p>
  7064. <pre><code class="language-yaml">update_user_directory_from_worker: worker1
  7065. </code></pre>
  7066. <p><em>Added in Synapse 1.59.0.</em></p>
  7067. <hr />
  7068. <h3 id="notify_appservices_from_worker"><a class="header" href="#notify_appservices_from_worker"><code>notify_appservices_from_worker</code></a></h3>
  7069. <p>The <a href="usage/configuration/../../workers.html#notifying-application-services">worker</a> that is used to
  7070. send output traffic to Application Services. If not provided this defaults
  7071. to the main process.</p>
  7072. <p>Example configuration:</p>
  7073. <pre><code class="language-yaml">notify_appservices_from_worker: worker1
  7074. </code></pre>
  7075. <p><em>Added in Synapse 1.59.0.</em></p>
  7076. <hr />
  7077. <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>
  7078. <p>The <a href="usage/configuration/../../workers.html#synapseappmedia_repository">worker</a> that is used to run
  7079. background tasks for media repository. If running multiple media repositories
  7080. you must configure a single instance to run the background tasks. If not provided
  7081. this defaults to the main process or your single <code>media_repository</code> worker.</p>
  7082. <p>Example configuration:</p>
  7083. <pre><code class="language-yaml">media_instance_running_background_jobs: worker1
  7084. </code></pre>
  7085. <p><em>Added in Synapse 1.16.0.</em></p>
  7086. <hr />
  7087. <h3 id="redis"><a class="header" href="#redis"><code>redis</code></a></h3>
  7088. <p>Configuration for Redis when using workers. This <em>must</em> be enabled when using workers.
  7089. This setting has the following sub-options:</p>
  7090. <ul>
  7091. <li>
  7092. <p><code>enabled</code>: whether to use Redis support. Defaults to false.</p>
  7093. </li>
  7094. <li>
  7095. <p><code>host</code> and <code>port</code>: Optional host and port to use to connect to redis. Defaults to
  7096. localhost and 6379</p>
  7097. </li>
  7098. <li>
  7099. <p><code>path</code>: The full path to a local Unix socket file. <strong>If this is used, <code>host</code> and
  7100. <code>port</code> are ignored.</strong> Defaults to `/tmp/redis.sock'</p>
  7101. </li>
  7102. <li>
  7103. <p><code>password</code>: Optional password if configured on the Redis instance.</p>
  7104. </li>
  7105. <li>
  7106. <p><code>dbid</code>: Optional redis dbid if needs to connect to specific redis logical db.</p>
  7107. </li>
  7108. <li>
  7109. <p><code>use_tls</code>: Whether to use tls connection. Defaults to false.</p>
  7110. </li>
  7111. <li>
  7112. <p><code>certificate_file</code>: Optional path to the certificate file</p>
  7113. </li>
  7114. <li>
  7115. <p><code>private_key_file</code>: Optional path to the private key file</p>
  7116. </li>
  7117. <li>
  7118. <p><code>ca_file</code>: Optional path to the CA certificate file. Use this one or:</p>
  7119. </li>
  7120. <li>
  7121. <p><code>ca_path</code>: Optional path to the folder containing the CA certificate file</p>
  7122. <p><em>Added in Synapse 1.78.0.</em></p>
  7123. <p><em>Changed in Synapse 1.84.0: Added use_tls, certificate_file, private_key_file, ca_file and ca_path attributes</em></p>
  7124. <p><em>Changed in Synapse 1.85.0: Added path option to use a local Unix socket</em></p>
  7125. </li>
  7126. </ul>
  7127. <p>Example configuration:</p>
  7128. <pre><code class="language-yaml">redis:
  7129. enabled: true
  7130. host: localhost
  7131. port: 6379
  7132. password: &lt;secret_password&gt;
  7133. dbid: &lt;dbid&gt;
  7134. #use_tls: True
  7135. #certificate_file: &lt;path_to_the_certificate_file&gt;
  7136. #private_key_file: &lt;path_to_the_private_key_file&gt;
  7137. #ca_file: &lt;path_to_the_ca_certificate_file&gt;
  7138. </code></pre>
  7139. <hr />
  7140. <h2 id="individual-worker-configuration"><a class="header" href="#individual-worker-configuration">Individual worker configuration</a></h2>
  7141. <p>These options configure an individual worker, in its worker configuration file.
  7142. They should be not be provided when configuring the main process.</p>
  7143. <p>Note also the configuration above for
  7144. <a href="usage/configuration/config_documentation.html#coordinating-workers">coordinating a cluster of workers</a>.</p>
  7145. <p>For guidance on setting up workers, see the <a href="usage/configuration/../../workers.html">worker documentation</a>.</p>
  7146. <hr />
  7147. <h3 id="worker_app"><a class="header" href="#worker_app"><code>worker_app</code></a></h3>
  7148. <p>The type of worker. The currently available worker applications are listed
  7149. in <a href="usage/configuration/../../workers.html#available-worker-applications">worker documentation</a>.</p>
  7150. <p>The most common worker is the
  7151. <a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a>.</p>
  7152. <p>Example configuration:</p>
  7153. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  7154. </code></pre>
  7155. <hr />
  7156. <h3 id="worker_name"><a class="header" href="#worker_name"><code>worker_name</code></a></h3>
  7157. <p>A unique name for the worker. The worker needs a name to be addressed in
  7158. further parameters and identification in log files. We strongly recommend
  7159. giving each worker a unique <code>worker_name</code>.</p>
  7160. <p>Example configuration:</p>
  7161. <pre><code class="language-yaml">worker_name: generic_worker1
  7162. </code></pre>
  7163. <hr />
  7164. <h3 id="worker_listeners"><a class="header" href="#worker_listeners"><code>worker_listeners</code></a></h3>
  7165. <p>A worker can handle HTTP requests. To do so, a <code>worker_listeners</code> option
  7166. must be declared, in the same way as the <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code> option</a>
  7167. in the shared config.</p>
  7168. <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>
  7169. will need to include a <code>replication</code> listener here, in order to accept internal HTTP
  7170. requests from other workers.</p>
  7171. <p>Example configuration:</p>
  7172. <pre><code class="language-yaml">worker_listeners:
  7173. - type: http
  7174. port: 8083
  7175. resources:
  7176. - names: [client, federation]
  7177. </code></pre>
  7178. <p>Example configuration(#2, using UNIX sockets with a <code>replication</code> listener):</p>
  7179. <pre><code class="language-yaml">worker_listeners:
  7180. - type: http
  7181. path: /var/run/synapse/worker_public.sock
  7182. resources:
  7183. - names: [client, federation]
  7184. - type: http
  7185. path: /var/run/synapse/worker_replication.sock
  7186. resources:
  7187. - names: [replication]
  7188. </code></pre>
  7189. <hr />
  7190. <h3 id="worker_manhole"><a class="header" href="#worker_manhole"><code>worker_manhole</code></a></h3>
  7191. <p>A worker may have a listener for <a href="usage/configuration/../../manhole.html"><code>manhole</code></a>.
  7192. It allows server administrators to access a Python shell on the worker.</p>
  7193. <p>Example configuration:</p>
  7194. <pre><code class="language-yaml">worker_manhole: 9000
  7195. </code></pre>
  7196. <p>This is a short form for:</p>
  7197. <pre><code class="language-yaml">worker_listeners:
  7198. - port: 9000
  7199. bind_addresses: ['127.0.0.1']
  7200. type: manhole
  7201. </code></pre>
  7202. <p>It needs also an additional <a href="usage/configuration/config_documentation.html#manhole_settings"><code>manhole_settings</code></a> configuration.</p>
  7203. <hr />
  7204. <h3 id="worker_daemonize"><a class="header" href="#worker_daemonize"><code>worker_daemonize</code></a></h3>
  7205. <p>Specifies whether the worker should be started as a daemon process.
  7206. If Synapse is being managed by <a href="usage/configuration/../../systemd-with-workers/">systemd</a>, this option
  7207. must be omitted or set to <code>false</code>.</p>
  7208. <p>Defaults to <code>false</code>.</p>
  7209. <p>Example configuration:</p>
  7210. <pre><code class="language-yaml">worker_daemonize: true
  7211. </code></pre>
  7212. <hr />
  7213. <h3 id="worker_pid_file"><a class="header" href="#worker_pid_file"><code>worker_pid_file</code></a></h3>
  7214. <p>When running a worker as a daemon, we need a place to store the
  7215. <a href="https://en.wikipedia.org/wiki/Process_identifier">PID</a> of the worker.
  7216. This option defines the location of that &quot;pid file&quot;.</p>
  7217. <p>This option is required if <code>worker_daemonize</code> is <code>true</code> and ignored
  7218. otherwise. It has no default.</p>
  7219. <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>
  7220. <p>Example configuration:</p>
  7221. <pre><code class="language-yaml">worker_pid_file: DATADIR/generic_worker1.pid
  7222. </code></pre>
  7223. <hr />
  7224. <h3 id="worker_log_config"><a class="header" href="#worker_log_config"><code>worker_log_config</code></a></h3>
  7225. <p>This option specifies a yaml python logging config file as described
  7226. <a href="https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema">here</a>.
  7227. 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>
  7228. <p>Example configuration:</p>
  7229. <pre><code class="language-yaml">worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  7230. </code></pre>
  7231. <hr />
  7232. <h2 id="background-updates"><a class="header" href="#background-updates">Background Updates</a></h2>
  7233. <p>Configuration settings related to background updates.</p>
  7234. <hr />
  7235. <h3 id="background_updates"><a class="header" href="#background_updates"><code>background_updates</code></a></h3>
  7236. <p>Background updates are database updates that are run in the background in batches.
  7237. The duration, minimum batch size, default batch size, whether to sleep between batches and if so, how long to
  7238. sleep can all be configured. This is helpful to speed up or slow down the updates.
  7239. This setting has the following sub-options:</p>
  7240. <ul>
  7241. <li><code>background_update_duration_ms</code>: How long in milliseconds to run a batch of background updates for. Defaults to 100.
  7242. Set a different time to change the default.</li>
  7243. <li><code>sleep_enabled</code>: Whether to sleep between updates. Defaults to true. Set to false to change the default.</li>
  7244. <li><code>sleep_duration_ms</code>: If sleeping between updates, how long in milliseconds to sleep for. Defaults to 1000.
  7245. Set a duration to change the default.</li>
  7246. <li><code>min_batch_size</code>: Minimum size a batch of background updates can be. Must be greater than 0. Defaults to 1.
  7247. Set a size to change the default.</li>
  7248. <li><code>default_batch_size</code>: The batch size to use for the first iteration of a new background update. The default is 100.
  7249. Set a size to change the default.</li>
  7250. </ul>
  7251. <p>Example configuration:</p>
  7252. <pre><code class="language-yaml">background_updates:
  7253. background_update_duration_ms: 500
  7254. sleep_enabled: false
  7255. sleep_duration_ms: 300
  7256. min_batch_size: 10
  7257. default_batch_size: 50
  7258. </code></pre>
  7259. <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>
  7260. <p>Below is a sample homeserver configuration file. The homeserver configuration file
  7261. can be tweaked to change the behaviour of your homeserver. A restart of the server is
  7262. generally required to apply any changes made to this file.</p>
  7263. <p>Note that the contents below are <em>not</em> intended to be copied and used as the basis for
  7264. a real homeserver.yaml. Instead, if you are starting from scratch, please generate
  7265. a fresh config using Synapse by following the instructions in
  7266. <a href="usage/configuration/../../setup/installation.html">Installation</a>.</p>
  7267. <p>Documentation for all configuration options can be found in the
  7268. <a href="usage/configuration/./config_documentation.html">Configuration Manual</a>.</p>
  7269. <pre><code class="language-yaml"># This file is maintained as an up-to-date snapshot of the default
  7270. # homeserver.yaml configuration generated by Synapse. You can find a
  7271. # complete accounting of possible configuration options at
  7272. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  7273. #
  7274. # It is *not* intended to be copied and used as the basis for a real
  7275. # homeserver.yaml. Instead, if you are starting from scratch, please generate
  7276. # a fresh config using Synapse by following the instructions in
  7277. # https://matrix-org.github.io/synapse/latest/setup/installation.html.
  7278. #
  7279. ################################################################################
  7280. # Configuration file for Synapse.
  7281. #
  7282. # This is a YAML file: see [1] for a quick introduction. Note in particular
  7283. # that *indentation is important*: all the elements of a list or dictionary
  7284. # should have the same indentation.
  7285. #
  7286. # [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  7287. #
  7288. # For more information on how to configure Synapse, including a complete accounting of
  7289. # each option, go to docs/usage/configuration/config_documentation.md or
  7290. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  7291. server_name: &quot;SERVERNAME&quot;
  7292. pid_file: DATADIR/homeserver.pid
  7293. listeners:
  7294. - port: 8008
  7295. tls: false
  7296. type: http
  7297. x_forwarded: true
  7298. bind_addresses: ['::1', '127.0.0.1']
  7299. resources:
  7300. - names: [client, federation]
  7301. compress: false
  7302. database:
  7303. name: sqlite3
  7304. args:
  7305. database: DATADIR/homeserver.db
  7306. log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  7307. media_store_path: DATADIR/media_store
  7308. signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  7309. trusted_key_servers:
  7310. - server_name: &quot;matrix.org&quot;
  7311. </code></pre>
  7312. <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>
  7313. <p>Below is a sample logging configuration file. This file can be tweaked to control how your
  7314. homeserver will output logs. The value of the <code>log_config</code> option in your homeserver config
  7315. should be the path to this file.</p>
  7316. <p>To apply changes made to this file, send Synapse a SIGHUP signal (or, if using <code>systemd</code>, run
  7317. <code>systemctl reload</code> on the Synapse service).</p>
  7318. <p>Note that a default logging configuration (shown below) is created automatically alongside
  7319. the homeserver config when following the <a href="usage/configuration/../../setup/installation.html">installation instructions</a>.
  7320. It should be named <code>&lt;SERVERNAME&gt;.log.config</code> by default.</p>
  7321. <pre><code class="language-yaml"># Log configuration for Synapse.
  7322. #
  7323. # This is a YAML file containing a standard Python logging configuration
  7324. # dictionary. See [1] for details on the valid settings.
  7325. #
  7326. # Synapse also supports structured logging for machine readable logs which can
  7327. # be ingested by ELK stacks. See [2] for details.
  7328. #
  7329. # [1]: https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema
  7330. # [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html
  7331. version: 1
  7332. formatters:
  7333. precise:
  7334. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
  7335. handlers:
  7336. file:
  7337. class: logging.handlers.TimedRotatingFileHandler
  7338. formatter: precise
  7339. filename: /var/log/matrix-synapse/homeserver.log
  7340. when: midnight
  7341. backupCount: 3 # Does not include the current log file.
  7342. encoding: utf8
  7343. # Default to buffering writes to log file for efficiency.
  7344. # WARNING/ERROR logs will still be flushed immediately, but there will be a
  7345. # delay (of up to `period` seconds, or until the buffer is full with
  7346. # `capacity` messages) before INFO/DEBUG logs get written.
  7347. buffer:
  7348. class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
  7349. target: file
  7350. # The capacity is the maximum number of log lines that are buffered
  7351. # before being written to disk. Increasing this will lead to better
  7352. # performance, at the expensive of it taking longer for log lines to
  7353. # be written to disk.
  7354. # This parameter is required.
  7355. capacity: 10
  7356. # Logs with a level at or above the flush level will cause the buffer to
  7357. # be flushed immediately.
  7358. # Default value: 40 (ERROR)
  7359. # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
  7360. flushLevel: 30 # Flush immediately for WARNING logs and higher
  7361. # The period of time, in seconds, between forced flushes.
  7362. # Messages will not be delayed for longer than this time.
  7363. # Default value: 5 seconds
  7364. period: 5
  7365. # A handler that writes logs to stderr. Unused by default, but can be used
  7366. # instead of &quot;buffer&quot; and &quot;file&quot; in the logger handlers.
  7367. console:
  7368. class: logging.StreamHandler
  7369. formatter: precise
  7370. loggers:
  7371. synapse.storage.SQL:
  7372. # beware: increasing this to DEBUG will make synapse log sensitive
  7373. # information such as access tokens.
  7374. level: INFO
  7375. root:
  7376. level: INFO
  7377. # Write logs to the `buffer` handler, which will buffer them together in memory,
  7378. # then write them to a file.
  7379. #
  7380. # Replace &quot;buffer&quot; with &quot;console&quot; to log to stderr instead.
  7381. #
  7382. handlers: [buffer]
  7383. disable_existing_loggers: false
  7384. </code></pre>
  7385. <div style="break-before: page; page-break-before: always;"></div><h1 id="structured-logging"><a class="header" href="#structured-logging">Structured Logging</a></h1>
  7386. <p>A structured logging system can be useful when your logs are destined for a
  7387. machine to parse and process. By maintaining its machine-readable characteristics,
  7388. it enables more efficient searching and aggregations when consumed by software
  7389. such as the &quot;ELK stack&quot;.</p>
  7390. <p>Synapse's structured logging system is configured via the file that Synapse's
  7391. <code>log_config</code> config option points to. The file should include a formatter which
  7392. uses the <code>synapse.logging.TerseJsonFormatter</code> class included with Synapse and a
  7393. handler which uses the above formatter.</p>
  7394. <p>There is also a <code>synapse.logging.JsonFormatter</code> option which does not include
  7395. a timestamp in the resulting JSON. This is useful if the log ingester adds its
  7396. own timestamp.</p>
  7397. <p>A structured logging configuration looks similar to the following:</p>
  7398. <pre><code class="language-yaml">version: 1
  7399. formatters:
  7400. structured:
  7401. class: synapse.logging.TerseJsonFormatter
  7402. handlers:
  7403. file:
  7404. class: logging.handlers.TimedRotatingFileHandler
  7405. formatter: structured
  7406. filename: /path/to/my/logs/homeserver.log
  7407. when: midnight
  7408. backupCount: 3 # Does not include the current log file.
  7409. encoding: utf8
  7410. loggers:
  7411. synapse:
  7412. level: INFO
  7413. handlers: [remote]
  7414. synapse.storage.SQL:
  7415. level: WARNING
  7416. </code></pre>
  7417. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  7418. with the SQL layer at 'WARNING', and will log to a file, stored as JSON.</p>
  7419. <p>It is also possible to configure Synapse to log to a remote endpoint by using the
  7420. <code>synapse.logging.RemoteHandler</code> class included with Synapse. It takes the
  7421. following arguments:</p>
  7422. <ul>
  7423. <li><code>host</code>: Hostname or IP address of the log aggregator.</li>
  7424. <li><code>port</code>: Numerical port to contact on the host.</li>
  7425. <li><code>maximum_buffer</code>: (Optional, defaults to 1000) The maximum buffer size to allow.</li>
  7426. </ul>
  7427. <p>A remote structured logging configuration looks similar to the following:</p>
  7428. <pre><code class="language-yaml">version: 1
  7429. formatters:
  7430. structured:
  7431. class: synapse.logging.TerseJsonFormatter
  7432. handlers:
  7433. remote:
  7434. class: synapse.logging.RemoteHandler
  7435. formatter: structured
  7436. host: 10.1.2.3
  7437. port: 9999
  7438. loggers:
  7439. synapse:
  7440. level: INFO
  7441. handlers: [remote]
  7442. synapse.storage.SQL:
  7443. level: WARNING
  7444. </code></pre>
  7445. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  7446. with the SQL layer at 'WARNING', and will log JSON formatted messages to a
  7447. remote endpoint at 10.1.2.3:9999.</p>
  7448. <div style="break-before: page; page-break-before: always;"></div><h1 id="templates"><a class="header" href="#templates">Templates</a></h1>
  7449. <p>Synapse uses parametrised templates to generate the content of emails it sends and
  7450. webpages it shows to users.</p>
  7451. <p>By default, Synapse will use the templates listed <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">here</a>.
  7452. Server admins can configure an additional directory for Synapse to look for templates
  7453. in, allowing them to specify custom templates:</p>
  7454. <pre><code class="language-yaml">templates:
  7455. custom_template_directory: /path/to/custom/templates/
  7456. </code></pre>
  7457. <p>If this setting is not set, or the files named below are not found within the directory,
  7458. default templates from within the Synapse package will be used.</p>
  7459. <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>.
  7460. Templates rendered by Jinja 2 can also access two functions on top of the functions
  7461. already available as part of Jinja 2:</p>
  7462. <pre><code class="language-python">format_ts(value: int, format: str) -&gt; str
  7463. </code></pre>
  7464. <p>Formats a timestamp in milliseconds.</p>
  7465. <p>Example: <code>reason.last_sent_ts|format_ts(&quot;%c&quot;)</code></p>
  7466. <pre><code class="language-python">mxc_to_http(value: str, width: int, height: int, resize_method: str = &quot;crop&quot;) -&gt; str
  7467. </code></pre>
  7468. <p>Turns a <code>mxc://</code> URL for media content into an HTTP(S) one using the homeserver's
  7469. <code>public_baseurl</code> configuration setting as the URL's base.</p>
  7470. <p>Example: <code>message.sender_avatar_url|mxc_to_http(32,32)</code></p>
  7471. <pre><code class="language-python">localpart_from_email(address: str) -&gt; str
  7472. </code></pre>
  7473. <p>Returns the local part of an email address (e.g. <code>alice</code> in <code>alice@example.com</code>).</p>
  7474. <p>Example: <code>user.email_address|localpart_from_email</code></p>
  7475. <h2 id="email-templates"><a class="header" href="#email-templates">Email templates</a></h2>
  7476. <p>Below are the templates Synapse will look for when generating the content of an email:</p>
  7477. <ul>
  7478. <li><code>notif_mail.html</code> and <code>notif_mail.txt</code>: The contents of email notifications of missed
  7479. events.
  7480. When rendering, this template is given the following variables:
  7481. <ul>
  7482. <li><code>user_display_name</code>: the display name for the user receiving the notification</li>
  7483. <li><code>unsubscribe_link</code>: the link users can click to unsubscribe from email notifications</li>
  7484. <li><code>summary_text</code>: a summary of the notification(s). The text used can be customised
  7485. by configuring the various settings in the <code>email.subjects</code> section of the
  7486. configuration file.</li>
  7487. <li><code>rooms</code>: a list of rooms containing events to include in the email. Each element is
  7488. an object with the following attributes:
  7489. <ul>
  7490. <li><code>title</code>: a human-readable name for the room</li>
  7491. <li><code>hash</code>: a hash of the ID of the room</li>
  7492. <li><code>invite</code>: a boolean, which is <code>True</code> if the room is an invite the user hasn't
  7493. accepted yet, <code>False</code> otherwise</li>
  7494. <li><code>notifs</code>: a list of events, or an empty list if <code>invite</code> is <code>True</code>. Each element
  7495. is an object with the following attributes:
  7496. <ul>
  7497. <li><code>link</code>: a <code>matrix.to</code> link to the event</li>
  7498. <li><code>ts</code>: the time in milliseconds at which the event was received</li>
  7499. <li><code>messages</code>: a list of messages containing one message before the event, the
  7500. message in the event, and one message after the event. Each element is an
  7501. object with the following attributes:
  7502. <ul>
  7503. <li><code>event_type</code>: the type of the event</li>
  7504. <li><code>is_historical</code>: a boolean, which is <code>False</code> if the message is the one
  7505. that triggered the notification, <code>True</code> otherwise</li>
  7506. <li><code>id</code>: the ID of the event</li>
  7507. <li><code>ts</code>: the time in milliseconds at which the event was sent</li>
  7508. <li><code>sender_name</code>: the display name for the event's sender</li>
  7509. <li><code>sender_avatar_url</code>: the avatar URL (as a <code>mxc://</code> URL) for the event's
  7510. sender</li>
  7511. <li><code>sender_hash</code>: a hash of the user ID of the sender</li>
  7512. <li><code>msgtype</code>: the type of the message</li>
  7513. <li><code>body_text_html</code>: html representation of the message</li>
  7514. <li><code>body_text_plain</code>: plaintext representation of the message</li>
  7515. <li><code>image_url</code>: mxc url of an image, when &quot;msgtype&quot; is &quot;m.image&quot;</li>
  7516. </ul>
  7517. </li>
  7518. </ul>
  7519. </li>
  7520. <li><code>link</code>: a <code>matrix.to</code> link to the room</li>
  7521. <li><code>avator_url</code>: url to the room's avator</li>
  7522. </ul>
  7523. </li>
  7524. <li><code>reason</code>: information on the event that triggered the email to be sent. It's an
  7525. object with the following attributes:
  7526. <ul>
  7527. <li><code>room_id</code>: the ID of the room the event was sent in</li>
  7528. <li><code>room_name</code>: a human-readable name for the room the event was sent in</li>
  7529. <li><code>now</code>: the current time in milliseconds</li>
  7530. <li><code>received_at</code>: the time in milliseconds at which the event was received</li>
  7531. <li><code>delay_before_mail_ms</code>: the amount of time in milliseconds Synapse always waits
  7532. before ever emailing about a notification (to give the user a chance to respond
  7533. to other push or notice the window)</li>
  7534. <li><code>last_sent_ts</code>: the time in milliseconds at which a notification was last sent
  7535. for an event in this room</li>
  7536. <li><code>throttle_ms</code>: the minimum amount of time in milliseconds between two
  7537. notifications can be sent for this room</li>
  7538. </ul>
  7539. </li>
  7540. </ul>
  7541. </li>
  7542. <li><code>password_reset.html</code> and <code>password_reset.txt</code>: The contents of password reset emails
  7543. sent by the homeserver.
  7544. When rendering, these templates are given a <code>link</code> variable which contains the link the
  7545. user must click in order to reset their password.</li>
  7546. <li><code>registration.html</code> and <code>registration.txt</code>: The contents of address verification emails
  7547. sent during registration.
  7548. When rendering, these templates are given a <code>link</code> variable which contains the link the
  7549. user must click in order to validate their email address.</li>
  7550. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code>: The contents of address verification emails
  7551. sent when an address is added to a Matrix account.
  7552. When rendering, these templates are given a <code>link</code> variable which contains the link the
  7553. user must click in order to validate their email address.</li>
  7554. </ul>
  7555. <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>
  7556. <p>Below are the templates Synapse will look for when generating pages related to
  7557. registration and password reset:</p>
  7558. <ul>
  7559. <li><code>password_reset_confirmation.html</code>: An HTML page that a user will see when they follow
  7560. the link in the password reset email. The user will be asked to confirm the action
  7561. before their password is reset.
  7562. When rendering, this template is given the following variables:
  7563. <ul>
  7564. <li><code>sid</code>: the session ID for the password reset</li>
  7565. <li><code>token</code>: the token for the password reset</li>
  7566. <li><code>client_secret</code>: the client secret for the password reset</li>
  7567. </ul>
  7568. </li>
  7569. <li><code>password_reset_success.html</code> and <code>password_reset_failure.html</code>: HTML pages for success
  7570. and failure that a user will see when they confirm the password reset flow using the
  7571. page above.
  7572. When rendering, <code>password_reset_success.html</code> is given no variable, and
  7573. <code>password_reset_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  7574. for the password reset failure. </li>
  7575. <li><code>registration_success.html</code> and <code>registration_failure.html</code>: HTML pages for success and
  7576. failure that a user will see when they follow the link in an address verification email
  7577. sent during registration.
  7578. When rendering, <code>registration_success.html</code> is given no variable, and
  7579. <code>registration_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  7580. for the registration failure.</li>
  7581. <li><code>add_threepid_success.html</code> and <code>add_threepid_failure.html</code>: HTML pages for success and
  7582. failure that a user will see when they follow the link in an address verification email
  7583. sent when an address is added to a Matrix account.
  7584. When rendering, <code>add_threepid_success.html</code> is given no variable, and
  7585. <code>add_threepid_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  7586. for the registration failure.</li>
  7587. </ul>
  7588. <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>
  7589. <p>Below are the templates Synapse will look for when generating pages related to SSO:</p>
  7590. <ul>
  7591. <li><code>sso_login_idp_picker.html</code>: HTML page to prompt the user to choose an
  7592. Identity Provider during login.
  7593. This is only used if multiple SSO Identity Providers are configured.
  7594. When rendering, this template is given the following variables:
  7595. <ul>
  7596. <li><code>redirect_url</code>: the URL that the user will be redirected to after
  7597. login.</li>
  7598. <li><code>server_name</code>: the homeserver's name.</li>
  7599. <li><code>providers</code>: a list of available Identity Providers. Each element is
  7600. an object with the following attributes:
  7601. <ul>
  7602. <li><code>idp_id</code>: unique identifier for the IdP</li>
  7603. <li><code>idp_name</code>: user-facing name for the IdP</li>
  7604. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  7605. for the IdP</li>
  7606. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  7607. for the brand of the IdP
  7608. The rendered HTML page should contain a form which submits its results
  7609. back as a GET request, with the following query parameters:</li>
  7610. </ul>
  7611. </li>
  7612. <li><code>redirectUrl</code>: the client redirect URI (ie, the <code>redirect_url</code> passed
  7613. to the template)</li>
  7614. <li><code>idp</code>: the 'idp_id' of the chosen IDP.</li>
  7615. </ul>
  7616. </li>
  7617. <li><code>sso_auth_account_details.html</code>: HTML page to prompt new users to enter a
  7618. userid and confirm other details. This is only shown if the
  7619. SSO implementation (with any <code>user_mapping_provider</code>) does not return
  7620. a localpart.
  7621. When rendering, this template is given the following variables:
  7622. <ul>
  7623. <li><code>server_name</code>: the homeserver's name.</li>
  7624. <li><code>idp</code>: details of the SSO Identity Provider that the user logged in
  7625. with: an object with the following attributes:
  7626. <ul>
  7627. <li><code>idp_id</code>: unique identifier for the IdP</li>
  7628. <li><code>idp_name</code>: user-facing name for the IdP</li>
  7629. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  7630. for the IdP</li>
  7631. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  7632. for the brand of the IdP</li>
  7633. </ul>
  7634. </li>
  7635. <li><code>user_attributes</code>: an object containing details about the user that
  7636. we received from the IdP. May have the following attributes:
  7637. <ul>
  7638. <li><code>display_name</code>: the user's display name</li>
  7639. <li><code>emails</code>: a list of email addresses</li>
  7640. <li><code>localpart</code>: the local part of the Matrix user ID to register,
  7641. if <code>localpart_template</code> is set in the mapping provider configuration (empty
  7642. string if not)
  7643. The template should render a form which submits the following fields:</li>
  7644. </ul>
  7645. </li>
  7646. <li><code>username</code>: the localpart of the user's chosen user id</li>
  7647. </ul>
  7648. </li>
  7649. <li><code>sso_new_user_consent.html</code>: HTML page allowing the user to consent to the
  7650. server's terms and conditions. This is only shown for new users, and only if
  7651. <code>user_consent.require_at_registration</code> is set.
  7652. When rendering, this template is given the following variables:
  7653. <ul>
  7654. <li><code>server_name</code>: the homeserver's name.</li>
  7655. <li><code>user_id</code>: the user's matrix proposed ID.</li>
  7656. <li><code>user_profile.display_name</code>: the user's proposed display name, if any.</li>
  7657. <li>consent_version: the version of the terms that the user will be
  7658. shown</li>
  7659. <li><code>terms_url</code>: a link to the page showing the terms.
  7660. The template should render a form which submits the following fields:</li>
  7661. <li><code>accepted_version</code>: the version of the terms accepted by the user
  7662. (ie, 'consent_version' from the input variables).</li>
  7663. </ul>
  7664. </li>
  7665. <li><code>sso_redirect_confirm.html</code>: HTML page for a confirmation step before redirecting back
  7666. to the client with the login token.
  7667. When rendering, this template is given the following variables:
  7668. <ul>
  7669. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  7670. <li><code>display_url</code>: the same as <code>redirect_url</code>, but with the query
  7671. parameters stripped. The intention is to have a
  7672. human-readable URL to show to users, not to use it as
  7673. the final address to redirect to.</li>
  7674. <li><code>server_name</code>: the homeserver's name.</li>
  7675. <li><code>new_user</code>: a boolean indicating whether this is the user's first time
  7676. logging in.</li>
  7677. <li><code>user_id</code>: the user's matrix ID.</li>
  7678. <li><code>user_profile.avatar_url</code>: an MXC URI for the user's avatar, if any.
  7679. <code>None</code> if the user has not set an avatar.</li>
  7680. <li><code>user_profile.display_name</code>: the user's display name. <code>None</code> if the user
  7681. has not set a display name.</li>
  7682. </ul>
  7683. </li>
  7684. <li><code>sso_auth_confirm.html</code>: HTML page which notifies the user that they are authenticating
  7685. to confirm an operation on their account during the user interactive authentication
  7686. process.
  7687. When rendering, this template is given the following variables:
  7688. <ul>
  7689. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  7690. <li><code>description</code>: the operation which the user is being asked to confirm</li>
  7691. <li><code>idp</code>: details of the Identity Provider that we will use to confirm
  7692. the user's identity: an object with the following attributes:
  7693. <ul>
  7694. <li><code>idp_id</code>: unique identifier for the IdP</li>
  7695. <li><code>idp_name</code>: user-facing name for the IdP</li>
  7696. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  7697. for the IdP</li>
  7698. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  7699. for the brand of the IdP</li>
  7700. </ul>
  7701. </li>
  7702. </ul>
  7703. </li>
  7704. <li><code>sso_auth_success.html</code>: HTML page shown after a successful user interactive
  7705. authentication session.
  7706. Note that this page must include the JavaScript which notifies of a successful
  7707. authentication (see https://matrix.org/docs/spec/client_server/r0.6.0#fallback).
  7708. This template has no additional variables.</li>
  7709. <li><code>sso_auth_bad_user.html</code>: HTML page shown after a user-interactive authentication
  7710. session which does not map correctly onto the expected user.
  7711. When rendering, this template is given the following variables:
  7712. <ul>
  7713. <li><code>server_name</code>: the homeserver's name.</li>
  7714. <li><code>user_id_to_verify</code>: the MXID of the user that we are trying to
  7715. validate.</li>
  7716. </ul>
  7717. </li>
  7718. <li><code>sso_account_deactivated.html</code>: HTML page shown during single sign-on if a deactivated
  7719. user (according to Synapse's database) attempts to login.
  7720. This template has no additional variables.</li>
  7721. <li><code>sso_error.html</code>: HTML page to display to users if something goes wrong during the
  7722. OpenID Connect authentication process.
  7723. When rendering, this template is given two variables:
  7724. <ul>
  7725. <li><code>error</code>: the technical name of the error</li>
  7726. <li><code>error_description</code>: a human-readable message for the error</li>
  7727. </ul>
  7728. </li>
  7729. </ul>
  7730. <div style="break-before: page; page-break-before: always;"></div><h1 id="user-authentication"><a class="header" href="#user-authentication">User Authentication</a></h1>
  7731. <p>Synapse supports multiple methods of authenticating users, either out-of-the-box or through custom pluggable
  7732. authentication modules.</p>
  7733. <p>Included in Synapse is support for authenticating users via:</p>
  7734. <ul>
  7735. <li>A username and password.</li>
  7736. <li>An email address and password.</li>
  7737. <li>Single Sign-On through the SAML, Open ID Connect or CAS protocols.</li>
  7738. <li>JSON Web Tokens.</li>
  7739. <li>An administrator's shared secret.</li>
  7740. </ul>
  7741. <p>Synapse can additionally be extended to support custom authentication schemes through optional &quot;password auth provider&quot;
  7742. modules.</p>
  7743. <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>
  7744. <p>Synapse supports single sign-on through the SAML, Open ID Connect or CAS protocols.
  7745. LDAP and other login methods are supported through first and third-party password
  7746. auth provider modules.</p>
  7747. <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>
  7748. <p>Synapse can be configured to use an OpenID Connect Provider (OP) for
  7749. authentication, instead of its own local password database.</p>
  7750. <p>Any OP should work with Synapse, as long as it supports the authorization code
  7751. flow. There are a few options for that:</p>
  7752. <ul>
  7753. <li>
  7754. <p>start a local OP. Synapse has been tested with <a href="https://www.ory.sh/docs/hydra/">Hydra</a> and
  7755. <a href="https://github.com/dexidp/dex">Dex</a>. Note that for an OP to work, it should be served under a
  7756. secure (HTTPS) origin. A certificate signed with a self-signed, locally
  7757. trusted CA should work. In that case, start Synapse with a <code>SSL_CERT_FILE</code>
  7758. environment variable set to the path of the CA.</p>
  7759. </li>
  7760. <li>
  7761. <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
  7762. <a href="https://www.okta.com/">Okta</a>. Synapse has been tested with Auth0 and Google.</p>
  7763. </li>
  7764. </ul>
  7765. <p>It may also be possible to use other OAuth2 providers which provide the
  7766. <a href="https://tools.ietf.org/html/rfc6749#section-4.1">authorization code grant type</a>,
  7767. such as <a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">Github</a>.</p>
  7768. <h2 id="preparing-synapse"><a class="header" href="#preparing-synapse">Preparing Synapse</a></h2>
  7769. <p>The OpenID integration in Synapse uses the
  7770. <a href="https://pypi.org/project/Authlib/"><code>authlib</code></a> library, which must be installed
  7771. as follows:</p>
  7772. <ul>
  7773. <li>
  7774. <p>The relevant libraries are included in the Docker images and Debian packages
  7775. provided by <code>matrix.org</code> so no further action is needed.</p>
  7776. </li>
  7777. <li>
  7778. <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>
  7779. </li>
  7780. <li>
  7781. <p>For other installation mechanisms, see the documentation provided by the
  7782. maintainer.</p>
  7783. </li>
  7784. </ul>
  7785. <p>To enable the OpenID integration, you should then add a section to the <code>oidc_providers</code>
  7786. setting in your configuration file.
  7787. See the <a href="usage/configuration/config_documentation.html#oidc_providers">configuration manual</a> for some sample settings, as well as
  7788. the text below for example configurations for specific providers.</p>
  7789. <h2 id="oidc-back-channel-logout"><a class="header" href="#oidc-back-channel-logout">OIDC Back-Channel Logout</a></h2>
  7790. <p>Synapse supports receiving <a href="https://openid.net/specs/openid-connect-backchannel-1_0.html">OpenID Connect Back-Channel Logout</a> notifications.</p>
  7791. <p>This lets the OpenID Connect Provider notify Synapse when a user logs out, so that Synapse can end that user session.
  7792. 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>
  7793. <h2 id="sample-configs"><a class="header" href="#sample-configs">Sample configs</a></h2>
  7794. <p>Here are a few configs for providers that should work with Synapse.</p>
  7795. <h3 id="microsoft-azure-active-directory"><a class="header" href="#microsoft-azure-active-directory">Microsoft Azure Active Directory</a></h3>
  7796. <p>Azure AD can act as an OpenID Connect Provider. Register a new application under
  7797. <em>App registrations</em> in the Azure AD management console. The RedirectURI for your
  7798. application should point to your matrix server:
  7799. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  7800. <p>Go to <em>Certificates &amp; secrets</em> and register a new client secret. Make note of your
  7801. Directory (tenant) ID as it will be used in the Azure links.
  7802. Edit your Synapse config file and change the <code>oidc_config</code> section:</p>
  7803. <pre><code class="language-yaml">oidc_providers:
  7804. - idp_id: microsoft
  7805. idp_name: Microsoft
  7806. issuer: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/v2.0&quot;
  7807. client_id: &quot;&lt;client id&gt;&quot;
  7808. client_secret: &quot;&lt;client secret&gt;&quot;
  7809. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7810. authorization_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/authorize&quot;
  7811. token_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/token&quot;
  7812. userinfo_endpoint: &quot;https://graph.microsoft.com/oidc/userinfo&quot;
  7813. user_mapping_provider:
  7814. config:
  7815. localpart_template: &quot;{{ user.preferred_username.split('@')[0] }}&quot;
  7816. display_name_template: &quot;{{ user.name }}&quot;
  7817. </code></pre>
  7818. <h3 id="apple"><a class="header" href="#apple">Apple</a></h3>
  7819. <p>Configuring &quot;Sign in with Apple&quot; (SiWA) requires an Apple Developer account.</p>
  7820. <p>You will need to create a new &quot;Services ID&quot; for SiWA, and create and download a
  7821. private key with &quot;SiWA&quot; enabled.</p>
  7822. <p>As well as the private key file, you will need:</p>
  7823. <ul>
  7824. <li>Client ID: the &quot;identifier&quot; you gave the &quot;Services ID&quot;</li>
  7825. <li>Team ID: a 10-character ID associated with your developer account.</li>
  7826. <li>Key ID: the 10-character identifier for the key.</li>
  7827. </ul>
  7828. <p><a href="https://help.apple.com/developer-account/?lang=en#/dev77c875b7e">Apple's developer documentation</a>
  7829. has more information on setting up SiWA.</p>
  7830. <p>The synapse config will look like this:</p>
  7831. <pre><code class="language-yaml"> - idp_id: apple
  7832. idp_name: Apple
  7833. issuer: &quot;https://appleid.apple.com&quot;
  7834. client_id: &quot;your-client-id&quot; # Set to the &quot;identifier&quot; for your &quot;ServicesID&quot;
  7835. client_auth_method: &quot;client_secret_post&quot;
  7836. client_secret_jwt_key:
  7837. key_file: &quot;/path/to/AuthKey_KEYIDCODE.p8&quot; # point to your key file
  7838. jwt_header:
  7839. alg: ES256
  7840. kid: &quot;KEYIDCODE&quot; # Set to the 10-char Key ID
  7841. jwt_payload:
  7842. iss: TEAMIDCODE # Set to the 10-char Team ID
  7843. scopes: [&quot;name&quot;, &quot;email&quot;, &quot;openid&quot;]
  7844. authorization_endpoint: https://appleid.apple.com/auth/authorize?response_mode=form_post
  7845. user_mapping_provider:
  7846. config:
  7847. email_template: &quot;{{ user.email }}&quot;
  7848. </code></pre>
  7849. <h3 id="auth0"><a class="header" href="#auth0">Auth0</a></h3>
  7850. <p><a href="https://auth0.com/">Auth0</a> is a hosted SaaS IdP solution.</p>
  7851. <ol>
  7852. <li>
  7853. <p>Create a regular web application for Synapse</p>
  7854. </li>
  7855. <li>
  7856. <p>Set the Allowed Callback URLs to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  7857. </li>
  7858. <li>
  7859. <p>Add a rule with any name to add the <code>preferred_username</code> claim.
  7860. (See https://auth0.com/docs/customize/rules/create-rules for more information on how to create rules.)</p>
  7861. <details>
  7862. <summary>Code sample</summary>
  7863. <pre><code class="language-js">function addPersistenceAttribute(user, context, callback) {
  7864. user.user_metadata = user.user_metadata || {};
  7865. user.user_metadata.preferred_username = user.user_metadata.preferred_username || user.user_id;
  7866. context.idToken.preferred_username = user.user_metadata.preferred_username;
  7867. auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
  7868. .then(function(){
  7869. callback(null, user, context);
  7870. })
  7871. .catch(function(err){
  7872. callback(err);
  7873. });
  7874. }
  7875. </code></pre>
  7876. </li>
  7877. </ol>
  7878. </details>
  7879. <p>Synapse config:</p>
  7880. <pre><code class="language-yaml">oidc_providers:
  7881. - idp_id: auth0
  7882. idp_name: Auth0
  7883. issuer: &quot;https://your-tier.eu.auth0.com/&quot; # TO BE FILLED
  7884. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7885. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7886. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7887. user_mapping_provider:
  7888. config:
  7889. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7890. display_name_template: &quot;{{ user.name }}&quot;
  7891. </code></pre>
  7892. <h3 id="authentik"><a class="header" href="#authentik">Authentik</a></h3>
  7893. <p><a href="https://goauthentik.io/">Authentik</a> is an open-source IdP solution.</p>
  7894. <ol>
  7895. <li>Create a provider in Authentik, with type OAuth2/OpenID.</li>
  7896. <li>The parameters are:</li>
  7897. </ol>
  7898. <ul>
  7899. <li>Client Type: Confidential</li>
  7900. <li>JWT Algorithm: RS256</li>
  7901. <li>Scopes: OpenID, Email and Profile</li>
  7902. <li>RSA Key: Select any available key</li>
  7903. <li>Redirect URIs: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7904. </ul>
  7905. <ol start="3">
  7906. <li>Create an application for synapse in Authentik and link it to the provider.</li>
  7907. <li>Note the slug of your application, Client ID and Client Secret.</li>
  7908. </ol>
  7909. <p>Note: RSA keys must be used for signing for Authentik, ECC keys do not work.</p>
  7910. <p>Synapse config:</p>
  7911. <pre><code class="language-yaml">oidc_providers:
  7912. - idp_id: authentik
  7913. idp_name: authentik
  7914. discover: true
  7915. issuer: &quot;https://your.authentik.example.org/application/o/your-app-slug/&quot; # TO BE FILLED: domain and slug
  7916. client_id: &quot;your client id&quot; # TO BE FILLED
  7917. client_secret: &quot;your client secret&quot; # TO BE FILLED
  7918. scopes:
  7919. - &quot;openid&quot;
  7920. - &quot;profile&quot;
  7921. - &quot;email&quot;
  7922. user_mapping_provider:
  7923. config:
  7924. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7925. 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.
  7926. </code></pre>
  7927. <h3 id="dex"><a class="header" href="#dex">Dex</a></h3>
  7928. <p><a href="https://github.com/dexidp/dex">Dex</a> is a simple, open-source OpenID Connect Provider.
  7929. Although it is designed to help building a full-blown provider with an
  7930. external database, it can be configured with static passwords in a config file.</p>
  7931. <p>Follow the <a href="https://dexidp.io/docs/getting-started/">Getting Started guide</a>
  7932. to install Dex.</p>
  7933. <p>Edit <code>examples/config-dev.yaml</code> config file from the Dex repo to add a client:</p>
  7934. <pre><code class="language-yaml">staticClients:
  7935. - id: synapse
  7936. secret: secret
  7937. redirectURIs:
  7938. - '[synapse public baseurl]/_synapse/client/oidc/callback'
  7939. name: 'Synapse'
  7940. </code></pre>
  7941. <p>Run with <code>dex serve examples/config-dev.yaml</code>.</p>
  7942. <p>Synapse config:</p>
  7943. <pre><code class="language-yaml">oidc_providers:
  7944. - idp_id: dex
  7945. idp_name: &quot;My Dex server&quot;
  7946. skip_verification: true # This is needed as Dex is served on an insecure endpoint
  7947. issuer: &quot;http://127.0.0.1:5556/dex&quot;
  7948. client_id: &quot;synapse&quot;
  7949. client_secret: &quot;secret&quot;
  7950. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7951. user_mapping_provider:
  7952. config:
  7953. localpart_template: &quot;{{ user.name }}&quot;
  7954. display_name_template: &quot;{{ user.name|capitalize }}&quot;
  7955. </code></pre>
  7956. <h3 id="django-oauth-toolkit"><a class="header" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h3>
  7957. <p><a href="https://github.com/jazzband/django-oauth-toolkit">django-oauth-toolkit</a> is a
  7958. Django application providing out of the box all the endpoints, data and logic
  7959. needed to add OAuth2 capabilities to your Django projects. It supports
  7960. <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html">OpenID Connect too</a>.</p>
  7961. <p>Configuration on Django's side:</p>
  7962. <ol>
  7963. <li>Add an application: <code>https://example.com/admin/oauth2_provider/application/add/</code> and choose parameters like this:</li>
  7964. </ol>
  7965. <ul>
  7966. <li><code>Redirect uris</code>: <code>https://synapse.example.com/_synapse/client/oidc/callback</code></li>
  7967. <li><code>Client type</code>: <code>Confidential</code></li>
  7968. <li><code>Authorization grant type</code>: <code>Authorization code</code></li>
  7969. <li><code>Algorithm</code>: <code>HMAC with SHA-2 256</code></li>
  7970. </ul>
  7971. <ol start="2">
  7972. <li>
  7973. <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>
  7974. <details>
  7975. <summary>Code sample</summary>
  7976. <pre><code class="language-python">class CustomOAuth2Validator(OAuth2Validator):
  7977. def get_additional_claims(self, request):
  7978. return {
  7979. &quot;sub&quot;: request.user.email,
  7980. &quot;email&quot;: request.user.email,
  7981. &quot;first_name&quot;: request.user.first_name,
  7982. &quot;last_name&quot;: request.user.last_name,
  7983. }
  7984. </code></pre>
  7985. </details>
  7986. </li>
  7987. </ol>
  7988. <p>Your synapse config is then:</p>
  7989. <pre><code class="language-yaml">oidc_providers:
  7990. - idp_id: django_example
  7991. idp_name: &quot;Django Example&quot;
  7992. issuer: &quot;https://example.com/o/&quot;
  7993. client_id: &quot;your-client-id&quot; # CHANGE ME
  7994. client_secret: &quot;your-client-secret&quot; # CHANGE ME
  7995. scopes: [&quot;openid&quot;]
  7996. user_profile_method: &quot;userinfo_endpoint&quot; # needed because oauth-toolkit does not include user information in the authorization response
  7997. user_mapping_provider:
  7998. config:
  7999. localpart_template: &quot;{{ user.email.split('@')[0] }}&quot;
  8000. display_name_template: &quot;{{ user.first_name }} {{ user.last_name }}&quot;
  8001. email_template: &quot;{{ user.email }}&quot;
  8002. </code></pre>
  8003. <h3 id="facebook"><a class="header" href="#facebook">Facebook</a></h3>
  8004. <ol start="0">
  8005. <li>You will need a Facebook developer account. You can register for one
  8006. <a href="https://developers.facebook.com/async/registration/">here</a>.</li>
  8007. <li>On the <a href="https://developers.facebook.com/apps/">apps</a> page of the developer
  8008. console, &quot;Create App&quot;, and choose &quot;Build Connected Experiences&quot;.</li>
  8009. <li>Once the app is created, add &quot;Facebook Login&quot; and choose &quot;Web&quot;. You don't
  8010. need to go through the whole form here.</li>
  8011. <li>In the left-hand menu, open &quot;Products&quot;/&quot;Facebook Login&quot;/&quot;Settings&quot;.
  8012. <ul>
  8013. <li>Add <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> as an OAuth Redirect
  8014. URL.</li>
  8015. </ul>
  8016. </li>
  8017. <li>In the left-hand menu, open &quot;Settings/Basic&quot;. Here you can copy the &quot;App ID&quot;
  8018. and &quot;App Secret&quot; for use below.</li>
  8019. </ol>
  8020. <p>Synapse config:</p>
  8021. <pre><code class="language-yaml"> - idp_id: facebook
  8022. idp_name: Facebook
  8023. idp_brand: &quot;facebook&quot; # optional: styling hint for clients
  8024. discover: false
  8025. issuer: &quot;https://www.facebook.com&quot;
  8026. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8027. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8028. scopes: [&quot;openid&quot;, &quot;email&quot;]
  8029. authorization_endpoint: &quot;https://facebook.com/dialog/oauth&quot;
  8030. token_endpoint: &quot;https://graph.facebook.com/v9.0/oauth/access_token&quot;
  8031. jwks_uri: &quot;https://www.facebook.com/.well-known/oauth/openid/jwks/&quot;
  8032. user_mapping_provider:
  8033. config:
  8034. display_name_template: &quot;{{ user.name }}&quot;
  8035. email_template: &quot;{{ user.email }}&quot;
  8036. </code></pre>
  8037. <p>Relevant documents:</p>
  8038. <ul>
  8039. <li><a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow">Manually Build a Login Flow</a></li>
  8040. <li><a href="https://developers.facebook.com/docs/graph-api/using-graph-api/">Using Facebook's Graph API</a></li>
  8041. <li><a href="https://developers.facebook.com/docs/graph-api/reference/user">Reference to the User endpoint</a></li>
  8042. </ul>
  8043. <p>Facebook do have an <a href="https://www.facebook.com/.well-known/openid-configuration">OIDC discovery endpoint</a>,
  8044. but it has a <code>response_types_supported</code> which excludes &quot;code&quot; (which we rely on, and
  8045. is even mentioned in their <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login">documentation</a>),
  8046. so we have to disable discovery and configure the URIs manually.</p>
  8047. <h3 id="github"><a class="header" href="#github">GitHub</a></h3>
  8048. <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
  8049. just a regular OAuth2 provider.</p>
  8050. <p>The <a href="https://developer.github.com/v3/users/#get-the-authenticated-user"><code>/user</code> API endpoint</a>
  8051. can be used to retrieve information on the authenticated user. As the Synapse
  8052. login mechanism needs an attribute to uniquely identify users, and that endpoint
  8053. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  8054. <ol>
  8055. <li>Create a new OAuth application: <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a>.</li>
  8056. <li>Set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  8057. </ol>
  8058. <p>Synapse config:</p>
  8059. <pre><code class="language-yaml">oidc_providers:
  8060. - idp_id: github
  8061. idp_name: Github
  8062. idp_brand: &quot;github&quot; # optional: styling hint for clients
  8063. discover: false
  8064. issuer: &quot;https://github.com/&quot;
  8065. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8066. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8067. authorization_endpoint: &quot;https://github.com/login/oauth/authorize&quot;
  8068. token_endpoint: &quot;https://github.com/login/oauth/access_token&quot;
  8069. userinfo_endpoint: &quot;https://api.github.com/user&quot;
  8070. scopes: [&quot;read:user&quot;]
  8071. user_mapping_provider:
  8072. config:
  8073. subject_claim: &quot;id&quot;
  8074. localpart_template: &quot;{{ user.login }}&quot;
  8075. display_name_template: &quot;{{ user.name }}&quot;
  8076. </code></pre>
  8077. <h3 id="gitlab"><a class="header" href="#gitlab">GitLab</a></h3>
  8078. <ol>
  8079. <li>Create a <a href="https://gitlab.com/profile/applications">new application</a>.</li>
  8080. <li>Add the <code>read_user</code> and <code>openid</code> scopes.</li>
  8081. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8082. </ol>
  8083. <p>Synapse config:</p>
  8084. <pre><code class="language-yaml">oidc_providers:
  8085. - idp_id: gitlab
  8086. idp_name: Gitlab
  8087. idp_brand: &quot;gitlab&quot; # optional: styling hint for clients
  8088. issuer: &quot;https://gitlab.com/&quot;
  8089. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8090. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8091. client_auth_method: &quot;client_secret_post&quot;
  8092. scopes: [&quot;openid&quot;, &quot;read_user&quot;]
  8093. user_profile_method: &quot;userinfo_endpoint&quot;
  8094. user_mapping_provider:
  8095. config:
  8096. localpart_template: '{{ user.nickname }}'
  8097. display_name_template: '{{ user.name }}'
  8098. </code></pre>
  8099. <h3 id="gitea"><a class="header" href="#gitea">Gitea</a></h3>
  8100. <p>Gitea is, like Github, not an OpenID provider, but just an OAuth2 provider.</p>
  8101. <p>The <a href="https://try.gitea.io/api/swagger#/user/userGetCurrent"><code>/user</code> API endpoint</a>
  8102. can be used to retrieve information on the authenticated user. As the Synapse
  8103. login mechanism needs an attribute to uniquely identify users, and that endpoint
  8104. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  8105. <ol>
  8106. <li>Create a new application.</li>
  8107. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8108. </ol>
  8109. <p>Synapse config:</p>
  8110. <pre><code class="language-yaml">oidc_providers:
  8111. - idp_id: gitea
  8112. idp_name: Gitea
  8113. discover: false
  8114. issuer: &quot;https://your-gitea.com/&quot;
  8115. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8116. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8117. client_auth_method: client_secret_post
  8118. scopes: [] # Gitea doesn't support Scopes
  8119. authorization_endpoint: &quot;https://your-gitea.com/login/oauth/authorize&quot;
  8120. token_endpoint: &quot;https://your-gitea.com/login/oauth/access_token&quot;
  8121. userinfo_endpoint: &quot;https://your-gitea.com/api/v1/user&quot;
  8122. user_mapping_provider:
  8123. config:
  8124. subject_claim: &quot;id&quot;
  8125. localpart_template: &quot;{{ user.login }}&quot;
  8126. display_name_template: &quot;{{ user.full_name }}&quot;
  8127. </code></pre>
  8128. <h3 id="google"><a class="header" href="#google">Google</a></h3>
  8129. <p><a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a> is an OpenID certified authentication and authorisation provider.</p>
  8130. <ol>
  8131. <li>Set up a project in the Google API Console (see
  8132. <a href="https://developers.google.com/identity/protocols/oauth2/openid-connect#appsetup">documentation</a>).</li>
  8133. <li>Add an &quot;OAuth Client ID&quot; for a Web Application under &quot;Credentials&quot;.</li>
  8134. <li>Copy the Client ID and Client Secret, and add the following to your synapse config:
  8135. <pre><code class="language-yaml">oidc_providers:
  8136. - idp_id: google
  8137. idp_name: Google
  8138. idp_brand: &quot;google&quot; # optional: styling hint for clients
  8139. issuer: &quot;https://accounts.google.com/&quot;
  8140. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8141. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8142. scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;] # email is optional, read below
  8143. user_mapping_provider:
  8144. config:
  8145. localpart_template: &quot;{{ user.given_name|lower }}&quot;
  8146. display_name_template: &quot;{{ user.name }}&quot;
  8147. email_template: &quot;{{ user.email }}&quot; # needs &quot;email&quot; in scopes above
  8148. </code></pre>
  8149. </li>
  8150. <li>Back in the Google console, add this Authorized redirect URI: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  8151. </ol>
  8152. <h3 id="keycloak"><a class="header" href="#keycloak">Keycloak</a></h3>
  8153. <p><a href="https://www.keycloak.org/docs/latest/server_admin/#sso-protocols">Keycloak</a> is an opensource IdP maintained by Red Hat.</p>
  8154. <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.
  8155. 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>
  8156. <p>Follow the <a href="https://www.keycloak.org/guides">Getting Started Guide</a> to install Keycloak and set up a realm.</p>
  8157. <ol>
  8158. <li>
  8159. <p>Click <code>Clients</code> in the sidebar and click <code>Create</code></p>
  8160. </li>
  8161. <li>
  8162. <p>Fill in the fields as below:</p>
  8163. </li>
  8164. </ol>
  8165. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  8166. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  8167. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  8168. </tbody></table>
  8169. <ol start="3">
  8170. <li>Click <code>Save</code></li>
  8171. <li>Fill in the fields as below:</li>
  8172. </ol>
  8173. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  8174. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  8175. <tr><td>Enabled</td><td><code>On</code></td></tr>
  8176. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  8177. <tr><td>Access Type</td><td><code>confidential</code></td></tr>
  8178. <tr><td>Valid Redirect URIs</td><td><code>[synapse public baseurl]/_synapse/client/oidc/callback</code></td></tr>
  8179. <tr><td>Backchannel Logout URL (optional)</td><td> <code>[synapse public baseurl]/_synapse/client/oidc/backchannel_logout</code></td></tr>
  8180. <tr><td>Backchannel Logout Session Required (optional)</td><td> <code>On</code></td></tr>
  8181. </tbody></table>
  8182. <ol start="5">
  8183. <li>Click <code>Save</code></li>
  8184. <li>On the Credentials tab, update the fields:</li>
  8185. </ol>
  8186. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  8187. <tr><td>Client Authenticator</td><td><code>Client ID and Secret</code></td></tr>
  8188. </tbody></table>
  8189. <ol start="7">
  8190. <li>Click <code>Regenerate Secret</code></li>
  8191. <li>Copy Secret</li>
  8192. </ol>
  8193. <pre><code class="language-yaml">oidc_providers:
  8194. - idp_id: keycloak
  8195. idp_name: &quot;My KeyCloak server&quot;
  8196. issuer: &quot;https://127.0.0.1:8443/realms/{realm_name}&quot;
  8197. client_id: &quot;synapse&quot;
  8198. client_secret: &quot;copy secret generated from above&quot;
  8199. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  8200. user_mapping_provider:
  8201. config:
  8202. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8203. display_name_template: &quot;{{ user.name }}&quot;
  8204. backchannel_logout_enabled: true # Optional
  8205. </code></pre>
  8206. <h3 id="lemonldap"><a class="header" href="#lemonldap">LemonLDAP</a></h3>
  8207. <p><a href="https://lemonldap-ng.org/">LemonLDAP::NG</a> is an open-source IdP solution.</p>
  8208. <ol>
  8209. <li>Create an OpenID Connect Relying Parties in LemonLDAP::NG</li>
  8210. <li>The parameters are:</li>
  8211. </ol>
  8212. <ul>
  8213. <li>Client ID under the basic menu of the new Relying Parties (<code>Options &gt; Basic &gt; Client ID</code>)</li>
  8214. <li>Client secret (<code>Options &gt; Basic &gt; Client secret</code>)</li>
  8215. <li>JWT Algorithm: RS256 within the security menu of the new Relying Parties
  8216. (<code>Options &gt; Security &gt; ID Token signature algorithm</code> and <code>Options &gt; Security &gt; Access Token signature algorithm</code>)</li>
  8217. <li>Scopes: OpenID, Email and Profile</li>
  8218. <li>Allowed redirection addresses for login (<code>Options &gt; Basic &gt; Allowed redirection addresses for login</code> ) :
  8219. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8220. </ul>
  8221. <p>Synapse config:</p>
  8222. <pre><code class="language-yaml">oidc_providers:
  8223. - idp_id: lemonldap
  8224. idp_name: lemonldap
  8225. discover: true
  8226. issuer: &quot;https://auth.example.org/&quot; # TO BE FILLED: replace with your domain
  8227. client_id: &quot;your client id&quot; # TO BE FILLED
  8228. client_secret: &quot;your client secret&quot; # TO BE FILLED
  8229. scopes:
  8230. - &quot;openid&quot;
  8231. - &quot;profile&quot;
  8232. - &quot;email&quot;
  8233. user_mapping_provider:
  8234. config:
  8235. localpart_template: &quot;{{ user.preferred_username }}}&quot;
  8236. # 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.
  8237. display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot;
  8238. </code></pre>
  8239. <h3 id="mastodon"><a class="header" href="#mastodon">Mastodon</a></h3>
  8240. <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>
  8241. <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>
  8242. <p>This example assumes that:</p>
  8243. <ul>
  8244. <li>the Mastodon instance website URL is <code>https://your.mastodon.instance.url</code>, and</li>
  8245. <li>Synapse will be registered as an app named <code>my_synapse_app</code>.</li>
  8246. </ul>
  8247. <p>Send the following request, substituting the value of <code>synapse_public_baseurl</code> from your Synapse installation.</p>
  8248. <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
  8249. </code></pre>
  8250. <p>You should receive a response similar to the following. Make sure to save it.</p>
  8251. <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;}
  8252. </code></pre>
  8253. <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>
  8254. <pre><code class="language-yaml">oidc_providers:
  8255. - idp_id: my_mastodon
  8256. idp_name: &quot;Mastodon Instance Example&quot;
  8257. discover: false
  8258. issuer: &quot;https://your.mastodon.instance.url/@admin&quot;
  8259. client_id: &quot;someclientid_123&quot;
  8260. client_secret: &quot;someclientsecret_123&quot;
  8261. authorization_endpoint: &quot;https://your.mastodon.instance.url/oauth/authorize&quot;
  8262. token_endpoint: &quot;https://your.mastodon.instance.url/oauth/token&quot;
  8263. userinfo_endpoint: &quot;https://your.mastodon.instance.url/api/v1/accounts/verify_credentials&quot;
  8264. scopes: [&quot;read&quot;]
  8265. user_mapping_provider:
  8266. config:
  8267. subject_template: &quot;{{ user.id }}&quot;
  8268. localpart_template: &quot;{{ user.username }}&quot;
  8269. display_name_template: &quot;{{ user.display_name }}&quot;
  8270. </code></pre>
  8271. <p>Note that the fields <code>client_id</code> and <code>client_secret</code> are taken from the CURL response above.</p>
  8272. <h3 id="shibboleth-with-oidc-plugin"><a class="header" href="#shibboleth-with-oidc-plugin">Shibboleth with OIDC Plugin</a></h3>
  8273. <p><a href="https://www.shibboleth.net/">Shibboleth</a> is an open Standard IdP solution widely used by Universities.</p>
  8274. <ol>
  8275. <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>
  8276. <li>Create a new config on the IdP Side, ensure that the <code>client_id</code> and <code>client_secret</code>
  8277. are randomly generated data.</li>
  8278. </ol>
  8279. <pre><code class="language-json">{
  8280. &quot;client_id&quot;: &quot;SOME-CLIENT-ID&quot;,
  8281. &quot;client_secret&quot;: &quot;SOME-SUPER-SECRET-SECRET&quot;,
  8282. &quot;response_types&quot;: [&quot;code&quot;],
  8283. &quot;grant_types&quot;: [&quot;authorization_code&quot;],
  8284. &quot;scope&quot;: &quot;openid profile email&quot;,
  8285. &quot;redirect_uris&quot;: [&quot;https://[synapse public baseurl]/_synapse/client/oidc/callback&quot;]
  8286. }
  8287. </code></pre>
  8288. <p>Synapse config:</p>
  8289. <pre><code class="language-yaml">oidc_providers:
  8290. # Shibboleth IDP
  8291. #
  8292. - idp_id: shibboleth
  8293. idp_name: &quot;Shibboleth Login&quot;
  8294. discover: true
  8295. issuer: &quot;https://YOUR-IDP-URL.TLD&quot;
  8296. client_id: &quot;YOUR_CLIENT_ID&quot;
  8297. client_secret: &quot;YOUR-CLIENT-SECRECT-FROM-YOUR-IDP&quot;
  8298. scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;]
  8299. allow_existing_users: true
  8300. user_profile_method: &quot;userinfo_endpoint&quot;
  8301. user_mapping_provider:
  8302. config:
  8303. subject_claim: &quot;sub&quot;
  8304. localpart_template: &quot;{{ user.sub.split('@')[0] }}&quot;
  8305. display_name_template: &quot;{{ user.name }}&quot;
  8306. email_template: &quot;{{ user.email }}&quot;
  8307. </code></pre>
  8308. <h3 id="twitch"><a class="header" href="#twitch">Twitch</a></h3>
  8309. <ol>
  8310. <li>Setup a developer account on <a href="https://dev.twitch.tv/">Twitch</a></li>
  8311. <li>Obtain the OAuth 2.0 credentials by <a href="https://dev.twitch.tv/console/apps/">creating an app</a></li>
  8312. <li>Add this OAuth Redirect URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8313. </ol>
  8314. <p>Synapse config:</p>
  8315. <pre><code class="language-yaml">oidc_providers:
  8316. - idp_id: twitch
  8317. idp_name: Twitch
  8318. issuer: &quot;https://id.twitch.tv/oauth2/&quot;
  8319. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8320. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8321. client_auth_method: &quot;client_secret_post&quot;
  8322. user_mapping_provider:
  8323. config:
  8324. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8325. display_name_template: &quot;{{ user.name }}&quot;
  8326. </code></pre>
  8327. <h3 id="twitter"><a class="header" href="#twitter">Twitter</a></h3>
  8328. <p><em>Using Twitter as an identity provider requires using Synapse 1.75.0 or later.</em></p>
  8329. <ol>
  8330. <li>Setup a developer account on <a href="https://developer.twitter.com/en/portal/dashboard">Twitter</a></li>
  8331. <li>Create a project &amp; app.</li>
  8332. <li>Enable user authentication and under &quot;Type of App&quot; choose &quot;Web App, Automated App or Bot&quot;.</li>
  8333. <li>Under &quot;App info&quot; set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  8334. <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>
  8335. </ol>
  8336. <p>Synapse config:</p>
  8337. <pre><code class="language-yaml">oidc_providers:
  8338. - idp_id: twitter
  8339. idp_name: Twitter
  8340. idp_brand: &quot;twitter&quot; # optional: styling hint for clients
  8341. discover: false # Twitter is not OpenID compliant.
  8342. issuer: &quot;https://twitter.com/&quot;
  8343. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8344. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8345. pkce_method: &quot;always&quot;
  8346. # offline.access providers refresh tokens, tweet.read and users.read needed for userinfo request.
  8347. scopes: [&quot;offline.access&quot;, &quot;tweet.read&quot;, &quot;users.read&quot;]
  8348. authorization_endpoint: https://twitter.com/i/oauth2/authorize
  8349. token_endpoint: https://api.twitter.com/2/oauth2/token
  8350. userinfo_endpoint: https://api.twitter.com/2/users/me?user.fields=profile_image_url
  8351. user_mapping_provider:
  8352. config:
  8353. subject_template: &quot;{{ user.data.id }}&quot;
  8354. localpart_template: &quot;{{ user.data.username }}&quot;
  8355. display_name_template: &quot;{{ user.data.name }}&quot;
  8356. picture_template: &quot;{{ user.data.profile_image_url }}&quot;
  8357. </code></pre>
  8358. <h3 id="xwiki"><a class="header" href="#xwiki">XWiki</a></h3>
  8359. <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>
  8360. <p>Synapse config:</p>
  8361. <pre><code class="language-yaml">oidc_providers:
  8362. - idp_id: xwiki
  8363. idp_name: &quot;XWiki&quot;
  8364. issuer: &quot;https://myxwikihost/xwiki/oidc/&quot;
  8365. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8366. client_auth_method: none
  8367. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  8368. user_profile_method: &quot;userinfo_endpoint&quot;
  8369. user_mapping_provider:
  8370. config:
  8371. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8372. display_name_template: &quot;{{ user.name }}&quot;
  8373. </code></pre>
  8374. <div style="break-before: page; page-break-before: always;"></div><h1 id="saml"><a class="header" href="#saml">SAML</a></h1>
  8375. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion
  8376. Markup Language</a>
  8377. (SAML) protocol natively.</p>
  8378. <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
  8379. file</a> for more details.</p>
  8380. <div style="break-before: page; page-break-before: always;"></div><h1 id="cas"><a class="header" href="#cas">CAS</a></h1>
  8381. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Central_Authentication_Service">Central Authentication
  8382. Service protocol</a>
  8383. (CAS) natively.</p>
  8384. <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>
  8385. sections of the configuration manual for more details.</p>
  8386. <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>
  8387. <p>A mapping provider is a Python class (loaded via a Python module) that
  8388. works out how to map attributes of a SSO response to Matrix-specific
  8389. user attributes. Details such as user ID localpart, displayname, and even avatar
  8390. URLs are all things that can be mapped from talking to a SSO service.</p>
  8391. <p>As an example, a SSO service may return the email address
  8392. &quot;john.smith@example.com&quot; for a user, whereas Synapse will need to figure out how
  8393. to turn that into a displayname when creating a Matrix user for this individual.
  8394. It may choose <code>John Smith</code>, or <code>Smith, John [Example.com]</code> or any number of
  8395. variations. As each Synapse configuration may want something different, this is
  8396. where SAML mapping providers come into play.</p>
  8397. <p>SSO mapping providers are currently supported for OpenID and SAML SSO
  8398. configurations. Please see the details below for how to implement your own.</p>
  8399. <p>It is up to the mapping provider whether the user should be assigned a predefined
  8400. Matrix ID based on the SSO attributes, or if the user should be allowed to
  8401. choose their own username.</p>
  8402. <p>In the first case - where users are automatically allocated a Matrix ID - it is
  8403. the responsibility of the mapping provider to normalise the SSO attributes and
  8404. map them to a valid Matrix ID. The <a href="https://spec.matrix.org/latest/appendices/#user-identifiers">specification for Matrix
  8405. IDs</a> has some
  8406. information about what is considered valid.</p>
  8407. <p>If the mapping provider does not assign a Matrix ID, then Synapse will
  8408. automatically serve an HTML page allowing the user to pick their own username.</p>
  8409. <p>External mapping providers are provided to Synapse in the form of an external
  8410. Python module. You can retrieve this module from <a href="https://pypi.org">PyPI</a> or elsewhere,
  8411. but it must be importable via Synapse (e.g. it must be in the same virtualenv
  8412. as Synapse). The Synapse config is then modified to point to the mapping provider
  8413. (and optionally provide additional configuration for it).</p>
  8414. <h2 id="openid-mapping-providers"><a class="header" href="#openid-mapping-providers">OpenID Mapping Providers</a></h2>
  8415. <p>The OpenID mapping provider can be customized by editing the
  8416. <a href="usage/configuration/config_documentation.html#oidc_providers"><code>oidc_providers.user_mapping_provider.module</code></a>
  8417. config option.</p>
  8418. <p><code>oidc_providers.user_mapping_provider.config</code> allows you to provide custom
  8419. configuration options to the module. Check with the module's documentation for
  8420. what options it provides (if any). The options listed by default are for the
  8421. user mapping provider built in to Synapse. If using a custom module, you should
  8422. comment these options out and use those specified by the module instead.</p>
  8423. <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>
  8424. <p>A custom mapping provider must specify the following methods:</p>
  8425. <ul>
  8426. <li><code>def __init__(self, parsed_config)</code>
  8427. <ul>
  8428. <li>Arguments:
  8429. <ul>
  8430. <li><code>parsed_config</code> - A configuration object that is the return value of the
  8431. <code>parse_config</code> method. You should set any configuration options needed by
  8432. the module here.</li>
  8433. </ul>
  8434. </li>
  8435. </ul>
  8436. </li>
  8437. <li><code>def parse_config(config)</code>
  8438. <ul>
  8439. <li>This method should have the <code>@staticmethod</code> decoration.</li>
  8440. <li>Arguments:
  8441. <ul>
  8442. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  8443. <code>oidc_providers.user_mapping_provider.config</code> homeserver config option.
  8444. Runs on homeserver startup. Providers should extract and validate
  8445. any option values they need here.</li>
  8446. </ul>
  8447. </li>
  8448. <li>Whatever is returned will be passed back to the user mapping provider module's
  8449. <code>__init__</code> method during construction.</li>
  8450. </ul>
  8451. </li>
  8452. <li><code>def get_remote_user_id(self, userinfo)</code>
  8453. <ul>
  8454. <li>Arguments:
  8455. <ul>
  8456. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  8457. information from.</li>
  8458. </ul>
  8459. </li>
  8460. <li>This method must return a string, which is the unique, immutable identifier
  8461. for the user. Commonly the <code>sub</code> claim of the response.</li>
  8462. </ul>
  8463. </li>
  8464. <li><code>async def map_user_attributes(self, userinfo, token, failures)</code>
  8465. <ul>
  8466. <li>This method must be async.</li>
  8467. <li>Arguments:
  8468. <ul>
  8469. <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>
  8470. object to extract user information from.</li>
  8471. <li><code>token</code> - A dictionary which includes information necessary to make
  8472. further requests to the OpenID provider.</li>
  8473. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  8474. mxid localpart mapping has failed. This should be used
  8475. to create a deduplicated mxid localpart which should be
  8476. returned instead. For example, if this method returns
  8477. <code>john.doe</code> as the value of <code>localpart</code> in the returned
  8478. dict, and that is already taken on the homeserver, this
  8479. method will be called again with the same parameters but
  8480. with failures=1. The method should then return a different
  8481. <code>localpart</code> value, such as <code>john.doe1</code>.</li>
  8482. </ul>
  8483. </li>
  8484. <li>Returns a dictionary with two keys:
  8485. <ul>
  8486. <li><code>localpart</code>: A string, used to generate the Matrix ID. If this is
  8487. <code>None</code>, the user is prompted to pick their own username. This is only used
  8488. during a user's first login. Once a localpart has been associated with a
  8489. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  8490. <li><code>confirm_localpart</code>: A boolean. If set to <code>True</code>, when a <code>localpart</code>
  8491. string is returned from this method, Synapse will prompt the user to
  8492. either accept this localpart or pick their own username. Otherwise this
  8493. option has no effect. If omitted, defaults to <code>False</code>.</li>
  8494. <li><code>display_name</code>: An optional string, the display name for the user.</li>
  8495. <li><code>emails</code>: A list of strings, the email address(es) to associate with
  8496. this user. If omitted, defaults to an empty list.</li>
  8497. </ul>
  8498. </li>
  8499. </ul>
  8500. </li>
  8501. <li><code>async def get_extra_attributes(self, userinfo, token)</code>
  8502. <ul>
  8503. <li>
  8504. <p>This method must be async.</p>
  8505. </li>
  8506. <li>
  8507. <p>Arguments:</p>
  8508. <ul>
  8509. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  8510. information from.</li>
  8511. <li><code>token</code> - A dictionary which includes information necessary to make
  8512. further requests to the OpenID provider.</li>
  8513. </ul>
  8514. </li>
  8515. <li>
  8516. <p>Returns a dictionary that is suitable to be serialized to JSON. This
  8517. will be returned as part of the response during a successful login.</p>
  8518. <p>Note that care should be taken to not overwrite any of the parameters
  8519. usually returned as part of the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3login">login response</a>.</p>
  8520. </li>
  8521. </ul>
  8522. </li>
  8523. </ul>
  8524. <h3 id="default-openid-mapping-provider"><a class="header" href="#default-openid-mapping-provider">Default OpenID Mapping Provider</a></h3>
  8525. <p>Synapse has a built-in OpenID mapping provider if a custom provider isn't
  8526. specified in the config. It is located at
  8527. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/oidc.py"><code>synapse.handlers.oidc.JinjaOidcMappingProvider</code></a>.</p>
  8528. <h2 id="saml-mapping-providers"><a class="header" href="#saml-mapping-providers">SAML Mapping Providers</a></h2>
  8529. <p>The SAML mapping provider can be customized by editing the
  8530. <a href="usage/configuration/config_documentation.html#saml2_config"><code>saml2_config.user_mapping_provider.module</code></a>
  8531. config option.</p>
  8532. <p><code>saml2_config.user_mapping_provider.config</code> allows you to provide custom
  8533. configuration options to the module. Check with the module's documentation for
  8534. what options it provides (if any). The options listed by default are for the
  8535. user mapping provider built in to Synapse. If using a custom module, you should
  8536. comment these options out and use those specified by the module instead.</p>
  8537. <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>
  8538. <p>A custom mapping provider must specify the following methods:</p>
  8539. <ul>
  8540. <li><code>def __init__(self, parsed_config, module_api)</code>
  8541. <ul>
  8542. <li>Arguments:
  8543. <ul>
  8544. <li><code>parsed_config</code> - A configuration object that is the return value of the
  8545. <code>parse_config</code> method. You should set any configuration options needed by
  8546. the module here.</li>
  8547. <li><code>module_api</code> - a <code>synapse.module_api.ModuleApi</code> object which provides the
  8548. stable API available for extension modules.</li>
  8549. </ul>
  8550. </li>
  8551. </ul>
  8552. </li>
  8553. <li><code>def parse_config(config)</code>
  8554. <ul>
  8555. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  8556. <li>Arguments:
  8557. <ul>
  8558. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  8559. <code>saml_config.user_mapping_provider.config</code> homeserver config option.
  8560. Runs on homeserver startup. Providers should extract and validate
  8561. any option values they need here.</li>
  8562. </ul>
  8563. </li>
  8564. <li>Whatever is returned will be passed back to the user mapping provider module's
  8565. <code>__init__</code> method during construction.</li>
  8566. </ul>
  8567. </li>
  8568. <li><code>def get_saml_attributes(config)</code>
  8569. <ul>
  8570. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  8571. <li>Arguments:
  8572. <ul>
  8573. <li><code>config</code> - A object resulting from a call to <code>parse_config</code>.</li>
  8574. </ul>
  8575. </li>
  8576. <li>Returns a tuple of two sets. The first set equates to the SAML auth
  8577. response attributes that are required for the module to function, whereas
  8578. the second set consists of those attributes which can be used if available,
  8579. but are not necessary.</li>
  8580. </ul>
  8581. </li>
  8582. <li><code>def get_remote_user_id(self, saml_response, client_redirect_url)</code>
  8583. <ul>
  8584. <li>Arguments:
  8585. <ul>
  8586. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  8587. information from.</li>
  8588. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  8589. redirected to.</li>
  8590. </ul>
  8591. </li>
  8592. <li>This method must return a string, which is the unique, immutable identifier
  8593. for the user. Commonly the <code>uid</code> claim of the response.</li>
  8594. </ul>
  8595. </li>
  8596. <li><code>def saml_response_to_user_attributes(self, saml_response, failures, client_redirect_url)</code>
  8597. <ul>
  8598. <li>
  8599. <p>Arguments:</p>
  8600. <ul>
  8601. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  8602. information from.</li>
  8603. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  8604. mxid localpart mapping has failed. This should be used
  8605. to create a deduplicated mxid localpart which should be
  8606. returned instead. For example, if this method returns
  8607. <code>john.doe</code> as the value of <code>mxid_localpart</code> in the returned
  8608. dict, and that is already taken on the homeserver, this
  8609. method will be called again with the same parameters but
  8610. with failures=1. The method should then return a different
  8611. <code>mxid_localpart</code> value, such as <code>john.doe1</code>.</li>
  8612. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  8613. redirected to.</li>
  8614. </ul>
  8615. </li>
  8616. <li>
  8617. <p>This method must return a dictionary, which will then be used by Synapse
  8618. to build a new user. The following keys are allowed:</p>
  8619. <ul>
  8620. <li><code>mxid_localpart</code> - A string, the mxid localpart of the new user. If this is
  8621. <code>None</code>, the user is prompted to pick their own username. This is only used
  8622. during a user's first login. Once a localpart has been associated with a
  8623. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  8624. <li><code>displayname</code> - The displayname of the new user. If not provided, will default to
  8625. the value of <code>mxid_localpart</code>.</li>
  8626. <li><code>emails</code> - A list of emails for the new user. If not provided, will
  8627. default to an empty list.</li>
  8628. </ul>
  8629. <p>Alternatively it can raise a <code>synapse.api.errors.RedirectException</code> to
  8630. redirect the user to another page. This is useful to prompt the user for
  8631. additional information, e.g. if you want them to provide their own username.
  8632. It is the responsibility of the mapping provider to either redirect back
  8633. to <code>client_redirect_url</code> (including any additional information) or to
  8634. complete registration using methods from the <code>ModuleApi</code>.</p>
  8635. </li>
  8636. </ul>
  8637. </li>
  8638. </ul>
  8639. <h3 id="default-saml-mapping-provider"><a class="header" href="#default-saml-mapping-provider">Default SAML Mapping Provider</a></h3>
  8640. <p>Synapse has a built-in SAML mapping provider if a custom provider isn't
  8641. specified in the config. It is located at
  8642. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/saml.py"><code>synapse.handlers.saml.DefaultSamlMappingProvider</code></a>.</p>
  8643. <div style="break-before: page; page-break-before: always;"></div><h2 style="color:red">
  8644. This page of the Synapse documentation is now deprecated. For up to date
  8645. documentation on setting up or writing a password auth provider module, please see
  8646. <a href="modules/index.html">this page</a>.
  8647. </h2>
  8648. <h1 id="password-auth-provider-modules"><a class="header" href="#password-auth-provider-modules">Password auth provider modules</a></h1>
  8649. <p>Password auth providers offer a way for server administrators to
  8650. integrate their Synapse installation with an existing authentication
  8651. system.</p>
  8652. <p>A password auth provider is a Python class which is dynamically loaded
  8653. into Synapse, and provides a number of methods by which it can integrate
  8654. with the authentication system.</p>
  8655. <p>This document serves as a reference for those looking to implement their
  8656. own password auth providers. Additionally, here is a list of known
  8657. password auth provider module implementations:</p>
  8658. <ul>
  8659. <li><a href="https://github.com/matrix-org/matrix-synapse-ldap3/">matrix-synapse-ldap3</a></li>
  8660. <li><a href="https://github.com/devture/matrix-synapse-shared-secret-auth">matrix-synapse-shared-secret-auth</a></li>
  8661. <li><a href="https://github.com/ma1uta/matrix-synapse-rest-password-provider">matrix-synapse-rest-password-provider</a></li>
  8662. </ul>
  8663. <h2 id="required-methods"><a class="header" href="#required-methods">Required methods</a></h2>
  8664. <p>Password auth provider classes must provide the following methods:</p>
  8665. <ul>
  8666. <li>
  8667. <p><code>parse_config(config)</code>
  8668. This method is passed the <code>config</code> object for this module from the
  8669. homeserver configuration file.</p>
  8670. <p>It should perform any appropriate sanity checks on the provided
  8671. configuration, and return an object which is then passed into
  8672. <code>__init__</code>.</p>
  8673. <p>This method should have the <code>@staticmethod</code> decoration.</p>
  8674. </li>
  8675. <li>
  8676. <p><code>__init__(self, config, account_handler)</code></p>
  8677. <p>The constructor is passed the config object returned by
  8678. <code>parse_config</code>, and a <code>synapse.module_api.ModuleApi</code> object which
  8679. allows the password provider to check if accounts exist and/or create
  8680. new ones.</p>
  8681. </li>
  8682. </ul>
  8683. <h2 id="optional-methods"><a class="header" href="#optional-methods">Optional methods</a></h2>
  8684. <p>Password auth provider classes may optionally provide the following methods:</p>
  8685. <ul>
  8686. <li>
  8687. <p><code>get_db_schema_files(self)</code></p>
  8688. <p>This method, if implemented, should return an Iterable of
  8689. <code>(name, stream)</code> pairs of database schema files. Each file is applied
  8690. in turn at initialisation, and a record is then made in the database
  8691. so that it is not re-applied on the next start.</p>
  8692. </li>
  8693. <li>
  8694. <p><code>get_supported_login_types(self)</code></p>
  8695. <p>This method, if implemented, should return a <code>dict</code> mapping from a
  8696. login type identifier (such as <code>m.login.password</code>) to an iterable
  8697. giving the fields which must be provided by the user in the submission
  8698. to <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">the <code>/login</code> API</a>.
  8699. These fields are passed in the <code>login_dict</code> dictionary to <code>check_auth</code>.</p>
  8700. <p>For example, if a password auth provider wants to implement a custom
  8701. login type of <code>com.example.custom_login</code>, where the client is expected
  8702. to pass the fields <code>secret1</code> and <code>secret2</code>, the provider should
  8703. implement this method and return the following dict:</p>
  8704. <pre><code class="language-python">{&quot;com.example.custom_login&quot;: (&quot;secret1&quot;, &quot;secret2&quot;)}
  8705. </code></pre>
  8706. </li>
  8707. <li>
  8708. <p><code>check_auth(self, username, login_type, login_dict)</code></p>
  8709. <p>This method does the real work. If implemented, it
  8710. will be called for each login attempt where the login type matches one
  8711. of the keys returned by <code>get_supported_login_types</code>.</p>
  8712. <p>It is passed the (possibly unqualified) <code>user</code> field provided by the client,
  8713. the login type, and a dictionary of login secrets passed by the
  8714. client.</p>
  8715. <p>The method should return an <code>Awaitable</code> object, which resolves
  8716. to the canonical <code>@localpart:domain</code> user ID if authentication is
  8717. successful, and <code>None</code> if not.</p>
  8718. <p>Alternatively, the <code>Awaitable</code> can resolve to a <code>(str, func)</code> tuple, in
  8719. which case the second field is a callback which will be called with
  8720. the result from the <code>/login</code> call (including <code>access_token</code>,
  8721. <code>device_id</code>, etc.)</p>
  8722. </li>
  8723. <li>
  8724. <p><code>check_3pid_auth(self, medium, address, password)</code></p>
  8725. <p>This method, if implemented, is called when a user attempts to
  8726. register or log in with a third party identifier, such as email. It is
  8727. passed the medium (ex. &quot;email&quot;), an address (ex.
  8728. &quot;<a href="mailto:jdoe@example.com">jdoe@example.com</a>&quot;) and the user's password.</p>
  8729. <p>The method should return an <code>Awaitable</code> object, which resolves
  8730. to a <code>str</code> containing the user's (canonical) User id if
  8731. authentication was successful, and <code>None</code> if not.</p>
  8732. <p>As with <code>check_auth</code>, the <code>Awaitable</code> may alternatively resolve to a
  8733. <code>(user_id, callback)</code> tuple.</p>
  8734. </li>
  8735. <li>
  8736. <p><code>check_password(self, user_id, password)</code></p>
  8737. <p>This method provides a simpler interface than
  8738. <code>get_supported_login_types</code> and <code>check_auth</code> for password auth
  8739. providers that just want to provide a mechanism for validating
  8740. <code>m.login.password</code> logins.</p>
  8741. <p>If implemented, it will be called to check logins with an
  8742. <code>m.login.password</code> login type. It is passed a qualified
  8743. <code>@localpart:domain</code> user id, and the password provided by the user.</p>
  8744. <p>The method should return an <code>Awaitable</code> object, which resolves
  8745. to <code>True</code> if authentication is successful, and <code>False</code> if not.</p>
  8746. </li>
  8747. <li>
  8748. <p><code>on_logged_out(self, user_id, device_id, access_token)</code></p>
  8749. <p>This method, if implemented, is called when a user logs out. It is
  8750. passed the qualified user ID, the ID of the deactivated device (if
  8751. any: access tokens are occasionally created without an associated
  8752. device ID), and the (now deactivated) access token.</p>
  8753. <p>It may return an <code>Awaitable</code> object; the logout request will
  8754. wait for the <code>Awaitable</code> to complete, but the result is ignored.</p>
  8755. </li>
  8756. </ul>
  8757. <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>
  8758. <p>Synapse comes with a non-standard login type to support
  8759. <a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JSON Web Tokens</a>. In general the
  8760. documentation for
  8761. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#login">the login endpoint</a>
  8762. is still valid (and the mechanism works similarly to the
  8763. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#token-based">token based login</a>).</p>
  8764. <p>To log in using a JSON Web Token, clients should submit a <code>/login</code> request as
  8765. follows:</p>
  8766. <pre><code class="language-json">{
  8767. &quot;type&quot;: &quot;org.matrix.login.jwt&quot;,
  8768. &quot;token&quot;: &quot;&lt;jwt&gt;&quot;
  8769. }
  8770. </code></pre>
  8771. <p>The <code>token</code> field should include the JSON web token with the following claims:</p>
  8772. <ul>
  8773. <li>A claim that encodes the local part of the user ID is required. By default,
  8774. the <code>sub</code> (subject) claim is used, or a custom claim can be set in the
  8775. configuration file.</li>
  8776. <li>The expiration time (<code>exp</code>), not before time (<code>nbf</code>), and issued at (<code>iat</code>)
  8777. claims are optional, but validated if present.</li>
  8778. <li>The issuer (<code>iss</code>) claim is optional, but required and validated if configured.</li>
  8779. <li>The audience (<code>aud</code>) claim is optional, but required and validated if configured.
  8780. Providing the audience claim when not configured will cause validation to fail.</li>
  8781. </ul>
  8782. <p>In the case that the token is not valid, the homeserver must respond with
  8783. <code>403 Forbidden</code> and an error code of <code>M_FORBIDDEN</code>.</p>
  8784. <p>As with other login types, there are additional fields (e.g. <code>device_id</code> and
  8785. <code>initial_device_display_name</code>) which can be included in the above request.</p>
  8786. <h2 id="preparing-synapse-1"><a class="header" href="#preparing-synapse-1">Preparing Synapse</a></h2>
  8787. <p>The JSON Web Token integration in Synapse uses the
  8788. <a href="https://docs.authlib.org/en/latest/index.html"><code>Authlib</code></a> library, which must be installed
  8789. as follows:</p>
  8790. <ul>
  8791. <li>
  8792. <p>The relevant libraries are included in the Docker images and Debian packages
  8793. provided by <code>matrix.org</code> so no further action is needed.</p>
  8794. </li>
  8795. <li>
  8796. <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>
  8797. </li>
  8798. <li>
  8799. <p>For other installation mechanisms, see the documentation provided by the
  8800. maintainer.</p>
  8801. </li>
  8802. </ul>
  8803. <p>To enable the JSON web token integration, you should then add a <code>jwt_config</code> option
  8804. to your configuration file. See the <a href="usage/configuration/config_documentation.html#jwt_config">configuration manual</a> for some
  8805. sample settings.</p>
  8806. <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>
  8807. <p>Although JSON Web Tokens are typically generated from an external server, the
  8808. example below uses a locally generated JWT.</p>
  8809. <ol>
  8810. <li>
  8811. <p>Configure Synapse with JWT logins, note that this example uses a pre-shared
  8812. secret and an algorithm of HS256:</p>
  8813. <pre><code class="language-yaml">jwt_config:
  8814. enabled: true
  8815. secret: &quot;my-secret-token&quot;
  8816. algorithm: &quot;HS256&quot;
  8817. </code></pre>
  8818. </li>
  8819. <li>
  8820. <p>Generate a JSON web token:</p>
  8821. <p>You can use the following short Python snippet to generate a JWT
  8822. protected by an HMAC.
  8823. Take care that the <code>secret</code> and the algorithm given in the <code>header</code> match
  8824. the entries from <code>jwt_config</code> above.</p>
  8825. <pre><code class="language-python">from authlib.jose import jwt
  8826. header = {&quot;alg&quot;: &quot;HS256&quot;}
  8827. payload = {&quot;sub&quot;: &quot;user1&quot;, &quot;aud&quot;: [&quot;audience&quot;]}
  8828. secret = &quot;my-secret-token&quot;
  8829. result = jwt.encode(header, payload, secret)
  8830. print(result.decode(&quot;ascii&quot;))
  8831. </code></pre>
  8832. </li>
  8833. <li>
  8834. <p>Query for the login types and ensure <code>org.matrix.login.jwt</code> is there:</p>
  8835. <pre><code class="language-bash">curl http://localhost:8080/_matrix/client/r0/login
  8836. </code></pre>
  8837. </li>
  8838. <li>
  8839. <p>Login used the generated JSON web token from above:</p>
  8840. <pre><code class="language-bash">$ curl http://localhost:8082/_matrix/client/r0/login -X POST \
  8841. --data '{&quot;type&quot;:&quot;org.matrix.login.jwt&quot;,&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc&quot;}'
  8842. {
  8843. &quot;access_token&quot;: &quot;&lt;access token&gt;&quot;,
  8844. &quot;device_id&quot;: &quot;ACBDEFGHI&quot;,
  8845. &quot;home_server&quot;: &quot;localhost:8080&quot;,
  8846. &quot;user_id&quot;: &quot;@test-user:localhost:8480&quot;
  8847. }
  8848. </code></pre>
  8849. </li>
  8850. </ol>
  8851. <p>You should now be able to use the returned access token to query the client API.</p>
  8852. <div style="break-before: page; page-break-before: always;"></div><h1 id="refresh-tokens"><a class="header" href="#refresh-tokens">Refresh Tokens</a></h1>
  8853. <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>
  8854. <h2 id="background-and-motivation"><a class="header" href="#background-and-motivation">Background and motivation</a></h2>
  8855. <p>Synapse users' sessions are identified by <strong>access tokens</strong>; access tokens are
  8856. issued to users on login. Each session gets a unique access token which identifies
  8857. it; the access token must be kept secret as it grants access to the user's account.</p>
  8858. <p>Traditionally, these access tokens were eternally valid (at least until the user
  8859. explicitly chose to log out).</p>
  8860. <p>In some cases, it may be desirable for these access tokens to expire so that the
  8861. potential damage caused by leaking an access token is reduced.
  8862. On the other hand, forcing a user to re-authenticate (log in again) often might
  8863. be too much of an inconvenience.</p>
  8864. <p><strong>Refresh tokens</strong> are a mechanism to avoid some of this inconvenience whilst
  8865. still getting most of the benefits of short access token lifetimes.
  8866. Refresh tokens are also a concept present in OAuth 2 — further reading is available
  8867. <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5">here</a>.</p>
  8868. <p>When refresh tokens are in use, both an access token and a refresh token will be
  8869. issued to users on login. The access token will expire after a predetermined amount
  8870. of time, but otherwise works in the same way as before. When the access token is
  8871. close to expiring (or has expired), the user's client should present the homeserver
  8872. (Synapse) with the refresh token.</p>
  8873. <p>The homeserver will then generate a new access token and refresh token for the user
  8874. and return them. The old refresh token is invalidated and can not be used again*.</p>
  8875. <p>Finally, refresh tokens also make it possible for sessions to be logged out if they
  8876. are inactive for too long, before the session naturally ends; see the configuration
  8877. guide below.</p>
  8878. <p>*To prevent issues if clients lose connection half-way through refreshing a token,
  8879. the refresh token is only invalidated once the new access token has been used at
  8880. least once. For all intents and purposes, the above simplification is sufficient.</p>
  8881. <h2 id="caveats"><a class="header" href="#caveats">Caveats</a></h2>
  8882. <p>There are some caveats:</p>
  8883. <ul>
  8884. <li>If a third party gets both your access token and refresh token, they will be able to
  8885. continue to enjoy access to your session.
  8886. <ul>
  8887. <li>This is still an improvement because you (the user) will notice when <em>your</em>
  8888. session expires and you're not able to use your refresh token.
  8889. That would be a giveaway that someone else has compromised your session.
  8890. You would be able to log in again and terminate that session.
  8891. Previously (with long-lived access tokens), a third party that has your access
  8892. token could go undetected for a very long time.</li>
  8893. </ul>
  8894. </li>
  8895. <li>Clients need to implement support for refresh tokens in order for them to be a
  8896. useful mechanism.
  8897. <ul>
  8898. <li>It is up to homeserver administrators if they want to issue long-lived access
  8899. tokens to clients not implementing refresh tokens.
  8900. <ul>
  8901. <li>For compatibility, it is likely that they should, at least until client support
  8902. is widespread.
  8903. <ul>
  8904. <li>Users with clients that support refresh tokens will still benefit from the
  8905. added security; it's not possible to downgrade a session to using long-lived
  8906. access tokens so this effectively gives users the choice.</li>
  8907. </ul>
  8908. </li>
  8909. <li>In a closed environment where all users use known clients, this may not be
  8910. an issue as the homeserver administrator can know if the clients have refresh
  8911. token support. In that case, the non-refreshable access token lifetime
  8912. may be set to a short duration so that a similar level of security is provided.</li>
  8913. </ul>
  8914. </li>
  8915. </ul>
  8916. </li>
  8917. </ul>
  8918. <h2 id="configuration-guide"><a class="header" href="#configuration-guide">Configuration Guide</a></h2>
  8919. <p>The following configuration options, in the <code>registration</code> section, are related:</p>
  8920. <ul>
  8921. <li><code>session_lifetime</code>: maximum length of a session, even if it's refreshed.
  8922. In other words, the client must log in again after this time period.
  8923. In most cases, this can be unset (infinite) or set to a long time (years or months).</li>
  8924. <li><code>refreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  8925. by clients supporting refresh tokens.
  8926. This should be short; a good value might be 5 minutes (<code>5m</code>).</li>
  8927. <li><code>nonrefreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  8928. by clients which don't support refresh tokens.
  8929. Make this short if you want to effectively force use of refresh tokens.
  8930. Make this long if you don't want to inconvenience users of clients which don't
  8931. support refresh tokens (by forcing them to frequently re-authenticate using
  8932. login credentials).</li>
  8933. <li><code>refresh_token_lifetime</code>: lifetime of refresh tokens.
  8934. In other words, the client must refresh within this time period to maintain its session.
  8935. Unless you want to log inactive sessions out, it is often fine to use a long
  8936. value here or even leave it unset (infinite).
  8937. Beware that making it too short will inconvenience clients that do not connect
  8938. very often, including mobile clients and clients of infrequent users (by making
  8939. it more difficult for them to refresh in time, which may force them to need to
  8940. re-authenticate using login credentials).</li>
  8941. </ul>
  8942. <p><strong>Note:</strong> All four options above only apply when tokens are created (by logging in or refreshing).
  8943. Changes to these settings do not apply retroactively.</p>
  8944. <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>
  8945. <p>If you'd like to force sessions to be logged out upon inactivity, you can enable
  8946. refreshable access token expiry and refresh token expiry.</p>
  8947. <p>This works because a client must refresh at least once within a period of
  8948. <code>refresh_token_lifetime</code> in order to maintain valid credentials to access the
  8949. account.</p>
  8950. <p>(It's suggested that <code>refresh_token_lifetime</code> should be longer than
  8951. <code>refreshable_access_token_lifetime</code> and this section assumes that to be the case
  8952. for simplicity.)</p>
  8953. <p>Note: this will only affect sessions using refresh tokens. You may wish to
  8954. set a short <code>nonrefreshable_access_token_lifetime</code> to prevent this being bypassed
  8955. by clients that do not support refresh tokens.</p>
  8956. <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>
  8957. <p>It may be desirable to permit some short periods of inactivity, for example to
  8958. accommodate brief outages in client connectivity.</p>
  8959. <p>The following model aims to provide guidance for choosing <code>refresh_token_lifetime</code>
  8960. and <code>refreshable_access_token_lifetime</code> to satisfy requirements of the form:</p>
  8961. <ol>
  8962. <li>inactivity longer than <code>L</code> <strong>MUST</strong> cause the session to be logged out; and</li>
  8963. <li>inactivity shorter than <code>S</code> <strong>MUST NOT</strong> cause the session to be logged out.</li>
  8964. </ol>
  8965. <p>This model makes the weakest assumption that all active clients will refresh as
  8966. needed to maintain an active access token, but no sooner.
  8967. <em>In reality, clients may refresh more often than this model assumes, but the
  8968. above requirements will still hold.</em></p>
  8969. <p>To satisfy the above model,</p>
  8970. <ul>
  8971. <li><code>refresh_token_lifetime</code> should be set to <code>L</code>; and</li>
  8972. <li><code>refreshable_access_token_lifetime</code> should be set to <code>L - S</code>.</li>
  8973. </ul>
  8974. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-2"><a class="header" href="#overview-2">Overview</a></h1>
  8975. <p>A captcha can be enabled on your homeserver to help prevent bots from registering
  8976. accounts. Synapse currently uses Google's reCAPTCHA service which requires API keys
  8977. from Google.</p>
  8978. <h2 id="getting-api-keys"><a class="header" href="#getting-api-keys">Getting API keys</a></h2>
  8979. <ol>
  8980. <li>Create a new site at <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></li>
  8981. <li>Set the label to anything you want</li>
  8982. <li>Set the type to reCAPTCHA v2 using the &quot;I'm not a robot&quot; Checkbox option.
  8983. This is the only type of captcha that works with Synapse.</li>
  8984. <li>Add the public hostname for your server, as set in <code>public_baseurl</code>
  8985. in <code>homeserver.yaml</code>, to the list of authorized domains. If you have not set
  8986. <code>public_baseurl</code>, use <code>server_name</code>.</li>
  8987. <li>Agree to the terms of service and submit.</li>
  8988. <li>Copy your site key and secret key and add them to your <code>homeserver.yaml</code>
  8989. configuration file
  8990. <pre><code class="language-yaml">recaptcha_public_key: YOUR_SITE_KEY
  8991. recaptcha_private_key: YOUR_SECRET_KEY
  8992. </code></pre>
  8993. </li>
  8994. <li>Enable the CAPTCHA for new registrations
  8995. <pre><code class="language-yaml">enable_registration_captcha: true
  8996. </code></pre>
  8997. </li>
  8998. <li>Go to the settings page for the CAPTCHA you just created</li>
  8999. <li>Uncheck the &quot;Verify the origin of reCAPTCHA solutions&quot; checkbox so that the
  9000. captcha can be displayed in any client. If you do not disable this option then you
  9001. must specify the domains of every client that is allowed to display the CAPTCHA.</li>
  9002. </ol>
  9003. <h2 id="configuring-ip-used-for-auth"><a class="header" href="#configuring-ip-used-for-auth">Configuring IP used for auth</a></h2>
  9004. <p>The reCAPTCHA API requires that the IP address of the user who solved the
  9005. CAPTCHA is sent. If the client is connecting through a proxy or load balancer,
  9006. it may be required to use the <code>X-Forwarded-For</code> (XFF) header instead of the origin
  9007. IP address. This can be configured using the <code>x_forwarded</code> directive in the
  9008. listeners section of the <code>homeserver.yaml</code> configuration file.</p>
  9009. <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>
  9010. <p>The registration of new application services depends on the homeserver used.
  9011. In synapse, you need to create a new configuration file for your AS and add it
  9012. to the list specified under the <code>app_service_config_files</code> config
  9013. option in your synapse config.</p>
  9014. <p>For example:</p>
  9015. <pre><code class="language-yaml">app_service_config_files:
  9016. - /home/matrix/.synapse/&lt;your-AS&gt;.yaml
  9017. </code></pre>
  9018. <p>The format of the AS configuration file is as follows:</p>
  9019. <pre><code class="language-yaml">id: &lt;your-AS-id&gt;
  9020. url: &lt;base url of AS&gt;
  9021. as_token: &lt;token AS will add to requests to HS&gt;
  9022. hs_token: &lt;token HS will add to requests to AS&gt;
  9023. sender_localpart: &lt;localpart of AS user&gt;
  9024. namespaces:
  9025. users: # List of users we're interested in
  9026. - exclusive: &lt;bool&gt;
  9027. regex: &lt;regex&gt;
  9028. group_id: &lt;group&gt;
  9029. - ...
  9030. aliases: [] # List of aliases we're interested in
  9031. rooms: [] # List of room ids we're interested in
  9032. </code></pre>
  9033. <p><code>exclusive</code>: If enabled, only this application service is allowed to register users in its namespace(s).
  9034. <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>
  9035. <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>
  9036. <div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices"><a class="header" href="#server-notices">Server Notices</a></h1>
  9037. <p>'Server Notices' are a new feature introduced in Synapse 0.30. They provide a
  9038. channel whereby server administrators can send messages to users on the server.</p>
  9039. <p>They are used as part of communication of the server polices (see
  9040. <a href="consent_tracking.html">Consent Tracking</a>), however the intention is that
  9041. they may also find a use for features such as &quot;Message of the day&quot;.</p>
  9042. <p>This is a feature specific to Synapse, but it uses standard Matrix
  9043. communication mechanisms, so should work with any Matrix client.</p>
  9044. <h2 id="user-experience"><a class="header" href="#user-experience">User experience</a></h2>
  9045. <p>When the user is first sent a server notice, they will get an invitation to a
  9046. room (typically called 'Server Notices', though this is configurable in
  9047. <code>homeserver.yaml</code>). They will be <strong>unable to reject</strong> this invitation -
  9048. attempts to do so will receive an error.</p>
  9049. <p>Once they accept the invitation, they will see the notice message in the room
  9050. history; it will appear to have come from the 'server notices user' (see
  9051. below).</p>
  9052. <p>The user is prevented from sending any messages in this room by the power
  9053. levels.</p>
  9054. <p>Having joined the room, the user can leave the room if they want. Subsequent
  9055. server notices will then cause a new room to be created.</p>
  9056. <h2 id="synapse-configuration"><a class="header" href="#synapse-configuration">Synapse configuration</a></h2>
  9057. <p>Server notices come from a specific user id on the server. Server
  9058. administrators are free to choose the user id - something like <code>server</code> is
  9059. suggested, meaning the notices will come from
  9060. <code>@server:&lt;your_server_name&gt;</code>. Once the Server Notices user is configured, that
  9061. user id becomes a special, privileged user, so administrators should ensure
  9062. that <strong>it is not already allocated</strong>.</p>
  9063. <p>In order to support server notices, it is necessary to add some configuration
  9064. to the <code>homeserver.yaml</code> file. In particular, you should add a <code>server_notices</code>
  9065. section, which should look like this:</p>
  9066. <pre><code class="language-yaml">server_notices:
  9067. system_mxid_localpart: server
  9068. system_mxid_display_name: &quot;Server Notices&quot;
  9069. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  9070. room_name: &quot;Server Notices&quot;
  9071. </code></pre>
  9072. <p>The only compulsory setting is <code>system_mxid_localpart</code>, which defines the user
  9073. id of the Server Notices user, as above. <code>room_name</code> defines the name of the
  9074. room which will be created.</p>
  9075. <p><code>system_mxid_display_name</code> and <code>system_mxid_avatar_url</code> can be used to set the
  9076. displayname and avatar of the Server Notices user.</p>
  9077. <h2 id="sending-notices"><a class="header" href="#sending-notices">Sending notices</a></h2>
  9078. <p>To send server notices to users you can use the
  9079. <a href="admin_api/server_notices.html">admin_api</a>.</p>
  9080. <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>
  9081. <p>Synapse 0.30 introduces support for tracking whether users have agreed to the
  9082. terms and conditions set by the administrator of a server - and blocking access
  9083. to the server until they have.</p>
  9084. <p>There are several parts to this functionality; each requires some specific
  9085. configuration in <code>homeserver.yaml</code> to be enabled.</p>
  9086. <p>Note that various parts of the configuation and this document refer to the
  9087. &quot;privacy policy&quot;: agreement with a privacy policy is one particular use of this
  9088. feature, but of course adminstrators can specify other terms and conditions
  9089. unrelated to &quot;privacy&quot; per se.</p>
  9090. <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>
  9091. <p>Synapse can be configured to serve the user a simple policy form with an
  9092. &quot;accept&quot; button. Clicking &quot;Accept&quot; records the user's acceptance in the
  9093. database and shows a success page.</p>
  9094. <p>To enable this, first create templates for the policy and success pages.
  9095. These should be stored on the local filesystem.</p>
  9096. <p>These templates use the <a href="http://jinja.pocoo.org">Jinja2</a> templating language,
  9097. and <a href="https://github.com/matrix-org/synapse/tree/develop/docs/privacy_policy_templates/">docs/privacy_policy_templates</a>
  9098. gives examples of the sort of thing that can be done.</p>
  9099. <p>Note that the templates must be stored under a name giving the language of the
  9100. template - currently this must always be <code>en</code> (for &quot;English&quot;);
  9101. internationalisation support is intended for the future.</p>
  9102. <p>The template for the policy itself should be versioned and named according to
  9103. the version: for example <code>1.0.html</code>. The version of the policy which the user
  9104. has agreed to is stored in the database.</p>
  9105. <p>Once the templates are in place, make the following changes to <code>homeserver.yaml</code>:</p>
  9106. <ol>
  9107. <li>
  9108. <p>Add a <code>user_consent</code> section, which should look like:</p>
  9109. <pre><code class="language-yaml">user_consent:
  9110. template_dir: privacy_policy_templates
  9111. version: 1.0
  9112. </code></pre>
  9113. <p><code>template_dir</code> points to the directory containing the policy
  9114. templates. <code>version</code> defines the version of the policy which will be served
  9115. to the user. In the example above, Synapse will serve
  9116. <code>privacy_policy_templates/en/1.0.html</code>.</p>
  9117. </li>
  9118. <li>
  9119. <p>Add a <code>form_secret</code> setting at the top level:</p>
  9120. <pre><code class="language-yaml">form_secret: &quot;&lt;unique secret&gt;&quot;
  9121. </code></pre>
  9122. <p>This should be set to an arbitrary secret string (try <code>pwgen -y 30</code> to
  9123. generate suitable secrets).</p>
  9124. <p>More on what this is used for below.</p>
  9125. </li>
  9126. <li>
  9127. <p>Add <code>consent</code> wherever the <code>client</code> resource is currently enabled in the
  9128. <code>listeners</code> configuration. For example:</p>
  9129. <pre><code class="language-yaml">listeners:
  9130. - port: 8008
  9131. resources:
  9132. - names:
  9133. - client
  9134. - consent
  9135. </code></pre>
  9136. </li>
  9137. </ol>
  9138. <p>Finally, ensure that <code>jinja2</code> is installed. If you are using a virtualenv, this
  9139. should be a matter of <code>pip install Jinja2</code>. On debian, try <code>apt-get install python-jinja2</code>.</p>
  9140. <p>Once this is complete, and the server has been restarted, try visiting
  9141. <code>https://&lt;server&gt;/_matrix/consent</code>. If correctly configured, this should give
  9142. an error &quot;Missing string query parameter 'u'&quot;. It is now possible to manually
  9143. construct URIs where users can give their consent.</p>
  9144. <h3 id="enabling-consent-tracking-at-registration"><a class="header" href="#enabling-consent-tracking-at-registration">Enabling consent tracking at registration</a></h3>
  9145. <ol>
  9146. <li>
  9147. <p>Add the following to your configuration:</p>
  9148. <pre><code class="language-yaml">user_consent:
  9149. require_at_registration: true
  9150. policy_name: &quot;Privacy Policy&quot; # or whatever you'd like to call the policy
  9151. </code></pre>
  9152. </li>
  9153. <li>
  9154. <p>In your consent templates, make use of the <code>public_version</code> variable to
  9155. see if an unauthenticated user is viewing the page. This is typically
  9156. wrapped around the form that would be used to actually agree to the document:</p>
  9157. <pre><code class="language-html">{% if not public_version %}
  9158. &lt;!-- The variables used here are only provided when the 'u' param is given to the homeserver --&gt;
  9159. &lt;form method=&quot;post&quot; action=&quot;consent&quot;&gt;
  9160. &lt;input type=&quot;hidden&quot; name=&quot;v&quot; value=&quot;{{version}}&quot;/&gt;
  9161. &lt;input type=&quot;hidden&quot; name=&quot;u&quot; value=&quot;{{user}}&quot;/&gt;
  9162. &lt;input type=&quot;hidden&quot; name=&quot;h&quot; value=&quot;{{userhmac}}&quot;/&gt;
  9163. &lt;input type=&quot;submit&quot; value=&quot;Sure thing!&quot;/&gt;
  9164. &lt;/form&gt;
  9165. {% endif %}
  9166. </code></pre>
  9167. </li>
  9168. <li>
  9169. <p>Restart Synapse to apply the changes.</p>
  9170. </li>
  9171. </ol>
  9172. <p>Visiting <code>https://&lt;server&gt;/_matrix/consent</code> should now give you a view of the privacy
  9173. document. This is what users will be able to see when registering for accounts.</p>
  9174. <h3 id="constructing-the-consent-uri"><a class="header" href="#constructing-the-consent-uri">Constructing the consent URI</a></h3>
  9175. <p>It may be useful to manually construct the &quot;consent URI&quot; for a given user - for
  9176. instance, in order to send them an email asking them to consent. To do this,
  9177. take the base <code>https://&lt;server&gt;/_matrix/consent</code> URL and add the following
  9178. query parameters:</p>
  9179. <ul>
  9180. <li>
  9181. <p><code>u</code>: the user id of the user. This can either be a full MXID
  9182. (<code>@user:server.com</code>) or just the localpart (<code>user</code>).</p>
  9183. </li>
  9184. <li>
  9185. <p><code>h</code>: hex-encoded HMAC-SHA256 of <code>u</code> using the <code>form_secret</code> as a key. It is
  9186. possible to calculate this on the commandline with something like:</p>
  9187. <pre><code class="language-bash">echo -n '&lt;user&gt;' | openssl sha256 -hmac '&lt;form_secret&gt;'
  9188. </code></pre>
  9189. <p>This should result in a URI which looks something like:
  9190. <code>https://&lt;server&gt;/_matrix/consent?u=&lt;user&gt;&amp;h=68a152465a4d...</code>.</p>
  9191. </li>
  9192. </ul>
  9193. <p>Note that not providing a <code>u</code> parameter will be interpreted as wanting to view
  9194. the document from an unauthenticated perspective, such as prior to registration.
  9195. Therefore, the <code>h</code> parameter is not required in this scenario. To enable this
  9196. behaviour, set <code>require_at_registration</code> to <code>true</code> in your <code>user_consent</code> config.</p>
  9197. <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>
  9198. <p>It is possible to configure Synapse to send a <a href="server_notices.html">server
  9199. notice</a> to anybody who has not yet agreed to the current
  9200. version of the policy. To do so:</p>
  9201. <ul>
  9202. <li>
  9203. <p>ensure that the consent resource is configured, as in the previous section</p>
  9204. </li>
  9205. <li>
  9206. <p>ensure that server notices are configured, as in <a href="server_notices.html">the server notice documentation</a>.</p>
  9207. </li>
  9208. <li>
  9209. <p>Add <code>server_notice_content</code> under <code>user_consent</code> in <code>homeserver.yaml</code>. For
  9210. example:</p>
  9211. <pre><code class="language-yaml">user_consent:
  9212. server_notice_content:
  9213. msgtype: m.text
  9214. body: &gt;-
  9215. Please give your consent to the privacy policy at %(consent_uri)s.
  9216. </code></pre>
  9217. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  9218. consent uri for that user.</p>
  9219. </li>
  9220. <li>
  9221. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  9222. URI that clients use to connect to the server. (It is used to construct
  9223. <code>consent_uri</code> in the server notice.)</p>
  9224. </li>
  9225. </ul>
  9226. <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>
  9227. <p>Synapse can be configured to block any attempts to join rooms or send messages
  9228. until the user has given their agreement to the policy. (Joining the server
  9229. notices room is exempted from this).</p>
  9230. <p>To enable this, add <code>block_events_error</code> under <code>user_consent</code>. For example:</p>
  9231. <pre><code class="language-yaml">user_consent:
  9232. block_events_error: &gt;-
  9233. You can't send any messages until you consent to the privacy policy at
  9234. %(consent_uri)s.
  9235. </code></pre>
  9236. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  9237. consent uri for that user.</p>
  9238. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  9239. URI that clients use to connect to the server. (It is used to construct
  9240. <code>consent_uri</code> in the error.)</p>
  9241. <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>
  9242. <p>The user directory is currently maintained based on the 'visible' users
  9243. on this particular server - i.e. ones which your account shares a room with, or
  9244. who are present in a publicly viewable room present on the server.</p>
  9245. <p>The directory info is stored in various tables, which can (typically after
  9246. DB corruption) get stale or out of sync. If this happens, for now the
  9247. solution to fix it is to use the <a href="usage/administration/admin_api/background_updates.html#run">admin API</a>
  9248. and execute the job <code>regenerate_directory</code>. This should then start a background task to
  9249. flush the current tables and regenerate the directory.</p>
  9250. <h2 id="data-model"><a class="header" href="#data-model">Data model</a></h2>
  9251. <p>There are five relevant tables that collectively form the &quot;user directory&quot;.
  9252. Three of them track a master list of all the users we could search for.
  9253. The last two (collectively called the &quot;search tables&quot;) track who can
  9254. see who.</p>
  9255. <p>From all of these tables we exclude three types of local user:</p>
  9256. <ul>
  9257. <li>support users</li>
  9258. <li>appservice users</li>
  9259. <li>deactivated users</li>
  9260. </ul>
  9261. <ul>
  9262. <li>
  9263. <p><code>user_directory</code>. This contains the user_id, display name and avatar we'll
  9264. return when you search the directory.</p>
  9265. <ul>
  9266. <li>Because there's only one directory entry per user, it's important that we only
  9267. ever put publicly visible names here. Otherwise we might leak a private
  9268. nickname or avatar used in a private room.</li>
  9269. <li>Indexed on rooms. Indexed on users.</li>
  9270. </ul>
  9271. </li>
  9272. <li>
  9273. <p><code>user_directory_search</code>. To be joined to <code>user_directory</code>. It contains an extra
  9274. column that enables full text search based on user ids and display names.
  9275. Different schemas for SQLite and Postgres with different code paths to match.</p>
  9276. <ul>
  9277. <li>Indexed on the full text search data. Indexed on users.</li>
  9278. </ul>
  9279. </li>
  9280. <li>
  9281. <p><code>user_directory_stream_pos</code>. When the initial background update to populate
  9282. the directory is complete, we record a stream position here. This indicates
  9283. that synapse should now listen for room changes and incrementally update
  9284. the directory where necessary.</p>
  9285. </li>
  9286. <li>
  9287. <p><code>users_in_public_rooms</code>. Contains associations between users and the public rooms they're in.
  9288. Used to determine which users are in public rooms and should be publicly visible in the directory.</p>
  9289. </li>
  9290. <li>
  9291. <p><code>users_who_share_private_rooms</code>. Rows are triples <code>(L, M, room id)</code> where <code>L</code>
  9292. is a local user and <code>M</code> is a local or remote user. <code>L</code> and <code>M</code> should be
  9293. different, but this isn't enforced by a constraint.</p>
  9294. </li>
  9295. </ul>
  9296. <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>
  9297. <p>Synapse admins can enable support for message retention policies on
  9298. their homeserver. Message retention policies exist at a room level,
  9299. follow the semantics described in
  9300. <a href="https://github.com/matrix-org/matrix-doc/blob/matthew/msc1763/proposals/1763-configurable-retention-periods.md">MSC1763</a>,
  9301. and allow server and room admins to configure how long messages should
  9302. be kept in a homeserver's database before being purged from it.
  9303. <strong>Please note that, as this feature isn't part of the Matrix
  9304. specification yet, this implementation is to be considered as
  9305. experimental. There are known bugs which may cause database corruption.
  9306. Proceed with caution.</strong> </p>
  9307. <p>A message retention policy is mainly defined by its <code>max_lifetime</code>
  9308. parameter, which defines how long a message can be kept around after
  9309. it was sent to the room. If a room doesn't have a message retention
  9310. policy, and there's no default one for a given server, then no message
  9311. sent in that room is ever purged on that server.</p>
  9312. <p>MSC1763 also specifies semantics for a <code>min_lifetime</code> parameter which
  9313. defines the amount of time after which an event <em>can</em> get purged (after
  9314. it was sent to the room), but Synapse doesn't currently support it
  9315. beyond registering it.</p>
  9316. <p>Both <code>max_lifetime</code> and <code>min_lifetime</code> are optional parameters.</p>
  9317. <p>Note that message retention policies don't apply to state events.</p>
  9318. <p>Once an event reaches its expiry date (defined as the time it was sent
  9319. plus the value for <code>max_lifetime</code> in the room), two things happen:</p>
  9320. <ul>
  9321. <li>Synapse stops serving the event to clients via any endpoint.</li>
  9322. <li>The message gets picked up by the next purge job (see the &quot;Purge jobs&quot;
  9323. section) and is removed from Synapse's database.</li>
  9324. </ul>
  9325. <p>Since purge jobs don't run continuously, this means that an event might
  9326. stay in a server's database for longer than the value for <code>max_lifetime</code>
  9327. in the room would allow, though hidden from clients.</p>
  9328. <p>Similarly, if a server (with support for message retention policies
  9329. enabled) receives from another server an event that should have been
  9330. purged according to its room's policy, then the receiving server will
  9331. process and store that event until it's picked up by the next purge job,
  9332. though it will always hide it from clients.</p>
  9333. <p>Synapse requires at least one message in each room, so it will never
  9334. delete the last message in a room. It will, however, hide it from
  9335. clients.</p>
  9336. <h2 id="server-configuration"><a class="header" href="#server-configuration">Server configuration</a></h2>
  9337. <p>Support for this feature can be enabled and configured by adding a the
  9338. <code>retention</code> in the Synapse configuration file (see
  9339. <a href="usage/configuration/config_documentation.html#retention">configuration manual</a>).</p>
  9340. <p>To enable support for message retention policies, set the setting
  9341. <code>enabled</code> in this section to <code>true</code>.</p>
  9342. <h3 id="default-policy"><a class="header" href="#default-policy">Default policy</a></h3>
  9343. <p>A default message retention policy is a policy defined in Synapse's
  9344. configuration that is used by Synapse for every room that doesn't have a
  9345. message retention policy configured in its state. This allows server
  9346. admins to ensure that messages are never kept indefinitely in a server's
  9347. database. </p>
  9348. <p>A default policy can be defined as such, by adding the <code>retention</code> option in
  9349. the configuration file and adding these sub-options:</p>
  9350. <pre><code class="language-yaml">default_policy:
  9351. min_lifetime: 1d
  9352. max_lifetime: 1y
  9353. </code></pre>
  9354. <p>Here, <code>min_lifetime</code> and <code>max_lifetime</code> have the same meaning and level
  9355. of support as previously described. They can be expressed either as a
  9356. duration (using the units <code>s</code> (seconds), <code>m</code> (minutes), <code>h</code> (hours),
  9357. <code>d</code> (days), <code>w</code> (weeks) and <code>y</code> (years)) or as a number of milliseconds.</p>
  9358. <h3 id="purge-jobs"><a class="header" href="#purge-jobs">Purge jobs</a></h3>
  9359. <p>Purge jobs are the jobs that Synapse runs in the background to purge
  9360. expired events from the database. They are only run if support for
  9361. message retention policies is enabled in the server's configuration. If
  9362. no configuration for purge jobs is configured by the server admin,
  9363. Synapse will use a default configuration, which is described here in the
  9364. <a href="usage/configuration/config_documentation.html#retention">configuration manual</a>.</p>
  9365. <p>Some server admins might want a finer control on when events are removed
  9366. depending on an event's room's policy. This can be done by setting the
  9367. <code>purge_jobs</code> sub-section in the <code>retention</code> section of the configuration
  9368. file. An example of such configuration could be:</p>
  9369. <pre><code class="language-yaml">purge_jobs:
  9370. - longest_max_lifetime: 3d
  9371. interval: 12h
  9372. - shortest_max_lifetime: 3d
  9373. longest_max_lifetime: 1w
  9374. interval: 1d
  9375. - shortest_max_lifetime: 1w
  9376. interval: 2d
  9377. </code></pre>
  9378. <p>In this example, we define three jobs:</p>
  9379. <ul>
  9380. <li>one that runs twice a day (every 12 hours) and purges events in rooms
  9381. which policy's <code>max_lifetime</code> is lower or equal to 3 days.</li>
  9382. <li>one that runs once a day and purges events in rooms which policy's
  9383. <code>max_lifetime</code> is between 3 days and a week.</li>
  9384. <li>one that runs once every 2 days and purges events in rooms which
  9385. policy's <code>max_lifetime</code> is greater than a week.</li>
  9386. </ul>
  9387. <p>Note that this example is tailored to show different configurations and
  9388. features slightly more jobs than it's probably necessary (in practice, a
  9389. server admin would probably consider it better to replace the two last
  9390. jobs with one that runs once a day and handles rooms which
  9391. policy's <code>max_lifetime</code> is greater than 3 days).</p>
  9392. <p>Keep in mind, when configuring these jobs, that a purge job can become
  9393. quite heavy on the server if it targets many rooms, therefore prefer
  9394. having jobs with a low interval that target a limited set of rooms. Also
  9395. make sure to include a job with no minimum and one with no maximum to
  9396. make sure your configuration handles every policy.</p>
  9397. <p>As previously mentioned in this documentation, while a purge job that
  9398. runs e.g. every day means that an expired event might stay in the
  9399. database for up to a day after its expiry, Synapse hides expired events
  9400. from clients as soon as they expire, so the event is not visible to
  9401. local users between its expiry date and the moment it gets purged from
  9402. the server's database.</p>
  9403. <h3 id="lifetime-limits"><a class="header" href="#lifetime-limits">Lifetime limits</a></h3>
  9404. <p>Server admins can set limits on the values of <code>max_lifetime</code> to use when
  9405. purging old events in a room. These limits can be defined under the
  9406. <code>retention</code> option in the configuration file:</p>
  9407. <pre><code class="language-yaml">allowed_lifetime_min: 1d
  9408. allowed_lifetime_max: 1y
  9409. </code></pre>
  9410. <p>The limits are considered when running purge jobs. If necessary, the
  9411. effective value of <code>max_lifetime</code> will be brought between
  9412. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> (inclusive).
  9413. This means that, if the value of <code>max_lifetime</code> defined in the room's state
  9414. is lower than <code>allowed_lifetime_min</code>, the value of <code>allowed_lifetime_min</code>
  9415. will be used instead. Likewise, if the value of <code>max_lifetime</code> is higher
  9416. than <code>allowed_lifetime_max</code>, the value of <code>allowed_lifetime_max</code> will be
  9417. used instead.</p>
  9418. <p>In the example above, we ensure Synapse never deletes events that are less
  9419. than one day old, and that it always deletes events that are over a year
  9420. old.</p>
  9421. <p>If a default policy is set, and its <code>max_lifetime</code> value is lower than
  9422. <code>allowed_lifetime_min</code> or higher than <code>allowed_lifetime_max</code>, the same
  9423. process applies.</p>
  9424. <p>Both parameters are optional; if one is omitted Synapse won't use it to
  9425. adjust the effective value of <code>max_lifetime</code>.</p>
  9426. <p>Like other settings in this section, these parameters can be expressed
  9427. either as a duration or as a number of milliseconds.</p>
  9428. <h2 id="room-configuration"><a class="header" href="#room-configuration">Room configuration</a></h2>
  9429. <p>To configure a room's message retention policy, a room's admin or
  9430. moderator needs to send a state event in that room with the type
  9431. <code>m.room.retention</code> and the following content:</p>
  9432. <pre><code class="language-json">{
  9433. &quot;max_lifetime&quot;: ...
  9434. }
  9435. </code></pre>
  9436. <p>In this event's content, the <code>max_lifetime</code> parameter has the same
  9437. meaning as previously described, and needs to be expressed in
  9438. milliseconds. The event's content can also include a <code>min_lifetime</code>
  9439. parameter, which has the same meaning and limited support as previously
  9440. described.</p>
  9441. <p>Note that over every server in the room, only the ones with support for
  9442. message retention policies will actually remove expired events. This
  9443. support is currently not enabled by default in Synapse.</p>
  9444. <h2 id="note-on-reclaiming-disk-space"><a class="header" href="#note-on-reclaiming-disk-space">Note on reclaiming disk space</a></h2>
  9445. <p>While purge jobs actually delete data from the database, the disk space
  9446. used by the database might not decrease immediately on the database's
  9447. host. However, even though the database engine won't free up the disk
  9448. space, it will start writing new data into where the purged data was.</p>
  9449. <p>If you want to reclaim the freed disk space anyway and return it to the
  9450. operating system, the server admin needs to run <code>VACUUM FULL;</code> (or
  9451. <code>VACUUM;</code> for SQLite databases) on Synapse's database (see the related
  9452. <a href="https://www.postgresql.org/docs/current/sql-vacuum.html">PostgreSQL documentation</a>).</p>
  9453. <div style="break-before: page; page-break-before: always;"></div><h1 id="modules-2"><a class="header" href="#modules-2">Modules</a></h1>
  9454. <p>Synapse supports extending its functionality by configuring external modules.</p>
  9455. <p><strong>Note</strong>: When using third-party modules, you effectively allow someone else to run
  9456. custom code on your Synapse homeserver. Server admins are encouraged to verify the
  9457. provenance of the modules they use on their homeserver and make sure the modules aren't
  9458. running malicious code on their instance.</p>
  9459. <h2 id="using-modules"><a class="header" href="#using-modules">Using modules</a></h2>
  9460. <p>To use a module on Synapse, add it to the <code>modules</code> section of the configuration file:</p>
  9461. <pre><code class="language-yaml">modules:
  9462. - module: my_super_module.MySuperClass
  9463. config:
  9464. do_thing: true
  9465. - module: my_other_super_module.SomeClass
  9466. config: {}
  9467. </code></pre>
  9468. <p>Each module is defined by a path to a Python class as well as a configuration. This
  9469. information for a given module should be available in the module's own documentation.</p>
  9470. <h2 id="using-multiple-modules"><a class="header" href="#using-multiple-modules">Using multiple modules</a></h2>
  9471. <p>The order in which modules are listed in this section is important. When processing an
  9472. action that can be handled by several modules, Synapse will always prioritise the module
  9473. that appears first (i.e. is the highest in the list). This means:</p>
  9474. <ul>
  9475. <li>If several modules register the same callback, the callback registered by the module
  9476. that appears first is used.</li>
  9477. <li>If several modules try to register a handler for the same HTTP path, only the handler
  9478. registered by the module that appears first is used. Handlers registered by the other
  9479. module(s) are ignored and Synapse will log a warning message about them.</li>
  9480. </ul>
  9481. <p>Note that Synapse doesn't allow multiple modules implementing authentication checkers via
  9482. the password auth provider feature for the same login type with different fields. If this
  9483. happens, Synapse will refuse to start.</p>
  9484. <h2 id="current-status"><a class="header" href="#current-status">Current status</a></h2>
  9485. <p>We are currently in the process of migrating module interfaces to this system. While some
  9486. interfaces might be compatible with it, others still require configuring modules in
  9487. another part of Synapse's configuration file.</p>
  9488. <p>Currently, only the following pre-existing interfaces are compatible with this new system:</p>
  9489. <ul>
  9490. <li>spam checker</li>
  9491. <li>third-party rules</li>
  9492. <li>presence router</li>
  9493. <li>password auth providers</li>
  9494. </ul>
  9495. <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>
  9496. <p>A module is a Python class that uses Synapse's module API to interact with the
  9497. homeserver. It can register callbacks that Synapse will call on specific operations, as
  9498. well as web resources to attach to Synapse's web server.</p>
  9499. <p>When instantiated, a module is given its parsed configuration as well as an instance of
  9500. the <code>synapse.module_api.ModuleApi</code> class. The configuration is a dictionary, and is
  9501. either the output of the module's <code>parse_config</code> static method (see below), or the
  9502. configuration associated with the module in Synapse's configuration file.</p>
  9503. <p>See the documentation for the <code>ModuleApi</code> class
  9504. <a href="https://github.com/matrix-org/synapse/blob/master/synapse/module_api/__init__.py">here</a>.</p>
  9505. <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>
  9506. <p>If Synapse is running with other modules configured, the order each module appears in
  9507. within the <code>modules</code> section of the Synapse configuration file might restrict what it can
  9508. or cannot register. See <a href="modules/index.html#using-multiple-modules">this section</a> for more
  9509. information.</p>
  9510. <p>On top of the rules listed in the link above, if a callback returns a value that should
  9511. cause the current operation to fail (e.g. if a callback checking an event returns with a
  9512. value that should cause the event to be denied), Synapse will fail the operation and
  9513. ignore any subsequent callbacks that should have been run after this one.</p>
  9514. <p>The documentation for each callback mentions how Synapse behaves when
  9515. multiple modules implement it.</p>
  9516. <h2 id="handling-the-modules-configuration"><a class="header" href="#handling-the-modules-configuration">Handling the module's configuration</a></h2>
  9517. <p>A module can implement the following static method:</p>
  9518. <pre><code class="language-python">@staticmethod
  9519. def parse_config(config: dict) -&gt; Any
  9520. </code></pre>
  9521. <p>This method is given a dictionary resulting from parsing the YAML configuration for the
  9522. module. It may modify it (for example by parsing durations expressed as strings (e.g.
  9523. &quot;5d&quot;) into milliseconds, etc.), and return the modified dictionary. It may also verify
  9524. that the configuration is correct, and raise an instance of
  9525. <code>synapse.module_api.errors.ConfigError</code> if not.</p>
  9526. <h2 id="registering-a-web-resource"><a class="header" href="#registering-a-web-resource">Registering a web resource</a></h2>
  9527. <p>Modules can register web resources onto Synapse's web server using the following module
  9528. API method:</p>
  9529. <pre><code class="language-python">def ModuleApi.register_web_resource(path: str, resource: IResource) -&gt; None
  9530. </code></pre>
  9531. <p>The path is the full absolute path to register the resource at. For example, if you
  9532. register a resource for the path <code>/_synapse/client/my_super_module/say_hello</code>, Synapse
  9533. will serve it at <code>http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello</code>. Note
  9534. that Synapse does not allow registering resources for several sub-paths in the <code>/_matrix</code>
  9535. namespace (such as anything under <code>/_matrix/client</code> for example). It is strongly
  9536. recommended that modules register their web resources under the <code>/_synapse/client</code>
  9537. namespace.</p>
  9538. <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>
  9539. interface (such as <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.web.resource.Resource.html">Resource</a>).</p>
  9540. <p>Only one resource can be registered for a given path. If several modules attempt to
  9541. register a resource for the same path, the module that appears first in Synapse's
  9542. configuration file takes priority.</p>
  9543. <p>Modules <strong>must</strong> register their web resources in their <code>__init__</code> method.</p>
  9544. <h2 id="registering-a-callback"><a class="header" href="#registering-a-callback">Registering a callback</a></h2>
  9545. <p>Modules can use Synapse's module API to register callbacks. Callbacks are functions that
  9546. Synapse will call when performing specific actions. Callbacks must be asynchronous (unless
  9547. specified otherwise), and are split in categories. A single module may implement callbacks
  9548. from multiple categories, and is under no obligation to implement all callbacks from the
  9549. categories it registers callbacks for.</p>
  9550. <p>Modules can register callbacks using one of the module API's <code>register_[...]_callbacks</code>
  9551. methods. The callback functions are passed to these methods as keyword arguments, with
  9552. the callback name as the argument name and the function as its value. A
  9553. <code>register_[...]_callbacks</code> method exists for each category.</p>
  9554. <p>Callbacks for each category can be found on their respective page of the
  9555. <a href="https://matrix-org.github.io/synapse">Synapse documentation website</a>.</p>
  9556. <h2 id="caching-1"><a class="header" href="#caching-1">Caching</a></h2>
  9557. <p><em>Added in Synapse 1.74.0.</em></p>
  9558. <p>Modules can leverage Synapse's caching tools to manage their own cached functions. This
  9559. can be helpful for modules that need to repeatedly request the same data from the database
  9560. or a remote service.</p>
  9561. <p>Functions that need to be wrapped with a cache need to be decorated with a <code>@cached()</code>
  9562. decorator (which can be imported from <code>synapse.module_api</code>) and registered with the
  9563. <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>
  9564. API when initialising the module. If the module needs to invalidate an entry in a cache,
  9565. 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>
  9566. API, with the function to invalidate the cache of and the key(s) of the entry to
  9567. invalidate.</p>
  9568. <p>Below is an example of a simple module using a cached function:</p>
  9569. <pre><code class="language-python">from typing import Any
  9570. from synapse.module_api import cached, ModuleApi
  9571. class MyModule:
  9572. def __init__(self, config: Any, api: ModuleApi):
  9573. self.api = api
  9574. # Register the cached function so Synapse knows how to correctly invalidate
  9575. # entries for it.
  9576. self.api.register_cached_function(self.get_user_from_id)
  9577. @cached()
  9578. async def get_department_for_user(self, user_id: str) -&gt; str:
  9579. &quot;&quot;&quot;A function with a cache.&quot;&quot;&quot;
  9580. # Request a department from an external service.
  9581. return await self.http_client.get_json(
  9582. &quot;https://int.example.com/users&quot;, {&quot;user_id&quot;: user_id)
  9583. )[&quot;department&quot;]
  9584. async def do_something_with_users(self) -&gt; None:
  9585. &quot;&quot;&quot;Calls the cached function and then invalidates an entry in its cache.&quot;&quot;&quot;
  9586. user_id = &quot;@alice:example.com&quot;
  9587. # Get the user. Since get_department_for_user is wrapped with a cache,
  9588. # the return value for this user_id will be cached.
  9589. department = await self.get_department_for_user(user_id)
  9590. # Do something with `department`...
  9591. # Let's say something has changed with our user, and the entry we have for
  9592. # them in the cache is out of date, so we want to invalidate it.
  9593. await self.api.invalidate_cache(self.get_department_for_user, (user_id,))
  9594. </code></pre>
  9595. <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>
  9596. <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>
  9597. <p>Spam checker callbacks allow module developers to implement spam mitigation actions for
  9598. Synapse instances. Spam checker callbacks can be registered using the module API's
  9599. <code>register_spam_checker_callbacks</code> method.</p>
  9600. <h2 id="callbacks"><a class="header" href="#callbacks">Callbacks</a></h2>
  9601. <p>The available spam checker callbacks are:</p>
  9602. <h3 id="check_event_for_spam"><a class="header" href="#check_event_for_spam"><code>check_event_for_spam</code></a></h3>
  9603. <p><em>First introduced in Synapse v1.37.0</em></p>
  9604. <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>
  9605. <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]
  9606. </code></pre>
  9607. <p>Called when receiving an event from a client or via federation. The callback must return one of:</p>
  9608. <ul>
  9609. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9610. decide to reject it.</li>
  9611. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9612. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  9613. <li>(deprecated) a non-<code>Codes</code> <code>str</code> to reject the operation and specify an error message. Note that clients
  9614. typically will not localize the error message to the user's preferred locale.</li>
  9615. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  9616. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  9617. </ul>
  9618. <p>If multiple modules implement this callback, they will be considered in order. If a
  9619. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9620. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9621. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9622. this callback.</p>
  9623. <h3 id="user_may_join_room"><a class="header" href="#user_may_join_room"><code>user_may_join_room</code></a></h3>
  9624. <p><em>First introduced in Synapse v1.37.0</em></p>
  9625. <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>
  9626. <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]
  9627. </code></pre>
  9628. <p>Called when a user is trying to join a room. The user is represented by their Matrix user ID (e.g.
  9629. <code>@alice:example.com</code>) and the room is represented by its Matrix ID (e.g.
  9630. <code>!room:example.com</code>). The module is also given a boolean to indicate whether the user
  9631. currently has a pending invite in the room.</p>
  9632. <p>This callback isn't called if the join is performed by a server administrator, or in the
  9633. context of a room creation.</p>
  9634. <p>The callback must return one of:</p>
  9635. <ul>
  9636. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9637. decide to reject it.</li>
  9638. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9639. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  9640. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  9641. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  9642. </ul>
  9643. <p>If multiple modules implement this callback, they will be considered in order. If a
  9644. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9645. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9646. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9647. this callback.</p>
  9648. <h3 id="user_may_invite"><a class="header" href="#user_may_invite"><code>user_may_invite</code></a></h3>
  9649. <p><em>First introduced in Synapse v1.37.0</em></p>
  9650. <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>
  9651. <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]
  9652. </code></pre>
  9653. <p>Called when processing an invitation. Both inviter and invitee are
  9654. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  9655. <p>The callback must return one of:</p>
  9656. <ul>
  9657. <li>
  9658. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9659. decide to reject it.</p>
  9660. </li>
  9661. <li>
  9662. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9663. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9664. </li>
  9665. <li>
  9666. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9667. </li>
  9668. <li>
  9669. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9670. </li>
  9671. </ul>
  9672. <p>If multiple modules implement this callback, they will be considered in order. If a
  9673. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9674. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9675. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9676. this callback.</p>
  9677. <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>
  9678. <p><em>First introduced in Synapse v1.45.0</em></p>
  9679. <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>
  9680. <pre><code class="language-python">async def user_may_send_3pid_invite(
  9681. inviter: str,
  9682. medium: str,
  9683. address: str,
  9684. room_id: str,
  9685. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  9686. </code></pre>
  9687. <p>Called when processing an invitation using a third-party identifier (also called a 3PID,
  9688. e.g. an email address or a phone number). </p>
  9689. <p>The inviter is represented by their Matrix user ID (e.g. <code>@alice:example.com</code>), and the
  9690. invitee is represented by its medium (e.g. &quot;email&quot;) and its address
  9691. (e.g. <code>alice@example.com</code>). See <a href="https://matrix.org/docs/spec/appendices#pid-types">the Matrix specification</a>
  9692. for more information regarding third-party identifiers.</p>
  9693. <p>For example, a call to this callback to send an invitation to the email address
  9694. <code>alice@example.com</code> would look like this:</p>
  9695. <pre><code class="language-python">await user_may_send_3pid_invite(
  9696. &quot;@bob:example.com&quot;, # The inviter's user ID
  9697. &quot;email&quot;, # The medium of the 3PID to invite
  9698. &quot;alice@example.com&quot;, # The address of the 3PID to invite
  9699. &quot;!some_room:example.com&quot;, # The ID of the room to send the invite into
  9700. )
  9701. </code></pre>
  9702. <p><strong>Note</strong>: If the third-party identifier is already associated with a matrix user ID,
  9703. <a href="modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a> will be used instead.</p>
  9704. <p>The callback must return one of:</p>
  9705. <ul>
  9706. <li>
  9707. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9708. decide to reject it.</p>
  9709. </li>
  9710. <li>
  9711. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9712. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9713. </li>
  9714. <li>
  9715. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9716. </li>
  9717. <li>
  9718. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9719. </li>
  9720. </ul>
  9721. <p>If multiple modules implement this callback, they will be considered in order. If a
  9722. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9723. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9724. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9725. this callback.</p>
  9726. <h3 id="user_may_create_room"><a class="header" href="#user_may_create_room"><code>user_may_create_room</code></a></h3>
  9727. <p><em>First introduced in Synapse v1.37.0</em></p>
  9728. <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>
  9729. <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]
  9730. </code></pre>
  9731. <p>Called when processing a room creation request.</p>
  9732. <p>The callback must return one of:</p>
  9733. <ul>
  9734. <li>
  9735. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9736. decide to reject it.</p>
  9737. </li>
  9738. <li>
  9739. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9740. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9741. </li>
  9742. <li>
  9743. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9744. </li>
  9745. <li>
  9746. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9747. </li>
  9748. </ul>
  9749. <p>If multiple modules implement this callback, they will be considered in order. If a
  9750. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9751. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9752. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9753. this callback.</p>
  9754. <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>
  9755. <p><em>First introduced in Synapse v1.37.0</em></p>
  9756. <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>
  9757. <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]
  9758. </code></pre>
  9759. <p>Called when trying to associate an alias with an existing room.</p>
  9760. <p>The callback must return one of:</p>
  9761. <ul>
  9762. <li>
  9763. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9764. decide to reject it.</p>
  9765. </li>
  9766. <li>
  9767. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9768. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9769. </li>
  9770. <li>
  9771. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9772. </li>
  9773. <li>
  9774. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9775. </li>
  9776. </ul>
  9777. <p>If multiple modules implement this callback, they will be considered in order. If a
  9778. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9779. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9780. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9781. this callback.</p>
  9782. <h3 id="user_may_publish_room"><a class="header" href="#user_may_publish_room"><code>user_may_publish_room</code></a></h3>
  9783. <p><em>First introduced in Synapse v1.37.0</em></p>
  9784. <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>
  9785. <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]
  9786. </code></pre>
  9787. <p>Called when trying to publish a room to the homeserver's public rooms directory.</p>
  9788. <p>The callback must return one of:</p>
  9789. <ul>
  9790. <li>
  9791. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9792. decide to reject it.</p>
  9793. </li>
  9794. <li>
  9795. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9796. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9797. </li>
  9798. <li>
  9799. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9800. </li>
  9801. <li>
  9802. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9803. </li>
  9804. </ul>
  9805. <p>If multiple modules implement this callback, they will be considered in order. If a
  9806. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9807. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9808. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9809. this callback.</p>
  9810. <h3 id="check_username_for_spam"><a class="header" href="#check_username_for_spam"><code>check_username_for_spam</code></a></h3>
  9811. <p><em>First introduced in Synapse v1.37.0</em></p>
  9812. <pre><code class="language-python">async def check_username_for_spam(user_profile: synapse.module_api.UserProfile) -&gt; bool
  9813. </code></pre>
  9814. <p>Called when computing search results in the user directory. The module must return a
  9815. <code>bool</code> indicating whether the given user should be excluded from user directory
  9816. searches. Return <code>True</code> to indicate that the user is spammy and exclude them from
  9817. search results; otherwise return <code>False</code>.</p>
  9818. <p>The profile is represented as a dictionary with the following keys:</p>
  9819. <ul>
  9820. <li><code>user_id: str</code>. The Matrix ID for this user.</li>
  9821. <li><code>display_name: Optional[str]</code>. The user's display name, or <code>None</code> if this user
  9822. has not set a display name.</li>
  9823. <li><code>avatar_url: Optional[str]</code>. The <code>mxc://</code> URL to the user's avatar, or <code>None</code>
  9824. if this user has not set an avatar.</li>
  9825. </ul>
  9826. <p>The module is given a copy of the original dictionary, so modifying it from within the
  9827. module cannot modify a user's profile when included in user directory search results.</p>
  9828. <p>If multiple modules implement this callback, they will be considered in order. If a
  9829. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  9830. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  9831. any of the subsequent implementations of this callback.</p>
  9832. <h3 id="check_registration_for_spam"><a class="header" href="#check_registration_for_spam"><code>check_registration_for_spam</code></a></h3>
  9833. <p><em>First introduced in Synapse v1.37.0</em></p>
  9834. <pre><code class="language-python">async def check_registration_for_spam(
  9835. email_threepid: Optional[dict],
  9836. username: Optional[str],
  9837. request_info: Collection[Tuple[str, str]],
  9838. auth_provider_id: Optional[str] = None,
  9839. ) -&gt; &quot;synapse.spam_checker_api.RegistrationBehaviour&quot;
  9840. </code></pre>
  9841. <p>Called when registering a new user. The module must return a <code>RegistrationBehaviour</code>
  9842. indicating whether the registration can go through or must be denied, or whether the user
  9843. may be allowed to register but will be shadow banned.</p>
  9844. <p>The arguments passed to this callback are:</p>
  9845. <ul>
  9846. <li><code>email_threepid</code>: The email address used for registering, if any.</li>
  9847. <li><code>username</code>: The username the user would like to register. Can be <code>None</code>, meaning that
  9848. Synapse will generate one later.</li>
  9849. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  9850. second item is an IP address. These user agents and IP addresses are the ones that were
  9851. used during the registration process.</li>
  9852. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  9853. </ul>
  9854. <p>If multiple modules implement this callback, they will be considered in order. If a
  9855. callback returns <code>RegistrationBehaviour.ALLOW</code>, Synapse falls through to the next one.
  9856. The value of the first callback that does not return <code>RegistrationBehaviour.ALLOW</code> will
  9857. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9858. this callback.</p>
  9859. <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>
  9860. <p><em>First introduced in Synapse v1.37.0</em></p>
  9861. <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>
  9862. <pre><code class="language-python">async def check_media_file_for_spam(
  9863. file_wrapper: &quot;synapse.media.media_storage.ReadableFileWrapper&quot;,
  9864. file_info: &quot;synapse.media._base.FileInfo&quot;,
  9865. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  9866. </code></pre>
  9867. <p>Called when storing a local or remote file.</p>
  9868. <p>The callback must return one of:</p>
  9869. <ul>
  9870. <li>
  9871. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9872. decide to reject it.</p>
  9873. </li>
  9874. <li>
  9875. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9876. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9877. </li>
  9878. <li>
  9879. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9880. </li>
  9881. <li>
  9882. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9883. </li>
  9884. </ul>
  9885. <p>If multiple modules implement this callback, they will be considered in order. If a
  9886. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9887. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9888. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9889. this callback.</p>
  9890. <h3 id="should_drop_federated_event"><a class="header" href="#should_drop_federated_event"><code>should_drop_federated_event</code></a></h3>
  9891. <p><em>First introduced in Synapse v1.60.0</em></p>
  9892. <pre><code class="language-python">async def should_drop_federated_event(event: &quot;synapse.events.EventBase&quot;) -&gt; bool
  9893. </code></pre>
  9894. <p>Called when checking whether a remote server can federate an event with us. <strong>Returning
  9895. <code>True</code> from this function will silently drop a federated event and split-brain our view
  9896. of a room's DAG, and thus you shouldn't use this callback unless you know what you are
  9897. doing.</strong></p>
  9898. <p>If multiple modules implement this callback, they will be considered in order. If a
  9899. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  9900. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  9901. any of the subsequent implementations of this callback.</p>
  9902. <h3 id="check_login_for_spam"><a class="header" href="#check_login_for_spam"><code>check_login_for_spam</code></a></h3>
  9903. <p><em>First introduced in Synapse v1.87.0</em></p>
  9904. <pre><code class="language-python">async def check_login_for_spam(
  9905. user_id: str,
  9906. device_id: Optional[str],
  9907. initial_display_name: Optional[str],
  9908. request_info: Collection[Tuple[Optional[str], str]],
  9909. auth_provider_id: Optional[str] = None,
  9910. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;]
  9911. </code></pre>
  9912. <p>Called when a user logs in.</p>
  9913. <p>The arguments passed to this callback are:</p>
  9914. <ul>
  9915. <li><code>user_id</code>: The user ID the user is logging in with</li>
  9916. <li><code>device_id</code>: The device ID the user is re-logging into.</li>
  9917. <li><code>initial_display_name</code>: The device display name, if any.</li>
  9918. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  9919. second item is an IP address. These user agents and IP addresses are the ones that were
  9920. used during the login process.</li>
  9921. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  9922. </ul>
  9923. <p>If multiple modules implement this callback, they will be considered in order. If a
  9924. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9925. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9926. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9927. this callback.</p>
  9928. <p><em>Note:</em> This will not be called when a user registers.</p>
  9929. <h2 id="example"><a class="header" href="#example">Example</a></h2>
  9930. <p>The example below is a module that implements the spam checker callback
  9931. <code>check_event_for_spam</code> to deny any message sent by users whose Matrix user IDs are
  9932. mentioned in a configured list, and registers a web resource to the path
  9933. <code>/_synapse/client/list_spam_checker/is_evil</code> that returns a JSON object indicating
  9934. whether the provided user appears in that list.</p>
  9935. <pre><code class="language-python">import json
  9936. from typing import Union
  9937. from twisted.web.resource import Resource
  9938. from twisted.web.server import Request
  9939. from synapse.module_api import ModuleApi
  9940. class IsUserEvilResource(Resource):
  9941. def __init__(self, config):
  9942. super(IsUserEvilResource, self).__init__()
  9943. self.evil_users = config.get(&quot;evil_users&quot;) or []
  9944. def render_GET(self, request: Request):
  9945. user = request.args.get(b&quot;user&quot;)[0].decode()
  9946. request.setHeader(b&quot;Content-Type&quot;, b&quot;application/json&quot;)
  9947. return json.dumps({&quot;evil&quot;: user in self.evil_users}).encode()
  9948. class ListSpamChecker:
  9949. def __init__(self, config: dict, api: ModuleApi):
  9950. self.api = api
  9951. self.evil_users = config.get(&quot;evil_users&quot;) or []
  9952. self.api.register_spam_checker_callbacks(
  9953. check_event_for_spam=self.check_event_for_spam,
  9954. )
  9955. self.api.register_web_resource(
  9956. path=&quot;/_synapse/client/list_spam_checker/is_evil&quot;,
  9957. resource=IsUserEvilResource(config),
  9958. )
  9959. async def check_event_for_spam(self, event: &quot;synapse.events.EventBase&quot;) -&gt; Union[Literal[&quot;NOT_SPAM&quot;], Codes]:
  9960. if event.sender in self.evil_users:
  9961. return Codes.FORBIDDEN
  9962. else:
  9963. return synapse.module_api.NOT_SPAM
  9964. </code></pre>
  9965. <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>
  9966. <p>Third party rules callbacks allow module developers to add extra checks to verify the
  9967. validity of incoming events. Third party event rules callbacks can be registered using
  9968. the module API's <code>register_third_party_rules_callbacks</code> method.</p>
  9969. <h2 id="callbacks-1"><a class="header" href="#callbacks-1">Callbacks</a></h2>
  9970. <p>The available third party rules callbacks are:</p>
  9971. <h3 id="check_event_allowed"><a class="header" href="#check_event_allowed"><code>check_event_allowed</code></a></h3>
  9972. <p><em>First introduced in Synapse v1.39.0</em></p>
  9973. <pre><code class="language-python">async def check_event_allowed(
  9974. event: &quot;synapse.events.EventBase&quot;,
  9975. state_events: &quot;synapse.types.StateMap&quot;,
  9976. ) -&gt; Tuple[bool, Optional[dict]]
  9977. </code></pre>
  9978. <p><strong><span style="color:red">
  9979. This callback is very experimental and can and will break without notice. Module developers
  9980. are encouraged to implement <code>check_event_for_spam</code> from the spam checker category instead.
  9981. </span></strong></p>
  9982. <p>Called when processing any incoming event, with the event and a <code>StateMap</code>
  9983. representing the current state of the room the event is being sent into. A <code>StateMap</code> is
  9984. a dictionary that maps tuples containing an event type and a state key to the
  9985. corresponding state event. For example retrieving the room's <code>m.room.create</code> event from
  9986. the <code>state_events</code> argument would look like this: <code>state_events.get((&quot;m.room.create&quot;, &quot;&quot;))</code>.
  9987. The module must return a boolean indicating whether the event can be allowed.</p>
  9988. <p>Note that this callback function processes incoming events coming via federation
  9989. traffic (on top of client traffic). This means denying an event might cause the local
  9990. copy of the room's history to diverge from that of remote servers. This may cause
  9991. federation issues in the room. It is strongly recommended to only deny events using this
  9992. callback function if the sender is a local user, or in a private federation in which all
  9993. servers are using the same module, with the same configuration.</p>
  9994. <p>If the boolean returned by the module is <code>True</code>, it may also tell Synapse to replace the
  9995. event with new data by returning the new event's data as a dictionary. In order to do
  9996. that, it is recommended the module calls <code>event.get_dict()</code> to get the current event as a
  9997. dictionary, and modify the returned dictionary accordingly.</p>
  9998. <p>If <code>check_event_allowed</code> raises an exception, the module is assumed to have failed.
  9999. The event will not be accepted but is not treated as explicitly rejected, either.
  10000. An HTTP request causing the module check will likely result in a 500 Internal
  10001. Server Error.</p>
  10002. <p>When the boolean returned by the module is <code>False</code>, the event is rejected.
  10003. (Module developers should not use exceptions for rejection.)</p>
  10004. <p>Note that replacing the event only works for events sent by local users, not for events
  10005. received over federation.</p>
  10006. <p>If multiple modules implement this callback, they will be considered in order. If a
  10007. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10008. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10009. any of the subsequent implementations of this callback.</p>
  10010. <h3 id="on_create_room"><a class="header" href="#on_create_room"><code>on_create_room</code></a></h3>
  10011. <p><em>First introduced in Synapse v1.39.0</em></p>
  10012. <pre><code class="language-python">async def on_create_room(
  10013. requester: &quot;synapse.types.Requester&quot;,
  10014. request_content: dict,
  10015. is_requester_admin: bool,
  10016. ) -&gt; None
  10017. </code></pre>
  10018. <p>Called when processing a room creation request, with the <code>Requester</code> object for the user
  10019. performing the request, a dictionary representing the room creation request's JSON body
  10020. (see <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom">the spec</a>
  10021. for a list of possible parameters), and a boolean indicating whether the user performing
  10022. the request is a server admin.</p>
  10023. <p>Modules can modify the <code>request_content</code> (by e.g. adding events to its <code>initial_state</code>),
  10024. or deny the room's creation by raising a <code>module_api.errors.SynapseError</code>.</p>
  10025. <p>If multiple modules implement this callback, they will be considered in order. If a
  10026. callback returns without raising an exception, Synapse falls through to the next one. The
  10027. room creation will be forbidden as soon as one of the callbacks raises an exception. If
  10028. this happens, Synapse will not call any of the subsequent implementations of this
  10029. callback.</p>
  10030. <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>
  10031. <p><em>First introduced in Synapse v1.39.0</em></p>
  10032. <pre><code class="language-python">async def check_threepid_can_be_invited(
  10033. medium: str,
  10034. address: str,
  10035. state_events: &quot;synapse.types.StateMap&quot;,
  10036. ) -&gt; bool:
  10037. </code></pre>
  10038. <p>Called when processing an invite via a third-party identifier (i.e. email or phone number).
  10039. The module must return a boolean indicating whether the invite can go through.</p>
  10040. <p>If multiple modules implement this callback, they will be considered in order. If a
  10041. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10042. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10043. any of the subsequent implementations of this callback.</p>
  10044. <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>
  10045. <p><em>First introduced in Synapse v1.39.0</em></p>
  10046. <pre><code class="language-python">async def check_visibility_can_be_modified(
  10047. room_id: str,
  10048. state_events: &quot;synapse.types.StateMap&quot;,
  10049. new_visibility: str,
  10050. ) -&gt; bool:
  10051. </code></pre>
  10052. <p>Called when changing the visibility of a room in the local public room directory. The
  10053. visibility is a string that's either &quot;public&quot; or &quot;private&quot;. The module must return a
  10054. boolean indicating whether the change can go through.</p>
  10055. <p>If multiple modules implement this callback, they will be considered in order. If a
  10056. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10057. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10058. any of the subsequent implementations of this callback.</p>
  10059. <h3 id="on_new_event"><a class="header" href="#on_new_event"><code>on_new_event</code></a></h3>
  10060. <p><em>First introduced in Synapse v1.47.0</em></p>
  10061. <pre><code class="language-python">async def on_new_event(
  10062. event: &quot;synapse.events.EventBase&quot;,
  10063. state_events: &quot;synapse.types.StateMap&quot;,
  10064. ) -&gt; None:
  10065. </code></pre>
  10066. <p>Called after sending an event into a room. The module is passed the event, as well
  10067. as the state of the room <em>after</em> the event. This means that if the event is a state event,
  10068. it will be included in this state.</p>
  10069. <p>Note that this callback is called when the event has already been processed and stored
  10070. into the room, which means this callback cannot be used to deny persisting the event. To
  10071. 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>
  10072. <p>For any given event, this callback will be called on every worker process, even if that worker will not end up
  10073. acting on that event. This callback will not be called for events that are marked as rejected.</p>
  10074. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10075. <h3 id="check_can_shutdown_room"><a class="header" href="#check_can_shutdown_room"><code>check_can_shutdown_room</code></a></h3>
  10076. <p><em>First introduced in Synapse v1.55.0</em></p>
  10077. <pre><code class="language-python">async def check_can_shutdown_room(
  10078. user_id: str, room_id: str,
  10079. ) -&gt; bool:
  10080. </code></pre>
  10081. <p>Called when an admin user requests the shutdown of a room. The module must return a
  10082. boolean indicating whether the shutdown can go through. If the callback returns <code>False</code>,
  10083. the shutdown will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  10084. <p>If multiple modules implement this callback, they will be considered in order. If a
  10085. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10086. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10087. any of the subsequent implementations of this callback.</p>
  10088. <h3 id="check_can_deactivate_user"><a class="header" href="#check_can_deactivate_user"><code>check_can_deactivate_user</code></a></h3>
  10089. <p><em>First introduced in Synapse v1.55.0</em></p>
  10090. <pre><code class="language-python">async def check_can_deactivate_user(
  10091. user_id: str, by_admin: bool,
  10092. ) -&gt; bool:
  10093. </code></pre>
  10094. <p>Called when the deactivation of a user is requested. User deactivation can be
  10095. performed by an admin or the user themselves, so developers are encouraged to check the
  10096. requester when implementing this callback. The module must return a
  10097. boolean indicating whether the deactivation can go through. If the callback returns <code>False</code>,
  10098. the deactivation will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  10099. <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>
  10100. <p>If multiple modules implement this callback, they will be considered in order. If a
  10101. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10102. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10103. any of the subsequent implementations of this callback.</p>
  10104. <h3 id="on_profile_update"><a class="header" href="#on_profile_update"><code>on_profile_update</code></a></h3>
  10105. <p><em>First introduced in Synapse v1.54.0</em></p>
  10106. <pre><code class="language-python">async def on_profile_update(
  10107. user_id: str,
  10108. new_profile: &quot;synapse.module_api.ProfileInfo&quot;,
  10109. by_admin: bool,
  10110. deactivation: bool,
  10111. ) -&gt; None:
  10112. </code></pre>
  10113. <p>Called after updating a local user's profile. The update can be triggered either by the
  10114. user themselves or a server admin. The update can also be triggered by a user being
  10115. deactivated (in which case their display name is set to an empty string (<code>&quot;&quot;</code>) and the
  10116. avatar URL is set to <code>None</code>). The module is passed the Matrix ID of the user whose profile
  10117. has been updated, their new profile, as well as a <code>by_admin</code> boolean that is <code>True</code> if the
  10118. update was triggered by a server admin (and <code>False</code> otherwise), and a <code>deactivated</code>
  10119. boolean that is <code>True</code> if the update is a result of the user being deactivated.</p>
  10120. <p>Note that the <code>by_admin</code> boolean is also <code>True</code> if the profile change happens as a result
  10121. of the user logging in through Single Sign-On, or if a server admin updates their own
  10122. profile.</p>
  10123. <p>Per-room profile changes do not trigger this callback to be called. Synapse administrators
  10124. wishing this callback to be called on every profile change are encouraged to disable
  10125. per-room profiles globally using the <code>allow_per_room_profiles</code> configuration setting in
  10126. Synapse's configuration file.
  10127. This callback is not called when registering a user, even when setting it through the
  10128. <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>
  10129. module callback.</p>
  10130. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10131. <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>
  10132. <p><em>First introduced in Synapse v1.54.0</em></p>
  10133. <pre><code class="language-python">async def on_user_deactivation_status_changed(
  10134. user_id: str, deactivated: bool, by_admin: bool
  10135. ) -&gt; None:
  10136. </code></pre>
  10137. <p>Called after deactivating a local user, or reactivating them through the admin API. The
  10138. deactivation can be triggered either by the user themselves or a server admin. The module
  10139. is passed the Matrix ID of the user whose status is changed, as well as a <code>deactivated</code>
  10140. boolean that is <code>True</code> if the user is being deactivated and <code>False</code> if they're being
  10141. reactivated, and a <code>by_admin</code> boolean that is <code>True</code> if the deactivation was triggered by
  10142. a server admin (and <code>False</code> otherwise). This latter <code>by_admin</code> boolean is always <code>True</code>
  10143. if the user is being reactivated, as this operation can only be performed through the
  10144. admin API.</p>
  10145. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10146. <h3 id="on_threepid_bind"><a class="header" href="#on_threepid_bind"><code>on_threepid_bind</code></a></h3>
  10147. <p><em>First introduced in Synapse v1.56.0</em></p>
  10148. <p><strong><span style="color:red">
  10149. This callback is deprecated in favour of the <code>on_add_user_third_party_identifier</code> callback, which
  10150. features the same functionality. The only difference is in name.
  10151. </span></strong></p>
  10152. <pre><code class="language-python">async def on_threepid_bind(user_id: str, medium: str, address: str) -&gt; None:
  10153. </code></pre>
  10154. <p>Called after creating an association between a local user and a third-party identifier
  10155. (email address, phone number). The module is given the Matrix ID of the user the
  10156. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  10157. third-party identifier.</p>
  10158. <p>Note that this callback is <em>not</em> called after a successful association on an <em>identity
  10159. server</em>.</p>
  10160. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10161. <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>
  10162. <p><em>First introduced in Synapse v1.79.0</em></p>
  10163. <pre><code class="language-python">async def on_add_user_third_party_identifier(user_id: str, medium: str, address: str) -&gt; None:
  10164. </code></pre>
  10165. <p>Called after successfully creating an association between a user and a third-party identifier
  10166. (email address, phone number). The module is given the Matrix ID of the user the
  10167. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  10168. third-party identifier (i.e. an email address).</p>
  10169. <p>Note that this callback is <em>not</em> called if a user attempts to bind their third-party identifier
  10170. 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>
  10171. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10172. <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>
  10173. <p><em>First introduced in Synapse v1.79.0</em></p>
  10174. <pre><code class="language-python">async def on_remove_user_third_party_identifier(user_id: str, medium: str, address: str) -&gt; None:
  10175. </code></pre>
  10176. <p>Called after successfully removing an association between a user and a third-party identifier
  10177. (email address, phone number). The module is given the Matrix ID of the user the
  10178. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  10179. third-party identifier (i.e. an email address).</p>
  10180. <p>Note that this callback is <em>not</em> called if a user attempts to unbind their third-party
  10181. 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>
  10182. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10183. <h2 id="example-1"><a class="header" href="#example-1">Example</a></h2>
  10184. <p>The example below is a module that implements the third-party rules callback
  10185. <code>check_event_allowed</code> to censor incoming messages as dictated by a third-party service.</p>
  10186. <pre><code class="language-python">from typing import Optional, Tuple
  10187. from synapse.module_api import ModuleApi
  10188. _DEFAULT_CENSOR_ENDPOINT = &quot;https://my-internal-service.local/censor-event&quot;
  10189. class EventCensorer:
  10190. def __init__(self, config: dict, api: ModuleApi):
  10191. self.api = api
  10192. self._endpoint = config.get(&quot;endpoint&quot;, _DEFAULT_CENSOR_ENDPOINT)
  10193. self.api.register_third_party_rules_callbacks(
  10194. check_event_allowed=self.check_event_allowed,
  10195. )
  10196. async def check_event_allowed(
  10197. self,
  10198. event: &quot;synapse.events.EventBase&quot;,
  10199. state_events: &quot;synapse.types.StateMap&quot;,
  10200. ) -&gt; Tuple[bool, Optional[dict]]:
  10201. event_dict = event.get_dict()
  10202. new_event_content = await self.api.http_client.post_json_get_json(
  10203. uri=self._endpoint, post_json=event_dict,
  10204. )
  10205. event_dict[&quot;content&quot;] = new_event_content
  10206. return event_dict
  10207. </code></pre>
  10208. <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>
  10209. <p>Presence router callbacks allow module developers to specify additional users (local or remote)
  10210. to receive certain presence updates from local users. Presence router callbacks can be
  10211. registered using the module API's <code>register_presence_router_callbacks</code> method.</p>
  10212. <h2 id="callbacks-2"><a class="header" href="#callbacks-2">Callbacks</a></h2>
  10213. <p>The available presence router callbacks are:</p>
  10214. <h3 id="get_users_for_states"><a class="header" href="#get_users_for_states"><code>get_users_for_states</code></a></h3>
  10215. <p><em>First introduced in Synapse v1.42.0</em></p>
  10216. <pre><code class="language-python">async def get_users_for_states(
  10217. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  10218. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]
  10219. </code></pre>
  10220. <p><strong>Requires</strong> <code>get_interested_users</code> to also be registered</p>
  10221. <p>Called when processing updates to the presence state of one or more users. This callback can
  10222. be used to instruct the server to forward that presence state to specific users. The module
  10223. must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the
  10224. <code>UserPresenceState</code> changes that they should be forwarded.</p>
  10225. <p>Synapse will then attempt to send the specified presence updates to each user when possible.</p>
  10226. <p>If multiple modules implement this callback, Synapse merges all the dictionaries returned
  10227. by the callbacks. If multiple callbacks return a dictionary containing the same key,
  10228. Synapse concatenates the sets associated with this key from each dictionary. </p>
  10229. <h3 id="get_interested_users"><a class="header" href="#get_interested_users"><code>get_interested_users</code></a></h3>
  10230. <p><em>First introduced in Synapse v1.42.0</em></p>
  10231. <pre><code class="language-python">async def get_interested_users(
  10232. user_id: str
  10233. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]
  10234. </code></pre>
  10235. <p><strong>Requires</strong> <code>get_users_for_states</code> to also be registered</p>
  10236. <p>Called when determining which users someone should be able to see the presence state of. This
  10237. callback should return complementary results to <code>get_users_for_state</code> or the presence information
  10238. may not be properly forwarded.</p>
  10239. <p>The callback is given the Matrix user ID for a local user that is requesting presence data and
  10240. should return the Matrix user IDs of the users whose presence state they are allowed to
  10241. query. The returned users can be local or remote. </p>
  10242. <p>Alternatively the callback can return <code>synapse.module_api.PRESENCE_ALL_USERS</code>
  10243. to indicate that the user should receive updates from all known users.</p>
  10244. <p>If multiple modules implement this callback, they will be considered in order. Synapse
  10245. calls each callback one by one, and use a concatenation of all the <code>set</code>s returned by the
  10246. callbacks. If one callback returns <code>synapse.module_api.PRESENCE_ALL_USERS</code>, Synapse uses
  10247. this value instead. If this happens, Synapse does not call any of the subsequent
  10248. implementations of this callback.</p>
  10249. <h2 id="example-2"><a class="header" href="#example-2">Example</a></h2>
  10250. <p>The example below is a module that implements both presence router callbacks, and ensures
  10251. that <code>@alice:example.org</code> receives all presence updates from <code>@bob:example.com</code> and
  10252. <code>@charlie:somewhere.org</code>, regardless of whether Alice shares a room with any of them.</p>
  10253. <pre><code class="language-python">from typing import Dict, Iterable, Set, Union
  10254. from synapse.module_api import ModuleApi
  10255. class CustomPresenceRouter:
  10256. def __init__(self, config: dict, api: ModuleApi):
  10257. self.api = api
  10258. self.api.register_presence_router_callbacks(
  10259. get_users_for_states=self.get_users_for_states,
  10260. get_interested_users=self.get_interested_users,
  10261. )
  10262. async def get_users_for_states(
  10263. self,
  10264. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  10265. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]:
  10266. res = {}
  10267. for update in state_updates:
  10268. if (
  10269. update.user_id == &quot;@bob:example.com&quot;
  10270. or update.user_id == &quot;@charlie:somewhere.org&quot;
  10271. ):
  10272. res.setdefault(&quot;@alice:example.com&quot;, set()).add(update)
  10273. return res
  10274. async def get_interested_users(
  10275. self,
  10276. user_id: str,
  10277. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]:
  10278. if user_id == &quot;@alice:example.com&quot;:
  10279. return {&quot;@bob:example.com&quot;, &quot;@charlie:somewhere.org&quot;}
  10280. return set()
  10281. </code></pre>
  10282. <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>
  10283. <p>Account validity callbacks allow module developers to add extra steps to verify the
  10284. validity on an account, i.e. see if a user can be granted access to their account on the
  10285. Synapse instance. Account validity callbacks can be registered using the module API's
  10286. <code>register_account_validity_callbacks</code> method.</p>
  10287. <p>The available account validity callbacks are:</p>
  10288. <h3 id="is_user_expired"><a class="header" href="#is_user_expired"><code>is_user_expired</code></a></h3>
  10289. <p><em>First introduced in Synapse v1.39.0</em></p>
  10290. <pre><code class="language-python">async def is_user_expired(user: str) -&gt; Optional[bool]
  10291. </code></pre>
  10292. <p>Called when processing any authenticated request (except for logout requests). The module
  10293. can return a <code>bool</code> to indicate whether the user has expired and should be locked out of
  10294. their account, or <code>None</code> if the module wasn't able to figure it out. The user is
  10295. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  10296. <p>If the module returns <code>True</code>, the current request will be denied with the error code
  10297. <code>ORG_MATRIX_EXPIRED_ACCOUNT</code> and the HTTP status code 403. Note that this doesn't
  10298. invalidate the user's access token.</p>
  10299. <p>If multiple modules implement this callback, they will be considered in order. If a
  10300. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10301. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10302. any of the subsequent implementations of this callback.</p>
  10303. <h3 id="on_user_registration"><a class="header" href="#on_user_registration"><code>on_user_registration</code></a></h3>
  10304. <p><em>First introduced in Synapse v1.39.0</em></p>
  10305. <pre><code class="language-python">async def on_user_registration(user: str) -&gt; None
  10306. </code></pre>
  10307. <p>Called after successfully registering a user, in case the module needs to perform extra
  10308. operations to keep track of them. (e.g. add them to a database table). The user is
  10309. represented by their Matrix user ID.</p>
  10310. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10311. <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>
  10312. <p>Password auth providers offer a way for server administrators to integrate
  10313. their Synapse installation with an external authentication system. The callbacks can be
  10314. registered by using the Module API's <code>register_password_auth_provider_callbacks</code> method.</p>
  10315. <h2 id="callbacks-3"><a class="header" href="#callbacks-3">Callbacks</a></h2>
  10316. <h3 id="auth_checkers"><a class="header" href="#auth_checkers"><code>auth_checkers</code></a></h3>
  10317. <p><em>First introduced in Synapse v1.46.0</em></p>
  10318. <pre><code class="language-python">auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
  10319. </code></pre>
  10320. <p>A dict mapping from tuples of a login type identifier (such as <code>m.login.password</code>) and a
  10321. tuple of field names (such as <code>(&quot;password&quot;, &quot;secret_thing&quot;)</code>) to authentication checking
  10322. callbacks, which should be of the following form:</p>
  10323. <pre><code class="language-python">async def check_auth(
  10324. user: str,
  10325. login_type: str,
  10326. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  10327. ) -&gt; Optional[
  10328. Tuple[
  10329. str,
  10330. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  10331. ]
  10332. ]
  10333. </code></pre>
  10334. <p>The login type and field names should be provided by the user in the
  10335. request to the <code>/login</code> API. <a href="https://matrix.org/docs/spec/client_server/latest#authentication-types">The Matrix specification</a>
  10336. defines some types, however user defined ones are also allowed.</p>
  10337. <p>The callback is passed the <code>user</code> field provided by the client (which might not be in
  10338. <code>@username:server</code> form), the login type, and a dictionary of login secrets passed by
  10339. the client.</p>
  10340. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  10341. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the
  10342. <code>/login</code> request. If the module doesn't wish to return a callback, it must return <code>None</code>
  10343. instead.</p>
  10344. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  10345. <p>Note that the user is not automatically registered, the <code>register_user(..)</code> method of
  10346. the <a href="modules/writing_a_module.html">module API</a> can be used to lazily create users.</p>
  10347. <p>If multiple modules register an auth checker for the same login type but with different
  10348. fields, Synapse will refuse to start.</p>
  10349. <p>If multiple modules register an auth checker for the same login type with the same fields,
  10350. then the callbacks will be executed in order, until one returns a Matrix User ID (and
  10351. optionally a callback). In that case, the return value of that callback will be accepted
  10352. and subsequent callbacks will not be fired. If every callback returns <code>None</code>, then the
  10353. authentication fails.</p>
  10354. <h3 id="check_3pid_auth"><a class="header" href="#check_3pid_auth"><code>check_3pid_auth</code></a></h3>
  10355. <p><em>First introduced in Synapse v1.46.0</em></p>
  10356. <pre><code class="language-python">async def check_3pid_auth(
  10357. medium: str,
  10358. address: str,
  10359. password: str,
  10360. ) -&gt; Optional[
  10361. Tuple[
  10362. str,
  10363. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  10364. ]
  10365. ]
  10366. </code></pre>
  10367. <p>Called when a user attempts to register or log in with a third party identifier,
  10368. such as email. It is passed the medium (eg. <code>email</code>), an address (eg. <code>jdoe@example.com</code>)
  10369. and the user's password.</p>
  10370. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  10371. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the <code>/login</code> request.
  10372. If the module doesn't wish to return a callback, it must return None instead.</p>
  10373. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  10374. <p>If multiple modules implement this callback, they will be considered in order. If a
  10375. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10376. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10377. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  10378. the authentication is denied.</p>
  10379. <h3 id="on_logged_out"><a class="header" href="#on_logged_out"><code>on_logged_out</code></a></h3>
  10380. <p><em>First introduced in Synapse v1.46.0</em></p>
  10381. <pre><code class="language-python">async def on_logged_out(
  10382. user_id: str,
  10383. device_id: Optional[str],
  10384. access_token: str
  10385. ) -&gt; None
  10386. </code></pre>
  10387. <p>Called during a logout request for a user. It is passed the qualified user ID, the ID of the
  10388. deactivated device (if any: access tokens are occasionally created without an associated
  10389. device ID), and the (now deactivated) access token.</p>
  10390. <p>Deleting the related pushers is done after calling <code>on_logged_out</code>, so you can rely on them
  10391. to still be present.</p>
  10392. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10393. <h3 id="get_username_for_registration"><a class="header" href="#get_username_for_registration"><code>get_username_for_registration</code></a></h3>
  10394. <p><em>First introduced in Synapse v1.52.0</em></p>
  10395. <pre><code class="language-python">async def get_username_for_registration(
  10396. uia_results: Dict[str, Any],
  10397. params: Dict[str, Any],
  10398. ) -&gt; Optional[str]
  10399. </code></pre>
  10400. <p>Called when registering a new user. The module can return a username to set for the user
  10401. being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  10402. username for this user. If a username is returned, it will be used as the local part of a
  10403. user's full Matrix ID (e.g. it's <code>alice</code> in <code>@alice:example.com</code>).</p>
  10404. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  10405. has been completed by the user. It is not called when registering a user via SSO. It is
  10406. passed two dictionaries, which include the information that the user has provided during
  10407. the registration process.</p>
  10408. <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>
  10409. flow followed by the user. Its keys are the identifiers of every step involved in the flow,
  10410. associated with either a boolean value indicating whether the step was correctly completed,
  10411. or additional information (e.g. email address, phone number...). A list of most existing
  10412. identifiers can be found in the <a href="https://spec.matrix.org/v1.1/client-server-api/#authentication-types">Matrix specification</a>.
  10413. Here's an example featuring all currently supported keys:</p>
  10414. <pre><code class="language-python">{
  10415. &quot;m.login.dummy&quot;: True, # Dummy authentication
  10416. &quot;m.login.terms&quot;: True, # User has accepted the terms of service for the homeserver
  10417. &quot;m.login.recaptcha&quot;: True, # User has completed the recaptcha challenge
  10418. &quot;m.login.email.identity&quot;: { # User has provided and verified an email address
  10419. &quot;medium&quot;: &quot;email&quot;,
  10420. &quot;address&quot;: &quot;alice@example.com&quot;,
  10421. &quot;validated_at&quot;: 1642701357084,
  10422. },
  10423. &quot;m.login.msisdn&quot;: { # User has provided and verified a phone number
  10424. &quot;medium&quot;: &quot;msisdn&quot;,
  10425. &quot;address&quot;: &quot;33123456789&quot;,
  10426. &quot;validated_at&quot;: 1642701357084,
  10427. },
  10428. &quot;m.login.registration_token&quot;: &quot;sometoken&quot;, # User has registered through a registration token
  10429. }
  10430. </code></pre>
  10431. <p>The second dictionary contains the parameters provided by the user's client in the request
  10432. to <code>/_matrix/client/v3/register</code>. See the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register">Matrix specification</a>
  10433. for a complete list of these parameters.</p>
  10434. <p>If the module cannot, or does not wish to, generate a username for this user, it must
  10435. return <code>None</code>.</p>
  10436. <p>If multiple modules implement this callback, they will be considered in order. If a
  10437. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10438. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10439. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  10440. the username provided by the user is used, if any (otherwise one is automatically
  10441. generated).</p>
  10442. <h3 id="get_displayname_for_registration"><a class="header" href="#get_displayname_for_registration"><code>get_displayname_for_registration</code></a></h3>
  10443. <p><em>First introduced in Synapse v1.54.0</em></p>
  10444. <pre><code class="language-python">async def get_displayname_for_registration(
  10445. uia_results: Dict[str, Any],
  10446. params: Dict[str, Any],
  10447. ) -&gt; Optional[str]
  10448. </code></pre>
  10449. <p>Called when registering a new user. The module can return a display name to set for the
  10450. user being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  10451. display name for this user.</p>
  10452. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  10453. has been completed by the user. It is not called when registering a user via SSO. It is
  10454. passed two dictionaries, which include the information that the user has provided during
  10455. the registration process. These dictionaries are identical to the ones passed to
  10456. <a href="modules/password_auth_provider_callbacks.html#get_username_for_registration"><code>get_username_for_registration</code></a>, so refer to the
  10457. documentation of this callback for more information about them.</p>
  10458. <p>If multiple modules implement this callback, they will be considered in order. If a
  10459. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10460. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10461. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  10462. the username will be used (e.g. <code>alice</code> if the user being registered is <code>@alice:example.com</code>).</p>
  10463. <h2 id="is_3pid_allowed"><a class="header" href="#is_3pid_allowed"><code>is_3pid_allowed</code></a></h2>
  10464. <p><em>First introduced in Synapse v1.53.0</em></p>
  10465. <pre><code class="language-python">async def is_3pid_allowed(self, medium: str, address: str, registration: bool) -&gt; bool
  10466. </code></pre>
  10467. <p>Called when attempting to bind a third-party identifier (i.e. an email address or a phone
  10468. number). The module is given the medium of the third-party identifier (which is <code>email</code> if
  10469. the identifier is an email address, or <code>msisdn</code> if the identifier is a phone number) and
  10470. its address, as well as a boolean indicating whether the attempt to bind is happening as
  10471. part of registering a new user. The module must return a boolean indicating whether the
  10472. identifier can be allowed to be bound to an account on the local homeserver.</p>
  10473. <p>If multiple modules implement this callback, they will be considered in order. If a
  10474. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10475. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10476. any of the subsequent implementations of this callback.</p>
  10477. <h2 id="example-3"><a class="header" href="#example-3">Example</a></h2>
  10478. <p>The example module below implements authentication checkers for two different login types: </p>
  10479. <ul>
  10480. <li><code>my.login.type</code>
  10481. <ul>
  10482. <li>Expects a <code>my_field</code> field to be sent to <code>/login</code></li>
  10483. <li>Is checked by the method: <code>self.check_my_login</code></li>
  10484. </ul>
  10485. </li>
  10486. <li><code>m.login.password</code> (defined in <a href="https://matrix.org/docs/spec/client_server/latest#password-based">the spec</a>)
  10487. <ul>
  10488. <li>Expects a <code>password</code> field to be sent to <code>/login</code></li>
  10489. <li>Is checked by the method: <code>self.check_pass</code></li>
  10490. </ul>
  10491. </li>
  10492. </ul>
  10493. <pre><code class="language-python">from typing import Awaitable, Callable, Optional, Tuple
  10494. import synapse
  10495. from synapse import module_api
  10496. class MyAuthProvider:
  10497. def __init__(self, config: dict, api: module_api):
  10498. self.api = api
  10499. self.credentials = {
  10500. &quot;bob&quot;: &quot;building&quot;,
  10501. &quot;@scoop:matrix.org&quot;: &quot;digging&quot;,
  10502. }
  10503. api.register_password_auth_provider_callbacks(
  10504. auth_checkers={
  10505. (&quot;my.login_type&quot;, (&quot;my_field&quot;,)): self.check_my_login,
  10506. (&quot;m.login.password&quot;, (&quot;password&quot;,)): self.check_pass,
  10507. },
  10508. )
  10509. async def check_my_login(
  10510. self,
  10511. username: str,
  10512. login_type: str,
  10513. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  10514. ) -&gt; Optional[
  10515. Tuple[
  10516. str,
  10517. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  10518. ]
  10519. ]:
  10520. if login_type != &quot;my.login_type&quot;:
  10521. return None
  10522. if self.credentials.get(username) == login_dict.get(&quot;my_field&quot;):
  10523. return (self.api.get_qualified_user_id(username), None)
  10524. async def check_pass(
  10525. self,
  10526. username: str,
  10527. login_type: str,
  10528. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  10529. ) -&gt; Optional[
  10530. Tuple[
  10531. str,
  10532. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  10533. ]
  10534. ]:
  10535. if login_type != &quot;m.login.password&quot;:
  10536. return None
  10537. if self.credentials.get(username) == login_dict.get(&quot;password&quot;):
  10538. return (self.api.get_qualified_user_id(username), None)
  10539. </code></pre>
  10540. <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>
  10541. <p>Background update controller callbacks allow module developers to control (e.g. rate-limit)
  10542. how database background updates are run. A database background update is an operation
  10543. Synapse runs on its database in the background after it starts. It's usually used to run
  10544. database operations that would take too long if they were run at the same time as schema
  10545. updates (which are run on startup) and delay Synapse's startup too much: populating a
  10546. table with a big amount of data, adding an index on a big table, deleting superfluous data,
  10547. etc.</p>
  10548. <p>Background update controller callbacks can be registered using the module API's
  10549. <code>register_background_update_controller_callbacks</code> method. Only the first module (in order
  10550. of appearance in Synapse's configuration file) calling this method can register background
  10551. update controller callbacks, subsequent calls are ignored.</p>
  10552. <p>The available background update controller callbacks are:</p>
  10553. <h3 id="on_update"><a class="header" href="#on_update"><code>on_update</code></a></h3>
  10554. <p><em>First introduced in Synapse v1.49.0</em></p>
  10555. <pre><code class="language-python">def on_update(update_name: str, database_name: str, one_shot: bool) -&gt; AsyncContextManager[int]
  10556. </code></pre>
  10557. <p>Called when about to do an iteration of a background update. The module is given the name
  10558. of the update, the name of the database, and a flag to indicate whether the background
  10559. update will happen in one go and may take a long time (e.g. creating indices). If this last
  10560. argument is set to <code>False</code>, the update will be run in batches.</p>
  10561. <p>The module must return an async context manager. It will be entered before Synapse runs a
  10562. background update; this should return the desired duration of the iteration, in
  10563. milliseconds.</p>
  10564. <p>The context manager will be exited when the iteration completes. Note that the duration
  10565. returned by the context manager is a target, and an iteration may take substantially longer
  10566. or shorter. If the <code>one_shot</code> flag is set to <code>True</code>, the duration returned is ignored.</p>
  10567. <p><strong>Note</strong>: Unlike most module callbacks in Synapse, this one is <em>synchronous</em>. This is
  10568. because asynchronous operations are expected to be run by the async context manager.</p>
  10569. <p>This callback is required when registering any other background update controller callback.</p>
  10570. <h3 id="default_batch_size"><a class="header" href="#default_batch_size"><code>default_batch_size</code></a></h3>
  10571. <p><em>First introduced in Synapse v1.49.0</em></p>
  10572. <pre><code class="language-python">async def default_batch_size(update_name: str, database_name: str) -&gt; int
  10573. </code></pre>
  10574. <p>Called before the first iteration of a background update, with the name of the update and
  10575. of the database. The module must return the number of elements to process in this first
  10576. iteration.</p>
  10577. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  10578. <h3 id="min_batch_size"><a class="header" href="#min_batch_size"><code>min_batch_size</code></a></h3>
  10579. <p><em>First introduced in Synapse v1.49.0</em></p>
  10580. <pre><code class="language-python">async def min_batch_size(update_name: str, database_name: str) -&gt; int
  10581. </code></pre>
  10582. <p>Called before running a new batch for a background update, with the name of the update and
  10583. of the database. The module must return an integer representing the minimum number of
  10584. elements to process in this iteration. This number must be at least 1, and is used to
  10585. ensure that progress is always made.</p>
  10586. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  10587. <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>
  10588. <p>Account data callbacks allow module developers to react to changes of the account data
  10589. of local users. Account data callbacks can be registered using the module API's
  10590. <code>register_account_data_callbacks</code> method.</p>
  10591. <h2 id="callbacks-4"><a class="header" href="#callbacks-4">Callbacks</a></h2>
  10592. <p>The available account data callbacks are:</p>
  10593. <h3 id="on_account_data_updated"><a class="header" href="#on_account_data_updated"><code>on_account_data_updated</code></a></h3>
  10594. <p><em>First introduced in Synapse v1.57.0</em></p>
  10595. <pre><code class="language-python">async def on_account_data_updated(
  10596. user_id: str,
  10597. room_id: Optional[str],
  10598. account_data_type: str,
  10599. content: &quot;synapse.module_api.JsonDict&quot;,
  10600. ) -&gt; None:
  10601. </code></pre>
  10602. <p>Called after user's account data has been updated. The module is given the
  10603. Matrix ID of the user whose account data is changing, the room ID the data is associated
  10604. with, the type associated with the change, as well as the new content. If the account
  10605. data is not associated with a specific room, then the room ID is <code>None</code>.</p>
  10606. <p>This callback is triggered when new account data is added or when the data associated with
  10607. a given type (and optionally room) changes. This includes deletion, since in Matrix,
  10608. deleting account data consists of replacing the data associated with a given type
  10609. (and optionally room) with an empty dictionary (<code>{}</code>).</p>
  10610. <p>Note that this doesn't trigger when changing the tags associated with a room, as these are
  10611. processed separately by Synapse.</p>
  10612. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10613. <h2 id="example-4"><a class="header" href="#example-4">Example</a></h2>
  10614. <p>The example below is a module that implements the <code>on_account_data_updated</code> callback, and
  10615. sends an event to an audit room when a user changes their account data.</p>
  10616. <pre><code class="language-python">import json
  10617. import attr
  10618. from typing import Any, Dict, Optional
  10619. from synapse.module_api import JsonDict, ModuleApi
  10620. from synapse.module_api.errors import ConfigError
  10621. @attr.s(auto_attribs=True)
  10622. class CustomAccountDataConfig:
  10623. audit_room: str
  10624. sender: str
  10625. class CustomAccountDataModule:
  10626. def __init__(self, config: CustomAccountDataConfig, api: ModuleApi):
  10627. self.api = api
  10628. self.config = config
  10629. self.api.register_account_data_callbacks(
  10630. on_account_data_updated=self.log_new_account_data,
  10631. )
  10632. @staticmethod
  10633. def parse_config(config: Dict[str, Any]) -&gt; CustomAccountDataConfig:
  10634. def check_in_config(param: str):
  10635. if param not in config:
  10636. raise ConfigError(f&quot;'{param}' is required&quot;)
  10637. check_in_config(&quot;audit_room&quot;)
  10638. check_in_config(&quot;sender&quot;)
  10639. return CustomAccountDataConfig(
  10640. audit_room=config[&quot;audit_room&quot;],
  10641. sender=config[&quot;sender&quot;],
  10642. )
  10643. async def log_new_account_data(
  10644. self,
  10645. user_id: str,
  10646. room_id: Optional[str],
  10647. account_data_type: str,
  10648. content: JsonDict,
  10649. ) -&gt; None:
  10650. content_raw = json.dumps(content)
  10651. msg_content = f&quot;{user_id} has changed their account data for type {account_data_type} to: {content_raw}&quot;
  10652. if room_id is not None:
  10653. msg_content += f&quot; (in room {room_id})&quot;
  10654. await self.api.create_and_send_event_into_room(
  10655. {
  10656. &quot;room_id&quot;: self.config.audit_room,
  10657. &quot;sender&quot;: self.config.sender,
  10658. &quot;type&quot;: &quot;m.room.message&quot;,
  10659. &quot;content&quot;: {
  10660. &quot;msgtype&quot;: &quot;m.text&quot;,
  10661. &quot;body&quot;: msg_content
  10662. }
  10663. }
  10664. )
  10665. </code></pre>
  10666. <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>
  10667. <p>In order to port a module that uses Synapse's old module interface, its author needs to:</p>
  10668. <ul>
  10669. <li>ensure the module's callbacks are all asynchronous.</li>
  10670. <li>register their callbacks using one or more of the <code>register_[...]_callbacks</code> methods
  10671. 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>
  10672. for more info).</li>
  10673. </ul>
  10674. <p>Additionally, if the module is packaged with an additional web resource, the module
  10675. should register this resource in its <code>__init__</code> method using the <code>register_web_resource</code>
  10676. method from the <code>ModuleApi</code> class (see <a href="modules/writing_a_module.html#registering-a-web-resource">this section</a> for
  10677. more info).</p>
  10678. <p>There is no longer a <code>get_db_schema_files</code> callback provided for password auth provider modules. Any
  10679. changes to the database should now be made by the module using the module API class.</p>
  10680. <p>The module's author should also update any example in the module's configuration to only
  10681. use the new <code>modules</code> section in Synapse's configuration file (see <a href="modules/index.html#using-modules">this section</a>
  10682. for more info).</p>
  10683. <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>
  10684. <p>For small instances it is recommended to run Synapse in the default monolith mode.
  10685. For larger instances where performance is a concern it can be helpful to split
  10686. out functionality into multiple separate python processes. These processes are
  10687. called 'workers', and are (eventually) intended to scale horizontally
  10688. independently.</p>
  10689. <p>Synapse's worker support is under active development and subject to change as
  10690. we attempt to rapidly scale ever larger Synapse instances. However we are
  10691. documenting it here to help admins needing a highly scalable Synapse instance
  10692. similar to the one running <code>matrix.org</code>.</p>
  10693. <p>All processes continue to share the same database instance, and as such,
  10694. workers only work with PostgreSQL-based Synapse deployments. SQLite should only
  10695. be used for demo purposes and any admin considering workers should already be
  10696. running PostgreSQL.</p>
  10697. <p>See also <a href="https://matrix.org/blog/2020/11/03/how-we-fixed-synapses-scalability">Matrix.org blog post</a>
  10698. for a higher level overview.</p>
  10699. <h2 id="main-processworker-communication"><a class="header" href="#main-processworker-communication">Main process/worker communication</a></h2>
  10700. <p>The processes communicate with each other via a Synapse-specific protocol called
  10701. 'replication' (analogous to MySQL- or Postgres-style database replication) which
  10702. feeds streams of newly written data between processes so they can be kept in
  10703. sync with the database state.</p>
  10704. <p>When configured to do so, Synapse uses a
  10705. <a href="https://redis.io/docs/manual/pubsub/">Redis pub/sub channel</a> to send the replication
  10706. stream between all configured Synapse processes. Additionally, processes may
  10707. make HTTP requests to each other, primarily for operations which need to wait
  10708. for a reply ─ such as sending an event.</p>
  10709. <p>All the workers and the main process connect to Redis, which relays replication
  10710. commands between processes.</p>
  10711. <p>If Redis support is enabled Synapse will use it as a shared cache, as well as a
  10712. pub/sub mechanism.</p>
  10713. <p>See the <a href="workers.html#architectural-diagram">Architectural diagram</a> section at the end for
  10714. a visualisation of what this looks like.</p>
  10715. <h2 id="setting-up-workers"><a class="header" href="#setting-up-workers">Setting up workers</a></h2>
  10716. <p>A Redis server is required to manage the communication between the processes.
  10717. The Redis server should be installed following the normal procedure for your
  10718. distribution (e.g. <code>apt install redis-server</code> on Debian). It is safe to use an
  10719. existing Redis deployment if you have one.</p>
  10720. <p>Once installed, check that Redis is running and accessible from the host running
  10721. Synapse, for example by executing <code>echo PING | nc -q1 localhost 6379</code> and seeing
  10722. a response of <code>+PONG</code>.</p>
  10723. <p>The appropriate dependencies must also be installed for Synapse. If using a
  10724. virtualenv, these can be installed with:</p>
  10725. <pre><code class="language-sh">pip install &quot;matrix-synapse[redis]&quot;
  10726. </code></pre>
  10727. <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
  10728. <code>matrix.org</code> and in the docker images at
  10729. https://hub.docker.com/r/matrixdotorg/synapse/.</p>
  10730. <p>To make effective use of the workers, you will need to configure an HTTP
  10731. reverse-proxy such as nginx or haproxy, which will direct incoming requests to
  10732. the correct worker, or to the main synapse instance. See
  10733. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a reverse
  10734. proxy.</p>
  10735. <p>When using workers, each worker process has its own configuration file which
  10736. contains settings specific to that worker, such as the HTTP listener that it
  10737. provides (if any), logging configuration, etc.</p>
  10738. <p>Normally, the worker processes are configured to read from a shared
  10739. configuration file as well as the worker-specific configuration files. This
  10740. makes it easier to keep common configuration settings synchronised across all
  10741. the processes.</p>
  10742. <p>The main process is somewhat special in this respect: it does not normally
  10743. need its own configuration file and can take all of its configuration from the
  10744. shared configuration file.</p>
  10745. <h3 id="shared-configuration"><a class="header" href="#shared-configuration">Shared configuration</a></h3>
  10746. <p>Normally, only a few changes are needed to make an existing configuration
  10747. file suitable for use with workers:</p>
  10748. <ul>
  10749. <li>First, you need to enable an
  10750. <a href="usage/configuration/config_documentation.html#listeners">&quot;HTTP replication listener&quot;</a>
  10751. for the main process</li>
  10752. <li>Secondly, you need to enable
  10753. <a href="usage/configuration/config_documentation.html#redis">redis-based replication</a></li>
  10754. <li>You will need to add an <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>
  10755. with the <code>main</code> process defined, as well as the relevant connection information from
  10756. it's HTTP <code>replication</code> listener (defined in step 1 above).
  10757. <ul>
  10758. <li>Note that the <code>host</code> defined is the address the worker needs to look for the <code>main</code>
  10759. process at, not necessarily the same address that is bound to.</li>
  10760. <li>If you are using Unix sockets for the <code>replication</code> resource, make sure to
  10761. use a <code>path</code> to the socket file instead of a <code>port</code>.</li>
  10762. </ul>
  10763. </li>
  10764. <li>Optionally, a <a href="usage/configuration/config_documentation.html#worker_replication_secret">shared secret</a>
  10765. can be used to authenticate HTTP traffic between workers. For example:</li>
  10766. </ul>
  10767. <pre><code class="language-yaml"># extend the existing `listeners` section. This defines the ports that the
  10768. # main process will listen on.
  10769. listeners:
  10770. # The HTTP replication port
  10771. - port: 9093
  10772. bind_address: '127.0.0.1'
  10773. type: http
  10774. resources:
  10775. - names: [replication]
  10776. # Add a random shared secret to authenticate traffic.
  10777. worker_replication_secret: &quot;&quot;
  10778. redis:
  10779. enabled: true
  10780. instance_map:
  10781. main:
  10782. host: 'localhost'
  10783. port: 9093
  10784. </code></pre>
  10785. <p>See the <a href="usage/configuration/config_documentation.html">configuration manual</a>
  10786. for the full documentation of each option.</p>
  10787. <p>Under <strong>no circumstances</strong> should the replication listener be exposed to the
  10788. public internet; replication traffic is:</p>
  10789. <ul>
  10790. <li>always unencrypted</li>
  10791. <li>unauthenticated, unless <a href="usage/configuration/config_documentation.html#worker_replication_secret"><code>worker_replication_secret</code></a>
  10792. is configured</li>
  10793. </ul>
  10794. <h3 id="worker-configuration"><a class="header" href="#worker-configuration">Worker configuration</a></h3>
  10795. <p>In the config file for each worker, you must specify:</p>
  10796. <ul>
  10797. <li>The type of worker (<a href="usage/configuration/config_documentation.html#worker_app"><code>worker_app</code></a>).
  10798. The currently available worker applications are listed <a href="workers.html#available-worker-applications">below</a>.</li>
  10799. <li>A unique name for the worker (<a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>).</li>
  10800. <li>If handling HTTP requests, a <a href="usage/configuration/config_documentation.html#worker_listeners"><code>worker_listeners</code></a> option
  10801. with an <code>http</code> listener.</li>
  10802. <li><strong>Synapse 1.72 and older:</strong> if handling the <code>^/_matrix/client/v3/keys/upload</code> endpoint, the HTTP URI for
  10803. 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>
  10804. </ul>
  10805. <p>For example:</p>
  10806. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  10807. worker_name: generic_worker1
  10808. worker_listeners:
  10809. - type: http
  10810. port: 8083
  10811. x_forwarded: true
  10812. resources:
  10813. - names: [client, federation]
  10814. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  10815. </code></pre>
  10816. <p>...is a full configuration for a generic worker instance, which will expose a
  10817. plain HTTP endpoint on port 8083 separately serving various endpoints, e.g.
  10818. <code>/sync</code>, which are listed below.</p>
  10819. <p>Obviously you should configure your reverse-proxy to route the relevant
  10820. endpoints to the worker (<code>localhost:8083</code> in the above example).</p>
  10821. <h3 id="running-synapse-with-workers"><a class="header" href="#running-synapse-with-workers">Running Synapse with workers</a></h3>
  10822. <p>Finally, you need to start your worker processes. This can be done with either
  10823. <code>synctl</code> or your distribution's preferred service manager such as <code>systemd</code>. We
  10824. recommend the use of <code>systemd</code> where available: for information on setting up
  10825. <code>systemd</code> to start synapse workers, see
  10826. <a href="systemd-with-workers/">Systemd with Workers</a>. To use <code>synctl</code>, see
  10827. <a href="synctl_workers.html">Using synctl with Workers</a>.</p>
  10828. <h2 id="start-synapse-with-poetry"><a class="header" href="#start-synapse-with-poetry">Start Synapse with Poetry</a></h2>
  10829. <p>The following applies to Synapse installations that have been installed from source using <code>poetry</code>.</p>
  10830. <p>You can start the main Synapse process with Poetry by running the following command:</p>
  10831. <pre><code class="language-console">poetry run synapse_homeserver --config-file [your homeserver.yaml]
  10832. </code></pre>
  10833. <p>For worker setups, you can run the following command</p>
  10834. <pre><code class="language-console">poetry run synapse_worker --config-file [your homeserver.yaml] --config-file [your worker.yaml]
  10835. </code></pre>
  10836. <h2 id="available-worker-applications"><a class="header" href="#available-worker-applications">Available worker applications</a></h2>
  10837. <h3 id="synapseappgeneric_worker"><a class="header" href="#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a></h3>
  10838. <p>This worker can handle API requests matching the following regular expressions.
  10839. These endpoints can be routed to any worker. If a worker is set up to handle a
  10840. stream then, for maximum efficiency, additional endpoints should be routed to that
  10841. worker: refer to the <a href="workers.html#stream-writers">stream writers</a> section below for further
  10842. information.</p>
  10843. <pre><code># Sync requests
  10844. ^/_matrix/client/(r0|v3)/sync$
  10845. ^/_matrix/client/(api/v1|r0|v3)/events$
  10846. ^/_matrix/client/(api/v1|r0|v3)/initialSync$
  10847. ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$
  10848. # Federation requests
  10849. ^/_matrix/federation/v1/event/
  10850. ^/_matrix/federation/v1/state/
  10851. ^/_matrix/federation/v1/state_ids/
  10852. ^/_matrix/federation/v1/backfill/
  10853. ^/_matrix/federation/v1/get_missing_events/
  10854. ^/_matrix/federation/v1/publicRooms
  10855. ^/_matrix/federation/v1/query/
  10856. ^/_matrix/federation/v1/make_join/
  10857. ^/_matrix/federation/v1/make_leave/
  10858. ^/_matrix/federation/(v1|v2)/send_join/
  10859. ^/_matrix/federation/(v1|v2)/send_leave/
  10860. ^/_matrix/federation/(v1|v2)/invite/
  10861. ^/_matrix/federation/v1/event_auth/
  10862. ^/_matrix/federation/v1/timestamp_to_event/
  10863. ^/_matrix/federation/v1/exchange_third_party_invite/
  10864. ^/_matrix/federation/v1/user/devices/
  10865. ^/_matrix/key/v2/query
  10866. ^/_matrix/federation/v1/hierarchy/
  10867. # Inbound federation transaction request
  10868. ^/_matrix/federation/v1/send/
  10869. # Client API requests
  10870. ^/_matrix/client/(api/v1|r0|v3|unstable)/createRoom$
  10871. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$
  10872. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$
  10873. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$
  10874. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$
  10875. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$
  10876. ^/_matrix/client/v1/rooms/.*/hierarchy$
  10877. ^/_matrix/client/(v1|unstable)/rooms/.*/relations/
  10878. ^/_matrix/client/v1/rooms/.*/threads$
  10879. ^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary$
  10880. ^/_matrix/client/(r0|v3|unstable)/account/3pid$
  10881. ^/_matrix/client/(r0|v3|unstable)/account/whoami$
  10882. ^/_matrix/client/(r0|v3|unstable)/devices$
  10883. ^/_matrix/client/versions$
  10884. ^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$
  10885. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event/
  10886. ^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms$
  10887. ^/_matrix/client/v1/rooms/.*/timestamp_to_event$
  10888. ^/_matrix/client/(api/v1|r0|v3|unstable/.*)/rooms/.*/aliases
  10889. ^/_matrix/client/(api/v1|r0|v3|unstable)/search$
  10890. ^/_matrix/client/(r0|v3|unstable)/user/.*/filter(/|$)
  10891. ^/_matrix/client/(api/v1|r0|v3|unstable)/directory/room/.*$
  10892. ^/_matrix/client/(r0|v3|unstable)/capabilities$
  10893. # Encryption requests
  10894. ^/_matrix/client/(r0|v3|unstable)/keys/query$
  10895. ^/_matrix/client/(r0|v3|unstable)/keys/changes$
  10896. ^/_matrix/client/(r0|v3|unstable)/keys/claim$
  10897. ^/_matrix/client/(r0|v3|unstable)/room_keys/
  10898. ^/_matrix/client/(r0|v3|unstable)/keys/upload/
  10899. # Registration/login requests
  10900. ^/_matrix/client/(api/v1|r0|v3|unstable)/login$
  10901. ^/_matrix/client/(r0|v3|unstable)/register$
  10902. ^/_matrix/client/(r0|v3|unstable)/register/available$
  10903. ^/_matrix/client/v1/register/m.login.registration_token/validity$
  10904. ^/_matrix/client/(r0|v3|unstable)/password_policy$
  10905. # Event sending requests
  10906. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact
  10907. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send
  10908. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state/
  10909. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$
  10910. ^/_matrix/client/(api/v1|r0|v3|unstable)/join/
  10911. ^/_matrix/client/(api/v1|r0|v3|unstable)/knock/
  10912. ^/_matrix/client/(api/v1|r0|v3|unstable)/profile/
  10913. # Account data requests
  10914. ^/_matrix/client/(r0|v3|unstable)/.*/tags
  10915. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  10916. # Receipts requests
  10917. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  10918. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  10919. # Presence requests
  10920. ^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  10921. # User directory search requests
  10922. ^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  10923. </code></pre>
  10924. <p>Additionally, the following REST endpoints can be handled for GET requests:</p>
  10925. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/pushrules/
  10926. </code></pre>
  10927. <p>Pagination requests can also be handled, but all requests for a given
  10928. room must be routed to the same instance. Additionally, care must be taken to
  10929. ensure that the purge history admin API is not used while pagination requests
  10930. for the room are in flight:</p>
  10931. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$
  10932. </code></pre>
  10933. <p>Additionally, the following endpoints should be included if Synapse is configured
  10934. to use SSO (you only need to include the ones for whichever SSO provider you're
  10935. using):</p>
  10936. <pre><code># for all SSO providers
  10937. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/sso/redirect
  10938. ^/_synapse/client/pick_idp$
  10939. ^/_synapse/client/pick_username
  10940. ^/_synapse/client/new_user_consent$
  10941. ^/_synapse/client/sso_register$
  10942. # OpenID Connect requests.
  10943. ^/_synapse/client/oidc/callback$
  10944. # SAML requests.
  10945. ^/_synapse/client/saml2/authn_response$
  10946. # CAS requests.
  10947. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/cas/ticket$
  10948. </code></pre>
  10949. <p>Ensure that all SSO logins go to a single process.
  10950. For multiple workers not handling the SSO endpoints properly, see
  10951. <a href="https://github.com/matrix-org/synapse/issues/7530">#7530</a> and
  10952. <a href="https://github.com/matrix-org/synapse/issues/9427">#9427</a>.</p>
  10953. <p>Note that a <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a>
  10954. with <code>client</code> and <code>federation</code> <code>resources</code> must be configured in the
  10955. <a href="usage/configuration/config_documentation.html#worker_listeners"><code>worker_listeners</code></a>
  10956. option in the worker config.</p>
  10957. <h4 id="load-balancing"><a class="header" href="#load-balancing">Load balancing</a></h4>
  10958. <p>It is possible to run multiple instances of this worker app, with incoming requests
  10959. being load-balanced between them by the reverse-proxy. However, different endpoints
  10960. have different characteristics and so admins
  10961. may wish to run multiple groups of workers handling different endpoints so that
  10962. load balancing can be done in different ways.</p>
  10963. <p>For <code>/sync</code> and <code>/initialSync</code> requests it will be more efficient if all
  10964. requests from a particular user are routed to a single instance. This can
  10965. be done in reverse proxy by extracting username part from the users access token.</p>
  10966. <p>Admins may additionally wish to separate out <code>/sync</code>
  10967. requests that have a <code>since</code> query parameter from those that don't (and
  10968. <code>/initialSync</code>), as requests that don't are known as &quot;initial sync&quot; that happens
  10969. when a user logs in on a new device and can be <em>very</em> resource intensive, so
  10970. isolating these requests will stop them from interfering with other users ongoing
  10971. syncs.</p>
  10972. <p>Example <code>nginx</code> configuration snippet that handles the cases above. This is just an
  10973. example and probably requires some changes according to your particular setup:</p>
  10974. <pre><code class="language-nginx"># Choose sync worker based on the existence of &quot;since&quot; query parameter
  10975. map $arg_since $sync {
  10976. default synapse_sync;
  10977. '' synapse_initial_sync;
  10978. }
  10979. # Extract username from access token passed as URL parameter
  10980. map $arg_access_token $accesstoken_from_urlparam {
  10981. # Defaults to just passing back the whole accesstoken
  10982. default $arg_access_token;
  10983. # Try to extract username part from accesstoken URL parameter
  10984. &quot;~syt_(?&lt;username&gt;.*?)_.*&quot; $username;
  10985. }
  10986. # Extract username from access token passed as authorization header
  10987. map $http_authorization $mxid_localpart {
  10988. # Defaults to just passing back the whole accesstoken
  10989. default $http_authorization;
  10990. # Try to extract username part from accesstoken header
  10991. &quot;~Bearer syt_(?&lt;username&gt;.*?)_.*&quot; $username;
  10992. # if no authorization-header exist, try mapper for URL parameter &quot;access_token&quot;
  10993. &quot;&quot; $accesstoken_from_urlparam;
  10994. }
  10995. upstream synapse_initial_sync {
  10996. # Use the username mapper result for hash key
  10997. hash $mxid_localpart consistent;
  10998. server 127.0.0.1:8016;
  10999. server 127.0.0.1:8036;
  11000. }
  11001. upstream synapse_sync {
  11002. # Use the username mapper result for hash key
  11003. hash $mxid_localpart consistent;
  11004. server 127.0.0.1:8013;
  11005. server 127.0.0.1:8037;
  11006. server 127.0.0.1:8038;
  11007. server 127.0.0.1:8039;
  11008. }
  11009. # Sync initial/normal
  11010. location ~ ^/_matrix/client/(r0|v3)/sync$ {
  11011. proxy_pass http://$sync;
  11012. }
  11013. # Normal sync
  11014. location ~ ^/_matrix/client/(api/v1|r0|v3)/events$ {
  11015. proxy_pass http://synapse_sync;
  11016. }
  11017. # Initial_sync
  11018. location ~ ^/_matrix/client/(api/v1|r0|v3)/initialSync$ {
  11019. proxy_pass http://synapse_initial_sync;
  11020. }
  11021. location ~ ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$ {
  11022. proxy_pass http://synapse_initial_sync;
  11023. }
  11024. </code></pre>
  11025. <p>Federation and client requests can be balanced via simple round robin.</p>
  11026. <p>The inbound federation transaction request <code>^/_matrix/federation/v1/send/</code>
  11027. should be balanced by source IP so that transactions from the same remote server
  11028. go to the same process.</p>
  11029. <p>Registration/login requests can be handled separately purely to help ensure that
  11030. unexpected load doesn't affect new logins and sign ups.</p>
  11031. <p>Finally, event sending requests can be balanced by the room ID in the URI (or
  11032. the full URI, or even just round robin), the room ID is the path component after
  11033. <code>/rooms/</code>. If there is a large bridge connected that is sending or may send lots
  11034. of events, then a dedicated set of workers can be provisioned to limit the
  11035. effects of bursts of events from that bridge on events sent by normal users.</p>
  11036. <h4 id="stream-writers"><a class="header" href="#stream-writers">Stream writers</a></h4>
  11037. <p>Additionally, the writing of specific streams (such as events) can be moved off
  11038. of the main process to a particular worker.</p>
  11039. <p>To enable this, the worker must have:</p>
  11040. <ul>
  11041. <li>An <a href="usage/configuration/config_documentation.html#listeners">HTTP <code>replication</code> listener</a> configured,</li>
  11042. <li>Have a <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>
  11043. and be listed in the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>
  11044. config. </li>
  11045. <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>
  11046. </ul>
  11047. <p>Note: The same worker can handle multiple streams, but unless otherwise documented,
  11048. each stream can only have a single writer.</p>
  11049. <p>For example, to move event persistence off to a dedicated worker, the shared
  11050. configuration would include:</p>
  11051. <pre><code class="language-yaml">instance_map:
  11052. main:
  11053. host: localhost
  11054. port: 8030
  11055. event_persister1:
  11056. host: localhost
  11057. port: 8034
  11058. stream_writers:
  11059. events: event_persister1
  11060. </code></pre>
  11061. <p>An example for a stream writer instance:</p>
  11062. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  11063. worker_name: event_persister1
  11064. worker_listeners:
  11065. - type: http
  11066. port: 8034
  11067. resources:
  11068. - names: [replication]
  11069. # Enable listener if this stream writer handles endpoints for the `typing` or
  11070. # `to_device` streams. Uses a different port to the `replication` listener to
  11071. # avoid exposing the `replication` listener publicly.
  11072. #
  11073. #- type: http
  11074. # port: 8035
  11075. # x_forwarded: true
  11076. # resources:
  11077. # - names: [client]
  11078. worker_log_config: /etc/matrix-synapse/event-persister-log.yaml
  11079. </code></pre>
  11080. <p>Some of the streams have associated endpoints which, for maximum efficiency, should
  11081. be routed to the workers handling that stream. See below for the currently supported
  11082. streams and the endpoints associated with them:</p>
  11083. <h5 id="the-events-stream"><a class="header" href="#the-events-stream">The <code>events</code> stream</a></h5>
  11084. <p>The <code>events</code> stream experimentally supports having multiple writer workers, where load
  11085. is sharded between them by room ID. Each writer is called an <em>event persister</em>. They are
  11086. responsible for</p>
  11087. <ul>
  11088. <li>receiving new events,</li>
  11089. <li>linking them to those already in the room <a href="development/room-dag-concepts.html">DAG</a>,</li>
  11090. <li>persisting them to the DB, and finally</li>
  11091. <li>updating the events stream.</li>
  11092. </ul>
  11093. <p>Because load is sharded in this way, you <em>must</em> restart all worker instances when
  11094. adding or removing event persisters.</p>
  11095. <p>An <code>event_persister</code> should not be mistaken for an <code>event_creator</code>.
  11096. An <code>event_creator</code> listens for requests from clients to create new events and does
  11097. so. It will then pass those events over HTTP replication to any configured event
  11098. persisters (or the main process if none are configured).</p>
  11099. <p>Note that <code>event_creator</code>s and <code>event_persister</code>s are implemented using the same
  11100. <a href="workers.html#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a>.</p>
  11101. <p>An example <a href="usage/configuration/config_documentation.html#stream_writers"><code>stream_writers</code></a>
  11102. configuration with multiple writers:</p>
  11103. <pre><code class="language-yaml">stream_writers:
  11104. events:
  11105. - event_persister1
  11106. - event_persister2
  11107. </code></pre>
  11108. <h5 id="the-typing-stream"><a class="header" href="#the-typing-stream">The <code>typing</code> stream</a></h5>
  11109. <p>The following endpoints should be routed directly to the worker configured as
  11110. the stream writer for the <code>typing</code> stream:</p>
  11111. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing
  11112. </code></pre>
  11113. <h5 id="the-to_device-stream"><a class="header" href="#the-to_device-stream">The <code>to_device</code> stream</a></h5>
  11114. <p>The following endpoints should be routed directly to the worker configured as
  11115. the stream writer for the <code>to_device</code> stream:</p>
  11116. <pre><code>^/_matrix/client/(r0|v3|unstable)/sendToDevice/
  11117. </code></pre>
  11118. <h5 id="the-account_data-stream"><a class="header" href="#the-account_data-stream">The <code>account_data</code> stream</a></h5>
  11119. <p>The following endpoints should be routed directly to the worker configured as
  11120. the stream writer for the <code>account_data</code> stream:</p>
  11121. <pre><code>^/_matrix/client/(r0|v3|unstable)/.*/tags
  11122. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  11123. </code></pre>
  11124. <h5 id="the-receipts-stream"><a class="header" href="#the-receipts-stream">The <code>receipts</code> stream</a></h5>
  11125. <p>The following endpoints should be routed directly to the worker configured as
  11126. the stream writer for the <code>receipts</code> stream:</p>
  11127. <pre><code>^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  11128. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  11129. </code></pre>
  11130. <h5 id="the-presence-stream"><a class="header" href="#the-presence-stream">The <code>presence</code> stream</a></h5>
  11131. <p>The following endpoints should be routed directly to the worker configured as
  11132. the stream writer for the <code>presence</code> stream:</p>
  11133. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  11134. </code></pre>
  11135. <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>
  11136. <p>The
  11137. <a href="usage/configuration/config_documentation.html#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a>
  11138. configuration is useful to make sure outbound federation traffic only goes through a
  11139. specified subset of workers. This allows you to set more strict access controls (like a
  11140. firewall) for all workers and only allow the <code>federation_sender</code>'s to contact the
  11141. outside world.</p>
  11142. <pre><code class="language-yaml">instance_map:
  11143. main:
  11144. host: localhost
  11145. port: 8030
  11146. federation_sender1:
  11147. host: localhost
  11148. port: 8034
  11149. outbound_federation_restricted_to:
  11150. - federation_sender1
  11151. worker_replication_secret: &quot;secret_secret&quot;
  11152. </code></pre>
  11153. <h4 id="background-tasks"><a class="header" href="#background-tasks">Background tasks</a></h4>
  11154. <p>There is also support for moving background tasks to a separate
  11155. worker. Background tasks are run periodically or started via replication. Exactly
  11156. which tasks are configured to run depends on your Synapse configuration (e.g. if
  11157. stats is enabled). This worker doesn't handle any REST endpoints itself.</p>
  11158. <p>To enable this, the worker must have a unique
  11159. <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>
  11160. and can be configured to run background tasks. For example, to move background tasks
  11161. to a dedicated worker, the shared configuration would include:</p>
  11162. <pre><code class="language-yaml">run_background_tasks_on: background_worker
  11163. </code></pre>
  11164. <p>You might also wish to investigate the
  11165. <a href="workers.html#updating-the-user-directory"><code>update_user_directory_from_worker</code></a> and
  11166. <a href="workers.html#synapseappmedia_repository"><code>media_instance_running_background_jobs</code></a> settings.</p>
  11167. <p>An example for a dedicated background worker instance:</p>
  11168. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  11169. worker_name: background_worker
  11170. worker_log_config: /etc/matrix-synapse/background-worker-log.yaml
  11171. </code></pre>
  11172. <h4 id="updating-the-user-directory"><a class="header" href="#updating-the-user-directory">Updating the User Directory</a></h4>
  11173. <p>You can designate one generic worker to update the user directory.</p>
  11174. <p>Specify its name in the <a href="usage/configuration/config_documentation.html#update_user_directory_from_worker">shared configuration</a>
  11175. as follows:</p>
  11176. <pre><code class="language-yaml">update_user_directory_from_worker: worker_name
  11177. </code></pre>
  11178. <p>This work cannot be load-balanced; please ensure the main process is restarted
  11179. after setting this option in the shared configuration!</p>
  11180. <p>User directory updates allow REST endpoints matching the following regular
  11181. expressions to work:</p>
  11182. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  11183. </code></pre>
  11184. <p>The above endpoints can be routed to any worker, though you may choose to route
  11185. it to the chosen user directory worker.</p>
  11186. <p>This style of configuration supersedes the legacy <code>synapse.app.user_dir</code>
  11187. worker application type.</p>
  11188. <h4 id="notifying-application-services"><a class="header" href="#notifying-application-services">Notifying Application Services</a></h4>
  11189. <p>You can designate one generic worker to send output traffic to Application Services.
  11190. Doesn't handle any REST endpoints itself, but you should specify its name in the
  11191. <a href="usage/configuration/config_documentation.html#notify_appservices_from_worker">shared configuration</a>
  11192. as follows:</p>
  11193. <pre><code class="language-yaml">notify_appservices_from_worker: worker_name
  11194. </code></pre>
  11195. <p>This work cannot be load-balanced; please ensure the main process is restarted
  11196. after setting this option in the shared configuration!</p>
  11197. <p>This style of configuration supersedes the legacy <code>synapse.app.appservice</code>
  11198. worker application type.</p>
  11199. <h4 id="push-notifications"><a class="header" href="#push-notifications">Push Notifications</a></h4>
  11200. <p>You can designate generic worker to sending push notifications to
  11201. a <a href="https://spec.matrix.org/v1.5/push-gateway-api/">push gateway</a> such as
  11202. <a href="https://github.com/matrix-org/sygnal">sygnal</a> and email.</p>
  11203. <p>This will stop the main process sending push notifications.</p>
  11204. <p>The workers responsible for sending push notifications can be defined using the
  11205. <a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a>
  11206. option. For example:</p>
  11207. <pre><code class="language-yaml">pusher_instances:
  11208. - pusher_worker1
  11209. - pusher_worker2
  11210. </code></pre>
  11211. <p>Multiple workers can be added to this map, in which case the work is balanced
  11212. across them. Ensure the main process and all pusher workers are restarted after changing
  11213. this option.</p>
  11214. <p>These workers don't need to accept incoming HTTP requests to send push notifications,
  11215. so no additional reverse proxy configuration is required for pusher workers.</p>
  11216. <p>This style of configuration supersedes the legacy <code>synapse.app.pusher</code>
  11217. worker application type.</p>
  11218. <h3 id="synapseapppusher"><a class="header" href="#synapseapppusher"><code>synapse.app.pusher</code></a></h3>
  11219. <p>It is likely this option will be deprecated in the future and is not recommended for new
  11220. installations. Instead, <a href="workers.html#push-notifications">use <code>synapse.app.generic_worker</code> with the <code>pusher_instances</code></a>.</p>
  11221. <p>Handles sending push notifications to sygnal and email. Doesn't handle any
  11222. REST endpoints itself, but you should set
  11223. <a href="usage/configuration/config_documentation.html#start_pushers"><code>start_pushers: false</code></a> in the
  11224. shared configuration file to stop the main synapse sending push notifications.</p>
  11225. <p>To run multiple instances at once the
  11226. <a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a>
  11227. option should list all pusher instances by their
  11228. <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>, e.g.:</p>
  11229. <pre><code class="language-yaml">start_pushers: false
  11230. pusher_instances:
  11231. - pusher_worker1
  11232. - pusher_worker2
  11233. </code></pre>
  11234. <p>An example for a pusher instance:</p>
  11235. <pre><code class="language-yaml">worker_app: synapse.app.pusher
  11236. worker_name: pusher_worker1
  11237. worker_log_config: /etc/matrix-synapse/pusher-worker-log.yaml
  11238. </code></pre>
  11239. <h3 id="synapseappappservice"><a class="header" href="#synapseappappservice"><code>synapse.app.appservice</code></a></h3>
  11240. <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
  11241. <code>notify_appservices_from_worker</code> option instead.</a></p>
  11242. <p>Handles sending output traffic to Application Services. Doesn't handle any
  11243. REST endpoints itself, but you should set <code>notify_appservices: False</code> in the
  11244. shared configuration file to stop the main synapse sending appservice notifications.</p>
  11245. <p>Note this worker cannot be load-balanced: only one instance should be active.</p>
  11246. <h3 id="synapseappfederation_sender"><a class="header" href="#synapseappfederation_sender"><code>synapse.app.federation_sender</code></a></h3>
  11247. <p>It is likely this option will be deprecated in the future and not recommended for
  11248. 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>
  11249. <p>Handles sending federation traffic to other servers. Doesn't handle any
  11250. REST endpoints itself, but you should set
  11251. <a href="usage/configuration/config_documentation.html#send_federation"><code>send_federation: false</code></a>
  11252. in the shared configuration file to stop the main synapse sending this traffic.</p>
  11253. <p>If running multiple federation senders then you must list each
  11254. instance in the
  11255. <a href="usage/configuration/config_documentation.html#federation_sender_instances"><code>federation_sender_instances</code></a>
  11256. option by their
  11257. <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>.
  11258. All instances must be stopped and started when adding or removing instances.
  11259. For example:</p>
  11260. <pre><code class="language-yaml">send_federation: false
  11261. federation_sender_instances:
  11262. - federation_sender1
  11263. - federation_sender2
  11264. </code></pre>
  11265. <p>An example for a federation sender instance:</p>
  11266. <pre><code class="language-yaml">worker_app: synapse.app.federation_sender
  11267. worker_name: federation_sender1
  11268. worker_log_config: /etc/matrix-synapse/federation-sender-log.yaml
  11269. </code></pre>
  11270. <h3 id="synapseappmedia_repository"><a class="header" href="#synapseappmedia_repository"><code>synapse.app.media_repository</code></a></h3>
  11271. <p>Handles the media repository. It can handle all endpoints starting with:</p>
  11272. <pre><code>/_matrix/media/
  11273. </code></pre>
  11274. <p>... and the following regular expressions matching media-specific administration APIs:</p>
  11275. <pre><code>^/_synapse/admin/v1/purge_media_cache$
  11276. ^/_synapse/admin/v1/room/.*/media.*$
  11277. ^/_synapse/admin/v1/user/.*/media.*$
  11278. ^/_synapse/admin/v1/media/.*$
  11279. ^/_synapse/admin/v1/quarantine_media/.*$
  11280. ^/_synapse/admin/v1/users/.*/media$
  11281. </code></pre>
  11282. <p>You should also set
  11283. <a href="usage/configuration/config_documentation.html#enable_media_repo"><code>enable_media_repo: False</code></a>
  11284. in the shared configuration
  11285. file to stop the main synapse running background jobs related to managing the
  11286. media repository. Note that doing so will prevent the main process from being
  11287. able to handle the above endpoints.</p>
  11288. <p>In the <code>media_repository</code> worker configuration file, configure the
  11289. <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a> to
  11290. expose the <code>media</code> resource. For example:</p>
  11291. <pre><code class="language-yaml">worker_app: synapse.app.media_repository
  11292. worker_name: media_worker
  11293. worker_listeners:
  11294. - type: http
  11295. port: 8085
  11296. x_forwarded: true
  11297. resources:
  11298. - names: [media]
  11299. worker_log_config: /etc/matrix-synapse/media-worker-log.yaml
  11300. </code></pre>
  11301. <p>Note that if running multiple media repositories they must be on the same server
  11302. and you must specify a single instance to run the background tasks in the
  11303. <a href="usage/configuration/config_documentation.html#media_instance_running_background_jobs">shared configuration</a>,
  11304. e.g.:</p>
  11305. <pre><code class="language-yaml">media_instance_running_background_jobs: &quot;media-repository-1&quot;
  11306. </code></pre>
  11307. <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>
  11308. <h3 id="synapseappuser_dir"><a class="header" href="#synapseappuser_dir"><code>synapse.app.user_dir</code></a></h3>
  11309. <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
  11310. <code>update_user_directory_from_worker</code> option instead.</a></p>
  11311. <p>Handles searches in the user directory. It can handle REST endpoints matching
  11312. the following regular expressions:</p>
  11313. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  11314. </code></pre>
  11315. <p>When using this worker you must also set <code>update_user_directory: false</code> in the
  11316. shared configuration file to stop the main synapse running background
  11317. jobs related to updating the user directory.</p>
  11318. <p>Above endpoint is not <em>required</em> to be routed to this worker. By default,
  11319. <code>update_user_directory</code> is set to <code>true</code>, which means the main process
  11320. will handle updates. All workers configured with <code>client</code> can handle the above
  11321. endpoint as long as either this worker or the main process are configured to
  11322. handle it, and are online.</p>
  11323. <p>If <code>update_user_directory</code> is set to <code>false</code>, and this worker is not running,
  11324. the above endpoint may give outdated results.</p>
  11325. <h3 id="historical-apps"><a class="header" href="#historical-apps">Historical apps</a></h3>
  11326. <p>The following used to be separate worker application types, but are now
  11327. equivalent to <code>synapse.app.generic_worker</code>:</p>
  11328. <ul>
  11329. <li><code>synapse.app.client_reader</code></li>
  11330. <li><code>synapse.app.event_creator</code></li>
  11331. <li><code>synapse.app.federation_reader</code></li>
  11332. <li><code>synapse.app.federation_sender</code></li>
  11333. <li><code>synapse.app.frontend_proxy</code></li>
  11334. <li><code>synapse.app.pusher</code></li>
  11335. <li><code>synapse.app.synchrotron</code></li>
  11336. </ul>
  11337. <h2 id="migration-from-old-config"><a class="header" href="#migration-from-old-config">Migration from old config</a></h2>
  11338. <p>A main change that has occurred is the merging of worker apps into
  11339. <code>synapse.app.generic_worker</code>. This change is backwards compatible and so no
  11340. changes to the config are required.</p>
  11341. <p>To migrate apps to use <code>synapse.app.generic_worker</code> simply update the
  11342. <code>worker_app</code> option in the worker configs, and where worker are started (e.g.
  11343. in systemd service files, but not required for synctl).</p>
  11344. <h2 id="architectural-diagram"><a class="header" href="#architectural-diagram">Architectural diagram</a></h2>
  11345. <p>The following shows an example setup using Redis and a reverse proxy:</p>
  11346. <pre><code> Clients &amp; Federation
  11347. |
  11348. v
  11349. +-----------+
  11350. | |
  11351. | Reverse |
  11352. | Proxy |
  11353. | |
  11354. +-----------+
  11355. | | |
  11356. | | | HTTP requests
  11357. +-------------------+ | +-----------+
  11358. | +---+ |
  11359. | | |
  11360. v v v
  11361. +--------------+ +--------------+ +--------------+ +--------------+
  11362. | Main | | Generic | | Generic | | Event |
  11363. | Process | | Worker 1 | | Worker 2 | | Persister |
  11364. +--------------+ +--------------+ +--------------+ +--------------+
  11365. ^ ^ | ^ | | ^ | | ^ ^
  11366. | | | | | | | | | | |
  11367. | | | | | HTTP | | | | | |
  11368. | +----------+&lt;--|---|---------+&lt;--|---|---------+ | |
  11369. | | +-------------|--&gt;+-------------+ |
  11370. | | | |
  11371. | | | |
  11372. v v v v
  11373. ======================================================================
  11374. Redis pub/sub channel
  11375. </code></pre>
  11376. <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>
  11377. <p>If you want to use <code>synctl</code> to manage your synapse processes, you will need to
  11378. create an an additional configuration file for the main synapse process. That
  11379. configuration should look like this:</p>
  11380. <pre><code class="language-yaml">worker_app: synapse.app.homeserver
  11381. </code></pre>
  11382. <p>Additionally, each worker app must be configured with the name of a &quot;pid file&quot;,
  11383. to which it will write its process ID when it starts. For example, for a
  11384. synchrotron, you might write:</p>
  11385. <pre><code class="language-yaml">worker_pid_file: /home/matrix/synapse/worker1.pid
  11386. </code></pre>
  11387. <p>Finally, to actually run your worker-based synapse, you must pass synctl the <code>-a</code>
  11388. commandline option to tell it to operate on all the worker configurations found
  11389. in the given directory, e.g.:</p>
  11390. <pre><code class="language-sh">synctl -a $CONFIG/workers start
  11391. </code></pre>
  11392. <p>Currently one should always restart all workers when restarting or upgrading
  11393. synapse, unless you explicitly know it's safe not to. For instance, restarting
  11394. synapse without restarting all the synchrotrons may result in broken typing
  11395. notifications.</p>
  11396. <p>To manipulate a specific worker, you pass the -w option to synctl:</p>
  11397. <pre><code class="language-sh">synctl -w $CONFIG/workers/worker1.yaml restart
  11398. </code></pre>
  11399. <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>
  11400. <p>This is a setup for managing synapse with systemd, including support for
  11401. managing workers. It provides a <code>matrix-synapse</code> service for the master, as
  11402. well as a <code>matrix-synapse-worker@</code> service template for any workers you
  11403. require. Additionally, to group the required services, it sets up a
  11404. <code>matrix-synapse.target</code>.</p>
  11405. <p>See the folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
  11406. for the systemd unit files.</p>
  11407. <p>The folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/workers/">workers</a>
  11408. contains an example configuration for the <code>generic_worker</code> worker.</p>
  11409. <h2 id="synapse-configuration-files"><a class="header" href="#synapse-configuration-files">Synapse configuration files</a></h2>
  11410. <p>See <a href="systemd-with-workers/../workers.html">the worker documentation</a> for information on how to set up the
  11411. configuration files and reverse-proxy correctly.
  11412. Below is a sample <code>generic_worker</code> worker configuration file.</p>
  11413. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  11414. worker_name: generic_worker1
  11415. worker_listeners:
  11416. - type: http
  11417. port: 8083
  11418. x_forwarded: true
  11419. resources:
  11420. - names: [client, federation]
  11421. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  11422. </code></pre>
  11423. <p>Systemd manages daemonization itself, so ensure that none of the configuration
  11424. files set either <code>daemonize</code> or <code>worker_daemonize</code>.</p>
  11425. <p>The config files of all workers are expected to be located in
  11426. <code>/etc/matrix-synapse/workers</code>. If you want to use a different location, edit
  11427. the provided <code>*.service</code> files accordingly.</p>
  11428. <p>There is no need for a separate configuration file for the master process.</p>
  11429. <h2 id="set-up"><a class="header" href="#set-up">Set up</a></h2>
  11430. <ol>
  11431. <li>Adjust synapse configuration files as above.</li>
  11432. <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>
  11433. to <code>/etc/systemd/system</code>.</li>
  11434. <li>Run <code>systemctl daemon-reload</code> to tell systemd to load the new unit files.</li>
  11435. <li>Run <code>systemctl enable matrix-synapse.service</code>. This will configure the
  11436. synapse master process to be started as part of the <code>matrix-synapse.target</code>
  11437. target.</li>
  11438. <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
  11439. should be a corresponding configuration file.
  11440. <code>/etc/matrix-synapse/workers/&lt;worker_name&gt;.yaml</code>.</li>
  11441. <li>Start all the synapse processes with <code>systemctl start matrix-synapse.target</code>.</li>
  11442. <li>Tell systemd to start synapse on boot with <code>systemctl enable matrix-synapse.target</code>.</li>
  11443. </ol>
  11444. <h2 id="usage"><a class="header" href="#usage">Usage</a></h2>
  11445. <p>Once the services are correctly set up, you can use the following commands
  11446. to manage your synapse installation:</p>
  11447. <pre><code class="language-sh"># Restart Synapse master and all workers
  11448. systemctl restart matrix-synapse.target
  11449. # Stop Synapse and all workers
  11450. systemctl stop matrix-synapse.target
  11451. # Restart the master alone
  11452. systemctl start matrix-synapse.service
  11453. # Restart a specific worker (eg. generic_worker); the master is
  11454. # unaffected by this.
  11455. systemctl restart matrix-synapse-worker@generic_worker.service
  11456. # Add a new worker (assuming all configs are set up already)
  11457. systemctl enable matrix-synapse-worker@federation_writer.service
  11458. systemctl restart matrix-synapse.target
  11459. </code></pre>
  11460. <h2 id="hardening"><a class="header" href="#hardening">Hardening</a></h2>
  11461. <p><strong>Optional:</strong> If further hardening is desired, the file
  11462. <code>override-hardened.conf</code> may be copied from
  11463. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/systemd/">contrib/systemd/override-hardened.conf</a>
  11464. in this repository to the location
  11465. <code>/etc/systemd/system/matrix-synapse.service.d/override-hardened.conf</code> (the
  11466. directory may have to be created). It enables certain sandboxing features in
  11467. systemd to further secure the synapse service. You may read the comments to
  11468. understand what the override file is doing. The same file will need to be copied to
  11469. <code>/etc/systemd/system/matrix-synapse-worker@.service.d/override-hardened-worker.conf</code>
  11470. (this directory may also have to be created) in order to apply the same
  11471. hardening options to any worker processes.</p>
  11472. <p>Once these files have been copied to their appropriate locations, simply reload
  11473. systemd's manager config files and restart all Synapse services to apply the hardening options. They will automatically
  11474. be applied at every restart as long as the override files are present at the
  11475. specified locations.</p>
  11476. <pre><code class="language-sh">systemctl daemon-reload
  11477. # Restart services
  11478. systemctl restart matrix-synapse.target
  11479. </code></pre>
  11480. <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
  11481. the changes being applied at a glance.</p>
  11482. <div style="break-before: page; page-break-before: always;"></div><h1 id="administration"><a class="header" href="#administration">Administration</a></h1>
  11483. <p>This section contains information on managing your Synapse homeserver. This includes:</p>
  11484. <ul>
  11485. <li>Managing users, rooms and media via the Admin API.</li>
  11486. <li>Setting up metrics and monitoring to give you insight into your homeserver's health.</li>
  11487. <li>Configuring structured logging.</li>
  11488. </ul>
  11489. <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>
  11490. <h2 id="authenticate-as-a-server-admin"><a class="header" href="#authenticate-as-a-server-admin">Authenticate as a server admin</a></h2>
  11491. <p>Many of the API calls in the admin api will require an <code>access_token</code> for a
  11492. server admin. (Note that a server admin is distinct from a room admin.)</p>
  11493. <p>An existing user can be marked as a server admin by updating the database directly.</p>
  11494. <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>
  11495. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  11496. </code></pre>
  11497. <p>A new server admin user can also be created using the <code>register_new_matrix_user</code>
  11498. command. This is a script that is distributed as part of synapse. It is possibly
  11499. already on your <code>$PATH</code> depending on how Synapse was installed.</p>
  11500. <p>Finding your user's <code>access_token</code> is client-dependent, but will usually be shown in the client's settings.</p>
  11501. <h2 id="making-an-admin-api-request"><a class="header" href="#making-an-admin-api-request">Making an Admin API request</a></h2>
  11502. <p>For security reasons, we <a href="usage/administration/admin_api/../../../reverse_proxy.html#synapse-administration-endpoints">recommend</a>
  11503. that the Admin API (<code>/_synapse/admin/...</code>) should be hidden from public view using a
  11504. reverse proxy. This means you should typically query the Admin API from a terminal on
  11505. the machine which runs Synapse.</p>
  11506. <p>Once you have your <code>access_token</code>, you will need to authenticate each request to an Admin API endpoint by
  11507. providing the token as either a query parameter or a request header. To add it as a request header in cURL:</p>
  11508. <pre><code class="language-sh">curl --header &quot;Authorization: Bearer &lt;access_token&gt;&quot; &lt;the_rest_of_your_API_request&gt;
  11509. </code></pre>
  11510. <p>For example, suppose we want to
  11511. <a href="usage/administration/admin_api/../../../admin_api/user_admin_api.html#query-user-account">query the account</a> of the user
  11512. <code>@foo:bar.com</code>. We need an admin access token (e.g.
  11513. <code>syt_AjfVef2_L33JNpafeif_0feKJfeaf0CQpoZk</code>), and we need to know which port
  11514. Synapse's <a href="usage/administration/admin_api/../../configuration/config_documentation.html#listeners"><code>client</code> listener</a> is listening
  11515. on (e.g. <code>8008</code>). Then we can use the following command to request the account
  11516. information from the Admin API.</p>
  11517. <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
  11518. </code></pre>
  11519. <p>For more details on access tokens in Matrix, please refer to the complete
  11520. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#using-access-tokens">matrix spec documentation</a>.</p>
  11521. <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>
  11522. <p>This API allows a server administrator to manage the validity of an account. To
  11523. use it, you must enable the account validity feature (under
  11524. <code>account_validity</code>) in Synapse's configuration.</p>
  11525. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11526. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11527. <h2 id="renew-account"><a class="header" href="#renew-account">Renew account</a></h2>
  11528. <p>This API extends the validity of an account by as much time as configured in the
  11529. <code>period</code> parameter from the <code>account_validity</code> configuration.</p>
  11530. <p>The API is:</p>
  11531. <pre><code>POST /_synapse/admin/v1/account_validity/validity
  11532. </code></pre>
  11533. <p>with the following body:</p>
  11534. <pre><code class="language-json">{
  11535. &quot;user_id&quot;: &quot;&lt;user ID for the account to renew&gt;&quot;,
  11536. &quot;expiration_ts&quot;: 0,
  11537. &quot;enable_renewal_emails&quot;: true
  11538. }
  11539. </code></pre>
  11540. <p><code>expiration_ts</code> is an optional parameter and overrides the expiration date,
  11541. which otherwise defaults to now + validity period.</p>
  11542. <p><code>enable_renewal_emails</code> is also an optional parameter and enables/disables
  11543. sending renewal emails to the user. Defaults to true.</p>
  11544. <p>The API returns with the new expiration date for this account, as a timestamp in
  11545. milliseconds since epoch:</p>
  11546. <pre><code class="language-json">{
  11547. &quot;expiration_ts&quot;: 0
  11548. }
  11549. </code></pre>
  11550. <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>
  11551. <p>This API allows a server administrator to manage the background updates being
  11552. run against the database.</p>
  11553. <h2 id="status"><a class="header" href="#status">Status</a></h2>
  11554. <p>This API gets the current status of the background updates.</p>
  11555. <p>The API is:</p>
  11556. <pre><code>GET /_synapse/admin/v1/background_updates/status
  11557. </code></pre>
  11558. <p>Returning:</p>
  11559. <pre><code class="language-json">{
  11560. &quot;enabled&quot;: true,
  11561. &quot;current_updates&quot;: {
  11562. &quot;&lt;db_name&gt;&quot;: {
  11563. &quot;name&quot;: &quot;&lt;background_update_name&gt;&quot;,
  11564. &quot;total_item_count&quot;: 50,
  11565. &quot;total_duration_ms&quot;: 10000.0,
  11566. &quot;average_items_per_ms&quot;: 2.2,
  11567. },
  11568. }
  11569. }
  11570. </code></pre>
  11571. <p><code>enabled</code> whether the background updates are enabled or disabled.</p>
  11572. <p><code>db_name</code> the database name (usually Synapse is configured with a single database named 'master').</p>
  11573. <p>For each update:</p>
  11574. <p><code>name</code> the name of the update.
  11575. <code>total_item_count</code> total number of &quot;items&quot; processed (the meaning of 'items' depends on the update in question).
  11576. <code>total_duration_ms</code> how long the background process has been running, not including time spent sleeping.
  11577. <code>average_items_per_ms</code> how many items are processed per millisecond based on an exponential average.</p>
  11578. <h2 id="enabled"><a class="header" href="#enabled">Enabled</a></h2>
  11579. <p>This API allow pausing background updates.</p>
  11580. <p>Background updates should <em>not</em> be paused for significant periods of time, as
  11581. this can affect the performance of Synapse.</p>
  11582. <p><em>Note</em>: This won't persist over restarts.</p>
  11583. <p><em>Note</em>: This won't cancel any update query that is currently running. This is
  11584. usually fine since most queries are short lived, except for <code>CREATE INDEX</code>
  11585. background updates which won't be cancelled once started.</p>
  11586. <p>The API is:</p>
  11587. <pre><code>POST /_synapse/admin/v1/background_updates/enabled
  11588. </code></pre>
  11589. <p>with the following body:</p>
  11590. <pre><code class="language-json">{
  11591. &quot;enabled&quot;: false
  11592. }
  11593. </code></pre>
  11594. <p><code>enabled</code> sets whether the background updates are enabled or disabled.</p>
  11595. <p>The API returns the <code>enabled</code> param.</p>
  11596. <pre><code class="language-json">{
  11597. &quot;enabled&quot;: false
  11598. }
  11599. </code></pre>
  11600. <p>There is also a <code>GET</code> version which returns the <code>enabled</code> state.</p>
  11601. <h2 id="run"><a class="header" href="#run">Run</a></h2>
  11602. <p>This API schedules a specific background update to run. The job starts immediately after calling the API.</p>
  11603. <p>The API is:</p>
  11604. <pre><code>POST /_synapse/admin/v1/background_updates/start_job
  11605. </code></pre>
  11606. <p>with the following body:</p>
  11607. <pre><code class="language-json">{
  11608. &quot;job_name&quot;: &quot;populate_stats_process_rooms&quot;
  11609. }
  11610. </code></pre>
  11611. <p>The following JSON body parameters are available:</p>
  11612. <ul>
  11613. <li><code>job_name</code> - A string which job to run. Valid values are:
  11614. <ul>
  11615. <li><code>populate_stats_process_rooms</code> - Recalculate the stats for all rooms.</li>
  11616. <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>
  11617. </ul>
  11618. </li>
  11619. </ul>
  11620. <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>
  11621. <p>This API returns information about reported events.</p>
  11622. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11623. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11624. <p>The api is:</p>
  11625. <pre><code>GET /_synapse/admin/v1/event_reports?from=0&amp;limit=10
  11626. </code></pre>
  11627. <p>It returns a JSON body like the following:</p>
  11628. <pre><code class="language-json">{
  11629. &quot;event_reports&quot;: [
  11630. {
  11631. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  11632. &quot;id&quot;: 2,
  11633. &quot;reason&quot;: &quot;foo&quot;,
  11634. &quot;score&quot;: -100,
  11635. &quot;received_ts&quot;: 1570897107409,
  11636. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  11637. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  11638. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11639. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11640. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  11641. },
  11642. {
  11643. &quot;event_id&quot;: &quot;$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I&quot;,
  11644. &quot;id&quot;: 3,
  11645. &quot;reason&quot;: &quot;bar&quot;,
  11646. &quot;score&quot;: -100,
  11647. &quot;received_ts&quot;: 1598889612059,
  11648. &quot;canonical_alias&quot;: &quot;#alias2:matrix.org&quot;,
  11649. &quot;room_id&quot;: &quot;!eGvUQuTCkHGVwNMOjv:matrix.org&quot;,
  11650. &quot;name&quot;: &quot;Your room name here&quot;,
  11651. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11652. &quot;user_id&quot;: &quot;@bar:matrix.org&quot;
  11653. }
  11654. ],
  11655. &quot;next_token&quot;: 2,
  11656. &quot;total&quot;: 4
  11657. }
  11658. </code></pre>
  11659. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again with <code>from</code>
  11660. set to the value of <code>next_token</code>. This will return a new page.</p>
  11661. <p>If the endpoint does not return a <code>next_token</code> then there are no more reports to
  11662. paginate through.</p>
  11663. <p><strong>URL parameters:</strong></p>
  11664. <ul>
  11665. <li><code>limit</code>: integer - Is optional but is used for pagination, denoting the maximum number
  11666. of items to return in this call. Defaults to <code>100</code>.</li>
  11667. <li><code>from</code>: integer - Is optional but used for pagination, denoting the offset in the
  11668. returned results. This should be treated as an opaque value and not explicitly set to
  11669. anything other than the return value of <code>next_token</code> from a previous call. Defaults to <code>0</code>.</li>
  11670. <li><code>dir</code>: string - Direction of event report order. Whether to fetch the most recent
  11671. first (<code>b</code>) or the oldest first (<code>f</code>). Defaults to <code>b</code>.</li>
  11672. <li><code>user_id</code>: string - Is optional and filters to only return users with user IDs that
  11673. contain this value. This is the user who reported the event and wrote the reason.</li>
  11674. <li><code>room_id</code>: string - Is optional and filters to only return rooms with room IDs that
  11675. contain this value.</li>
  11676. </ul>
  11677. <p><strong>Response</strong></p>
  11678. <p>The following fields are returned in the JSON response body:</p>
  11679. <ul>
  11680. <li><code>id</code>: integer - ID of event report.</li>
  11681. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  11682. report was sent.</li>
  11683. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  11684. <li><code>name</code>: string - The name of the room.</li>
  11685. <li><code>event_id</code>: string - The ID of the reported event.</li>
  11686. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  11687. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank or <code>null</code>.</li>
  11688. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  11689. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;. May be <code>null</code>.</li>
  11690. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  11691. was reported.</li>
  11692. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  11693. have a canonical alias set.</li>
  11694. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  11695. <li><code>total</code>: integer - Total number of event reports related to the query
  11696. (<code>user_id</code> and <code>room_id</code>).</li>
  11697. </ul>
  11698. <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>
  11699. <p>This API returns information about a specific event report.</p>
  11700. <p>The api is:</p>
  11701. <pre><code>GET /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  11702. </code></pre>
  11703. <p>It returns a JSON body like the following:</p>
  11704. <pre><code class="language-json">{
  11705. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  11706. &quot;event_json&quot;: {
  11707. &quot;auth_events&quot;: [
  11708. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;,
  11709. &quot;$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws&quot;
  11710. ],
  11711. &quot;content&quot;: {
  11712. &quot;body&quot;: &quot;matrix.org: This Week in Matrix&quot;,
  11713. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  11714. &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;,
  11715. &quot;msgtype&quot;: &quot;m.notice&quot;
  11716. },
  11717. &quot;depth&quot;: 546,
  11718. &quot;hashes&quot;: {
  11719. &quot;sha256&quot;: &quot;xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw&quot;
  11720. },
  11721. &quot;origin&quot;: &quot;matrix.org&quot;,
  11722. &quot;origin_server_ts&quot;: 1592291711430,
  11723. &quot;prev_events&quot;: [
  11724. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;
  11725. ],
  11726. &quot;prev_state&quot;: [],
  11727. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  11728. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11729. &quot;signatures&quot;: {
  11730. &quot;matrix.org&quot;: {
  11731. &quot;ed25519:a_JaEG&quot;: &quot;cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg&quot;
  11732. }
  11733. },
  11734. &quot;type&quot;: &quot;m.room.message&quot;,
  11735. &quot;unsigned&quot;: {
  11736. &quot;age_ts&quot;: 1592291711430
  11737. }
  11738. },
  11739. &quot;id&quot;: &lt;report_id&gt;,
  11740. &quot;reason&quot;: &quot;foo&quot;,
  11741. &quot;score&quot;: -100,
  11742. &quot;received_ts&quot;: 1570897107409,
  11743. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  11744. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  11745. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11746. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11747. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  11748. }
  11749. </code></pre>
  11750. <p><strong>URL parameters:</strong></p>
  11751. <ul>
  11752. <li><code>report_id</code>: string - The ID of the event report.</li>
  11753. </ul>
  11754. <p><strong>Response</strong></p>
  11755. <p>The following fields are returned in the JSON response body:</p>
  11756. <ul>
  11757. <li><code>id</code>: integer - ID of event report.</li>
  11758. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  11759. report was sent.</li>
  11760. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  11761. <li><code>name</code>: string - The name of the room.</li>
  11762. <li><code>event_id</code>: string - The ID of the reported event.</li>
  11763. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  11764. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank.</li>
  11765. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  11766. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;.</li>
  11767. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  11768. was reported.</li>
  11769. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  11770. have a canonical alias set.</li>
  11771. <li><code>event_json</code>: object - Details of the original event that was reported.</li>
  11772. </ul>
  11773. <h1 id="delete-a-specific-event-report"><a class="header" href="#delete-a-specific-event-report">Delete a specific event report</a></h1>
  11774. <p>This API deletes a specific event report. If the request is successful, the response body
  11775. will be an empty JSON object.</p>
  11776. <p>The api is:</p>
  11777. <pre><code>DELETE /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  11778. </code></pre>
  11779. <p><strong>URL parameters:</strong></p>
  11780. <ul>
  11781. <li><code>report_id</code>: string - The ID of the event report.</li>
  11782. </ul>
  11783. <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>
  11784. <p>This API allows a server administrator to enable or disable some experimental features on a per-user
  11785. basis. The currently supported features are: </p>
  11786. <ul>
  11787. <li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3026">MSC3026</a>: busy
  11788. presence state enabled</li>
  11789. <li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3881">MSC3881</a>: enable remotely toggling push notifications
  11790. for another client </li>
  11791. <li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3967">MSC3967</a>: do not require
  11792. UIA when first uploading cross-signing keys. </li>
  11793. </ul>
  11794. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11795. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11796. <h2 id="enablingdisabling-features"><a class="header" href="#enablingdisabling-features">Enabling/Disabling Features</a></h2>
  11797. <p>This API allows a server administrator to enable experimental features for a given user. The request must
  11798. provide a body containing the user id and listing the features to enable/disable in the following format:</p>
  11799. <pre><code class="language-json">{
  11800. &quot;features&quot;: {
  11801. &quot;msc3026&quot;:true,
  11802. &quot;msc3881&quot;:true
  11803. }
  11804. }
  11805. </code></pre>
  11806. <p>where true is used to enable the feature, and false is used to disable the feature.</p>
  11807. <p>The API is:</p>
  11808. <pre><code>PUT /_synapse/admin/v1/experimental_features/&lt;user_id&gt;
  11809. </code></pre>
  11810. <h2 id="listing-enabled-features"><a class="header" href="#listing-enabled-features">Listing Enabled Features</a></h2>
  11811. <p>To list which features are enabled/disabled for a given user send a request to the following API:</p>
  11812. <pre><code>GET /_synapse/admin/v1/experimental_features/&lt;user_id&gt;
  11813. </code></pre>
  11814. <p>It will return a list of possible features and indicate whether they are enabled or disabled for the
  11815. user like so:</p>
  11816. <pre><code class="language-json">{
  11817. &quot;features&quot;: {
  11818. &quot;msc3026&quot;: true,
  11819. &quot;msc3881&quot;: false,
  11820. &quot;msc3967&quot;: false
  11821. }
  11822. }
  11823. </code></pre>
  11824. <div style="break-before: page; page-break-before: always;"></div><h1 id="querying-media"><a class="header" href="#querying-media">Querying media</a></h1>
  11825. <p>These APIs allow extracting media information from the homeserver.</p>
  11826. <p>Details about the format of the <code>media_id</code> and storage of the media in the file system
  11827. are documented under <a href="admin_api/../media_repository.html">media repository</a>.</p>
  11828. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11829. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11830. <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>
  11831. <p>This API gets a list of known media in a room.
  11832. However, it only shows media from unencrypted events or rooms.</p>
  11833. <p>The API is:</p>
  11834. <pre><code>GET /_synapse/admin/v1/room/&lt;room_id&gt;/media
  11835. </code></pre>
  11836. <p>The API returns a JSON body like the following:</p>
  11837. <pre><code class="language-json">{
  11838. &quot;local&quot;: [
  11839. &quot;mxc://localhost/xwvutsrqponmlkjihgfedcba&quot;,
  11840. &quot;mxc://localhost/abcdefghijklmnopqrstuvwx&quot;
  11841. ],
  11842. &quot;remote&quot;: [
  11843. &quot;mxc://matrix.org/xwvutsrqponmlkjihgfedcba&quot;,
  11844. &quot;mxc://matrix.org/abcdefghijklmnopqrstuvwx&quot;
  11845. ]
  11846. }
  11847. </code></pre>
  11848. <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>
  11849. <p>Listing all media that has been uploaded by a local user can be achieved through
  11850. the use of the
  11851. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>
  11852. Admin API.</p>
  11853. <h1 id="quarantine-media"><a class="header" href="#quarantine-media">Quarantine media</a></h1>
  11854. <p>Quarantining media means that it is marked as inaccessible by users. It applies
  11855. to any local media, and any locally-cached copies of remote media.</p>
  11856. <p>The media file itself (and any thumbnails) is not deleted from the server.</p>
  11857. <h2 id="quarantining-media-by-id"><a class="header" href="#quarantining-media-by-id">Quarantining media by ID</a></h2>
  11858. <p>This API quarantines a single piece of local or remote media.</p>
  11859. <p>Request:</p>
  11860. <pre><code>POST /_synapse/admin/v1/media/quarantine/&lt;server_name&gt;/&lt;media_id&gt;
  11861. {}
  11862. </code></pre>
  11863. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  11864. form of <code>abcdefg12345...</code>.</p>
  11865. <p>Response:</p>
  11866. <pre><code class="language-json">{}
  11867. </code></pre>
  11868. <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>
  11869. <p>This API removes a single piece of local or remote media from quarantine.</p>
  11870. <p>Request:</p>
  11871. <pre><code>POST /_synapse/admin/v1/media/unquarantine/&lt;server_name&gt;/&lt;media_id&gt;
  11872. {}
  11873. </code></pre>
  11874. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  11875. form of <code>abcdefg12345...</code>.</p>
  11876. <p>Response:</p>
  11877. <pre><code class="language-json">{}
  11878. </code></pre>
  11879. <h2 id="quarantining-media-in-a-room"><a class="header" href="#quarantining-media-in-a-room">Quarantining media in a room</a></h2>
  11880. <p>This API quarantines all local and remote media in a room.</p>
  11881. <p>Request:</p>
  11882. <pre><code>POST /_synapse/admin/v1/room/&lt;room_id&gt;/media/quarantine
  11883. {}
  11884. </code></pre>
  11885. <p>Where <code>room_id</code> is in the form of <code>!roomid12345:example.org</code>.</p>
  11886. <p>Response:</p>
  11887. <pre><code class="language-json">{
  11888. &quot;num_quarantined&quot;: 10
  11889. }
  11890. </code></pre>
  11891. <p>The following fields are returned in the JSON response body:</p>
  11892. <ul>
  11893. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  11894. </ul>
  11895. <p>Note that there is a legacy endpoint, <code>POST /_synapse/admin/v1/quarantine_media/&lt;room_id&gt;</code>, that operates the same.
  11896. However, it is deprecated and may be removed in a future release.</p>
  11897. <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>
  11898. <p>This API quarantines all <em>local</em> media that a <em>local</em> user has uploaded. That is to say, if
  11899. you would like to quarantine media uploaded by a user on a remote homeserver, you should
  11900. instead use one of the other APIs.</p>
  11901. <p>Request:</p>
  11902. <pre><code>POST /_synapse/admin/v1/user/&lt;user_id&gt;/media/quarantine
  11903. {}
  11904. </code></pre>
  11905. <p>URL Parameters</p>
  11906. <ul>
  11907. <li><code>user_id</code>: string - User ID in the form of <code>@bob:example.org</code></li>
  11908. </ul>
  11909. <p>Response:</p>
  11910. <pre><code class="language-json">{
  11911. &quot;num_quarantined&quot;: 10
  11912. }
  11913. </code></pre>
  11914. <p>The following fields are returned in the JSON response body:</p>
  11915. <ul>
  11916. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  11917. </ul>
  11918. <h2 id="protecting-media-from-being-quarantined"><a class="header" href="#protecting-media-from-being-quarantined">Protecting media from being quarantined</a></h2>
  11919. <p>This API protects a single piece of local media from being quarantined using the
  11920. above APIs. This is useful for sticker packs and other shared media which you do
  11921. not want to get quarantined, especially when
  11922. <a href="admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantining media in a room</a>.</p>
  11923. <p>Request:</p>
  11924. <pre><code>POST /_synapse/admin/v1/media/protect/&lt;media_id&gt;
  11925. {}
  11926. </code></pre>
  11927. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  11928. <p>Response:</p>
  11929. <pre><code class="language-json">{}
  11930. </code></pre>
  11931. <h2 id="unprotecting-media-from-being-quarantined"><a class="header" href="#unprotecting-media-from-being-quarantined">Unprotecting media from being quarantined</a></h2>
  11932. <p>This API reverts the protection of a media.</p>
  11933. <p>Request:</p>
  11934. <pre><code>POST /_synapse/admin/v1/media/unprotect/&lt;media_id&gt;
  11935. {}
  11936. </code></pre>
  11937. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  11938. <p>Response:</p>
  11939. <pre><code class="language-json">{}
  11940. </code></pre>
  11941. <h1 id="delete-local-media"><a class="header" href="#delete-local-media">Delete local media</a></h1>
  11942. <p>This API deletes the <em>local</em> media from the disk of your own server.
  11943. This includes any local thumbnails and copies of media downloaded from
  11944. remote homeservers.
  11945. This API will not affect media that has been uploaded to external
  11946. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).
  11947. See also <a href="admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a>.</p>
  11948. <h2 id="delete-a-specific-local-media"><a class="header" href="#delete-a-specific-local-media">Delete a specific local media</a></h2>
  11949. <p>Delete a specific <code>media_id</code>.</p>
  11950. <p>Request:</p>
  11951. <pre><code>DELETE /_synapse/admin/v1/media/&lt;server_name&gt;/&lt;media_id&gt;
  11952. {}
  11953. </code></pre>
  11954. <p>URL Parameters</p>
  11955. <ul>
  11956. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>)</li>
  11957. <li><code>media_id</code>: string - The ID of the media (e.g <code>abcdefghijklmnopqrstuvwx</code>)</li>
  11958. </ul>
  11959. <p>Response:</p>
  11960. <pre><code class="language-json">{
  11961. &quot;deleted_media&quot;: [
  11962. &quot;abcdefghijklmnopqrstuvwx&quot;
  11963. ],
  11964. &quot;total&quot;: 1
  11965. }
  11966. </code></pre>
  11967. <p>The following fields are returned in the JSON response body:</p>
  11968. <ul>
  11969. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  11970. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  11971. </ul>
  11972. <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>
  11973. <p>Request:</p>
  11974. <pre><code>POST /_synapse/admin/v1/media/delete?before_ts=&lt;before_ts&gt;
  11975. {}
  11976. </code></pre>
  11977. <p><em>Deprecated in Synapse v1.78.0:</em> This API is available at the deprecated endpoint:</p>
  11978. <pre><code>POST /_synapse/admin/v1/media/&lt;server_name&gt;/delete?before_ts=&lt;before_ts&gt;
  11979. {}
  11980. </code></pre>
  11981. <p>URL Parameters</p>
  11982. <ul>
  11983. <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>
  11984. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  11985. Files that were last used before this timestamp will be deleted. It is the timestamp of
  11986. last access, not the timestamp when the file was created.</li>
  11987. <li><code>size_gt</code>: Optional - string representing a positive integer - Size of the media in bytes.
  11988. Files that are larger will be deleted. Defaults to <code>0</code>.</li>
  11989. <li><code>keep_profiles</code>: Optional - string representing a boolean - Switch to also delete files
  11990. that are still used in image data (e.g user profile, room avatar).
  11991. If <code>false</code> these files will be deleted. Defaults to <code>true</code>.</li>
  11992. </ul>
  11993. <p>Response:</p>
  11994. <pre><code class="language-json">{
  11995. &quot;deleted_media&quot;: [
  11996. &quot;abcdefghijklmnopqrstuvwx&quot;,
  11997. &quot;abcdefghijklmnopqrstuvwz&quot;
  11998. ],
  11999. &quot;total&quot;: 2
  12000. }
  12001. </code></pre>
  12002. <p>The following fields are returned in the JSON response body:</p>
  12003. <ul>
  12004. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  12005. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  12006. </ul>
  12007. <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>
  12008. <p>You can find details of how to delete multiple media uploaded by a user in
  12009. <a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">User Admin API</a>.</p>
  12010. <h1 id="purge-remote-media-api"><a class="header" href="#purge-remote-media-api">Purge Remote Media API</a></h1>
  12011. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  12012. <p>The API is:</p>
  12013. <pre><code>POST /_synapse/admin/v1/purge_media_cache?before_ts=&lt;unix_timestamp_in_ms&gt;
  12014. {}
  12015. </code></pre>
  12016. <p>URL Parameters</p>
  12017. <ul>
  12018. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  12019. All cached media that was last accessed before this timestamp will be removed.</li>
  12020. </ul>
  12021. <p>Response:</p>
  12022. <pre><code class="language-json">{
  12023. &quot;deleted&quot;: 10
  12024. }
  12025. </code></pre>
  12026. <p>The following fields are returned in the JSON response body:</p>
  12027. <ul>
  12028. <li><code>deleted</code>: integer - The number of media items successfully deleted</li>
  12029. </ul>
  12030. <p>If the user re-requests purged remote media, synapse will re-request the media
  12031. from the originating server.</p>
  12032. <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>
  12033. <p>The purge history API allows server admins to purge historic events from their
  12034. database, reclaiming disk space.</p>
  12035. <p>Depending on the amount of history being purged a call to the API may take
  12036. several minutes or longer. During this period users will not be able to
  12037. paginate further back in the room from the point being purged from.</p>
  12038. <p>Note that Synapse requires at least one message in each room, so it will never
  12039. delete the last message in a room.</p>
  12040. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12041. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12042. <p>The API is:</p>
  12043. <pre><code>POST /_synapse/admin/v1/purge_history/&lt;room_id&gt;[/&lt;event_id&gt;]
  12044. </code></pre>
  12045. <p>By default, events sent by local users are not deleted, as they may represent
  12046. the only copies of this content in existence. (Events sent by remote users are
  12047. deleted.)</p>
  12048. <p>Room state data (such as joins, leaves, topic) is always preserved.</p>
  12049. <p>To delete local message events as well, set <code>delete_local_events</code> in the body:</p>
  12050. <pre><code class="language-json">{
  12051. &quot;delete_local_events&quot;: true
  12052. }
  12053. </code></pre>
  12054. <p>The caller must specify the point in the room to purge up to. This can be
  12055. specified by including an event_id in the URI, or by setting a
  12056. <code>purge_up_to_event_id</code> or <code>purge_up_to_ts</code> in the request body. If an event
  12057. id is given, that event (and others at the same graph depth) will be retained.
  12058. If <code>purge_up_to_ts</code> is given, it should be a timestamp since the unix epoch,
  12059. in milliseconds.</p>
  12060. <p>The API starts the purge running, and returns immediately with a JSON body with
  12061. a purge id:</p>
  12062. <pre><code class="language-json">{
  12063. &quot;purge_id&quot;: &quot;&lt;opaque id&gt;&quot;
  12064. }
  12065. </code></pre>
  12066. <h2 id="purge-status-query"><a class="header" href="#purge-status-query">Purge status query</a></h2>
  12067. <p>It is possible to poll for updates on recent purges with a second API;</p>
  12068. <pre><code>GET /_synapse/admin/v1/purge_history_status/&lt;purge_id&gt;
  12069. </code></pre>
  12070. <p>This API returns a JSON body like the following:</p>
  12071. <pre><code class="language-json">{
  12072. &quot;status&quot;: &quot;active&quot;
  12073. }
  12074. </code></pre>
  12075. <p>The status will be one of <code>active</code>, <code>complete</code>, or <code>failed</code>.</p>
  12076. <p>If <code>status</code> is <code>failed</code> there will be a string <code>error</code> with the error message.</p>
  12077. <h2 id="reclaim-disk-space-postgres"><a class="header" href="#reclaim-disk-space-postgres">Reclaim disk space (Postgres)</a></h2>
  12078. <p>To reclaim the disk space and return it to the operating system, you need to run
  12079. <code>VACUUM FULL;</code> on the database.</p>
  12080. <p><a href="https://www.postgresql.org/docs/current/sql-vacuum.html">https://www.postgresql.org/docs/current/sql-vacuum.html</a></p>
  12081. <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>
  12082. <p>This API allows for the creation of users in an administrative and
  12083. non-interactive way. This is generally used for bootstrapping a Synapse
  12084. instance with administrator accounts.</p>
  12085. <p>To authenticate yourself to the server, you will need both the shared secret
  12086. (<a href="admin_api/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>
  12087. in the homeserver configuration), and a one-time nonce. If the registration
  12088. shared secret is not configured, this API is not enabled.</p>
  12089. <p>To fetch the nonce, you need to request one from the API:</p>
  12090. <pre><code>&gt; GET /_synapse/admin/v1/register
  12091. &lt; {&quot;nonce&quot;: &quot;thisisanonce&quot;}
  12092. </code></pre>
  12093. <p>Once you have the nonce, you can make a <code>POST</code> to the same URL with a JSON
  12094. body containing the nonce, username, password, whether they are an admin
  12095. (optional, False by default), and a HMAC digest of the content. Also you can
  12096. set the displayname (optional, <code>username</code> by default).</p>
  12097. <p>As an example:</p>
  12098. <pre><code>&gt; POST /_synapse/admin/v1/register
  12099. &gt; {
  12100. &quot;nonce&quot;: &quot;thisisanonce&quot;,
  12101. &quot;username&quot;: &quot;pepper_roni&quot;,
  12102. &quot;displayname&quot;: &quot;Pepper Roni&quot;,
  12103. &quot;password&quot;: &quot;pizza&quot;,
  12104. &quot;admin&quot;: true,
  12105. &quot;mac&quot;: &quot;mac_digest_here&quot;
  12106. }
  12107. &lt; {
  12108. &quot;access_token&quot;: &quot;token_here&quot;,
  12109. &quot;user_id&quot;: &quot;@pepper_roni:localhost&quot;,
  12110. &quot;home_server&quot;: &quot;test&quot;,
  12111. &quot;device_id&quot;: &quot;device_id_here&quot;
  12112. }
  12113. </code></pre>
  12114. <p>The MAC is the hex digest output of the HMAC-SHA1 algorithm, with the key being
  12115. the shared secret and the content being the nonce, user, password, either the
  12116. string &quot;admin&quot; or &quot;notadmin&quot;, and optionally the user_type
  12117. each separated by NULs.</p>
  12118. <p>Here is an easy way to generate the HMAC digest if you have Bash and OpenSSL:</p>
  12119. <pre><code class="language-bash"># Update these values and then paste this code block into a bash terminal
  12120. nonce='thisisanonce'
  12121. username='pepper_roni'
  12122. password='pizza'
  12123. admin='admin'
  12124. secret='shared_secret'
  12125. printf '%s\0%s\0%s\0%s' &quot;$nonce&quot; &quot;$username&quot; &quot;$password&quot; &quot;$admin&quot; |
  12126. openssl sha1 -hmac &quot;$secret&quot; |
  12127. awk '{print $2}'
  12128. </code></pre>
  12129. <p>For an example of generation in Python:</p>
  12130. <pre><code class="language-python">import hmac, hashlib
  12131. def generate_mac(nonce, user, password, admin=False, user_type=None):
  12132. mac = hmac.new(
  12133. key=shared_secret,
  12134. digestmod=hashlib.sha1,
  12135. )
  12136. mac.update(nonce.encode('utf8'))
  12137. mac.update(b&quot;\x00&quot;)
  12138. mac.update(user.encode('utf8'))
  12139. mac.update(b&quot;\x00&quot;)
  12140. mac.update(password.encode('utf8'))
  12141. mac.update(b&quot;\x00&quot;)
  12142. mac.update(b&quot;admin&quot; if admin else b&quot;notadmin&quot;)
  12143. if user_type:
  12144. mac.update(b&quot;\x00&quot;)
  12145. mac.update(user_type.encode('utf8'))
  12146. return mac.hexdigest()
  12147. </code></pre>
  12148. <div style="break-before: page; page-break-before: always;"></div><h1 id="registration-tokens"><a class="header" href="#registration-tokens">Registration Tokens</a></h1>
  12149. <p>This API allows you to manage tokens which can be used to authenticate
  12150. registration requests, as proposed in
  12151. <a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md">MSC3231</a>
  12152. and stabilised in version 1.2 of the Matrix specification.
  12153. To use it, you will need to enable the <code>registration_requires_token</code> config
  12154. option, and authenticate by providing an <code>access_token</code> for a server admin:
  12155. see <a href="usage/administration/admin_api/../admin_api/">Admin API</a>.</p>
  12156. <h2 id="registration-token-objects"><a class="header" href="#registration-token-objects">Registration token objects</a></h2>
  12157. <p>Most endpoints make use of JSON objects that contain details about tokens.
  12158. These objects have the following fields:</p>
  12159. <ul>
  12160. <li><code>token</code>: The token which can be used to authenticate registration.</li>
  12161. <li><code>uses_allowed</code>: The number of times the token can be used to complete a
  12162. registration before it becomes invalid.</li>
  12163. <li><code>pending</code>: The number of pending uses the token has. When someone uses
  12164. the token to authenticate themselves, the pending counter is incremented
  12165. so that the token is not used more than the permitted number of times.
  12166. When the person completes registration the pending counter is decremented,
  12167. and the completed counter is incremented.</li>
  12168. <li><code>completed</code>: The number of times the token has been used to successfully
  12169. complete a registration.</li>
  12170. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  12171. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  12172. To convert this into a human-readable form you can remove the milliseconds
  12173. and use the <code>date</code> command. For example, <code>date -d '@1625394937'</code>.</li>
  12174. </ul>
  12175. <h2 id="list-all-tokens"><a class="header" href="#list-all-tokens">List all tokens</a></h2>
  12176. <p>Lists all tokens and details about them. If the request is successful, the top
  12177. level JSON object will have a <code>registration_tokens</code> key which is an array of
  12178. registration token objects.</p>
  12179. <pre><code>GET /_synapse/admin/v1/registration_tokens
  12180. </code></pre>
  12181. <p>Optional query parameters:</p>
  12182. <ul>
  12183. <li><code>valid</code>: <code>true</code> or <code>false</code>. If <code>true</code>, only valid tokens are returned.
  12184. If <code>false</code>, only tokens that have expired or have had all uses exhausted are
  12185. returned. If omitted, all tokens are returned regardless of validity.</li>
  12186. </ul>
  12187. <p>Example:</p>
  12188. <pre><code>GET /_synapse/admin/v1/registration_tokens
  12189. </code></pre>
  12190. <pre><code>200 OK
  12191. {
  12192. &quot;registration_tokens&quot;: [
  12193. {
  12194. &quot;token&quot;: &quot;abcd&quot;,
  12195. &quot;uses_allowed&quot;: 3,
  12196. &quot;pending&quot;: 0,
  12197. &quot;completed&quot;: 1,
  12198. &quot;expiry_time&quot;: null
  12199. },
  12200. {
  12201. &quot;token&quot;: &quot;pqrs&quot;,
  12202. &quot;uses_allowed&quot;: 2,
  12203. &quot;pending&quot;: 1,
  12204. &quot;completed&quot;: 1,
  12205. &quot;expiry_time&quot;: null
  12206. },
  12207. {
  12208. &quot;token&quot;: &quot;wxyz&quot;,
  12209. &quot;uses_allowed&quot;: null,
  12210. &quot;pending&quot;: 0,
  12211. &quot;completed&quot;: 9,
  12212. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  12213. }
  12214. ]
  12215. }
  12216. </code></pre>
  12217. <p>Example using the <code>valid</code> query parameter:</p>
  12218. <pre><code>GET /_synapse/admin/v1/registration_tokens?valid=false
  12219. </code></pre>
  12220. <pre><code>200 OK
  12221. {
  12222. &quot;registration_tokens&quot;: [
  12223. {
  12224. &quot;token&quot;: &quot;pqrs&quot;,
  12225. &quot;uses_allowed&quot;: 2,
  12226. &quot;pending&quot;: 1,
  12227. &quot;completed&quot;: 1,
  12228. &quot;expiry_time&quot;: null
  12229. },
  12230. {
  12231. &quot;token&quot;: &quot;wxyz&quot;,
  12232. &quot;uses_allowed&quot;: null,
  12233. &quot;pending&quot;: 0,
  12234. &quot;completed&quot;: 9,
  12235. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  12236. }
  12237. ]
  12238. }
  12239. </code></pre>
  12240. <h2 id="get-one-token"><a class="header" href="#get-one-token">Get one token</a></h2>
  12241. <p>Get details about a single token. If the request is successful, the response
  12242. body will be a registration token object.</p>
  12243. <pre><code>GET /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  12244. </code></pre>
  12245. <p>Path parameters:</p>
  12246. <ul>
  12247. <li><code>token</code>: The registration token to return details of.</li>
  12248. </ul>
  12249. <p>Example:</p>
  12250. <pre><code>GET /_synapse/admin/v1/registration_tokens/abcd
  12251. </code></pre>
  12252. <pre><code>200 OK
  12253. {
  12254. &quot;token&quot;: &quot;abcd&quot;,
  12255. &quot;uses_allowed&quot;: 3,
  12256. &quot;pending&quot;: 0,
  12257. &quot;completed&quot;: 1,
  12258. &quot;expiry_time&quot;: null
  12259. }
  12260. </code></pre>
  12261. <h2 id="create-token"><a class="header" href="#create-token">Create token</a></h2>
  12262. <p>Create a new registration token. If the request is successful, the newly created
  12263. token will be returned as a registration token object in the response body.</p>
  12264. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  12265. </code></pre>
  12266. <p>The request body must be a JSON object and can contain the following fields:</p>
  12267. <ul>
  12268. <li><code>token</code>: The registration token. A string of no more than 64 characters that
  12269. consists only of characters matched by the regex <code>[A-Za-z0-9._~-]</code>.
  12270. Default: randomly generated.</li>
  12271. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  12272. a registration before it becomes invalid.
  12273. Default: <code>null</code> (unlimited uses).</li>
  12274. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  12275. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  12276. You could use, for example, <code>date '+%s000' -d 'tomorrow'</code>.
  12277. Default: <code>null</code> (token does not expire).</li>
  12278. <li><code>length</code>: The length of the token randomly generated if <code>token</code> is not
  12279. specified. Must be between 1 and 64 inclusive. Default: <code>16</code>.</li>
  12280. </ul>
  12281. <p>If a field is omitted the default is used.</p>
  12282. <p>Example using defaults:</p>
  12283. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  12284. {}
  12285. </code></pre>
  12286. <pre><code>200 OK
  12287. {
  12288. &quot;token&quot;: &quot;0M-9jbkf2t_Tgiw1&quot;,
  12289. &quot;uses_allowed&quot;: null,
  12290. &quot;pending&quot;: 0,
  12291. &quot;completed&quot;: 0,
  12292. &quot;expiry_time&quot;: null
  12293. }
  12294. </code></pre>
  12295. <p>Example specifying some fields:</p>
  12296. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  12297. {
  12298. &quot;token&quot;: &quot;defg&quot;,
  12299. &quot;uses_allowed&quot;: 1
  12300. }
  12301. </code></pre>
  12302. <pre><code>200 OK
  12303. {
  12304. &quot;token&quot;: &quot;defg&quot;,
  12305. &quot;uses_allowed&quot;: 1,
  12306. &quot;pending&quot;: 0,
  12307. &quot;completed&quot;: 0,
  12308. &quot;expiry_time&quot;: null
  12309. }
  12310. </code></pre>
  12311. <h2 id="update-token"><a class="header" href="#update-token">Update token</a></h2>
  12312. <p>Update the number of allowed uses or expiry time of a token. If the request is
  12313. successful, the updated token will be returned as a registration token object
  12314. in the response body.</p>
  12315. <pre><code>PUT /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  12316. </code></pre>
  12317. <p>Path parameters:</p>
  12318. <ul>
  12319. <li><code>token</code>: The registration token to update.</li>
  12320. </ul>
  12321. <p>The request body must be a JSON object and can contain the following fields:</p>
  12322. <ul>
  12323. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  12324. a registration before it becomes invalid. By setting <code>uses_allowed</code> to <code>0</code>
  12325. the token can be easily made invalid without deleting it.
  12326. If <code>null</code> the token will have an unlimited number of uses.</li>
  12327. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  12328. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  12329. If <code>null</code> the token will not expire.</li>
  12330. </ul>
  12331. <p>If a field is omitted its value is not modified.</p>
  12332. <p>Example:</p>
  12333. <pre><code>PUT /_synapse/admin/v1/registration_tokens/defg
  12334. {
  12335. &quot;expiry_time&quot;: 4781243146000 // 2121-07-06 11:05:46 UTC
  12336. }
  12337. </code></pre>
  12338. <pre><code>200 OK
  12339. {
  12340. &quot;token&quot;: &quot;defg&quot;,
  12341. &quot;uses_allowed&quot;: 1,
  12342. &quot;pending&quot;: 0,
  12343. &quot;completed&quot;: 0,
  12344. &quot;expiry_time&quot;: 4781243146000
  12345. }
  12346. </code></pre>
  12347. <h2 id="delete-token"><a class="header" href="#delete-token">Delete token</a></h2>
  12348. <p>Delete a registration token. If the request is successful, the response body
  12349. will be an empty JSON object.</p>
  12350. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  12351. </code></pre>
  12352. <p>Path parameters:</p>
  12353. <ul>
  12354. <li><code>token</code>: The registration token to delete.</li>
  12355. </ul>
  12356. <p>Example:</p>
  12357. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/wxyz
  12358. </code></pre>
  12359. <pre><code>200 OK
  12360. {}
  12361. </code></pre>
  12362. <h2 id="errors"><a class="header" href="#errors">Errors</a></h2>
  12363. <p>If a request fails a &quot;standard error response&quot; will be returned as defined in
  12364. the <a href="https://matrix.org/docs/spec/client_server/r0.6.1#api-standards">Matrix Client-Server API specification</a>.</p>
  12365. <p>For example, if the token specified in a path parameter does not exist a
  12366. <code>404 Not Found</code> error will be returned.</p>
  12367. <pre><code>GET /_synapse/admin/v1/registration_tokens/1234
  12368. </code></pre>
  12369. <pre><code>404 Not Found
  12370. {
  12371. &quot;errcode&quot;: &quot;M_NOT_FOUND&quot;,
  12372. &quot;error&quot;: &quot;No such registration token: 1234&quot;
  12373. }
  12374. </code></pre>
  12375. <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>
  12376. <p>This API allows an administrator to join an user account with a given <code>user_id</code>
  12377. to a room with a given <code>room_id_or_alias</code>. You can only modify the membership of
  12378. local users. The server administrator must be in the room and have permission to
  12379. invite users.</p>
  12380. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12381. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12382. <h2 id="parameters"><a class="header" href="#parameters">Parameters</a></h2>
  12383. <p>The following parameters are available:</p>
  12384. <ul>
  12385. <li><code>user_id</code> - Fully qualified user: for example, <code>@user:server.com</code>.</li>
  12386. <li><code>room_id_or_alias</code> - The room identifier or alias to join: for example,
  12387. <code>!636q39766251:server.com</code>.</li>
  12388. </ul>
  12389. <h2 id="usage-1"><a class="header" href="#usage-1">Usage</a></h2>
  12390. <pre><code>POST /_synapse/admin/v1/join/&lt;room_id_or_alias&gt;
  12391. {
  12392. &quot;user_id&quot;: &quot;@user:server.com&quot;
  12393. }
  12394. </code></pre>
  12395. <p>Response:</p>
  12396. <pre><code class="language-json">{
  12397. &quot;room_id&quot;: &quot;!636q39766251:server.com&quot;
  12398. }
  12399. </code></pre>
  12400. <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>
  12401. <p>The List Room admin API allows server admins to get a list of rooms on their
  12402. server. There are various parameters available that allow for filtering and
  12403. sorting the returned list. This API supports pagination.</p>
  12404. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12405. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12406. <p><strong>Parameters</strong></p>
  12407. <p>The following query parameters are available:</p>
  12408. <ul>
  12409. <li>
  12410. <p><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</p>
  12411. </li>
  12412. <li>
  12413. <p><code>limit</code> - Maximum amount of rooms to return. Defaults to <code>100</code>.</p>
  12414. </li>
  12415. <li>
  12416. <p><code>order_by</code> - The method in which to sort the returned list of rooms. Valid values are:</p>
  12417. <ul>
  12418. <li><code>alphabetical</code> - Same as <code>name</code>. This is deprecated.</li>
  12419. <li><code>size</code> - Same as <code>joined_members</code>. This is deprecated.</li>
  12420. <li><code>name</code> - Rooms are ordered alphabetically by room name. This is the default.</li>
  12421. <li><code>canonical_alias</code> - Rooms are ordered alphabetically by main alias address of the room.</li>
  12422. <li><code>joined_members</code> - Rooms are ordered by the number of members. Largest to smallest.</li>
  12423. <li><code>joined_local_members</code> - Rooms are ordered by the number of local members. Largest to smallest.</li>
  12424. <li><code>version</code> - Rooms are ordered by room version. Largest to smallest.</li>
  12425. <li><code>creator</code> - Rooms are ordered alphabetically by creator of the room.</li>
  12426. <li><code>encryption</code> - Rooms are ordered alphabetically by the end-to-end encryption algorithm.</li>
  12427. <li><code>federatable</code> - Rooms are ordered by whether the room is federatable.</li>
  12428. <li><code>public</code> - Rooms are ordered by visibility in room list.</li>
  12429. <li><code>join_rules</code> - Rooms are ordered alphabetically by join rules of the room.</li>
  12430. <li><code>guest_access</code> - Rooms are ordered alphabetically by guest access option of the room.</li>
  12431. <li><code>history_visibility</code> - Rooms are ordered alphabetically by visibility of history of the room.</li>
  12432. <li><code>state_events</code> - Rooms are ordered by number of state events. Largest to smallest.</li>
  12433. </ul>
  12434. </li>
  12435. <li>
  12436. <p><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  12437. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  12438. </li>
  12439. <li>
  12440. <p><code>search_term</code> - Filter rooms by their room name, canonical alias and room id.
  12441. Specifically, rooms are selected if the search term is contained in</p>
  12442. <ul>
  12443. <li>the room's name,</li>
  12444. <li>the local part of the room's canonical alias, or</li>
  12445. <li>the complete (local and server part) room's id (case sensitive).</li>
  12446. </ul>
  12447. <p>Defaults to no filtering.</p>
  12448. </li>
  12449. </ul>
  12450. <p><strong>Response</strong></p>
  12451. <p>The following fields are possible in the JSON response body:</p>
  12452. <ul>
  12453. <li><code>rooms</code> - An array of objects, each containing information about a room.
  12454. <ul>
  12455. <li>Room objects contain the following fields:
  12456. <ul>
  12457. <li><code>room_id</code> - The ID of the room.</li>
  12458. <li><code>name</code> - The name of the room.</li>
  12459. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  12460. <li><code>joined_members</code> - How many users are currently in the room.</li>
  12461. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  12462. <li><code>version</code> - The version of the room as a string.</li>
  12463. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  12464. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  12465. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  12466. <li><code>public</code> - Whether the room is visible in room directory.</li>
  12467. <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>
  12468. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  12469. <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>
  12470. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  12471. <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>
  12472. </ul>
  12473. </li>
  12474. </ul>
  12475. </li>
  12476. <li><code>offset</code> - The current pagination offset in rooms. This parameter should be
  12477. used instead of <code>next_token</code> for room offset as <code>next_token</code> is
  12478. not intended to be parsed.</li>
  12479. <li><code>total_rooms</code> - The total number of rooms this query can return. Using this
  12480. and <code>offset</code>, you have enough information to know the current
  12481. progression through the list.</li>
  12482. <li><code>next_batch</code> - If this field is present, we know that there are potentially
  12483. more rooms on the server that did not all fit into this response.
  12484. We can use <code>next_batch</code> to get the &quot;next page&quot; of results. To do
  12485. so, simply repeat your request, setting the <code>from</code> parameter to
  12486. the value of <code>next_batch</code>.</li>
  12487. <li><code>prev_batch</code> - If this field is present, it is possible to paginate backwards.
  12488. Use <code>prev_batch</code> for the <code>from</code> value in the next request to
  12489. get the &quot;previous page&quot; of results.</li>
  12490. </ul>
  12491. <p>The API is:</p>
  12492. <p>A standard request with no filtering:</p>
  12493. <pre><code>GET /_synapse/admin/v1/rooms
  12494. </code></pre>
  12495. <p>A response body like the following is returned:</p>
  12496. <pre><code class="language-json">{
  12497. &quot;rooms&quot;: [
  12498. {
  12499. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  12500. &quot;name&quot;: &quot;Matrix HQ&quot;,
  12501. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  12502. &quot;joined_members&quot;: 8326,
  12503. &quot;joined_local_members&quot;: 2,
  12504. &quot;version&quot;: &quot;1&quot;,
  12505. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12506. &quot;encryption&quot;: null,
  12507. &quot;federatable&quot;: true,
  12508. &quot;public&quot;: true,
  12509. &quot;join_rules&quot;: &quot;invite&quot;,
  12510. &quot;guest_access&quot;: null,
  12511. &quot;history_visibility&quot;: &quot;shared&quot;,
  12512. &quot;state_events&quot;: 93534,
  12513. &quot;room_type&quot;: &quot;m.space&quot;
  12514. },
  12515. ... (8 hidden items) ...
  12516. {
  12517. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12518. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  12519. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  12520. &quot;joined_members&quot;: 314,
  12521. &quot;joined_local_members&quot;: 20,
  12522. &quot;version&quot;: &quot;4&quot;,
  12523. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12524. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  12525. &quot;federatable&quot;: true,
  12526. &quot;public&quot;: false,
  12527. &quot;join_rules&quot;: &quot;invite&quot;,
  12528. &quot;guest_access&quot;: null,
  12529. &quot;history_visibility&quot;: &quot;shared&quot;,
  12530. &quot;state_events&quot;: 8345,
  12531. &quot;room_type&quot;: null
  12532. }
  12533. ],
  12534. &quot;offset&quot;: 0,
  12535. &quot;total_rooms&quot;: 10
  12536. }
  12537. </code></pre>
  12538. <p>Filtering by room name:</p>
  12539. <pre><code>GET /_synapse/admin/v1/rooms?search_term=TWIM
  12540. </code></pre>
  12541. <p>A response body like the following is returned:</p>
  12542. <pre><code class="language-json">{
  12543. &quot;rooms&quot;: [
  12544. {
  12545. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12546. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  12547. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  12548. &quot;joined_members&quot;: 314,
  12549. &quot;joined_local_members&quot;: 20,
  12550. &quot;version&quot;: &quot;4&quot;,
  12551. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12552. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  12553. &quot;federatable&quot;: true,
  12554. &quot;public&quot;: false,
  12555. &quot;join_rules&quot;: &quot;invite&quot;,
  12556. &quot;guest_access&quot;: null,
  12557. &quot;history_visibility&quot;: &quot;shared&quot;,
  12558. &quot;state_events&quot;: 8,
  12559. &quot;room_type&quot;: null
  12560. }
  12561. ],
  12562. &quot;offset&quot;: 0,
  12563. &quot;total_rooms&quot;: 1
  12564. }
  12565. </code></pre>
  12566. <p>Paginating through a list of rooms:</p>
  12567. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size
  12568. </code></pre>
  12569. <p>A response body like the following is returned:</p>
  12570. <pre><code class="language-json">{
  12571. &quot;rooms&quot;: [
  12572. {
  12573. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  12574. &quot;name&quot;: &quot;Matrix HQ&quot;,
  12575. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  12576. &quot;joined_members&quot;: 8326,
  12577. &quot;joined_local_members&quot;: 2,
  12578. &quot;version&quot;: &quot;1&quot;,
  12579. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12580. &quot;encryption&quot;: null,
  12581. &quot;federatable&quot;: true,
  12582. &quot;public&quot;: true,
  12583. &quot;join_rules&quot;: &quot;invite&quot;,
  12584. &quot;guest_access&quot;: null,
  12585. &quot;history_visibility&quot;: &quot;shared&quot;,
  12586. &quot;state_events&quot;: 93534,
  12587. &quot;room_type&quot;: null
  12588. },
  12589. ... (98 hidden items) ...
  12590. {
  12591. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12592. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  12593. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  12594. &quot;joined_members&quot;: 314,
  12595. &quot;joined_local_members&quot;: 20,
  12596. &quot;version&quot;: &quot;4&quot;,
  12597. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12598. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  12599. &quot;federatable&quot;: true,
  12600. &quot;public&quot;: false,
  12601. &quot;join_rules&quot;: &quot;invite&quot;,
  12602. &quot;guest_access&quot;: null,
  12603. &quot;history_visibility&quot;: &quot;shared&quot;,
  12604. &quot;state_events&quot;: 8345,
  12605. &quot;room_type&quot;: &quot;m.space&quot;
  12606. }
  12607. ],
  12608. &quot;offset&quot;: 0,
  12609. &quot;total_rooms&quot;: 150,
  12610. &quot;next_token&quot;: 100
  12611. }
  12612. </code></pre>
  12613. <p>The presence of the <code>next_token</code> parameter tells us that there are more rooms
  12614. than returned in this request, and we need to make another request to get them.
  12615. To get the next batch of room results, we repeat our request, setting the <code>from</code>
  12616. parameter to the value of <code>next_token</code>.</p>
  12617. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size&amp;from=100
  12618. </code></pre>
  12619. <p>A response body like the following is returned:</p>
  12620. <pre><code class="language-json">{
  12621. &quot;rooms&quot;: [
  12622. {
  12623. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  12624. &quot;name&quot;: &quot;Music Theory&quot;,
  12625. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  12626. &quot;joined_members&quot;: 127,
  12627. &quot;joined_local_members&quot;: 2,
  12628. &quot;version&quot;: &quot;1&quot;,
  12629. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12630. &quot;encryption&quot;: null,
  12631. &quot;federatable&quot;: true,
  12632. &quot;public&quot;: true,
  12633. &quot;join_rules&quot;: &quot;invite&quot;,
  12634. &quot;guest_access&quot;: null,
  12635. &quot;history_visibility&quot;: &quot;shared&quot;,
  12636. &quot;state_events&quot;: 93534,
  12637. &quot;room_type&quot;: &quot;m.space&quot;
  12638. },
  12639. ... (48 hidden items) ...
  12640. {
  12641. &quot;room_id&quot;: &quot;!twcBhHVdZlQWuuxBhN:termina.org.uk&quot;,
  12642. &quot;name&quot;: &quot;weechat-matrix&quot;,
  12643. &quot;canonical_alias&quot;: &quot;#weechat-matrix:termina.org.uk&quot;,
  12644. &quot;joined_members&quot;: 137,
  12645. &quot;joined_local_members&quot;: 20,
  12646. &quot;version&quot;: &quot;4&quot;,
  12647. &quot;creator&quot;: &quot;@foo:termina.org.uk&quot;,
  12648. &quot;encryption&quot;: null,
  12649. &quot;federatable&quot;: true,
  12650. &quot;public&quot;: true,
  12651. &quot;join_rules&quot;: &quot;invite&quot;,
  12652. &quot;guest_access&quot;: null,
  12653. &quot;history_visibility&quot;: &quot;shared&quot;,
  12654. &quot;state_events&quot;: 8345,
  12655. &quot;room_type&quot;: null
  12656. }
  12657. ],
  12658. &quot;offset&quot;: 100,
  12659. &quot;prev_batch&quot;: 0,
  12660. &quot;total_rooms&quot;: 150
  12661. }
  12662. </code></pre>
  12663. <p>Once the <code>next_token</code> parameter is no longer present, we know we've reached the
  12664. end of the list.</p>
  12665. <h1 id="room-details-api"><a class="header" href="#room-details-api">Room Details API</a></h1>
  12666. <p>The Room Details admin API allows server admins to get all details of a room.</p>
  12667. <p>The following fields are possible in the JSON response body:</p>
  12668. <ul>
  12669. <li><code>room_id</code> - The ID of the room.</li>
  12670. <li><code>name</code> - The name of the room.</li>
  12671. <li><code>topic</code> - The topic of the room.</li>
  12672. <li><code>avatar</code> - The <code>mxc</code> URI to the avatar of the room.</li>
  12673. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  12674. <li><code>joined_members</code> - How many users are currently in the room.</li>
  12675. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  12676. <li><code>joined_local_devices</code> - How many local devices are currently in the room.</li>
  12677. <li><code>version</code> - The version of the room as a string.</li>
  12678. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  12679. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  12680. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  12681. <li><code>public</code> - Whether the room is visible in room directory.</li>
  12682. <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>
  12683. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  12684. <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>
  12685. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  12686. <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.
  12687. If the room does not define a type, the value will be <code>null</code>.</li>
  12688. <li><code>forgotten</code> - Whether all local users have
  12689. <a href="https://spec.matrix.org/latest/client-server-api/#leaving-rooms">forgotten</a> the room.</li>
  12690. </ul>
  12691. <p>The API is:</p>
  12692. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;
  12693. </code></pre>
  12694. <p>A response body like the following is returned:</p>
  12695. <pre><code class="language-json">{
  12696. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  12697. &quot;name&quot;: &quot;Music Theory&quot;,
  12698. &quot;avatar&quot;: &quot;mxc://matrix.org/AQDaVFlbkQoErdOgqWRgiGSV&quot;,
  12699. &quot;topic&quot;: &quot;Theory, Composition, Notation, Analysis&quot;,
  12700. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  12701. &quot;joined_members&quot;: 127,
  12702. &quot;joined_local_members&quot;: 2,
  12703. &quot;joined_local_devices&quot;: 2,
  12704. &quot;version&quot;: &quot;1&quot;,
  12705. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12706. &quot;encryption&quot;: null,
  12707. &quot;federatable&quot;: true,
  12708. &quot;public&quot;: true,
  12709. &quot;join_rules&quot;: &quot;invite&quot;,
  12710. &quot;guest_access&quot;: null,
  12711. &quot;history_visibility&quot;: &quot;shared&quot;,
  12712. &quot;state_events&quot;: 93534,
  12713. &quot;room_type&quot;: &quot;m.space&quot;,
  12714. &quot;forgotten&quot;: false
  12715. }
  12716. </code></pre>
  12717. <p><em>Changed in Synapse 1.66:</em> Added the <code>forgotten</code> key to the response body.</p>
  12718. <h1 id="room-members-api"><a class="header" href="#room-members-api">Room Members API</a></h1>
  12719. <p>The Room Members admin API allows server admins to get a list of all members of a room.</p>
  12720. <p>The response includes the following fields:</p>
  12721. <ul>
  12722. <li><code>members</code> - A list of all the members that are present in the room, represented by their ids.</li>
  12723. <li><code>total</code> - Total number of members in the room.</li>
  12724. </ul>
  12725. <p>The API is:</p>
  12726. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/members
  12727. </code></pre>
  12728. <p>A response body like the following is returned:</p>
  12729. <pre><code class="language-json">{
  12730. &quot;members&quot;: [
  12731. &quot;@foo:matrix.org&quot;,
  12732. &quot;@bar:matrix.org&quot;,
  12733. &quot;@foobar:matrix.org&quot;
  12734. ],
  12735. &quot;total&quot;: 3
  12736. }
  12737. </code></pre>
  12738. <h1 id="room-state-api"><a class="header" href="#room-state-api">Room State API</a></h1>
  12739. <p>The Room State admin API allows server admins to get a list of all state events in a room.</p>
  12740. <p>The response includes the following fields:</p>
  12741. <ul>
  12742. <li><code>state</code> - The current state of the room at the time of request.</li>
  12743. </ul>
  12744. <p>The API is:</p>
  12745. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/state
  12746. </code></pre>
  12747. <p>A response body like the following is returned:</p>
  12748. <pre><code class="language-json">{
  12749. &quot;state&quot;: [
  12750. {&quot;type&quot;: &quot;m.room.create&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  12751. {&quot;type&quot;: &quot;m.room.power_levels&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  12752. {&quot;type&quot;: &quot;m.room.name&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true}
  12753. ]
  12754. }
  12755. </code></pre>
  12756. <h1 id="room-messages-api"><a class="header" href="#room-messages-api">Room Messages API</a></h1>
  12757. <p>The Room Messages admin API allows server admins to get all messages
  12758. sent to a room in a given timeframe. There are various parameters available
  12759. that allow for filtering and ordering the returned list. This API supports pagination.</p>
  12760. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12761. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12762. <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>
  12763. <p>The API is:</p>
  12764. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/messages
  12765. </code></pre>
  12766. <p><strong>Parameters</strong></p>
  12767. <p>The following path parameters are required:</p>
  12768. <ul>
  12769. <li><code>room_id</code> - The ID of the room you wish you fetch messages from.</li>
  12770. </ul>
  12771. <p>The following query parameters are available:</p>
  12772. <ul>
  12773. <li><code>from</code> (required) - The token to start returning events from. This token can be obtained from a prev_batch
  12774. or next_batch token returned by the /sync endpoint, or from an end token returned by a previous request to this endpoint.</li>
  12775. <li><code>to</code> - The token to stop returning events at.</li>
  12776. <li><code>limit</code> - The maximum number of events to return. Defaults to <code>10</code>.</li>
  12777. <li><code>filter</code> - A JSON RoomEventFilter to filter returned events with.</li>
  12778. <li><code>dir</code> - The direction to return events from. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  12779. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  12780. </ul>
  12781. <p><strong>Response</strong></p>
  12782. <p>The following fields are possible in the JSON response body:</p>
  12783. <ul>
  12784. <li><code>chunk</code> - A list of room events. The order depends on the dir parameter.
  12785. 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>
  12786. <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.
  12787. If no further events are available, this property is omitted from the response.</li>
  12788. <li><code>start</code> - A token corresponding to the start of chunk.</li>
  12789. <li><code>state</code> - A list of state events relevant to showing the chunk.</li>
  12790. </ul>
  12791. <p><strong>Example</strong></p>
  12792. <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>
  12793. <pre><code class="language-json">{
  12794. &quot;chunk&quot;: [
  12795. {
  12796. &quot;content&quot;: {
  12797. &quot;body&quot;: &quot;This is an example text message&quot;,
  12798. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  12799. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;,
  12800. &quot;msgtype&quot;: &quot;m.text&quot;
  12801. },
  12802. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12803. &quot;origin_server_ts&quot;: 1432735824653,
  12804. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12805. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12806. &quot;type&quot;: &quot;m.room.message&quot;,
  12807. &quot;unsigned&quot;: {
  12808. &quot;age&quot;: 1234
  12809. }
  12810. },
  12811. {
  12812. &quot;content&quot;: {
  12813. &quot;name&quot;: &quot;The room name&quot;
  12814. },
  12815. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12816. &quot;origin_server_ts&quot;: 1432735824653,
  12817. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12818. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12819. &quot;state_key&quot;: &quot;&quot;,
  12820. &quot;type&quot;: &quot;m.room.name&quot;,
  12821. &quot;unsigned&quot;: {
  12822. &quot;age&quot;: 1234
  12823. }
  12824. },
  12825. {
  12826. &quot;content&quot;: {
  12827. &quot;body&quot;: &quot;Gangnam Style&quot;,
  12828. &quot;info&quot;: {
  12829. &quot;duration&quot;: 2140786,
  12830. &quot;h&quot;: 320,
  12831. &quot;mimetype&quot;: &quot;video/mp4&quot;,
  12832. &quot;size&quot;: 1563685,
  12833. &quot;thumbnail_info&quot;: {
  12834. &quot;h&quot;: 300,
  12835. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  12836. &quot;size&quot;: 46144,
  12837. &quot;w&quot;: 300
  12838. },
  12839. &quot;thumbnail_url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;,
  12840. &quot;w&quot;: 480
  12841. },
  12842. &quot;msgtype&quot;: &quot;m.video&quot;,
  12843. &quot;url&quot;: &quot;mxc://example.org/a526eYUSFFxlgbQYZmo442&quot;
  12844. },
  12845. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12846. &quot;origin_server_ts&quot;: 1432735824653,
  12847. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12848. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12849. &quot;type&quot;: &quot;m.room.message&quot;,
  12850. &quot;unsigned&quot;: {
  12851. &quot;age&quot;: 1234
  12852. }
  12853. }
  12854. ],
  12855. &quot;end&quot;: &quot;t47409-4357353_219380_26003_2265&quot;,
  12856. &quot;start&quot;: &quot;t47429-4392820_219380_26003_2265&quot;
  12857. }
  12858. </code></pre>
  12859. <h1 id="room-timestamp-to-event-api"><a class="header" href="#room-timestamp-to-event-api">Room Timestamp to Event API</a></h1>
  12860. <p>The Room Timestamp to Event API endpoint fetches the <code>event_id</code> of the closest event to the given
  12861. timestamp (<code>ts</code> query parameter) in the given direction (<code>dir</code> query parameter).</p>
  12862. <p>Useful for cases like jump to date so you can start paginating messages from
  12863. a given date in the archive.</p>
  12864. <p>The API is:</p>
  12865. <pre><code> GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/timestamp_to_event
  12866. </code></pre>
  12867. <p><strong>Parameters</strong></p>
  12868. <p>The following path parameters are required:</p>
  12869. <ul>
  12870. <li><code>room_id</code> - The ID of the room you wish to check.</li>
  12871. </ul>
  12872. <p>The following query parameters are available:</p>
  12873. <ul>
  12874. <li><code>ts</code> - a timestamp in milliseconds where we will find the closest event in
  12875. the given direction.</li>
  12876. <li><code>dir</code> - can be <code>f</code> or <code>b</code> to indicate forwards and backwards in time from the
  12877. given timestamp. Defaults to <code>f</code>.</li>
  12878. </ul>
  12879. <p><strong>Response</strong></p>
  12880. <ul>
  12881. <li><code>event_id</code> - converted from timestamp</li>
  12882. </ul>
  12883. <h1 id="block-room-api"><a class="header" href="#block-room-api">Block Room API</a></h1>
  12884. <p>The Block Room admin API allows server admins to block and unblock rooms,
  12885. and query to see if a given room is blocked.
  12886. This API can be used to pre-emptively block a room, even if it's unknown to this
  12887. homeserver. Users will be prevented from joining a blocked room.</p>
  12888. <h2 id="block-or-unblock-a-room"><a class="header" href="#block-or-unblock-a-room">Block or unblock a room</a></h2>
  12889. <p>The API is:</p>
  12890. <pre><code>PUT /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  12891. </code></pre>
  12892. <p>with a body of:</p>
  12893. <pre><code class="language-json">{
  12894. &quot;block&quot;: true
  12895. }
  12896. </code></pre>
  12897. <p>A response body like the following is returned:</p>
  12898. <pre><code class="language-json">{
  12899. &quot;block&quot;: true
  12900. }
  12901. </code></pre>
  12902. <p><strong>Parameters</strong></p>
  12903. <p>The following parameters should be set in the URL:</p>
  12904. <ul>
  12905. <li><code>room_id</code> - The ID of the room.</li>
  12906. </ul>
  12907. <p>The following JSON body parameters are available:</p>
  12908. <ul>
  12909. <li><code>block</code> - If <code>true</code> the room will be blocked and if <code>false</code> the room will be unblocked.</li>
  12910. </ul>
  12911. <p><strong>Response</strong></p>
  12912. <p>The following fields are possible in the JSON response body:</p>
  12913. <ul>
  12914. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  12915. </ul>
  12916. <h2 id="get-block-status"><a class="header" href="#get-block-status">Get block status</a></h2>
  12917. <p>The API is:</p>
  12918. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  12919. </code></pre>
  12920. <p>A response body like the following is returned:</p>
  12921. <pre><code class="language-json">{
  12922. &quot;block&quot;: true,
  12923. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12924. }
  12925. </code></pre>
  12926. <p><strong>Parameters</strong></p>
  12927. <p>The following parameters should be set in the URL:</p>
  12928. <ul>
  12929. <li><code>room_id</code> - The ID of the room.</li>
  12930. </ul>
  12931. <p><strong>Response</strong></p>
  12932. <p>The following fields are possible in the JSON response body:</p>
  12933. <ul>
  12934. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  12935. <li><code>user_id</code> - An optional string. If the room is blocked (<code>block</code> is <code>true</code>) shows
  12936. the user who has add the room to blocking list. Otherwise it is not displayed.</li>
  12937. </ul>
  12938. <h1 id="delete-room-api"><a class="header" href="#delete-room-api">Delete Room API</a></h1>
  12939. <p>The Delete Room admin API allows server admins to remove rooms from the server
  12940. and block these rooms.</p>
  12941. <p>Shuts down a room. Moves all local users and room aliases automatically to a
  12942. new room if <code>new_room_user_id</code> is set. Otherwise local users only
  12943. leave the room without any information.</p>
  12944. <p>The new room will be created with the user specified by the <code>new_room_user_id</code> parameter
  12945. as room administrator and will contain a message explaining what happened. Users invited
  12946. to the new room will have power level <code>-10</code> by default, and thus be unable to speak.</p>
  12947. <p>If <code>block</code> is <code>true</code>, users will be prevented from joining the old room.
  12948. This option can in <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> also be used to pre-emptively
  12949. block a room, even if it's unknown to this homeserver. In this case, the room will be
  12950. blocked, and no further action will be taken. If <code>block</code> is <code>false</code>, attempting to
  12951. delete an unknown room is invalid and will be rejected as a bad request.</p>
  12952. <p>This API will remove all trace of the old room from your database after removing
  12953. all local users. If <code>purge</code> is <code>true</code> (the default), all traces of the old room will
  12954. be removed from your database after removing all local users. If you do not want
  12955. this to happen, set <code>purge</code> to <code>false</code>.
  12956. Depending on the amount of history being purged, a call to the API may take
  12957. several minutes or longer.</p>
  12958. <p>The local server will only have the power to move local user and room aliases to
  12959. the new room. Users on other servers will be unaffected.</p>
  12960. <h2 id="version-1-old-version"><a class="header" href="#version-1-old-version">Version 1 (old version)</a></h2>
  12961. <p>This version works synchronously. That means you only get the response once the server has
  12962. finished the action, which may take a long time. If you request the same action
  12963. a second time, and the server has not finished the first one, the second request will block.
  12964. This is fixed in version 2 of this API. The parameters are the same in both APIs.
  12965. This API will become deprecated in the future.</p>
  12966. <p>The API is:</p>
  12967. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id&gt;
  12968. </code></pre>
  12969. <p>with a body of:</p>
  12970. <pre><code class="language-json">{
  12971. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  12972. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  12973. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  12974. &quot;block&quot;: true,
  12975. &quot;purge&quot;: true
  12976. }
  12977. </code></pre>
  12978. <p>A response body like the following is returned:</p>
  12979. <pre><code class="language-json">{
  12980. &quot;kicked_users&quot;: [
  12981. &quot;@foobar:example.com&quot;
  12982. ],
  12983. &quot;failed_to_kick_users&quot;: [],
  12984. &quot;local_aliases&quot;: [
  12985. &quot;#badroom:example.com&quot;,
  12986. &quot;#evilsaloon:example.com&quot;
  12987. ],
  12988. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  12989. }
  12990. </code></pre>
  12991. <p>The parameters and response values have the same format as
  12992. <a href="admin_api/rooms.html#version-2-new-version">version 2</a> of the API.</p>
  12993. <h2 id="version-2-new-version"><a class="header" href="#version-2-new-version">Version 2 (new version)</a></h2>
  12994. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  12995. <p>This version works asynchronously, meaning you get the response from server immediately
  12996. while the server works on that task in background. You can then request the status of the action
  12997. to check if it has completed.</p>
  12998. <p>The API is:</p>
  12999. <pre><code>DELETE /_synapse/admin/v2/rooms/&lt;room_id&gt;
  13000. </code></pre>
  13001. <p>with a body of:</p>
  13002. <pre><code class="language-json">{
  13003. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  13004. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  13005. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  13006. &quot;block&quot;: true,
  13007. &quot;purge&quot;: true
  13008. }
  13009. </code></pre>
  13010. <p>The API starts the shut down and purge running, and returns immediately with a JSON body with
  13011. a purge id:</p>
  13012. <pre><code class="language-json">{
  13013. &quot;delete_id&quot;: &quot;&lt;opaque id&gt;&quot;
  13014. }
  13015. </code></pre>
  13016. <p><strong>Parameters</strong></p>
  13017. <p>The following parameters should be set in the URL:</p>
  13018. <ul>
  13019. <li><code>room_id</code> - The ID of the room.</li>
  13020. </ul>
  13021. <p>The following JSON body parameters are available:</p>
  13022. <ul>
  13023. <li><code>new_room_user_id</code> - Optional. If set, a new room will be created with this user ID
  13024. as the creator and admin, and all users in the old room will be moved into that
  13025. room. If not set, no new room will be created and the users will just be removed
  13026. from the old room. The user ID must be on the local server, but does not necessarily
  13027. have to belong to a registered user.</li>
  13028. <li><code>room_name</code> - Optional. A string representing the name of the room that new users will be
  13029. invited to. Defaults to <code>Content Violation Notification</code></li>
  13030. <li><code>message</code> - Optional. A string containing the first message that will be sent as
  13031. <code>new_room_user_id</code> in the new room. Ideally this will clearly convey why the
  13032. 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>
  13033. <li><code>block</code> - Optional. If set to <code>true</code>, this room will be added to a blocking list,
  13034. preventing future attempts to join the room. Rooms can be blocked
  13035. even if they're not yet known to the homeserver (only with
  13036. <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> of the API). Defaults to <code>false</code>.</li>
  13037. <li><code>purge</code> - Optional. If set to <code>true</code>, it will remove all traces of the room from your database.
  13038. Defaults to <code>true</code>.</li>
  13039. <li><code>force_purge</code> - Optional, and ignored unless <code>purge</code> is <code>true</code>. If set to <code>true</code>, it
  13040. will force a purge to go ahead even if there are local users still in the room. Do not
  13041. use this unless a regular <code>purge</code> operation fails, as it could leave those users'
  13042. clients in a confused state.</li>
  13043. </ul>
  13044. <p>The JSON body must not be empty. The body must be at least <code>{}</code>.</p>
  13045. <h2 id="status-of-deleting-rooms"><a class="header" href="#status-of-deleting-rooms">Status of deleting rooms</a></h2>
  13046. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  13047. <p>It is possible to query the status of the background task for deleting rooms.
  13048. The status can be queried up to 24 hours after completion of the task,
  13049. or until Synapse is restarted (whichever happens first).</p>
  13050. <h3 id="query-by-room_id"><a class="header" href="#query-by-room_id">Query by <code>room_id</code></a></h3>
  13051. <p>With this API you can get the status of all active deletion tasks, and all those completed in the last 24h,
  13052. for the given <code>room_id</code>.</p>
  13053. <p>The API is:</p>
  13054. <pre><code>GET /_synapse/admin/v2/rooms/&lt;room_id&gt;/delete_status
  13055. </code></pre>
  13056. <p>A response body like the following is returned:</p>
  13057. <pre><code class="language-json">{
  13058. &quot;results&quot;: [
  13059. {
  13060. &quot;delete_id&quot;: &quot;delete_id1&quot;,
  13061. &quot;status&quot;: &quot;failed&quot;,
  13062. &quot;error&quot;: &quot;error message&quot;,
  13063. &quot;shutdown_room&quot;: {
  13064. &quot;kicked_users&quot;: [],
  13065. &quot;failed_to_kick_users&quot;: [],
  13066. &quot;local_aliases&quot;: [],
  13067. &quot;new_room_id&quot;: null
  13068. }
  13069. }, {
  13070. &quot;delete_id&quot;: &quot;delete_id2&quot;,
  13071. &quot;status&quot;: &quot;purging&quot;,
  13072. &quot;shutdown_room&quot;: {
  13073. &quot;kicked_users&quot;: [
  13074. &quot;@foobar:example.com&quot;
  13075. ],
  13076. &quot;failed_to_kick_users&quot;: [],
  13077. &quot;local_aliases&quot;: [
  13078. &quot;#badroom:example.com&quot;,
  13079. &quot;#evilsaloon:example.com&quot;
  13080. ],
  13081. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  13082. }
  13083. }
  13084. ]
  13085. }
  13086. </code></pre>
  13087. <p><strong>Parameters</strong></p>
  13088. <p>The following parameters should be set in the URL:</p>
  13089. <ul>
  13090. <li><code>room_id</code> - The ID of the room.</li>
  13091. </ul>
  13092. <h3 id="query-by-delete_id"><a class="header" href="#query-by-delete_id">Query by <code>delete_id</code></a></h3>
  13093. <p>With this API you can get the status of one specific task by <code>delete_id</code>.</p>
  13094. <p>The API is:</p>
  13095. <pre><code>GET /_synapse/admin/v2/rooms/delete_status/&lt;delete_id&gt;
  13096. </code></pre>
  13097. <p>A response body like the following is returned:</p>
  13098. <pre><code class="language-json">{
  13099. &quot;status&quot;: &quot;purging&quot;,
  13100. &quot;shutdown_room&quot;: {
  13101. &quot;kicked_users&quot;: [
  13102. &quot;@foobar:example.com&quot;
  13103. ],
  13104. &quot;failed_to_kick_users&quot;: [],
  13105. &quot;local_aliases&quot;: [
  13106. &quot;#badroom:example.com&quot;,
  13107. &quot;#evilsaloon:example.com&quot;
  13108. ],
  13109. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  13110. }
  13111. }
  13112. </code></pre>
  13113. <p><strong>Parameters</strong></p>
  13114. <p>The following parameters should be set in the URL:</p>
  13115. <ul>
  13116. <li><code>delete_id</code> - The ID for this delete.</li>
  13117. </ul>
  13118. <h3 id="response"><a class="header" href="#response">Response</a></h3>
  13119. <p>The following fields are returned in the JSON response body:</p>
  13120. <ul>
  13121. <li><code>results</code> - An array of objects, each containing information about one task.
  13122. This field is omitted from the result when you query by <code>delete_id</code>.
  13123. Task objects contain the following fields:
  13124. <ul>
  13125. <li><code>delete_id</code> - The ID for this purge if you query by <code>room_id</code>.</li>
  13126. <li><code>status</code> - The status will be one of:
  13127. <ul>
  13128. <li><code>shutting_down</code> - The process is removing users from the room.</li>
  13129. <li><code>purging</code> - The process is purging the room and event data from database.</li>
  13130. <li><code>complete</code> - The process has completed successfully.</li>
  13131. <li><code>failed</code> - The process is aborted, an error has occurred.</li>
  13132. </ul>
  13133. </li>
  13134. <li><code>error</code> - A string that shows an error message if <code>status</code> is <code>failed</code>.
  13135. Otherwise this field is hidden.</li>
  13136. <li><code>shutdown_room</code> - An object containing information about the result of shutting down the room.
  13137. <em>Note:</em> The result is shown after removing the room members.
  13138. The delete process can still be running. Please pay attention to the <code>status</code>.
  13139. <ul>
  13140. <li><code>kicked_users</code> - An array of users (<code>user_id</code>) that were kicked.</li>
  13141. <li><code>failed_to_kick_users</code> - An array of users (<code>user_id</code>) that that were not kicked.</li>
  13142. <li><code>local_aliases</code> - An array of strings representing the local aliases that were
  13143. migrated from the old room to the new.</li>
  13144. <li><code>new_room_id</code> - A string representing the room ID of the new room, or <code>null</code> if
  13145. no such room was created.</li>
  13146. </ul>
  13147. </li>
  13148. </ul>
  13149. </li>
  13150. </ul>
  13151. <h2 id="undoing-room-deletions"><a class="header" href="#undoing-room-deletions">Undoing room deletions</a></h2>
  13152. <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,
  13153. the structure can and does change without notice.</p>
  13154. <p>First, it's important to understand that a room deletion is very destructive. Undoing a deletion is not as simple as pretending it
  13155. 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
  13156. to recover at all:</p>
  13157. <ul>
  13158. <li>If the room was invite-only, your users will need to be re-invited.</li>
  13159. <li>If the room no longer has any members at all, it'll be impossible to rejoin.</li>
  13160. <li>The first user to rejoin will have to do so via an alias on a different
  13161. server (or receive an invite from a user on a different server).</li>
  13162. </ul>
  13163. <p>With all that being said, if you still want to try and recover the room:</p>
  13164. <ol>
  13165. <li>
  13166. <p>If the room was <code>block</code>ed, you must unblock it on your server. This can be
  13167. accomplished as follows:</p>
  13168. <ol>
  13169. <li>For safety reasons, shut down Synapse.</li>
  13170. <li>In the database, run <code>DELETE FROM blocked_rooms WHERE room_id = '!example:example.org';</code>
  13171. <ul>
  13172. <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>
  13173. <li>The room ID is the same one supplied to the delete room API, not the Content Violation room.</li>
  13174. </ul>
  13175. </li>
  13176. <li>Restart Synapse.</li>
  13177. </ol>
  13178. <p>This step is unnecessary if <code>block</code> was not set.</p>
  13179. </li>
  13180. <li>
  13181. <p>Any room aliases on your server that pointed to the deleted room may have
  13182. been deleted, or redirected to the Content Violation room. These will need
  13183. to be restored manually.</p>
  13184. </li>
  13185. <li>
  13186. <p>Users on your server that were in the deleted room will have been kicked
  13187. from the room. Consider whether you want to update their membership
  13188. (possibly via the <a href="admin_api/room_membership.html">Edit Room Membership API</a>) or let
  13189. them handle rejoining themselves.</p>
  13190. </li>
  13191. <li>
  13192. <p>If <code>new_room_user_id</code> was given, a 'Content Violation' will have been
  13193. created. Consider whether you want to delete that roomm.</p>
  13194. </li>
  13195. </ol>
  13196. <h1 id="make-room-admin-api"><a class="header" href="#make-room-admin-api">Make Room Admin API</a></h1>
  13197. <p>Grants another user the highest power available to a local user who is in the room.
  13198. If the user is not in the room, and it is not publicly joinable, then invite the user.</p>
  13199. <p>By default the server admin (the caller) is granted power, but another user can
  13200. optionally be specified, e.g.:</p>
  13201. <pre><code>POST /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/make_room_admin
  13202. {
  13203. &quot;user_id&quot;: &quot;@foo:example.com&quot;
  13204. }
  13205. </code></pre>
  13206. <h1 id="forward-extremities-admin-api"><a class="header" href="#forward-extremities-admin-api">Forward Extremities Admin API</a></h1>
  13207. <p>Enables querying and deleting forward extremities from rooms. When a lot of forward
  13208. extremities accumulate in a room, performance can become degraded. For details, see
  13209. <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
  13210. <h2 id="check-for-forward-extremities"><a class="header" href="#check-for-forward-extremities">Check for forward extremities</a></h2>
  13211. <p>To check the status of forward extremities for a room:</p>
  13212. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  13213. </code></pre>
  13214. <p>A response as follows will be returned:</p>
  13215. <pre><code class="language-json">{
  13216. &quot;count&quot;: 1,
  13217. &quot;results&quot;: [
  13218. {
  13219. &quot;event_id&quot;: &quot;$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdefgh&quot;,
  13220. &quot;state_group&quot;: 439,
  13221. &quot;depth&quot;: 123,
  13222. &quot;received_ts&quot;: 1611263016761
  13223. }
  13224. ]
  13225. }
  13226. </code></pre>
  13227. <h2 id="deleting-forward-extremities"><a class="header" href="#deleting-forward-extremities">Deleting forward extremities</a></h2>
  13228. <p><strong>WARNING</strong>: Please ensure you know what you're doing and have read
  13229. the related issue <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.
  13230. Under no situations should this API be executed as an automated maintenance task!</p>
  13231. <p>If a room has lots of forward extremities, the extra can be
  13232. deleted as follows:</p>
  13233. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  13234. </code></pre>
  13235. <p>A response as follows will be returned, indicating the amount of forward extremities
  13236. that were deleted.</p>
  13237. <pre><code class="language-json">{
  13238. &quot;deleted&quot;: 1
  13239. }
  13240. </code></pre>
  13241. <h1 id="event-context-api"><a class="header" href="#event-context-api">Event Context API</a></h1>
  13242. <p>This API lets a client find the context of an event. This is designed primarily to investigate abuse reports.</p>
  13243. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/context/&lt;event_id&gt;
  13244. </code></pre>
  13245. <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>
  13246. <p>Example response:</p>
  13247. <pre><code class="language-json">{
  13248. &quot;end&quot;: &quot;t29-57_2_0_2&quot;,
  13249. &quot;events_after&quot;: [
  13250. {
  13251. &quot;content&quot;: {
  13252. &quot;body&quot;: &quot;This is an example text message&quot;,
  13253. &quot;msgtype&quot;: &quot;m.text&quot;,
  13254. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  13255. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;
  13256. },
  13257. &quot;type&quot;: &quot;m.room.message&quot;,
  13258. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13259. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13260. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13261. &quot;origin_server_ts&quot;: 1432735824653,
  13262. &quot;unsigned&quot;: {
  13263. &quot;age&quot;: 1234
  13264. }
  13265. }
  13266. ],
  13267. &quot;event&quot;: {
  13268. &quot;content&quot;: {
  13269. &quot;body&quot;: &quot;filename.jpg&quot;,
  13270. &quot;info&quot;: {
  13271. &quot;h&quot;: 398,
  13272. &quot;w&quot;: 394,
  13273. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  13274. &quot;size&quot;: 31037
  13275. },
  13276. &quot;url&quot;: &quot;mxc://example.org/JWEIFJgwEIhweiWJE&quot;,
  13277. &quot;msgtype&quot;: &quot;m.image&quot;
  13278. },
  13279. &quot;type&quot;: &quot;m.room.message&quot;,
  13280. &quot;event_id&quot;: &quot;$f3h4d129462ha:example.com&quot;,
  13281. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13282. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13283. &quot;origin_server_ts&quot;: 1432735824653,
  13284. &quot;unsigned&quot;: {
  13285. &quot;age&quot;: 1234
  13286. }
  13287. },
  13288. &quot;events_before&quot;: [
  13289. {
  13290. &quot;content&quot;: {
  13291. &quot;body&quot;: &quot;something-important.doc&quot;,
  13292. &quot;filename&quot;: &quot;something-important.doc&quot;,
  13293. &quot;info&quot;: {
  13294. &quot;mimetype&quot;: &quot;application/msword&quot;,
  13295. &quot;size&quot;: 46144
  13296. },
  13297. &quot;msgtype&quot;: &quot;m.file&quot;,
  13298. &quot;url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;
  13299. },
  13300. &quot;type&quot;: &quot;m.room.message&quot;,
  13301. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13302. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13303. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13304. &quot;origin_server_ts&quot;: 1432735824653,
  13305. &quot;unsigned&quot;: {
  13306. &quot;age&quot;: 1234
  13307. }
  13308. }
  13309. ],
  13310. &quot;start&quot;: &quot;t27-54_2_0_2&quot;,
  13311. &quot;state&quot;: [
  13312. {
  13313. &quot;content&quot;: {
  13314. &quot;creator&quot;: &quot;@example:example.org&quot;,
  13315. &quot;room_version&quot;: &quot;1&quot;,
  13316. &quot;m.federate&quot;: true,
  13317. &quot;predecessor&quot;: {
  13318. &quot;event_id&quot;: &quot;$something:example.org&quot;,
  13319. &quot;room_id&quot;: &quot;!oldroom:example.org&quot;
  13320. }
  13321. },
  13322. &quot;type&quot;: &quot;m.room.create&quot;,
  13323. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13324. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13325. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13326. &quot;origin_server_ts&quot;: 1432735824653,
  13327. &quot;unsigned&quot;: {
  13328. &quot;age&quot;: 1234
  13329. },
  13330. &quot;state_key&quot;: &quot;&quot;
  13331. },
  13332. {
  13333. &quot;content&quot;: {
  13334. &quot;membership&quot;: &quot;join&quot;,
  13335. &quot;avatar_url&quot;: &quot;mxc://example.org/SEsfnsuifSDFSSEF&quot;,
  13336. &quot;displayname&quot;: &quot;Alice Margatroid&quot;
  13337. },
  13338. &quot;type&quot;: &quot;m.room.member&quot;,
  13339. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13340. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13341. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13342. &quot;origin_server_ts&quot;: 1432735824653,
  13343. &quot;unsigned&quot;: {
  13344. &quot;age&quot;: 1234
  13345. },
  13346. &quot;state_key&quot;: &quot;@alice:example.org&quot;
  13347. }
  13348. ]
  13349. }
  13350. </code></pre>
  13351. <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>
  13352. <p>The API to send notices is as follows:</p>
  13353. <pre><code>POST /_synapse/admin/v1/send_server_notice
  13354. </code></pre>
  13355. <p>or:</p>
  13356. <pre><code>PUT /_synapse/admin/v1/send_server_notice/{txnId}
  13357. </code></pre>
  13358. <p>You will need to authenticate with an access token for an admin user.</p>
  13359. <p>When using the <code>PUT</code> form, retransmissions with the same transaction ID will be
  13360. ignored in the same way as with <code>PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}</code>.</p>
  13361. <p>The request body should look something like the following:</p>
  13362. <pre><code class="language-json">{
  13363. &quot;user_id&quot;: &quot;@target_user:server_name&quot;,
  13364. &quot;content&quot;: {
  13365. &quot;msgtype&quot;: &quot;m.text&quot;,
  13366. &quot;body&quot;: &quot;This is my message&quot;
  13367. }
  13368. }
  13369. </code></pre>
  13370. <p>You can optionally include the following additional parameters:</p>
  13371. <ul>
  13372. <li><code>type</code>: the type of event. Defaults to <code>m.room.message</code>.</li>
  13373. <li><code>state_key</code>: Setting this will result in a state event being sent.</li>
  13374. </ul>
  13375. <p>Once the notice has been sent, the API will return the following response:</p>
  13376. <pre><code class="language-json">{
  13377. &quot;event_id&quot;: &quot;&lt;event_id&gt;&quot;
  13378. }
  13379. </code></pre>
  13380. <p>Note that server notices must be enabled in <code>homeserver.yaml</code> before this API
  13381. can be used. See <a href="admin_api/../server_notices.html">the server notices documentation</a> for more information.</p>
  13382. <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>
  13383. <p>Returns information about all local media usage of users. Gives the
  13384. possibility to filter them by time and user.</p>
  13385. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  13386. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  13387. <p>The API is:</p>
  13388. <pre><code>GET /_synapse/admin/v1/statistics/users/media
  13389. </code></pre>
  13390. <p>A response body like the following is returned:</p>
  13391. <pre><code class="language-json">{
  13392. &quot;users&quot;: [
  13393. {
  13394. &quot;displayname&quot;: &quot;foo_user_0&quot;,
  13395. &quot;media_count&quot;: 2,
  13396. &quot;media_length&quot;: 134,
  13397. &quot;user_id&quot;: &quot;@foo_user_0:test&quot;
  13398. },
  13399. {
  13400. &quot;displayname&quot;: &quot;foo_user_1&quot;,
  13401. &quot;media_count&quot;: 2,
  13402. &quot;media_length&quot;: 134,
  13403. &quot;user_id&quot;: &quot;@foo_user_1:test&quot;
  13404. }
  13405. ],
  13406. &quot;next_token&quot;: 3,
  13407. &quot;total&quot;: 10
  13408. }
  13409. </code></pre>
  13410. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint
  13411. again with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  13412. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  13413. reports to paginate through.</p>
  13414. <p><strong>Parameters</strong></p>
  13415. <p>The following parameters should be set in the URL:</p>
  13416. <ul>
  13417. <li><code>limit</code>: string representing a positive integer - Is optional but is
  13418. used for pagination, denoting the maximum number of items to return
  13419. in this call. Defaults to <code>100</code>.</li>
  13420. <li><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  13421. denoting the offset in the returned results. This should be treated as an opaque value
  13422. and not explicitly set to anything other than the return value of <code>next_token</code> from a
  13423. previous call. Defaults to <code>0</code>.</li>
  13424. <li><code>order_by</code> - string - The method in which to sort the returned list of users. Valid values are:
  13425. <ul>
  13426. <li><code>user_id</code> - Users are ordered alphabetically by <code>user_id</code>. This is the default.</li>
  13427. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  13428. <li><code>media_length</code> - Users are ordered by the total size of uploaded media in bytes.
  13429. Smallest to largest.</li>
  13430. <li><code>media_count</code> - Users are ordered by number of uploaded media. Smallest to largest.</li>
  13431. </ul>
  13432. </li>
  13433. <li><code>from_ts</code> - string representing a positive integer - Considers only
  13434. files created at this timestamp or later. Unix timestamp in ms.</li>
  13435. <li><code>until_ts</code> - string representing a positive integer - Considers only
  13436. files created at this timestamp or earlier. Unix timestamp in ms.</li>
  13437. <li><code>search_term</code> - string - Filter users by their user ID localpart <strong>or</strong> displayname.
  13438. The search term can be found in any part of the string.
  13439. Defaults to no filtering.</li>
  13440. <li><code>dir</code> - string - Direction of order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  13441. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  13442. </ul>
  13443. <p><strong>Response</strong></p>
  13444. <p>The following fields are returned in the JSON response body:</p>
  13445. <ul>
  13446. <li><code>users</code> - An array of objects, each containing information
  13447. about the user and their local media. Objects contain the following fields:
  13448. <ul>
  13449. <li><code>displayname</code> - string - Displayname of this user.</li>
  13450. <li><code>media_count</code> - integer - Number of uploaded media by this user.</li>
  13451. <li><code>media_length</code> - integer - Size of uploaded media in bytes by this user.</li>
  13452. <li><code>user_id</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  13453. </ul>
  13454. </li>
  13455. <li><code>next_token</code> - integer - Opaque value used for pagination. See above.</li>
  13456. <li><code>total</code> - integer - Total number of users after filtering.</li>
  13457. </ul>
  13458. <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>
  13459. <p>Returns the 10 largest rooms and an estimate of how much space in the database
  13460. they are taking.</p>
  13461. <p>This does not include the size of any associated media associated with the room.</p>
  13462. <p>Returns an error on SQLite.</p>
  13463. <p><em>Note:</em> This uses the planner statistics from PostgreSQL to do the estimates,
  13464. which means that the returned information can vary widely from reality. However,
  13465. it should be enough to get a rough idea of where database disk space is going.</p>
  13466. <p>The API is:</p>
  13467. <pre><code>GET /_synapse/admin/v1/statistics/database/rooms
  13468. </code></pre>
  13469. <p>A response body like the following is returned:</p>
  13470. <pre><code class="language-json">{
  13471. &quot;rooms&quot;: [
  13472. {
  13473. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  13474. &quot;estimated_size&quot;: 47325417353
  13475. }
  13476. ],
  13477. }
  13478. </code></pre>
  13479. <p><strong>Response</strong></p>
  13480. <p>The following fields are returned in the JSON response body:</p>
  13481. <ul>
  13482. <li><code>rooms</code> - An array of objects, sorted by largest room first. Objects contain
  13483. the following fields:
  13484. <ul>
  13485. <li><code>room_id</code> - string - The room ID.</li>
  13486. <li><code>estimated_size</code> - integer - Estimated disk space used in bytes by the room
  13487. in the database.</li>
  13488. </ul>
  13489. </li>
  13490. </ul>
  13491. <p><em>Added in Synapse 1.83.0</em></p>
  13492. <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>
  13493. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  13494. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  13495. <h2 id="query-user-account"><a class="header" href="#query-user-account">Query User Account</a></h2>
  13496. <p>This API returns information about a specific user account.</p>
  13497. <p>The api is:</p>
  13498. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;
  13499. </code></pre>
  13500. <p>It returns a JSON body like the following:</p>
  13501. <pre><code class="language-jsonc">{
  13502. &quot;name&quot;: &quot;@user:example.com&quot;,
  13503. &quot;displayname&quot;: &quot;User&quot;, // can be null if not set
  13504. &quot;threepids&quot;: [
  13505. {
  13506. &quot;medium&quot;: &quot;email&quot;,
  13507. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;,
  13508. &quot;added_at&quot;: 1586458409743,
  13509. &quot;validated_at&quot;: 1586458409743
  13510. },
  13511. {
  13512. &quot;medium&quot;: &quot;email&quot;,
  13513. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;,
  13514. &quot;added_at&quot;: 1586458409743,
  13515. &quot;validated_at&quot;: 1586458409743
  13516. }
  13517. ],
  13518. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;, // can be null if not set
  13519. &quot;is_guest&quot;: 0,
  13520. &quot;admin&quot;: 0,
  13521. &quot;deactivated&quot;: 0,
  13522. &quot;erased&quot;: false,
  13523. &quot;shadow_banned&quot;: 0,
  13524. &quot;creation_ts&quot;: 1560432506,
  13525. &quot;appservice_id&quot;: null,
  13526. &quot;consent_server_notice_sent&quot;: null,
  13527. &quot;consent_version&quot;: null,
  13528. &quot;consent_ts&quot;: null,
  13529. &quot;external_ids&quot;: [
  13530. {
  13531. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  13532. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  13533. },
  13534. {
  13535. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  13536. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  13537. }
  13538. ],
  13539. &quot;user_type&quot;: null
  13540. }
  13541. </code></pre>
  13542. <p>URL parameters:</p>
  13543. <ul>
  13544. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  13545. </ul>
  13546. <h2 id="create-or-modify-account"><a class="header" href="#create-or-modify-account">Create or modify account</a></h2>
  13547. <p>This API allows an administrator to create or modify a user account with a
  13548. specific <code>user_id</code>.</p>
  13549. <p>This api is:</p>
  13550. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;
  13551. </code></pre>
  13552. <p>with a body of:</p>
  13553. <pre><code class="language-json">{
  13554. &quot;password&quot;: &quot;user_password&quot;,
  13555. &quot;logout_devices&quot;: false,
  13556. &quot;displayname&quot;: &quot;Alice Marigold&quot;,
  13557. &quot;avatar_url&quot;: &quot;mxc://example.com/abcde12345&quot;,
  13558. &quot;threepids&quot;: [
  13559. {
  13560. &quot;medium&quot;: &quot;email&quot;,
  13561. &quot;address&quot;: &quot;alice@example.com&quot;
  13562. },
  13563. {
  13564. &quot;medium&quot;: &quot;email&quot;,
  13565. &quot;address&quot;: &quot;alice@domain.org&quot;
  13566. }
  13567. ],
  13568. &quot;external_ids&quot;: [
  13569. {
  13570. &quot;auth_provider&quot;: &quot;example&quot;,
  13571. &quot;external_id&quot;: &quot;12345&quot;
  13572. },
  13573. {
  13574. &quot;auth_provider&quot;: &quot;example2&quot;,
  13575. &quot;external_id&quot;: &quot;abc54321&quot;
  13576. }
  13577. ],
  13578. &quot;admin&quot;: false,
  13579. &quot;deactivated&quot;: false,
  13580. &quot;user_type&quot;: null
  13581. }
  13582. </code></pre>
  13583. <p>Returns HTTP status code:</p>
  13584. <ul>
  13585. <li><code>201</code> - When a new user object was created.</li>
  13586. <li><code>200</code> - When a user was modified.</li>
  13587. </ul>
  13588. <p>URL parameters:</p>
  13589. <ul>
  13590. <li><code>user_id</code> - A fully-qualified user id. For example, <code>@user:server.com</code>.</li>
  13591. </ul>
  13592. <p>Body parameters:</p>
  13593. <ul>
  13594. <li>
  13595. <p><code>password</code> - <strong>string</strong>, optional. If provided, the user's password is updated and all
  13596. devices are logged out, unless <code>logout_devices</code> is set to <code>false</code>.</p>
  13597. </li>
  13598. <li>
  13599. <p><code>logout_devices</code> - <strong>bool</strong>, optional, defaults to <code>true</code>. If set to <code>false</code>, devices aren't
  13600. logged out even when <code>password</code> is provided.</p>
  13601. </li>
  13602. <li>
  13603. <p><code>displayname</code> - <strong>string</strong>, optional. If set to an empty string (<code>&quot;&quot;</code>), the user's display name
  13604. will be removed.</p>
  13605. </li>
  13606. <li>
  13607. <p><code>avatar_url</code> - <strong>string</strong>, optional. Must be a
  13608. <a href="https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris">MXC URI</a>.
  13609. If set to an empty string (<code>&quot;&quot;</code>), the user's avatar is removed.</p>
  13610. </li>
  13611. <li>
  13612. <p><code>threepids</code> - <strong>array</strong>, optional. If provided, the user's third-party IDs (email, msisdn) are
  13613. entirely replaced with the given list. Each item in the array is an object with the following
  13614. fields:</p>
  13615. <ul>
  13616. <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>
  13617. <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
  13618. <code>447470274584</code> (for a phone number with country code &quot;44&quot;) and <code>19254857364</code> (for a phone number
  13619. with country code &quot;1&quot;) for <code>msisdn</code>.
  13620. Note: If a threepid is removed from a user via this option, Synapse will also attempt to remove
  13621. that threepid from any identity servers it is aware has a binding for it.</li>
  13622. </ul>
  13623. </li>
  13624. <li>
  13625. <p><code>external_ids</code> - <strong>array</strong>, optional. Allow setting the identifier of the external identity
  13626. provider for SSO (Single sign-on). More details are in the configuration manual under the
  13627. 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>
  13628. <ul>
  13629. <li><code>auth_provider</code> - <strong>string</strong>, required. The unique, internal ID of the external identity provider.
  13630. The same as <code>idp_id</code> from the homeserver configuration. Note that no error is raised if the
  13631. provided value is not in the homeserver configuration.</li>
  13632. <li><code>external_id</code> - <strong>string</strong>, required. An identifier for the user in the external identity provider.
  13633. When the user logs in to the identity provider, this must be the unique ID that they map to.</li>
  13634. </ul>
  13635. </li>
  13636. <li>
  13637. <p><code>admin</code> - <strong>bool</strong>, optional, defaults to <code>false</code>. Whether the user is a homeserver administrator,
  13638. granting them access to the Admin API, among other things.</p>
  13639. </li>
  13640. <li>
  13641. <p><code>deactivated</code> - <strong>bool</strong>, optional. If unspecified, deactivation state will be left unchanged.</p>
  13642. <p>Note: the <code>password</code> field must also be set if both of the following are true:</p>
  13643. <ul>
  13644. <li><code>deactivated</code> is set to <code>false</code> and the user was previously deactivated (you are reactivating this user)</li>
  13645. <li>Users are allowed to set their password on this homeserver (both <code>password_config.enabled</code> and
  13646. <code>password_config.localdb_enabled</code> config options are set to <code>true</code>).
  13647. Users' passwords are wiped upon account deactivation, hence the need to set a new one here.</li>
  13648. </ul>
  13649. <p>Note: a user cannot be erased with this API. For more details on
  13650. deactivating and erasing users see <a href="admin_api/user_admin_api.html#deactivate-account">Deactivate Account</a>.</p>
  13651. </li>
  13652. <li>
  13653. <p><code>user_type</code> - <strong>string</strong> or null, optional. If not provided, the user type will be
  13654. not be changed. If <code>null</code> is given, the user type will be cleared.
  13655. Other allowed options are: <code>bot</code> and <code>support</code>.</p>
  13656. </li>
  13657. </ul>
  13658. <h2 id="list-accounts"><a class="header" href="#list-accounts">List Accounts</a></h2>
  13659. <p>This API returns all local user accounts.
  13660. By default, the response is ordered by ascending user ID.</p>
  13661. <pre><code>GET /_synapse/admin/v2/users?from=0&amp;limit=10&amp;guests=false
  13662. </code></pre>
  13663. <p>A response body like the following is returned:</p>
  13664. <pre><code class="language-json">{
  13665. &quot;users&quot;: [
  13666. {
  13667. &quot;name&quot;: &quot;&lt;user_id1&gt;&quot;,
  13668. &quot;is_guest&quot;: 0,
  13669. &quot;admin&quot;: 0,
  13670. &quot;user_type&quot;: null,
  13671. &quot;deactivated&quot;: 0,
  13672. &quot;erased&quot;: false,
  13673. &quot;shadow_banned&quot;: 0,
  13674. &quot;displayname&quot;: &quot;&lt;User One&gt;&quot;,
  13675. &quot;avatar_url&quot;: null,
  13676. &quot;creation_ts&quot;: 1560432668000
  13677. }, {
  13678. &quot;name&quot;: &quot;&lt;user_id2&gt;&quot;,
  13679. &quot;is_guest&quot;: 0,
  13680. &quot;admin&quot;: 1,
  13681. &quot;user_type&quot;: null,
  13682. &quot;deactivated&quot;: 0,
  13683. &quot;erased&quot;: false,
  13684. &quot;shadow_banned&quot;: 0,
  13685. &quot;displayname&quot;: &quot;&lt;User Two&gt;&quot;,
  13686. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  13687. &quot;creation_ts&quot;: 1561550621000
  13688. }
  13689. ],
  13690. &quot;next_token&quot;: &quot;100&quot;,
  13691. &quot;total&quot;: 200
  13692. }
  13693. </code></pre>
  13694. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  13695. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  13696. <p>If the endpoint does not return a <code>next_token</code> then there are no more users
  13697. to paginate through.</p>
  13698. <p><strong>Parameters</strong></p>
  13699. <p>The following parameters should be set in the URL:</p>
  13700. <ul>
  13701. <li>
  13702. <p><code>user_id</code> - Is optional and filters to only return users with user IDs
  13703. that contain this value. This parameter is ignored when using the <code>name</code> parameter.</p>
  13704. </li>
  13705. <li>
  13706. <p><code>name</code> - Is optional and filters to only return users with user ID localparts
  13707. <strong>or</strong> displaynames that contain this value.</p>
  13708. </li>
  13709. <li>
  13710. <p><code>guests</code> - string representing a bool - Is optional and if <code>false</code> will <strong>exclude</strong> guest users.
  13711. Defaults to <code>true</code> to include guest users.</p>
  13712. </li>
  13713. <li>
  13714. <p><code>deactivated</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> deactivated users.
  13715. Defaults to <code>false</code> to exclude deactivated users.</p>
  13716. </li>
  13717. <li>
  13718. <p><code>limit</code> - string representing a positive integer - Is optional but is used for pagination,
  13719. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  13720. </li>
  13721. <li>
  13722. <p><code>from</code> - string representing a positive integer - Is optional but used for pagination,
  13723. denoting the offset in the returned results. This should be treated as an opaque value and
  13724. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  13725. Defaults to <code>0</code>.</p>
  13726. </li>
  13727. <li>
  13728. <p><code>order_by</code> - The method by which to sort the returned list of users.
  13729. If the ordered field has duplicates, the second order is always by ascending <code>name</code>,
  13730. which guarantees a stable ordering. Valid values are:</p>
  13731. <ul>
  13732. <li><code>name</code> - Users are ordered alphabetically by <code>name</code>. This is the default.</li>
  13733. <li><code>is_guest</code> - Users are ordered by <code>is_guest</code> status.</li>
  13734. <li><code>admin</code> - Users are ordered by <code>admin</code> status.</li>
  13735. <li><code>user_type</code> - Users are ordered alphabetically by <code>user_type</code>.</li>
  13736. <li><code>deactivated</code> - Users are ordered by <code>deactivated</code> status.</li>
  13737. <li><code>shadow_banned</code> - Users are ordered by <code>shadow_banned</code> status.</li>
  13738. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  13739. <li><code>avatar_url</code> - Users are ordered alphabetically by avatar URL.</li>
  13740. <li><code>creation_ts</code> - Users are ordered by when the users was created in ms.</li>
  13741. </ul>
  13742. </li>
  13743. <li>
  13744. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  13745. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  13746. </li>
  13747. <li>
  13748. <p><code>not_user_type</code> - Exclude certain user types, such as bot users, from the request.
  13749. Can be provided multiple times. Possible values are <code>bot</code>, <code>support</code> or &quot;empty string&quot;.
  13750. &quot;empty string&quot; here means to exclude users without a type.</p>
  13751. </li>
  13752. </ul>
  13753. <p>Caution. The database only has indexes on the columns <code>name</code> and <code>creation_ts</code>.
  13754. This means that if a different sort order is used (<code>is_guest</code>, <code>admin</code>,
  13755. <code>user_type</code>, <code>deactivated</code>, <code>shadow_banned</code>, <code>avatar_url</code> or <code>displayname</code>),
  13756. this can cause a large load on the database, especially for large environments.</p>
  13757. <p><strong>Response</strong></p>
  13758. <p>The following fields are returned in the JSON response body:</p>
  13759. <ul>
  13760. <li>
  13761. <p><code>users</code> - An array of objects, each containing information about an user.
  13762. User objects contain the following fields:</p>
  13763. <ul>
  13764. <li><code>name</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  13765. <li><code>is_guest</code> - bool - Status if that user is a guest account.</li>
  13766. <li><code>admin</code> - bool - Status if that user is a server administrator.</li>
  13767. <li><code>user_type</code> - string - Type of the user. Normal users are type <code>None</code>.
  13768. This allows user type specific behaviour. There are also types <code>support</code> and <code>bot</code>. </li>
  13769. <li><code>deactivated</code> - bool - Status if that user has been marked as deactivated.</li>
  13770. <li><code>erased</code> - bool - Status if that user has been marked as erased.</li>
  13771. <li><code>shadow_banned</code> - bool - Status if that user has been marked as shadow banned.</li>
  13772. <li><code>displayname</code> - string - The user's display name if they have set one.</li>
  13773. <li><code>avatar_url</code> - string - The user's avatar URL if they have set one.</li>
  13774. <li><code>creation_ts</code> - integer - The user's creation timestamp in ms.</li>
  13775. </ul>
  13776. </li>
  13777. <li>
  13778. <p><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</p>
  13779. </li>
  13780. <li>
  13781. <p><code>total</code> - integer - Total number of media.</p>
  13782. </li>
  13783. </ul>
  13784. <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>
  13785. <p>This API returns information about the active sessions for a specific user.</p>
  13786. <p>The endpoints are:</p>
  13787. <pre><code>GET /_synapse/admin/v1/whois/&lt;user_id&gt;
  13788. </code></pre>
  13789. <p>and:</p>
  13790. <pre><code>GET /_matrix/client/r0/admin/whois/&lt;userId&gt;
  13791. </code></pre>
  13792. <p>See also: <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">Client Server
  13793. API Whois</a>.</p>
  13794. <p>It returns a JSON body like the following:</p>
  13795. <pre><code class="language-json">{
  13796. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;,
  13797. &quot;devices&quot;: {
  13798. &quot;&quot;: {
  13799. &quot;sessions&quot;: [
  13800. {
  13801. &quot;connections&quot;: [
  13802. {
  13803. &quot;ip&quot;: &quot;1.2.3.4&quot;,
  13804. &quot;last_seen&quot;: 1417222374433,
  13805. &quot;user_agent&quot;: &quot;Mozilla/5.0 ...&quot;
  13806. },
  13807. {
  13808. &quot;ip&quot;: &quot;1.2.3.10&quot;,
  13809. &quot;last_seen&quot;: 1417222374500,
  13810. &quot;user_agent&quot;: &quot;Dalvik/2.1.0 ...&quot;
  13811. }
  13812. ]
  13813. }
  13814. ]
  13815. }
  13816. }
  13817. }
  13818. </code></pre>
  13819. <p><code>last_seen</code> is measured in milliseconds since the Unix epoch.</p>
  13820. <h2 id="deactivate-account"><a class="header" href="#deactivate-account">Deactivate Account</a></h2>
  13821. <p>This API deactivates an account. It removes active access tokens, resets the
  13822. password, and deletes third-party IDs (to prevent the user requesting a
  13823. password reset).</p>
  13824. <p>It can also mark the user as GDPR-erased. This means messages sent by the
  13825. user will still be visible by anyone that was in the room when these messages
  13826. were sent, but hidden from users joining the room afterwards.</p>
  13827. <p>The api is:</p>
  13828. <pre><code>POST /_synapse/admin/v1/deactivate/&lt;user_id&gt;
  13829. </code></pre>
  13830. <p>with a body of:</p>
  13831. <pre><code class="language-json">{
  13832. &quot;erase&quot;: true
  13833. }
  13834. </code></pre>
  13835. <p>The erase parameter is optional and defaults to <code>false</code>.
  13836. An empty body may be passed for backwards compatibility.</p>
  13837. <p>The following actions are performed when deactivating an user:</p>
  13838. <ul>
  13839. <li>Try to unbind 3PIDs from the identity server</li>
  13840. <li>Remove all 3PIDs from the homeserver</li>
  13841. <li>Delete all devices and E2EE keys</li>
  13842. <li>Delete all access tokens</li>
  13843. <li>Delete all pushers</li>
  13844. <li>Delete the password hash</li>
  13845. <li>Removal from all rooms the user is a member of</li>
  13846. <li>Remove the user from the user directory</li>
  13847. <li>Reject all pending invites</li>
  13848. <li>Remove all account validity information related to the user</li>
  13849. <li>Remove the arbitrary data store known as <em>account data</em>. For example, this includes:
  13850. <ul>
  13851. <li>list of ignored users;</li>
  13852. <li>push rules;</li>
  13853. <li>secret storage keys; and</li>
  13854. <li>cross-signing keys.</li>
  13855. </ul>
  13856. </li>
  13857. </ul>
  13858. <p>The following additional actions are performed during deactivation if <code>erase</code>
  13859. is set to <code>true</code>:</p>
  13860. <ul>
  13861. <li>Remove the user's display name</li>
  13862. <li>Remove the user's avatar URL</li>
  13863. <li>Mark the user as erased</li>
  13864. </ul>
  13865. <p>The following actions are <strong>NOT</strong> performed. The list may be incomplete.</p>
  13866. <ul>
  13867. <li>Remove mappings of SSO IDs</li>
  13868. <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>
  13869. <li>Delete sent and received messages</li>
  13870. <li>Remove the user's creation (registration) timestamp</li>
  13871. <li><a href="admin_api/user_admin_api.html#override-ratelimiting-for-users">Remove rate limit overrides</a></li>
  13872. <li>Remove from monthly active users</li>
  13873. <li>Remove user's consent information (consent version and timestamp)</li>
  13874. </ul>
  13875. <h2 id="reset-password"><a class="header" href="#reset-password">Reset password</a></h2>
  13876. <p>Changes the password of another user. This will automatically log the user out of all their devices.</p>
  13877. <p>The api is:</p>
  13878. <pre><code>POST /_synapse/admin/v1/reset_password/&lt;user_id&gt;
  13879. </code></pre>
  13880. <p>with a body of:</p>
  13881. <pre><code class="language-json">{
  13882. &quot;new_password&quot;: &quot;&lt;secret&gt;&quot;,
  13883. &quot;logout_devices&quot;: true
  13884. }
  13885. </code></pre>
  13886. <p>The parameter <code>new_password</code> is required.
  13887. The parameter <code>logout_devices</code> is optional and defaults to <code>true</code>.</p>
  13888. <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>
  13889. <p>The api is:</p>
  13890. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  13891. </code></pre>
  13892. <p>A response body like the following is returned:</p>
  13893. <pre><code class="language-json">{
  13894. &quot;admin&quot;: true
  13895. }
  13896. </code></pre>
  13897. <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>
  13898. <p>Note that you cannot demote yourself.</p>
  13899. <p>The api is:</p>
  13900. <pre><code>PUT /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  13901. </code></pre>
  13902. <p>with a body of:</p>
  13903. <pre><code class="language-json">{
  13904. &quot;admin&quot;: true
  13905. }
  13906. </code></pre>
  13907. <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>
  13908. <p>Gets a list of all <code>room_id</code> that a specific <code>user_id</code> is member.</p>
  13909. <p>The API is:</p>
  13910. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/joined_rooms
  13911. </code></pre>
  13912. <p>A response body like the following is returned:</p>
  13913. <pre><code class="language-json"> {
  13914. &quot;joined_rooms&quot;: [
  13915. &quot;!DuGcnbhHGaSZQoNQR:matrix.org&quot;,
  13916. &quot;!ZtSaPCawyWtxfWiIy:matrix.org&quot;
  13917. ],
  13918. &quot;total&quot;: 2
  13919. }
  13920. </code></pre>
  13921. <p>The server returns the list of rooms of which the user and the server
  13922. are member. If the user is local, all the rooms of which the user is
  13923. member are returned.</p>
  13924. <p><strong>Parameters</strong></p>
  13925. <p>The following parameters should be set in the URL:</p>
  13926. <ul>
  13927. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  13928. </ul>
  13929. <p><strong>Response</strong></p>
  13930. <p>The following fields are returned in the JSON response body:</p>
  13931. <ul>
  13932. <li><code>joined_rooms</code> - An array of <code>room_id</code>.</li>
  13933. <li><code>total</code> - Number of rooms.</li>
  13934. </ul>
  13935. <h2 id="account-data"><a class="header" href="#account-data">Account Data</a></h2>
  13936. <p>Gets information about account data for a specific <code>user_id</code>.</p>
  13937. <p>The API is:</p>
  13938. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/accountdata
  13939. </code></pre>
  13940. <p>A response body like the following is returned:</p>
  13941. <pre><code class="language-json">{
  13942. &quot;account_data&quot;: {
  13943. &quot;global&quot;: {
  13944. &quot;m.secret_storage.key.LmIGHTg5W&quot;: {
  13945. &quot;algorithm&quot;: &quot;m.secret_storage.v1.aes-hmac-sha2&quot;,
  13946. &quot;iv&quot;: &quot;fwjNZatxg==&quot;,
  13947. &quot;mac&quot;: &quot;eWh9kNnLWZUNOgnc=&quot;
  13948. },
  13949. &quot;im.vector.hide_profile&quot;: {
  13950. &quot;hide_profile&quot;: true
  13951. },
  13952. &quot;org.matrix.preview_urls&quot;: {
  13953. &quot;disable&quot;: false
  13954. },
  13955. &quot;im.vector.riot.breadcrumb_rooms&quot;: {
  13956. &quot;rooms&quot;: [
  13957. &quot;!LxcBDAsDUVAfJDEo:matrix.org&quot;,
  13958. &quot;!MAhRxqasbItjOqxu:matrix.org&quot;
  13959. ]
  13960. },
  13961. &quot;m.accepted_terms&quot;: {
  13962. &quot;accepted&quot;: [
  13963. &quot;https://example.org/somewhere/privacy-1.2-en.html&quot;,
  13964. &quot;https://example.org/somewhere/terms-2.0-en.html&quot;
  13965. ]
  13966. },
  13967. &quot;im.vector.setting.breadcrumbs&quot;: {
  13968. &quot;recent_rooms&quot;: [
  13969. &quot;!MAhRxqasbItqxuEt:matrix.org&quot;,
  13970. &quot;!ZtSaPCawyWtxiImy:matrix.org&quot;
  13971. ]
  13972. }
  13973. },
  13974. &quot;rooms&quot;: {
  13975. &quot;!GUdfZSHUJibpiVqHYd:matrix.org&quot;: {
  13976. &quot;m.fully_read&quot;: {
  13977. &quot;event_id&quot;: &quot;$156334540fYIhZ:matrix.org&quot;
  13978. }
  13979. },
  13980. &quot;!tOZwOOiqwCYQkLhV:matrix.org&quot;: {
  13981. &quot;m.fully_read&quot;: {
  13982. &quot;event_id&quot;: &quot;$xjsIyp4_NaVl2yPvIZs_k1Jl8tsC_Sp23wjqXPno&quot;
  13983. }
  13984. }
  13985. }
  13986. }
  13987. }
  13988. </code></pre>
  13989. <p><strong>Parameters</strong></p>
  13990. <p>The following parameters should be set in the URL:</p>
  13991. <ul>
  13992. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  13993. </ul>
  13994. <p><strong>Response</strong></p>
  13995. <p>The following fields are returned in the JSON response body:</p>
  13996. <ul>
  13997. <li><code>account_data</code> - A map containing the account data for the user
  13998. <ul>
  13999. <li><code>global</code> - A map containing the global account data for the user</li>
  14000. <li><code>rooms</code> - A map containing the account data per room for the user</li>
  14001. </ul>
  14002. </li>
  14003. </ul>
  14004. <h2 id="user-media"><a class="header" href="#user-media">User media</a></h2>
  14005. <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>
  14006. <p>Gets a list of all local media that a specific <code>user_id</code> has created.
  14007. These are media that the user has uploaded themselves
  14008. (<a href="admin_api/../media_repository.html#local-media">local media</a>), as well as
  14009. <a href="admin_api/../media_repository.html#url-previews">URL preview images</a> requested by the user if the
  14010. <a href="admin_api/../usage/configuration/config_documentation.html#url_preview_enabled">feature is enabled</a>.</p>
  14011. <p>By default, the response is ordered by descending creation date and ascending media ID.
  14012. The newest media is on top. You can change the order with parameters
  14013. <code>order_by</code> and <code>dir</code>.</p>
  14014. <p>The API is:</p>
  14015. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/media
  14016. </code></pre>
  14017. <p>A response body like the following is returned:</p>
  14018. <pre><code class="language-json">{
  14019. &quot;media&quot;: [
  14020. {
  14021. &quot;created_ts&quot;: 100400,
  14022. &quot;last_access_ts&quot;: null,
  14023. &quot;media_id&quot;: &quot;qXhyRzulkwLsNHTbpHreuEgo&quot;,
  14024. &quot;media_length&quot;: 67,
  14025. &quot;media_type&quot;: &quot;image/png&quot;,
  14026. &quot;quarantined_by&quot;: null,
  14027. &quot;safe_from_quarantine&quot;: false,
  14028. &quot;upload_name&quot;: &quot;test1.png&quot;
  14029. },
  14030. {
  14031. &quot;created_ts&quot;: 200400,
  14032. &quot;last_access_ts&quot;: null,
  14033. &quot;media_id&quot;: &quot;FHfiSnzoINDatrXHQIXBtahw&quot;,
  14034. &quot;media_length&quot;: 67,
  14035. &quot;media_type&quot;: &quot;image/png&quot;,
  14036. &quot;quarantined_by&quot;: null,
  14037. &quot;safe_from_quarantine&quot;: false,
  14038. &quot;upload_name&quot;: &quot;test2.png&quot;
  14039. }
  14040. ],
  14041. &quot;next_token&quot;: 3,
  14042. &quot;total&quot;: 2
  14043. }
  14044. </code></pre>
  14045. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  14046. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  14047. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  14048. reports to paginate through.</p>
  14049. <p><strong>Parameters</strong></p>
  14050. <p>The following parameters should be set in the URL:</p>
  14051. <ul>
  14052. <li>
  14053. <p><code>user_id</code> - string - fully qualified: for example, <code>@user:server.com</code>.</p>
  14054. </li>
  14055. <li>
  14056. <p><code>limit</code>: string representing a positive integer - Is optional but is used for pagination,
  14057. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  14058. </li>
  14059. <li>
  14060. <p><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  14061. denoting the offset in the returned results. This should be treated as an opaque value and
  14062. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  14063. Defaults to <code>0</code>.</p>
  14064. </li>
  14065. <li>
  14066. <p><code>order_by</code> - The method by which to sort the returned list of media.
  14067. If the ordered field has duplicates, the second order is always by ascending <code>media_id</code>,
  14068. which guarantees a stable ordering. Valid values are:</p>
  14069. <ul>
  14070. <li><code>media_id</code> - Media are ordered alphabetically by <code>media_id</code>.</li>
  14071. <li><code>upload_name</code> - Media are ordered alphabetically by name the media was uploaded with.</li>
  14072. <li><code>created_ts</code> - Media are ordered by when the content was uploaded in ms.
  14073. Smallest to largest. This is the default.</li>
  14074. <li><code>last_access_ts</code> - Media are ordered by when the content was last accessed in ms.
  14075. Smallest to largest.</li>
  14076. <li><code>media_length</code> - Media are ordered by length of the media in bytes.
  14077. Smallest to largest.</li>
  14078. <li><code>media_type</code> - Media are ordered alphabetically by MIME-type.</li>
  14079. <li><code>quarantined_by</code> - Media are ordered alphabetically by the user ID that
  14080. initiated the quarantine request for this media.</li>
  14081. <li><code>safe_from_quarantine</code> - Media are ordered by the status if this media is safe
  14082. from quarantining.</li>
  14083. </ul>
  14084. </li>
  14085. <li>
  14086. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  14087. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  14088. </li>
  14089. </ul>
  14090. <p>If neither <code>order_by</code> nor <code>dir</code> is set, the default order is newest media on top
  14091. (corresponds to <code>order_by</code> = <code>created_ts</code> and <code>dir</code> = <code>b</code>).</p>
  14092. <p>Caution. The database only has indexes on the columns <code>media_id</code>,
  14093. <code>user_id</code> and <code>created_ts</code>. This means that if a different sort order is used
  14094. (<code>upload_name</code>, <code>last_access_ts</code>, <code>media_length</code>, <code>media_type</code>,
  14095. <code>quarantined_by</code> or <code>safe_from_quarantine</code>), this can cause a large load on the
  14096. database, especially for large environments.</p>
  14097. <p><strong>Response</strong></p>
  14098. <p>The following fields are returned in the JSON response body:</p>
  14099. <ul>
  14100. <li><code>media</code> - An array of objects, each containing information about a media.
  14101. Media objects contain the following fields:
  14102. <ul>
  14103. <li><code>created_ts</code> - integer - Timestamp when the content was uploaded in ms.</li>
  14104. <li><code>last_access_ts</code> - integer - Timestamp when the content was last accessed in ms.</li>
  14105. <li><code>media_id</code> - string - The id used to refer to the media. Details about the format
  14106. are documented under
  14107. <a href="admin_api/../media_repository.html">media repository</a>.</li>
  14108. <li><code>media_length</code> - integer - Length of the media in bytes.</li>
  14109. <li><code>media_type</code> - string - The MIME-type of the media.</li>
  14110. <li><code>quarantined_by</code> - string - The user ID that initiated the quarantine request
  14111. for this media.</li>
  14112. <li><code>safe_from_quarantine</code> - bool - Status if this media is safe from quarantining.</li>
  14113. <li><code>upload_name</code> - string - The name the media was uploaded with.</li>
  14114. </ul>
  14115. </li>
  14116. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  14117. <li><code>total</code> - integer - Total number of media.</li>
  14118. </ul>
  14119. <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>
  14120. <p>This API deletes the <em>local</em> media from the disk of your own server
  14121. that a specific <code>user_id</code> has created. This includes any local thumbnails.</p>
  14122. <p>This API will not affect media that has been uploaded to external
  14123. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).</p>
  14124. <p>By default, the API deletes media ordered by descending creation date and ascending media ID.
  14125. The newest media is deleted first. You can change the order with parameters
  14126. <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>
  14127. <p>The API is:</p>
  14128. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/media
  14129. </code></pre>
  14130. <p>A response body like the following is returned:</p>
  14131. <pre><code class="language-json">{
  14132. &quot;deleted_media&quot;: [
  14133. &quot;abcdefghijklmnopqrstuvwx&quot;
  14134. ],
  14135. &quot;total&quot;: 1
  14136. }
  14137. </code></pre>
  14138. <p>The following fields are returned in the JSON response body:</p>
  14139. <ul>
  14140. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  14141. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  14142. </ul>
  14143. <p><strong>Note</strong>: There is no <code>next_token</code>. This is not useful for deleting media, because
  14144. after deleting media the remaining media have a new order.</p>
  14145. <p><strong>Parameters</strong></p>
  14146. <p>This API has the same parameters as
  14147. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>.
  14148. With the parameters you can for example limit the number of files to delete at once or
  14149. delete largest/smallest or newest/oldest files first.</p>
  14150. <h2 id="login-as-a-user"><a class="header" href="#login-as-a-user">Login as a user</a></h2>
  14151. <p>Get an access token that can be used to authenticate as that user. Useful for
  14152. when admins wish to do actions on behalf of a user.</p>
  14153. <p>The API is:</p>
  14154. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/login
  14155. {}
  14156. </code></pre>
  14157. <p>An optional <code>valid_until_ms</code> field can be specified in the request body as an
  14158. integer timestamp that specifies when the token should expire. By default tokens
  14159. do not expire. Note that this API does not allow a user to login as themselves
  14160. (to create more tokens).</p>
  14161. <p>A response body like the following is returned:</p>
  14162. <pre><code class="language-json">{
  14163. &quot;access_token&quot;: &quot;&lt;opaque_access_token_string&gt;&quot;
  14164. }
  14165. </code></pre>
  14166. <p>This API does <em>not</em> generate a new device for the user, and so will not appear
  14167. their <code>/devices</code> list, and in general the target user should not be able to
  14168. tell they have been logged in as.</p>
  14169. <p>To expire the token call the standard <code>/logout</code> API with the token.</p>
  14170. <p>Note: The token will expire if the <em>admin</em> user calls <code>/logout/all</code> from any
  14171. of their devices, but the token will <em>not</em> expire if the target user does the
  14172. same.</p>
  14173. <h2 id="user-devices"><a class="header" href="#user-devices">User devices</a></h2>
  14174. <h3 id="list-all-devices"><a class="header" href="#list-all-devices">List all devices</a></h3>
  14175. <p>Gets information about all devices for a specific <code>user_id</code>.</p>
  14176. <p>The API is:</p>
  14177. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  14178. </code></pre>
  14179. <p>A response body like the following is returned:</p>
  14180. <pre><code class="language-json">{
  14181. &quot;devices&quot;: [
  14182. {
  14183. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;,
  14184. &quot;display_name&quot;: &quot;android&quot;,
  14185. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  14186. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  14187. &quot;last_seen_ts&quot;: 1474491775024,
  14188. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  14189. },
  14190. {
  14191. &quot;device_id&quot;: &quot;AUIECTSRND&quot;,
  14192. &quot;display_name&quot;: &quot;ios&quot;,
  14193. &quot;last_seen_ip&quot;: &quot;1.2.3.5&quot;,
  14194. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  14195. &quot;last_seen_ts&quot;: 1474491775025,
  14196. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  14197. }
  14198. ],
  14199. &quot;total&quot;: 2
  14200. }
  14201. </code></pre>
  14202. <p><strong>Parameters</strong></p>
  14203. <p>The following parameters should be set in the URL:</p>
  14204. <ul>
  14205. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14206. </ul>
  14207. <p><strong>Response</strong></p>
  14208. <p>The following fields are returned in the JSON response body:</p>
  14209. <ul>
  14210. <li>
  14211. <p><code>devices</code> - An array of objects, each containing information about a device.
  14212. Device objects contain the following fields:</p>
  14213. <ul>
  14214. <li><code>device_id</code> - Identifier of device.</li>
  14215. <li><code>display_name</code> - Display name set by the user for this device.
  14216. Absent if no name has been set.</li>
  14217. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  14218. (May be a few minutes out of date, for efficiency reasons).</li>
  14219. <li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
  14220. (May be a few minutes out of date, for efficiency reasons).</li>
  14221. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  14222. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  14223. <li><code>user_id</code> - Owner of device.</li>
  14224. </ul>
  14225. </li>
  14226. <li>
  14227. <p><code>total</code> - Total number of user's devices.</p>
  14228. </li>
  14229. </ul>
  14230. <h3 id="create-a-device"><a class="header" href="#create-a-device">Create a device</a></h3>
  14231. <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>
  14232. exists already.</p>
  14233. <p>The API is:</p>
  14234. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  14235. {
  14236. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;
  14237. }
  14238. </code></pre>
  14239. <p>An empty JSON dict is returned.</p>
  14240. <p><strong>Parameters</strong></p>
  14241. <p>The following parameters should be set in the URL:</p>
  14242. <ul>
  14243. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14244. </ul>
  14245. <p>The following fields are required in the JSON request body:</p>
  14246. <ul>
  14247. <li><code>device_id</code> - The device ID to create.</li>
  14248. </ul>
  14249. <h3 id="delete-multiple-devices"><a class="header" href="#delete-multiple-devices">Delete multiple devices</a></h3>
  14250. <p>Deletes the given devices for a specific <code>user_id</code>, and invalidates
  14251. any access token associated with them.</p>
  14252. <p>The API is:</p>
  14253. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/delete_devices
  14254. {
  14255. &quot;devices&quot;: [
  14256. &quot;QBUAZIFURK&quot;,
  14257. &quot;AUIECTSRND&quot;
  14258. ]
  14259. }
  14260. </code></pre>
  14261. <p>An empty JSON dict is returned.</p>
  14262. <p><strong>Parameters</strong></p>
  14263. <p>The following parameters should be set in the URL:</p>
  14264. <ul>
  14265. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14266. </ul>
  14267. <p>The following fields are required in the JSON request body:</p>
  14268. <ul>
  14269. <li><code>devices</code> - The list of device IDs to delete.</li>
  14270. </ul>
  14271. <h3 id="show-a-device"><a class="header" href="#show-a-device">Show a device</a></h3>
  14272. <p>Gets information on a single device, by <code>device_id</code> for a specific <code>user_id</code>.</p>
  14273. <p>The API is:</p>
  14274. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  14275. </code></pre>
  14276. <p>A response body like the following is returned:</p>
  14277. <pre><code class="language-json">{
  14278. &quot;device_id&quot;: &quot;&lt;device_id&gt;&quot;,
  14279. &quot;display_name&quot;: &quot;android&quot;,
  14280. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  14281. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  14282. &quot;last_seen_ts&quot;: 1474491775024,
  14283. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  14284. }
  14285. </code></pre>
  14286. <p><strong>Parameters</strong></p>
  14287. <p>The following parameters should be set in the URL:</p>
  14288. <ul>
  14289. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14290. <li><code>device_id</code> - The device to retrieve.</li>
  14291. </ul>
  14292. <p><strong>Response</strong></p>
  14293. <p>The following fields are returned in the JSON response body:</p>
  14294. <ul>
  14295. <li><code>device_id</code> - Identifier of device.</li>
  14296. <li><code>display_name</code> - Display name set by the user for this device.
  14297. Absent if no name has been set.</li>
  14298. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  14299. (May be a few minutes out of date, for efficiency reasons).
  14300. <ul>
  14301. <li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
  14302. (May be a few minutes out of date, for efficiency reasons).</li>
  14303. </ul>
  14304. </li>
  14305. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  14306. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  14307. <li><code>user_id</code> - Owner of device.</li>
  14308. </ul>
  14309. <h3 id="update-a-device"><a class="header" href="#update-a-device">Update a device</a></h3>
  14310. <p>Updates the metadata on the given <code>device_id</code> for a specific <code>user_id</code>.</p>
  14311. <p>The API is:</p>
  14312. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  14313. {
  14314. &quot;display_name&quot;: &quot;My other phone&quot;
  14315. }
  14316. </code></pre>
  14317. <p>An empty JSON dict is returned.</p>
  14318. <p><strong>Parameters</strong></p>
  14319. <p>The following parameters should be set in the URL:</p>
  14320. <ul>
  14321. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14322. <li><code>device_id</code> - The device to update.</li>
  14323. </ul>
  14324. <p>The following fields are required in the JSON request body:</p>
  14325. <ul>
  14326. <li><code>display_name</code> - The new display name for this device. If not given,
  14327. the display name is unchanged.</li>
  14328. </ul>
  14329. <h3 id="delete-a-device"><a class="header" href="#delete-a-device">Delete a device</a></h3>
  14330. <p>Deletes the given <code>device_id</code> for a specific <code>user_id</code>,
  14331. and invalidates any access token associated with it.</p>
  14332. <p>The API is:</p>
  14333. <pre><code>DELETE /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  14334. {}
  14335. </code></pre>
  14336. <p>An empty JSON dict is returned.</p>
  14337. <p><strong>Parameters</strong></p>
  14338. <p>The following parameters should be set in the URL:</p>
  14339. <ul>
  14340. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14341. <li><code>device_id</code> - The device to delete.</li>
  14342. </ul>
  14343. <h2 id="list-all-pushers"><a class="header" href="#list-all-pushers">List all pushers</a></h2>
  14344. <p>Gets information about all pushers for a specific <code>user_id</code>.</p>
  14345. <p>The API is:</p>
  14346. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/pushers
  14347. </code></pre>
  14348. <p>A response body like the following is returned:</p>
  14349. <pre><code class="language-json">{
  14350. &quot;pushers&quot;: [
  14351. {
  14352. &quot;app_display_name&quot;:&quot;HTTP Push Notifications&quot;,
  14353. &quot;app_id&quot;:&quot;m.http&quot;,
  14354. &quot;data&quot;: {
  14355. &quot;url&quot;:&quot;example.com&quot;
  14356. },
  14357. &quot;device_display_name&quot;:&quot;pushy push&quot;,
  14358. &quot;kind&quot;:&quot;http&quot;,
  14359. &quot;lang&quot;:&quot;None&quot;,
  14360. &quot;profile_tag&quot;:&quot;&quot;,
  14361. &quot;pushkey&quot;:&quot;a@example.com&quot;
  14362. }
  14363. ],
  14364. &quot;total&quot;: 1
  14365. }
  14366. </code></pre>
  14367. <p><strong>Parameters</strong></p>
  14368. <p>The following parameters should be set in the URL:</p>
  14369. <ul>
  14370. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14371. </ul>
  14372. <p><strong>Response</strong></p>
  14373. <p>The following fields are returned in the JSON response body:</p>
  14374. <ul>
  14375. <li>
  14376. <p><code>pushers</code> - An array containing the current pushers for the user</p>
  14377. <ul>
  14378. <li>
  14379. <p><code>app_display_name</code> - string - A string that will allow the user to identify
  14380. what application owns this pusher.</p>
  14381. </li>
  14382. <li>
  14383. <p><code>app_id</code> - string - This is a reverse-DNS style identifier for the application.
  14384. Max length, 64 chars.</p>
  14385. </li>
  14386. <li>
  14387. <p><code>data</code> - A dictionary of information for the pusher implementation itself.</p>
  14388. <ul>
  14389. <li>
  14390. <p><code>url</code> - string - Required if <code>kind</code> is <code>http</code>. The URL to use to send
  14391. notifications to.</p>
  14392. </li>
  14393. <li>
  14394. <p><code>format</code> - string - The format to use when sending notifications to the
  14395. Push Gateway.</p>
  14396. </li>
  14397. </ul>
  14398. </li>
  14399. <li>
  14400. <p><code>device_display_name</code> - string - A string that will allow the user to identify
  14401. what device owns this pusher.</p>
  14402. </li>
  14403. <li>
  14404. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  14405. this pusher executes.</p>
  14406. </li>
  14407. <li>
  14408. <p><code>kind</code> - string - The kind of pusher. &quot;http&quot; is a pusher that sends HTTP pokes.</p>
  14409. </li>
  14410. <li>
  14411. <p><code>lang</code> - string - The preferred language for receiving notifications
  14412. (e.g. 'en' or 'en-US')</p>
  14413. </li>
  14414. <li>
  14415. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  14416. this pusher executes.</p>
  14417. </li>
  14418. <li>
  14419. <p><code>pushkey</code> - string - This is a unique identifier for this pusher.
  14420. Max length, 512 bytes.</p>
  14421. </li>
  14422. </ul>
  14423. </li>
  14424. <li>
  14425. <p><code>total</code> - integer - Number of pushers.</p>
  14426. </li>
  14427. </ul>
  14428. <p>See also the
  14429. <a href="https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushers">Client-Server API Spec on pushers</a>.</p>
  14430. <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>
  14431. <p>Shadow-banning is a useful tool for moderating malicious or egregiously abusive users.
  14432. A shadow-banned users receives successful responses to their client-server API requests,
  14433. but the events are not propagated into rooms. This can be an effective tool as it
  14434. (hopefully) takes longer for the user to realise they are being moderated before
  14435. pivoting to another account.</p>
  14436. <p>Shadow-banning a user should be used as a tool of last resort and may lead to confusing
  14437. or broken behaviour for the client. A shadow-banned user will not receive any
  14438. notification and it is generally more appropriate to ban or kick abusive users.
  14439. A shadow-banned user will be unable to contact anyone on the server.</p>
  14440. <p>To shadow-ban a user the API is:</p>
  14441. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  14442. </code></pre>
  14443. <p>To un-shadow-ban a user the API is:</p>
  14444. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  14445. </code></pre>
  14446. <p>An empty JSON dict is returned in both cases.</p>
  14447. <p><strong>Parameters</strong></p>
  14448. <p>The following parameters should be set in the URL:</p>
  14449. <ul>
  14450. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14451. be local.</li>
  14452. </ul>
  14453. <h2 id="override-ratelimiting-for-users"><a class="header" href="#override-ratelimiting-for-users">Override ratelimiting for users</a></h2>
  14454. <p>This API allows to override or disable ratelimiting for a specific user.
  14455. There are specific APIs to set, get and delete a ratelimit.</p>
  14456. <h3 id="get-status-of-ratelimit"><a class="header" href="#get-status-of-ratelimit">Get status of ratelimit</a></h3>
  14457. <p>The API is:</p>
  14458. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  14459. </code></pre>
  14460. <p>A response body like the following is returned:</p>
  14461. <pre><code class="language-json">{
  14462. &quot;messages_per_second&quot;: 0,
  14463. &quot;burst_count&quot;: 0
  14464. }
  14465. </code></pre>
  14466. <p><strong>Parameters</strong></p>
  14467. <p>The following parameters should be set in the URL:</p>
  14468. <ul>
  14469. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14470. be local.</li>
  14471. </ul>
  14472. <p><strong>Response</strong></p>
  14473. <p>The following fields are returned in the JSON response body:</p>
  14474. <ul>
  14475. <li><code>messages_per_second</code> - integer - The number of actions that can
  14476. be performed in a second. <code>0</code> mean that ratelimiting is disabled for this user.</li>
  14477. <li><code>burst_count</code> - integer - How many actions that can be performed before
  14478. being limited.</li>
  14479. </ul>
  14480. <p>If <strong>no</strong> custom ratelimit is set, an empty JSON dict is returned.</p>
  14481. <pre><code class="language-json">{}
  14482. </code></pre>
  14483. <h3 id="set-ratelimit"><a class="header" href="#set-ratelimit">Set ratelimit</a></h3>
  14484. <p>The API is:</p>
  14485. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  14486. </code></pre>
  14487. <p>A response body like the following is returned:</p>
  14488. <pre><code class="language-json">{
  14489. &quot;messages_per_second&quot;: 0,
  14490. &quot;burst_count&quot;: 0
  14491. }
  14492. </code></pre>
  14493. <p><strong>Parameters</strong></p>
  14494. <p>The following parameters should be set in the URL:</p>
  14495. <ul>
  14496. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14497. be local.</li>
  14498. </ul>
  14499. <p>Body parameters:</p>
  14500. <ul>
  14501. <li><code>messages_per_second</code> - positive integer, optional. The number of actions that can
  14502. be performed in a second. Defaults to <code>0</code>.</li>
  14503. <li><code>burst_count</code> - positive integer, optional. How many actions that can be performed
  14504. before being limited. Defaults to <code>0</code>.</li>
  14505. </ul>
  14506. <p>To disable users' ratelimit set both values to <code>0</code>.</p>
  14507. <p><strong>Response</strong></p>
  14508. <p>The following fields are returned in the JSON response body:</p>
  14509. <ul>
  14510. <li><code>messages_per_second</code> - integer - The number of actions that can
  14511. be performed in a second.</li>
  14512. <li><code>burst_count</code> - integer - How many actions that can be performed before
  14513. being limited.</li>
  14514. </ul>
  14515. <h3 id="delete-ratelimit"><a class="header" href="#delete-ratelimit">Delete ratelimit</a></h3>
  14516. <p>The API is:</p>
  14517. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  14518. </code></pre>
  14519. <p>An empty JSON dict is returned.</p>
  14520. <pre><code class="language-json">{}
  14521. </code></pre>
  14522. <p><strong>Parameters</strong></p>
  14523. <p>The following parameters should be set in the URL:</p>
  14524. <ul>
  14525. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14526. be local.</li>
  14527. </ul>
  14528. <h2 id="check-username-availability"><a class="header" href="#check-username-availability">Check username availability</a></h2>
  14529. <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
  14530. API</a>
  14531. for more information.</p>
  14532. <p>This endpoint will work even if registration is disabled on the server, unlike
  14533. <code>/_matrix/client/r0/register/available</code>.</p>
  14534. <p>The API is:</p>
  14535. <pre><code>GET /_synapse/admin/v1/username_available?username=$localpart
  14536. </code></pre>
  14537. <p>The request and response format is the same as the
  14538. <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>
  14539. <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>
  14540. <p>The API is:</p>
  14541. <pre><code>GET /_synapse/admin/v1/auth_providers/$provider/users/$external_id
  14542. </code></pre>
  14543. <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>
  14544. <pre><code class="language-json">{
  14545. &quot;user_id&quot;: &quot;@hello:example.org&quot;
  14546. }
  14547. </code></pre>
  14548. <p><strong>Parameters</strong></p>
  14549. <p>The following parameters should be set in the URL:</p>
  14550. <ul>
  14551. <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>
  14552. <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>
  14553. </ul>
  14554. <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>
  14555. <p><strong>Errors</strong></p>
  14556. <p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
  14557. <pre><code class="language-json">{
  14558. &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
  14559. &quot;error&quot;:&quot;User not found&quot;
  14560. }
  14561. </code></pre>
  14562. <p><em>Added in Synapse 1.68.0.</em></p>
  14563. <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>
  14564. <p>The API is:</p>
  14565. <pre><code>GET /_synapse/admin/v1/threepid/$medium/users/$address
  14566. </code></pre>
  14567. <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>
  14568. <pre><code class="language-json">{
  14569. &quot;user_id&quot;: &quot;@hello:example.org&quot;
  14570. }
  14571. </code></pre>
  14572. <p><strong>Parameters</strong></p>
  14573. <p>The following parameters should be set in the URL:</p>
  14574. <ul>
  14575. <li><code>medium</code> - Kind of third-party ID, either <code>email</code> or <code>msisdn</code>.</li>
  14576. <li><code>address</code> - Value of the third-party ID.</li>
  14577. </ul>
  14578. <p>The <code>address</code> may have characters that are not URL-safe, so it is advised to URL-encode those parameters.</p>
  14579. <p><strong>Errors</strong></p>
  14580. <p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
  14581. <pre><code class="language-json">{
  14582. &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
  14583. &quot;error&quot;:&quot;User not found&quot;
  14584. }
  14585. </code></pre>
  14586. <p><em>Added in Synapse 1.72.0.</em></p>
  14587. <div style="break-before: page; page-break-before: always;"></div><h1 id="version-api"><a class="header" href="#version-api">Version API</a></h1>
  14588. <p>This API returns the running Synapse version and the Python version
  14589. on which Synapse is being run. This is useful when a Synapse instance
  14590. is behind a proxy that does not forward the 'Server' header (which also
  14591. contains Synapse version information).</p>
  14592. <p>The api is:</p>
  14593. <pre><code>GET /_synapse/admin/v1/server_version
  14594. </code></pre>
  14595. <p>It returns a JSON body like the following:</p>
  14596. <pre><code class="language-json">{
  14597. &quot;server_version&quot;: &quot;0.99.2rc1 (b=develop, abcdef123)&quot;,
  14598. &quot;python_version&quot;: &quot;3.7.8&quot;
  14599. }
  14600. </code></pre>
  14601. <div style="break-before: page; page-break-before: always;"></div><h1 id="federation-api"><a class="header" href="#federation-api">Federation API</a></h1>
  14602. <p>This API allows a server administrator to manage Synapse's federation with other homeservers.</p>
  14603. <p>Note: This API is new, experimental and &quot;subject to change&quot;.</p>
  14604. <h2 id="list-of-destinations"><a class="header" href="#list-of-destinations">List of destinations</a></h2>
  14605. <p>This API gets the current destination retry timing info for all remote servers.</p>
  14606. <p>The list contains all the servers with which the server federates,
  14607. regardless of whether an error occurred or not.
  14608. If an error occurs, it may take up to 20 minutes for the error to be displayed here,
  14609. as a complete retry must have failed.</p>
  14610. <p>The API is:</p>
  14611. <p>A standard request with no filtering:</p>
  14612. <pre><code>GET /_synapse/admin/v1/federation/destinations
  14613. </code></pre>
  14614. <p>A response body like the following is returned:</p>
  14615. <pre><code class="language-json">{
  14616. &quot;destinations&quot;:[
  14617. {
  14618. &quot;destination&quot;: &quot;matrix.org&quot;,
  14619. &quot;retry_last_ts&quot;: 1557332397936,
  14620. &quot;retry_interval&quot;: 3000000,
  14621. &quot;failure_ts&quot;: 1557329397936,
  14622. &quot;last_successful_stream_ordering&quot;: null
  14623. }
  14624. ],
  14625. &quot;total&quot;: 1
  14626. }
  14627. </code></pre>
  14628. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  14629. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  14630. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  14631. to paginate through.</p>
  14632. <p><strong>Parameters</strong></p>
  14633. <p>The following query parameters are available:</p>
  14634. <ul>
  14635. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  14636. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  14637. <li><code>order_by</code> - The method in which to sort the returned list of destinations.
  14638. Valid values are:
  14639. <ul>
  14640. <li><code>destination</code> - Destinations are ordered alphabetically by remote server name.
  14641. This is the default.</li>
  14642. <li><code>retry_last_ts</code> - Destinations are ordered by time of last retry attempt in ms.</li>
  14643. <li><code>retry_interval</code> - Destinations are ordered by how long until next retry in ms.</li>
  14644. <li><code>failure_ts</code> - Destinations are ordered by when the server started failing in ms.</li>
  14645. <li><code>last_successful_stream_ordering</code> - Destinations are ordered by the stream ordering
  14646. of the most recent successfully-sent PDU.</li>
  14647. </ul>
  14648. </li>
  14649. <li><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  14650. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  14651. </ul>
  14652. <p><em>Caution:</em> The database only has an index on the column <code>destination</code>.
  14653. This means that if a different sort order is used,
  14654. this can cause a large load on the database, especially for large environments.</p>
  14655. <p><strong>Response</strong></p>
  14656. <p>The following fields are returned in the JSON response body:</p>
  14657. <ul>
  14658. <li><code>destinations</code> - An array of objects, each containing information about a destination.
  14659. Destination objects contain the following fields:
  14660. <ul>
  14661. <li><code>destination</code> - string - Name of the remote server to federate.</li>
  14662. <li><code>retry_last_ts</code> - integer - The last time Synapse tried and failed to reach the
  14663. remote server, in ms. This is <code>0</code> if the last attempt to communicate with the
  14664. remote server was successful.</li>
  14665. <li><code>retry_interval</code> - integer - How long since the last time Synapse tried to reach
  14666. the remote server before trying again, in ms. This is <code>0</code> if no further retrying occuring.</li>
  14667. <li><code>failure_ts</code> - nullable integer - The first time Synapse tried and failed to reach the
  14668. remote server, in ms. This is <code>null</code> if communication with the remote server has never failed.</li>
  14669. <li><code>last_successful_stream_ordering</code> - nullable integer - The stream ordering of the most
  14670. recent successfully-sent <a href="usage/administration/admin_api/../understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  14671. to this destination, or <code>null</code> if this information has not been tracked yet.</li>
  14672. </ul>
  14673. </li>
  14674. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  14675. <li><code>total</code> - integer - Total number of destinations.</li>
  14676. </ul>
  14677. <h2 id="destination-details-api"><a class="header" href="#destination-details-api">Destination Details API</a></h2>
  14678. <p>This API gets the retry timing info for a specific remote server.</p>
  14679. <p>The API is:</p>
  14680. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;
  14681. </code></pre>
  14682. <p>A response body like the following is returned:</p>
  14683. <pre><code class="language-json">{
  14684. &quot;destination&quot;: &quot;matrix.org&quot;,
  14685. &quot;retry_last_ts&quot;: 1557332397936,
  14686. &quot;retry_interval&quot;: 3000000,
  14687. &quot;failure_ts&quot;: 1557329397936,
  14688. &quot;last_successful_stream_ordering&quot;: null
  14689. }
  14690. </code></pre>
  14691. <p><strong>Parameters</strong></p>
  14692. <p>The following parameters should be set in the URL:</p>
  14693. <ul>
  14694. <li><code>destination</code> - Name of the remote server.</li>
  14695. </ul>
  14696. <p><strong>Response</strong></p>
  14697. <p>The response fields are the same like in the <code>destinations</code> array in
  14698. <a href="usage/administration/admin_api/federation.html#list-of-destinations">List of destinations</a> response.</p>
  14699. <h2 id="destination-rooms"><a class="header" href="#destination-rooms">Destination rooms</a></h2>
  14700. <p>This API gets the rooms that federate with a specific remote server.</p>
  14701. <p>The API is:</p>
  14702. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/rooms
  14703. </code></pre>
  14704. <p>A response body like the following is returned:</p>
  14705. <pre><code class="language-json">{
  14706. &quot;rooms&quot;:[
  14707. {
  14708. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  14709. &quot;stream_ordering&quot;: 8326
  14710. },
  14711. {
  14712. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  14713. &quot;stream_ordering&quot;: 93534
  14714. }
  14715. ],
  14716. &quot;total&quot;: 2
  14717. }
  14718. </code></pre>
  14719. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  14720. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  14721. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  14722. to paginate through.</p>
  14723. <p><strong>Parameters</strong></p>
  14724. <p>The following parameters should be set in the URL:</p>
  14725. <ul>
  14726. <li><code>destination</code> - Name of the remote server.</li>
  14727. </ul>
  14728. <p>The following query parameters are available:</p>
  14729. <ul>
  14730. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  14731. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  14732. <li><code>dir</code> - Direction of room order by <code>room_id</code>. Either <code>f</code> for forwards or <code>b</code> for
  14733. backwards. Defaults to <code>f</code>.</li>
  14734. </ul>
  14735. <p><strong>Response</strong></p>
  14736. <p>The following fields are returned in the JSON response body:</p>
  14737. <ul>
  14738. <li><code>rooms</code> - An array of objects, each containing information about a room.
  14739. Room objects contain the following fields:
  14740. <ul>
  14741. <li><code>room_id</code> - string - The ID of the room.</li>
  14742. <li><code>stream_ordering</code> - integer - The stream ordering of the most recent
  14743. successfully-sent <a href="usage/administration/admin_api/../understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  14744. to this destination in this room.</li>
  14745. </ul>
  14746. </li>
  14747. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  14748. <li><code>total</code> - integer - Total number of destinations.</li>
  14749. </ul>
  14750. <h2 id="reset-connection-timeout"><a class="header" href="#reset-connection-timeout">Reset connection timeout</a></h2>
  14751. <p>Synapse makes federation requests to other homeservers. If a federation request fails,
  14752. Synapse will mark the destination homeserver as offline, preventing any future requests
  14753. to that server for a &quot;cooldown&quot; period. This period grows over time if the server
  14754. continues to fail its responses
  14755. (<a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>).</p>
  14756. <p>Admins can cancel the cooldown period with this API.</p>
  14757. <p>This API resets the retry timing for a specific remote server and tries to connect to
  14758. the remote server again. It does not wait for the next <code>retry_interval</code>.
  14759. The connection must have previously run into an error and <code>retry_last_ts</code>
  14760. (<a href="usage/administration/admin_api/federation.html#destination-details-api">Destination Details API</a>) must not be equal to <code>0</code>.</p>
  14761. <p>The connection attempt is carried out in the background and can take a while
  14762. even if the API already returns the http status 200.</p>
  14763. <p>The API is:</p>
  14764. <pre><code>POST /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/reset_connection
  14765. {}
  14766. </code></pre>
  14767. <p><strong>Parameters</strong></p>
  14768. <p>The following parameters should be set in the URL:</p>
  14769. <ul>
  14770. <li><code>destination</code> - Name of the remote server.</li>
  14771. </ul>
  14772. <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>
  14773. <p>The &quot;manhole&quot; allows server administrators to access a Python shell on a running
  14774. Synapse installation. This is a very powerful mechanism for administration and
  14775. debugging.</p>
  14776. <p><strong><em>Security Warning</em></strong></p>
  14777. <p>Note that this will give administrative access to synapse to <strong>all users</strong> with
  14778. shell access to the server. It should therefore <strong>not</strong> be enabled in
  14779. environments where untrusted users have shell access.</p>
  14780. <h2 id="configuring-the-manhole"><a class="header" href="#configuring-the-manhole">Configuring the manhole</a></h2>
  14781. <p>To enable it, first add the <code>manhole</code> listener configuration in your
  14782. <code>homeserver.yaml</code>. You can find information on how to do that
  14783. in the <a href="usage/configuration/config_documentation.html#manhole_settings">configuration manual</a>.
  14784. The configuration is slightly different if you're using docker.</p>
  14785. <h4 id="docker-config"><a class="header" href="#docker-config">Docker config</a></h4>
  14786. <p>If you are using Docker, set <code>bind_addresses</code> to <code>['0.0.0.0']</code> as shown:</p>
  14787. <pre><code class="language-yaml">listeners:
  14788. - port: 9000
  14789. bind_addresses: ['0.0.0.0']
  14790. type: manhole
  14791. </code></pre>
  14792. <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
  14793. <code>manhole</code> port forwarding. The <code>-p 127.0.0.1:9000:9000</code> below is important: it
  14794. ensures that access to the <code>manhole</code> is only possible for local users.</p>
  14795. <pre><code class="language-bash">docker run -d --name synapse \
  14796. --mount type=volume,src=synapse-data,dst=/data \
  14797. -p 8008:8008 \
  14798. -p 127.0.0.1:9000:9000 \
  14799. matrixdotorg/synapse:latest
  14800. </code></pre>
  14801. <h4 id="native-config"><a class="header" href="#native-config">Native config</a></h4>
  14802. <p>If you are not using docker, set <code>bind_addresses</code> to <code>['::1', '127.0.0.1']</code> as shown.
  14803. The <code>bind_addresses</code> in the example below is important: it ensures that access to the
  14804. <code>manhole</code> is only possible for local users).</p>
  14805. <pre><code class="language-yaml">listeners:
  14806. - port: 9000
  14807. bind_addresses: ['::1', '127.0.0.1']
  14808. type: manhole
  14809. </code></pre>
  14810. <h3 id="security-settings"><a class="header" href="#security-settings">Security settings</a></h3>
  14811. <p>The following config options are available:</p>
  14812. <ul>
  14813. <li><code>username</code> - The username for the manhole (defaults to <code>matrix</code>)</li>
  14814. <li><code>password</code> - The password for the manhole (defaults to <code>rabbithole</code>)</li>
  14815. <li><code>ssh_priv_key</code> - The path to a private SSH key (defaults to a hardcoded value)</li>
  14816. <li><code>ssh_pub_key</code> - The path to a public SSH key (defaults to a hardcoded value)</li>
  14817. </ul>
  14818. <p>For example:</p>
  14819. <pre><code class="language-yaml">manhole_settings:
  14820. username: manhole
  14821. password: mypassword
  14822. ssh_priv_key: &quot;/home/synapse/manhole_keys/id_rsa&quot;
  14823. ssh_pub_key: &quot;/home/synapse/manhole_keys/id_rsa.pub&quot;
  14824. </code></pre>
  14825. <h2 id="accessing-synapse-manhole"><a class="header" href="#accessing-synapse-manhole">Accessing synapse manhole</a></h2>
  14826. <p>Then restart synapse, and point an ssh client at port 9000 on localhost, using
  14827. the username and password configured in <code>homeserver.yaml</code> - with the default
  14828. configuration, this would be:</p>
  14829. <pre><code class="language-bash">ssh -p9000 matrix@localhost
  14830. </code></pre>
  14831. <p>Then enter the password when prompted (the default is <code>rabbithole</code>).</p>
  14832. <p>This gives a Python REPL in which <code>hs</code> gives access to the
  14833. <code>synapse.server.HomeServer</code> object - which in turn gives access to many other
  14834. parts of the process.</p>
  14835. <p>Note that, prior to Synapse 1.41, any call which returns a coroutine will need to be wrapped in <code>ensureDeferred</code>.</p>
  14836. <p>As a simple example, retrieving an event from the database:</p>
  14837. <pre><code class="language-pycon">&gt;&gt;&gt; from twisted.internet import defer
  14838. &gt;&gt;&gt; defer.ensureDeferred(hs.get_datastores().main.get_event('$1416420717069yeQaw:matrix.org'))
  14839. &lt;Deferred at 0x7ff253fc6998 current result: &lt;FrozenEvent event_id='$1416420717069yeQaw:matrix.org', type='m.room.create', state_key=''&gt;&gt;
  14840. </code></pre>
  14841. <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>
  14842. <ol>
  14843. <li>
  14844. <p>Install Prometheus:</p>
  14845. <p>Follow instructions at
  14846. <a href="http://prometheus.io/docs/introduction/install/">http://prometheus.io/docs/introduction/install/</a></p>
  14847. </li>
  14848. <li>
  14849. <p>Enable Synapse metrics:</p>
  14850. <p>In <code>homeserver.yaml</code>, make sure <code>enable_metrics</code> is
  14851. set to <code>True</code>.</p>
  14852. </li>
  14853. <li>
  14854. <p>Enable the <code>/_synapse/metrics</code> Synapse endpoint that Prometheus uses to
  14855. collect data:</p>
  14856. <p>There are two methods of enabling the metrics endpoint in Synapse.</p>
  14857. <p>The first serves the metrics as a part of the usual web server and
  14858. can be enabled by adding the <code>metrics</code> resource to the existing
  14859. listener as such as in this example:</p>
  14860. <pre><code class="language-yaml">listeners:
  14861. - port: 8008
  14862. tls: false
  14863. type: http
  14864. x_forwarded: true
  14865. bind_addresses: ['::1', '127.0.0.1']
  14866. resources:
  14867. # added &quot;metrics&quot; in this line
  14868. - names: [client, federation, metrics]
  14869. compress: false
  14870. </code></pre>
  14871. <p>This provides a simple way of adding metrics to your Synapse
  14872. installation, and serves under <code>/_synapse/metrics</code>. If you do not
  14873. wish your metrics be publicly exposed, you will need to either
  14874. filter it out at your load balancer, or use the second method.</p>
  14875. <p>The second method runs the metrics server on a different port, in a
  14876. different thread to Synapse. This can make it more resilient to
  14877. heavy load meaning metrics cannot be retrieved, and can be exposed
  14878. to just internal networks easier. The served metrics are available
  14879. over HTTP only, and will be available at <code>/_synapse/metrics</code>.</p>
  14880. <p>Add a new listener to homeserver.yaml as in this example:</p>
  14881. <pre><code class="language-yaml">listeners:
  14882. - port: 8008
  14883. tls: false
  14884. type: http
  14885. x_forwarded: true
  14886. bind_addresses: ['::1', '127.0.0.1']
  14887. resources:
  14888. - names: [client, federation]
  14889. compress: false
  14890. # beginning of the new metrics listener
  14891. - port: 9000
  14892. type: metrics
  14893. bind_addresses: ['::1', '127.0.0.1']
  14894. </code></pre>
  14895. </li>
  14896. <li>
  14897. <p>Restart Synapse.</p>
  14898. </li>
  14899. <li>
  14900. <p>Add a Prometheus target for Synapse.</p>
  14901. <p>It needs to set the <code>metrics_path</code> to a non-default value (under
  14902. <code>scrape_configs</code>):</p>
  14903. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  14904. scrape_interval: 15s
  14905. metrics_path: &quot;/_synapse/metrics&quot;
  14906. static_configs:
  14907. - targets: [&quot;my.server.here:port&quot;]
  14908. </code></pre>
  14909. <p>where <code>my.server.here</code> is the IP address of Synapse, and <code>port</code> is
  14910. the listener port configured with the <code>metrics</code> resource.</p>
  14911. <p>If your prometheus is older than 1.5.2, you will need to replace
  14912. <code>static_configs</code> in the above with <code>target_groups</code>.</p>
  14913. </li>
  14914. <li>
  14915. <p>Restart Prometheus.</p>
  14916. </li>
  14917. <li>
  14918. <p>Consider using the <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana/">grafana dashboard</a>
  14919. and required <a href="https://github.com/matrix-org/synapse/tree/master/contrib/prometheus/">recording rules</a> </p>
  14920. </li>
  14921. </ol>
  14922. <h2 id="monitoring-workers"><a class="header" href="#monitoring-workers">Monitoring workers</a></h2>
  14923. <p>To monitor a Synapse installation using <a href="workers.html">workers</a>,
  14924. every worker needs to be monitored independently, in addition to
  14925. the main homeserver process. This is because workers don't send
  14926. their metrics to the main homeserver process, but expose them
  14927. directly (if they are configured to do so).</p>
  14928. <p>To allow collecting metrics from a worker, you need to add a
  14929. <code>metrics</code> listener to its configuration, by adding the following
  14930. under <code>worker_listeners</code>:</p>
  14931. <pre><code class="language-yaml"> - type: metrics
  14932. bind_address: ''
  14933. port: 9101
  14934. </code></pre>
  14935. <p>The <code>bind_address</code> and <code>port</code> parameters should be set so that
  14936. the resulting listener can be reached by prometheus, and they
  14937. don't clash with an existing worker.
  14938. With this example, the worker's metrics would then be available
  14939. on <code>http://127.0.0.1:9101</code>.</p>
  14940. <p>Example Prometheus target for Synapse with workers:</p>
  14941. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  14942. scrape_interval: 15s
  14943. metrics_path: &quot;/_synapse/metrics&quot;
  14944. static_configs:
  14945. - targets: [&quot;my.server.here:port&quot;]
  14946. labels:
  14947. instance: &quot;my.server&quot;
  14948. job: &quot;master&quot;
  14949. index: 1
  14950. - targets: [&quot;my.workerserver.here:port&quot;]
  14951. labels:
  14952. instance: &quot;my.server&quot;
  14953. job: &quot;generic_worker&quot;
  14954. index: 1
  14955. - targets: [&quot;my.workerserver.here:port&quot;]
  14956. labels:
  14957. instance: &quot;my.server&quot;
  14958. job: &quot;generic_worker&quot;
  14959. index: 2
  14960. - targets: [&quot;my.workerserver.here:port&quot;]
  14961. labels:
  14962. instance: &quot;my.server&quot;
  14963. job: &quot;media_repository&quot;
  14964. index: 1
  14965. </code></pre>
  14966. <p>Labels (<code>instance</code>, <code>job</code>, <code>index</code>) can be defined as anything.
  14967. The labels are used to group graphs in grafana.</p>
  14968. <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>
  14969. <p>Synapse 1.2 updates the Prometheus metrics to match the naming
  14970. convention of the upstream <code>prometheus_client</code>. The old names are
  14971. considered deprecated and will be removed in a future version of
  14972. Synapse.
  14973. <strong>The old names will be disabled by default in Synapse v1.71.0 and removed
  14974. altogether in Synapse v1.73.0.</strong></p>
  14975. <table><thead><tr><th>New Name</th><th>Old Name</th></tr></thead><tbody>
  14976. <tr><td>python_gc_objects_collected_total</td><td>python_gc_objects_collected</td></tr>
  14977. <tr><td>python_gc_objects_uncollectable_total</td><td>python_gc_objects_uncollectable</td></tr>
  14978. <tr><td>python_gc_collections_total</td><td>python_gc_collections</td></tr>
  14979. <tr><td>process_cpu_seconds_total</td><td>process_cpu_seconds</td></tr>
  14980. <tr><td>synapse_federation_client_sent_transactions_total</td><td>synapse_federation_client_sent_transactions</td></tr>
  14981. <tr><td>synapse_federation_client_events_processed_total</td><td>synapse_federation_client_events_processed</td></tr>
  14982. <tr><td>synapse_event_processing_loop_count_total</td><td>synapse_event_processing_loop_count</td></tr>
  14983. <tr><td>synapse_event_processing_loop_room_count_total</td><td>synapse_event_processing_loop_room_count</td></tr>
  14984. <tr><td>synapse_util_caches_cache_hits</td><td>synapse_util_caches_cache:hits</td></tr>
  14985. <tr><td>synapse_util_caches_cache_size</td><td>synapse_util_caches_cache:size</td></tr>
  14986. <tr><td>synapse_util_caches_cache_evicted_size</td><td>synapse_util_caches_cache:evicted_size</td></tr>
  14987. <tr><td>synapse_util_caches_cache</td><td>synapse_util_caches_cache:total</td></tr>
  14988. <tr><td>synapse_util_caches_response_cache_size</td><td>synapse_util_caches_response_cache:size</td></tr>
  14989. <tr><td>synapse_util_caches_response_cache_hits</td><td>synapse_util_caches_response_cache:hits</td></tr>
  14990. <tr><td>synapse_util_caches_response_cache_evicted_size</td><td>synapse_util_caches_response_cache:evicted_size</td></tr>
  14991. <tr><td>synapse_util_metrics_block_count_total</td><td>synapse_util_metrics_block_count</td></tr>
  14992. <tr><td>synapse_util_metrics_block_time_seconds_total</td><td>synapse_util_metrics_block_time_seconds</td></tr>
  14993. <tr><td>synapse_util_metrics_block_ru_utime_seconds_total</td><td>synapse_util_metrics_block_ru_utime_seconds</td></tr>
  14994. <tr><td>synapse_util_metrics_block_ru_stime_seconds_total</td><td>synapse_util_metrics_block_ru_stime_seconds</td></tr>
  14995. <tr><td>synapse_util_metrics_block_db_txn_count_total</td><td>synapse_util_metrics_block_db_txn_count</td></tr>
  14996. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds_total</td><td>synapse_util_metrics_block_db_txn_duration_seconds</td></tr>
  14997. <tr><td>synapse_util_metrics_block_db_sched_duration_seconds_total</td><td>synapse_util_metrics_block_db_sched_duration_seconds</td></tr>
  14998. <tr><td>synapse_background_process_start_count_total</td><td>synapse_background_process_start_count</td></tr>
  14999. <tr><td>synapse_background_process_ru_utime_seconds_total</td><td>synapse_background_process_ru_utime_seconds</td></tr>
  15000. <tr><td>synapse_background_process_ru_stime_seconds_total</td><td>synapse_background_process_ru_stime_seconds</td></tr>
  15001. <tr><td>synapse_background_process_db_txn_count_total</td><td>synapse_background_process_db_txn_count</td></tr>
  15002. <tr><td>synapse_background_process_db_txn_duration_seconds_total</td><td>synapse_background_process_db_txn_duration_seconds</td></tr>
  15003. <tr><td>synapse_background_process_db_sched_duration_seconds_total</td><td>synapse_background_process_db_sched_duration_seconds</td></tr>
  15004. <tr><td>synapse_storage_events_persisted_events_total</td><td>synapse_storage_events_persisted_events</td></tr>
  15005. <tr><td>synapse_storage_events_persisted_events_sep_total</td><td>synapse_storage_events_persisted_events_sep</td></tr>
  15006. <tr><td>synapse_storage_events_state_delta_total</td><td>synapse_storage_events_state_delta</td></tr>
  15007. <tr><td>synapse_storage_events_state_delta_single_event_total</td><td>synapse_storage_events_state_delta_single_event</td></tr>
  15008. <tr><td>synapse_storage_events_state_delta_reuse_delta_total</td><td>synapse_storage_events_state_delta_reuse_delta</td></tr>
  15009. <tr><td>synapse_federation_server_received_pdus_total</td><td>synapse_federation_server_received_pdus</td></tr>
  15010. <tr><td>synapse_federation_server_received_edus_total</td><td>synapse_federation_server_received_edus</td></tr>
  15011. <tr><td>synapse_handler_presence_notified_presence_total</td><td>synapse_handler_presence_notified_presence</td></tr>
  15012. <tr><td>synapse_handler_presence_federation_presence_out_total</td><td>synapse_handler_presence_federation_presence_out</td></tr>
  15013. <tr><td>synapse_handler_presence_presence_updates_total</td><td>synapse_handler_presence_presence_updates</td></tr>
  15014. <tr><td>synapse_handler_presence_timers_fired_total</td><td>synapse_handler_presence_timers_fired</td></tr>
  15015. <tr><td>synapse_handler_presence_federation_presence_total</td><td>synapse_handler_presence_federation_presence</td></tr>
  15016. <tr><td>synapse_handler_presence_bump_active_time_total</td><td>synapse_handler_presence_bump_active_time</td></tr>
  15017. <tr><td>synapse_federation_client_sent_edus_total</td><td>synapse_federation_client_sent_edus</td></tr>
  15018. <tr><td>synapse_federation_client_sent_pdu_destinations_count_total</td><td>synapse_federation_client_sent_pdu_destinations:count</td></tr>
  15019. <tr><td>synapse_federation_client_sent_pdu_destinations_total</td><td>synapse_federation_client_sent_pdu_destinations:total</td></tr>
  15020. <tr><td>synapse_handlers_appservice_events_processed_total</td><td>synapse_handlers_appservice_events_processed</td></tr>
  15021. <tr><td>synapse_notifier_notified_events_total</td><td>synapse_notifier_notified_events</td></tr>
  15022. <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>
  15023. <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>
  15024. <tr><td>synapse_http_httppusher_http_pushes_processed_total</td><td>synapse_http_httppusher_http_pushes_processed</td></tr>
  15025. <tr><td>synapse_http_httppusher_http_pushes_failed_total</td><td>synapse_http_httppusher_http_pushes_failed</td></tr>
  15026. <tr><td>synapse_http_httppusher_badge_updates_processed_total</td><td>synapse_http_httppusher_badge_updates_processed</td></tr>
  15027. <tr><td>synapse_http_httppusher_badge_updates_failed_total</td><td>synapse_http_httppusher_badge_updates_failed</td></tr>
  15028. <tr><td>synapse_admin_mau_current</td><td>synapse_admin_mau:current</td></tr>
  15029. <tr><td>synapse_admin_mau_max</td><td>synapse_admin_mau:max</td></tr>
  15030. <tr><td>synapse_admin_mau_registered_reserved_users</td><td>synapse_admin_mau:registered_reserved_users</td></tr>
  15031. </tbody></table>
  15032. <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>
  15033. <p>The duplicated metrics deprecated in Synapse 0.27.0 have been removed.</p>
  15034. <p>All time duration-based metrics have been changed to be seconds. This
  15035. affects:</p>
  15036. <table><thead><tr><th>msec -&gt; sec metrics</th></tr></thead><tbody>
  15037. <tr><td>python_gc_time</td></tr>
  15038. <tr><td>python_twisted_reactor_tick_time</td></tr>
  15039. <tr><td>synapse_storage_query_time</td></tr>
  15040. <tr><td>synapse_storage_schedule_time</td></tr>
  15041. <tr><td>synapse_storage_transaction_time</td></tr>
  15042. </tbody></table>
  15043. <p>Several metrics have been changed to be histograms, which sort entries
  15044. into buckets and allow better analysis. The following metrics are now
  15045. histograms:</p>
  15046. <table><thead><tr><th>Altered metrics</th></tr></thead><tbody>
  15047. <tr><td>python_gc_time</td></tr>
  15048. <tr><td>python_twisted_reactor_pending_calls</td></tr>
  15049. <tr><td>python_twisted_reactor_tick_time</td></tr>
  15050. <tr><td>synapse_http_server_response_time_seconds</td></tr>
  15051. <tr><td>synapse_storage_query_time</td></tr>
  15052. <tr><td>synapse_storage_schedule_time</td></tr>
  15053. <tr><td>synapse_storage_transaction_time</td></tr>
  15054. </tbody></table>
  15055. <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>
  15056. <p>Synapse 0.27.0 begins the process of rationalising the duplicate
  15057. <code>*:count</code> metrics reported for the resource tracking for code blocks and
  15058. HTTP requests.</p>
  15059. <p>At the same time, the corresponding <code>*:total</code> metrics are being renamed,
  15060. as the <code>:total</code> suffix no longer makes sense in the absence of a
  15061. corresponding <code>:count</code> metric.</p>
  15062. <p>To enable a graceful migration path, this release just adds new names
  15063. for the metrics being renamed. A future release will remove the old
  15064. ones.</p>
  15065. <p>The following table shows the new metrics, and the old metrics which
  15066. they are replacing.</p>
  15067. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15068. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_timer:count</td></tr>
  15069. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_utime:count</td></tr>
  15070. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_stime:count</td></tr>
  15071. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_count:count</td></tr>
  15072. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_duration:count</td></tr>
  15073. <tr><td>synapse_util_metrics_block_time_seconds</td><td>synapse_util_metrics_block_timer:total</td></tr>
  15074. <tr><td>synapse_util_metrics_block_ru_utime_seconds</td><td>synapse_util_metrics_block_ru_utime:total</td></tr>
  15075. <tr><td>synapse_util_metrics_block_ru_stime_seconds</td><td>synapse_util_metrics_block_ru_stime:total</td></tr>
  15076. <tr><td>synapse_util_metrics_block_db_txn_count</td><td>synapse_util_metrics_block_db_txn_count:total</td></tr>
  15077. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds</td><td>synapse_util_metrics_block_db_txn_duration:total</td></tr>
  15078. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_requests</td></tr>
  15079. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_time:count</td></tr>
  15080. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_utime:count</td></tr>
  15081. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_stime:count</td></tr>
  15082. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_count:count</td></tr>
  15083. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_duration:count</td></tr>
  15084. <tr><td>synapse_http_server_response_time_seconds</td><td>synapse_http_server_response_time:total</td></tr>
  15085. <tr><td>synapse_http_server_response_ru_utime_seconds</td><td>synapse_http_server_response_ru_utime:total</td></tr>
  15086. <tr><td>synapse_http_server_response_ru_stime_seconds</td><td>synapse_http_server_response_ru_stime:total</td></tr>
  15087. <tr><td>synapse_http_server_response_db_txn_count</td><td>synapse_http_server_response_db_txn_count:total</td></tr>
  15088. <tr><td>synapse_http_server_response_db_txn_duration_seconds</td><td>synapse_http_server_response_db_txn_duration:total</td></tr>
  15089. </tbody></table>
  15090. <h2 id="standard-metric-names"><a class="header" href="#standard-metric-names">Standard Metric Names</a></h2>
  15091. <p>As of synapse version 0.18.2, the format of the process-wide metrics has
  15092. been changed to fit prometheus standard naming conventions. Additionally
  15093. the units have been changed to seconds, from milliseconds.</p>
  15094. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15095. <tr><td>process_cpu_user_seconds_total</td><td>process_resource_utime / 1000</td></tr>
  15096. <tr><td>process_cpu_system_seconds_total</td><td>process_resource_stime / 1000</td></tr>
  15097. <tr><td>process_open_fds (no 'type' label)</td><td>process_fds</td></tr>
  15098. </tbody></table>
  15099. <p>The python-specific counts of garbage collector performance have been
  15100. renamed.</p>
  15101. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15102. <tr><td>python_gc_time</td><td>reactor_gc_time</td></tr>
  15103. <tr><td>python_gc_unreachable_total</td><td>reactor_gc_unreachable</td></tr>
  15104. <tr><td>python_gc_counts</td><td>reactor_gc_counts</td></tr>
  15105. </tbody></table>
  15106. <p>The twisted-specific reactor metrics have been renamed.</p>
  15107. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15108. <tr><td>python_twisted_reactor_pending_calls</td><td>reactor_pending_calls</td></tr>
  15109. <tr><td>python_twisted_reactor_tick_time</td><td>reactor_tick_time</td></tr>
  15110. </tbody></table>
  15111. <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>
  15112. <p>When generating your Synapse configuration file, you are asked whether you
  15113. would like to report usage statistics to Matrix.org. These statistics
  15114. provide the foundation a glimpse into the number of Synapse homeservers
  15115. participating in the network, as well as statistics such as the number of
  15116. rooms being created and messages being sent. This feature is sometimes
  15117. affectionately called &quot;phone home&quot; stats. Reporting
  15118. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats">is optional</a>
  15119. and the reporting endpoint
  15120. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint">can be configured</a>,
  15121. in case you would like to instead report statistics from a set of homeservers
  15122. to your own infrastructure.</p>
  15123. <p>This documentation aims to define the statistics available and the
  15124. homeserver configuration options that exist to tweak it.</p>
  15125. <h2 id="available-statistics"><a class="header" href="#available-statistics">Available Statistics</a></h2>
  15126. <p>The following statistics are sent to the configured reporting endpoint:</p>
  15127. <table><thead><tr><th>Statistic Name</th><th>Type</th><th>Description</th></tr></thead><tbody>
  15128. <tr><td><code>homeserver</code></td><td>string</td><td>The homeserver's server name.</td></tr>
  15129. <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>
  15130. <tr><td><code>cpu_average</code></td><td>int</td><td>CPU time in % of a single core (not % of all cores).</td></tr>
  15131. <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>
  15132. <tr><td><code>timestamp</code></td><td>int</td><td>The current time, represented as the number of seconds since the epoch.</td></tr>
  15133. <tr><td><code>uptime_seconds</code></td><td>int</td><td>The number of seconds since the homeserver was last started.</td></tr>
  15134. <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>
  15135. <tr><td><code>total_users</code></td><td>int</td><td>The number of registered users on the homeserver.</td></tr>
  15136. <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>
  15137. <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>
  15138. <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>
  15139. <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>
  15140. <tr><td><code>total_room_count</code></td><td>int</td><td>The total number of rooms present on the homeserver.</td></tr>
  15141. <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>
  15142. <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>
  15143. <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>
  15144. <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>
  15145. <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>
  15146. <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>
  15147. <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>
  15148. <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>
  15149. <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>
  15150. <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>
  15151. <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>
  15152. <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>
  15153. <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>
  15154. <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>
  15155. <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>
  15156. <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>
  15157. <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>
  15158. <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>
  15159. </tbody></table>
  15160. <div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
  15161. <p>Native matrix users and guests are always counted. If the
  15162. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a>
  15163. option is set to <code>true</code>, &quot;puppeted&quot; users (users that an Application Service have performed
  15164. <a href="https://spec.matrix.org/v1.3/application-service-api/#identity-assertion">an action on behalf of</a>)
  15165. will also be counted. Note that an Application Service can &quot;puppet&quot; any user in their
  15166. <a href="https://spec.matrix.org/v1.3/application-service-api/#registration">user namespace</a>,
  15167. not only users that the Application Service has created. If this happens, the Application Service
  15168. will additionally be counted as a user (irrespective of <code>track_puppeted_user_ips</code>).</p>
  15169. </div>
  15170. <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>
  15171. <p>If statistics reporting is enabled, the endpoint that Synapse sends metrics to is configured by the
  15172. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint"><code>report_stats_endpoint</code></a> config
  15173. option. By default, statistics are sent to Matrix.org.</p>
  15174. <p>If you would like to set up your own statistics collection server and send metrics there, you may
  15175. consider using one of the following known implementations:</p>
  15176. <ul>
  15177. <li><a href="https://github.com/matrix-org/panopticon">Matrix.org's Panopticon</a></li>
  15178. <li><a href="https://gitlab.com/famedly/infra/services/barad-dur">Famedly's Barad-dûr</a></li>
  15179. </ul>
  15180. <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>
  15181. <p>Synapse can be configured to record the number of monthly active users (also referred to as MAU) on a given homeserver.
  15182. For clarity's sake, MAU only tracks local users.</p>
  15183. <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>
  15184. are calculated differently. The <code>monthly_active_users</code> from the usage stats does not take into account any
  15185. of the rules below, and counts any users who have made a request to the homeserver in the last 30 days.</p>
  15186. <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>
  15187. <h2 id="calculating-active-users"><a class="header" href="#calculating-active-users">Calculating active users</a></h2>
  15188. <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
  15189. calculating the MAU figure, any users with a recorded action in the last 30 days are considered part of the cohort. Days are measured
  15190. as a rolling window from the current system time to 30 days ago.</p>
  15191. <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>
  15192. <p>A user is <strong>never</strong> considered active if they are either:</p>
  15193. <ul>
  15194. <li>Part of the trial day cohort (described below)</li>
  15195. <li>Owned by an application service.
  15196. <ul>
  15197. <li>Note: This <strong>only</strong> covers users that are part of an application service <code>namespaces.users</code> registration. The namespace
  15198. must also be marked as <code>exclusive</code>.</li>
  15199. </ul>
  15200. </li>
  15201. </ul>
  15202. <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>
  15203. they register with a 3pid that is included in the config field <code>mau_limits_reserved_threepids</code>.</p>
  15204. <p>The Prometheus metric for MAU is refreshed every 5 minutes.</p>
  15205. <p>Once an hour, Synapse checks to see if any users are inactive (with only activity timestamps later than 30 days). These users
  15206. are removed from the active users cohort. If they then become active, they are immediately restored to the cohort.</p>
  15207. <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
  15208. perform actions they will eventually be removed from the cohort.</p>
  15209. <h3 id="trial-days"><a class="header" href="#trial-days">Trial days</a></h3>
  15210. <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
  15211. trial period if their registration timestamp (also known as the <code>creation_ts</code>) is less than <code>mau_trial_days</code> old.</p>
  15212. <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>
  15213. <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.
  15214. 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>
  15215. <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>
  15216. <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
  15217. homeserver will begin to block some actions.</p>
  15218. <p>Individual users matching <strong>any</strong> of the below criteria never have their actions blocked:</p>
  15219. <ul>
  15220. <li>Considered part of the cohort of MAU users.</li>
  15221. <li>Considered part of the trial period.</li>
  15222. <li>Registered as a <code>support</code> user.</li>
  15223. <li>Application service users if <code>track_appservice_user_ips</code> is NOT set.</li>
  15224. </ul>
  15225. <p>Please not that server admins are <strong>not</strong> exempt from blocking.</p>
  15226. <p>The following actions are blocked when the MAU limit is exceeded:</p>
  15227. <ul>
  15228. <li>Logging in</li>
  15229. <li>Sending events</li>
  15230. <li>Creating rooms</li>
  15231. <li>Syncing</li>
  15232. </ul>
  15233. <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>
  15234. config value.</p>
  15235. <p>When a request is blocked, the response will have the <code>errcode</code> <code>M_RESOURCE_LIMIT_EXCEEDED</code>.</p>
  15236. <h2 id="metrics-1"><a class="header" href="#metrics-1">Metrics</a></h2>
  15237. <p>Synapse records several different prometheus metrics for MAU.</p>
  15238. <p><code>synapse_admin_mau_current</code> records the current MAU figure for native (non-application-service) users.</p>
  15239. <p><code>synapse_admin_mau_max</code> records the maximum MAU as dictated by the <code>max_mau_value</code> config value.</p>
  15240. <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
  15241. to filter by a specific service ID. This <em>also</em> includes non-application-service users under <code>app_service=native</code> .</p>
  15242. <p><code>synapse_admin_mau_registered_reserved_users</code> records the number of users specified in <code>mau_limits_reserved_threepids</code> which have
  15243. registered accounts on the homeserver.</p>
  15244. <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>
  15245. <p>It is possible to monitor much of the internal state of Synapse using <a href="https://prometheus.io">Prometheus</a>
  15246. metrics and <a href="https://grafana.com/">Grafana</a>.
  15247. A guide for configuring Synapse to provide metrics is available <a href="usage/administration/../../metrics-howto.html">here</a>
  15248. and information on setting up Grafana is <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana">here</a>.
  15249. In this setup, Prometheus will periodically scrape the information Synapse provides and
  15250. store a record of it over time. Grafana is then used as an interface to query and
  15251. present this information through a series of pretty graphs.</p>
  15252. <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>
  15253. <h2 id="message-event-send-time"><a class="header" href="#message-event-send-time">Message Event Send Time</a></h2>
  15254. <p><img src="https://user-images.githubusercontent.com/1342360/82239409-a1c8e900-9930-11ea-8081-e4614e0c63f4.png" alt="image" /></p>
  15255. <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>
  15256. <h2 id="transaction-count-and-transaction-duration"><a class="header" href="#transaction-count-and-transaction-duration">Transaction Count and Transaction Duration</a></h2>
  15257. <p><img src="https://user-images.githubusercontent.com/1342360/82239985-8d392080-9931-11ea-80d0-843ab2f22e1e.png" alt="image" /></p>
  15258. <p><img src="https://user-images.githubusercontent.com/1342360/82240050-ab068580-9931-11ea-98f1-f94671cbac9a.png" alt="image" /></p>
  15259. <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>
  15260. <p><img src="https://user-images.githubusercontent.com/1342360/82240192-e86b1300-9931-11ea-9aac-3e2c9bfa6fdc.png" alt="image" /></p>
  15261. <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>
  15262. <p><img src="https://user-images.githubusercontent.com/1342360/82240467-62030100-9932-11ea-8db9-917f2d977fe1.png" alt="image" /></p>
  15263. <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>
  15264. <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>
  15265. <h2 id="federation-2"><a class="header" href="#federation-2">Federation</a></h2>
  15266. <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>
  15267. <ul>
  15268. <li>PDU (Persistent Data Unit) - room events: messages, state events (join/leave), etc. These are permanently stored in the database.</li>
  15269. <li>EDU (Ephemeral Data Unit) - other data, which need not be stored permanently, such as read receipts, typing notifications.</li>
  15270. </ul>
  15271. <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>
  15272. <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>
  15273. <h2 id="caches"><a class="header" href="#caches">Caches</a></h2>
  15274. <p><img src="https://user-images.githubusercontent.com/1342360/82240572-8b239180-9932-11ea-96ff-6b5f0e57ebe5.png" alt="image" /></p>
  15275. <p><img src="https://user-images.githubusercontent.com/1342360/82240666-b8703f80-9932-11ea-86af-9f663988d8da.png" alt="image" /></p>
  15276. <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>
  15277. <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>
  15278. <p><img src="https://user-images.githubusercontent.com/1342360/82240766-de95df80-9932-11ea-8c15-5acfc57c48da.png" alt="image" /></p>
  15279. <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>
  15280. <h2 id="forward-extremities"><a class="header" href="#forward-extremities">Forward Extremities</a></h2>
  15281. <p><img src="https://user-images.githubusercontent.com/1342360/82241440-13566680-9934-11ea-8b88-ba468db937ed.png" alt="image" /></p>
  15282. <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>
  15283. <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>
  15284. <h2 id="garbage-collection"><a class="header" href="#garbage-collection">Garbage Collection</a></h2>
  15285. <p><img src="https://user-images.githubusercontent.com/1342360/82241911-da6ac180-9934-11ea-9a0d-a311fe22acd0.png" alt="image" /></p>
  15286. <p>Large spikes in garbage collection times (bigger than shown here, I'm talking in the
  15287. multiple seconds range), can cause lots of problems in Synapse performance. It's more an
  15288. indicator of problems, and a symptom of other problems though, so check other graphs for what might be causing it.</p>
  15289. <h2 id="final-thoughts"><a class="header" href="#final-thoughts">Final Thoughts</a></h2>
  15290. <p>If you're still having performance problems with your Synapse instance and you've
  15291. tried everything you can, it may just be a lack of system resources. Consider adding
  15292. more CPU and RAM, and make use of <a href="usage/administration/../../workers.html">worker mode</a>
  15293. to make use of multiple CPU cores / multiple machines for your homeserver.</p>
  15294. <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>
  15295. <h2 id="size-of-full-matrix-db"><a class="header" href="#size-of-full-matrix-db">Size of full matrix db</a></h2>
  15296. <pre><code class="language-sql">SELECT pg_size_pretty( pg_database_size( 'matrix' ) );
  15297. </code></pre>
  15298. <h3 id="result-example"><a class="header" href="#result-example">Result example:</a></h3>
  15299. <pre><code>pg_size_pretty
  15300. ----------------
  15301. 6420 MB
  15302. (1 row)
  15303. </code></pre>
  15304. <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>
  15305. <pre><code class="language-sql">SELECT relname, n_live_tup AS &quot;rows&quot;
  15306. FROM pg_stat_user_tables
  15307. ORDER BY n_live_tup DESC
  15308. LIMIT 20;
  15309. </code></pre>
  15310. <p>This query is quick, but may be very approximate, for exact number of rows use:</p>
  15311. <pre><code class="language-sql">SELECT COUNT(*) FROM &lt;table_name&gt;;
  15312. </code></pre>
  15313. <h3 id="result-example-1"><a class="header" href="#result-example-1">Result example:</a></h3>
  15314. <pre><code>state_groups_state - 161687170
  15315. event_auth - 8584785
  15316. event_edges - 6995633
  15317. event_json - 6585916
  15318. event_reference_hashes - 6580990
  15319. events - 6578879
  15320. received_transactions - 5713989
  15321. event_to_state_groups - 4873377
  15322. stream_ordering_to_exterm - 4136285
  15323. current_state_delta_stream - 3770972
  15324. event_search - 3670521
  15325. state_events - 2845082
  15326. room_memberships - 2785854
  15327. cache_invalidation_stream - 2448218
  15328. state_groups - 1255467
  15329. state_group_edges - 1229849
  15330. current_state_events - 1222905
  15331. users_in_public_rooms - 364059
  15332. device_lists_stream - 326903
  15333. user_directory_search - 316433
  15334. </code></pre>
  15335. <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>
  15336. <pre><code class="language-sql">SELECT nspname || '.' || relname AS &quot;relation&quot;,
  15337. pg_size_pretty(pg_total_relation_size(c.oid)) AS &quot;total_size&quot;
  15338. FROM pg_class c
  15339. LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
  15340. WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  15341. AND c.relkind &lt;&gt; 'i'
  15342. AND nspname !~ '^pg_toast'
  15343. ORDER BY pg_total_relation_size(c.oid) DESC
  15344. LIMIT 20;
  15345. </code></pre>
  15346. <h3 id="result-example-2"><a class="header" href="#result-example-2">Result example:</a></h3>
  15347. <pre><code>public.state_groups_state - 27 GB
  15348. public.event_json - 9855 MB
  15349. public.events - 3675 MB
  15350. public.event_edges - 3404 MB
  15351. public.received_transactions - 2745 MB
  15352. public.event_reference_hashes - 1864 MB
  15353. public.event_auth - 1775 MB
  15354. public.stream_ordering_to_exterm - 1663 MB
  15355. public.event_search - 1370 MB
  15356. public.room_memberships - 1050 MB
  15357. public.event_to_state_groups - 948 MB
  15358. public.current_state_delta_stream - 711 MB
  15359. public.state_events - 611 MB
  15360. public.presence_stream - 530 MB
  15361. public.current_state_events - 525 MB
  15362. public.cache_invalidation_stream - 466 MB
  15363. public.receipts_linearized - 279 MB
  15364. public.state_groups - 160 MB
  15365. public.device_lists_remote_cache - 124 MB
  15366. public.state_group_edges - 122 MB
  15367. </code></pre>
  15368. <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>
  15369. <p>You get the same information when you use the
  15370. <a href="usage/administration/../../admin_api/rooms.html#list-room-api">admin API</a>
  15371. and set parameter <code>order_by=state_events</code>.</p>
  15372. <pre><code class="language-sql">SELECT r.name, s.room_id, s.current_state_events
  15373. FROM room_stats_current s
  15374. LEFT JOIN room_stats_state r USING (room_id)
  15375. ORDER BY current_state_events DESC
  15376. LIMIT 20;
  15377. </code></pre>
  15378. <p>and by state_group_events count:</p>
  15379. <pre><code class="language-sql">SELECT rss.name, s.room_id, COUNT(s.room_id)
  15380. FROM state_groups_state s
  15381. LEFT JOIN room_stats_state rss USING (room_id)
  15382. GROUP BY s.room_id, rss.name
  15383. ORDER BY COUNT(s.room_id) DESC
  15384. LIMIT 20;
  15385. </code></pre>
  15386. <p>plus same, but with join removed for performance reasons:</p>
  15387. <pre><code class="language-sql">SELECT s.room_id, COUNT(s.room_id)
  15388. FROM state_groups_state s
  15389. GROUP BY s.room_id
  15390. ORDER BY COUNT(s.room_id) DESC
  15391. LIMIT 20;
  15392. </code></pre>
  15393. <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>
  15394. <pre><code class="language-sql">SELECT e.room_id, r.name, COUNT(e.event_id) cnt
  15395. FROM events e
  15396. LEFT JOIN room_stats_state r USING (room_id)
  15397. WHERE e.origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 day') * 1000
  15398. GROUP BY e.room_id, r.name
  15399. ORDER BY cnt DESC
  15400. LIMIT 20;
  15401. </code></pre>
  15402. <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>
  15403. <p>Caution. This query does not use any indexes, can be slow and create load on the database.</p>
  15404. <pre><code class="language-sql">SELECT COUNT(*), sender
  15405. FROM events
  15406. WHERE (type = 'm.room.encrypted' OR type = 'm.room.message')
  15407. AND origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 month') * 1000
  15408. GROUP BY sender
  15409. ORDER BY COUNT(*) DESC
  15410. LIMIT 20;
  15411. </code></pre>
  15412. <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>
  15413. <pre><code class="language-sql">SELECT e.room_id, r.name, e.event_id, e.type, e.content, j.json
  15414. FROM events e
  15415. LEFT JOIN event_json j USING (room_id)
  15416. LEFT JOIN room_stats_state r USING (room_id)
  15417. WHERE sender = '@LOGIN:example.com'
  15418. AND e.type = 'm.room.message'
  15419. ORDER BY stream_ordering DESC
  15420. LIMIT 100;
  15421. </code></pre>
  15422. <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>
  15423. <p><strong>Sort and order with bash</strong></p>
  15424. <pre><code class="language-bash">echo &quot;SELECT event_json.room_id, room_stats_state.name FROM event_json, room_stats_state \
  15425. WHERE room_stats_state.room_id = event_json.room_id&quot; | psql -d synapse -h localhost -U synapse_user -t \
  15426. | sort | uniq -c | sort -n
  15427. </code></pre>
  15428. <p>Documentation for <code>psql</code> command line parameters: https://www.postgresql.org/docs/current/app-psql.html</p>
  15429. <p><strong>Sort and order with SQL</strong></p>
  15430. <pre><code class="language-sql">SELECT COUNT(*), event_json.room_id, room_stats_state.name
  15431. FROM event_json, room_stats_state
  15432. WHERE room_stats_state.room_id = event_json.room_id
  15433. GROUP BY event_json.room_id, room_stats_state.name
  15434. ORDER BY COUNT(*) DESC
  15435. LIMIT 50;
  15436. </code></pre>
  15437. <h3 id="result-example-3"><a class="header" href="#result-example-3">Result example:</a></h3>
  15438. <pre><code> 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix
  15439. 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix (TWIM)
  15440. 17799 !iDIOImbmXxwNngznsa:matrix.org | Linux in Russian
  15441. 18739 !GnEEPYXUhoaHbkFBNX:matrix.org | Riot Android
  15442. 23373 !QtykxKocfZaZOUrTwp:matrix.org | Matrix HQ
  15443. 39504 !gTQfWzbYncrtNrvEkB:matrix.org | ru.[matrix]
  15444. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot
  15445. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot Web/Desktop
  15446. </code></pre>
  15447. <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>
  15448. <p>You get the same information when you use the
  15449. <a href="usage/administration/../../admin_api/rooms.html#room-details-api">admin API</a>.</p>
  15450. <pre><code class="language-sql">SELECT rss.room_id, rss.name, rss.canonical_alias, rss.topic, rss.encryption,
  15451. rsc.joined_members, rsc.local_users_in_room, rss.join_rules
  15452. FROM room_stats_state rss
  15453. LEFT JOIN room_stats_current rsc USING (room_id)
  15454. WHERE room_id IN ( WHERE room_id IN (
  15455. '!OGEhHVWSdvArJzumhm:matrix.org',
  15456. '!YTvKGNlinIzlkMTVRl:matrix.org'
  15457. );
  15458. </code></pre>
  15459. <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>
  15460. <pre><code class="language-sql">SELECT user_id, device_id, user_agent, TO_TIMESTAMP(last_seen / 1000) AS &quot;last_seen&quot;
  15461. FROM devices
  15462. WHERE last_seen &lt; DATE_PART('epoch', NOW() - INTERVAL '3 month') * 1000;
  15463. </code></pre>
  15464. <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>
  15465. <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>
  15466. <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>
  15467. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  15468. <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>
  15469. <p>This API deletes the <em>local</em> media from the disk of your own server.</p>
  15470. <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>
  15471. <p>The purge history API allows server admins to purge historic events from their database, reclaiming disk space.</p>
  15472. <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>
  15473. <p>Tool for compressing (deduplicating) <code>state_groups_state</code> table.</p>
  15474. <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>
  15475. <p>Some easy SQL that reports useful stats about your Synapse database.</p>
  15476. <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>
  15477. <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>
  15478. <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>
  15479. <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>
  15480. <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>
  15481. <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>
  15482. <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>
  15483. <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>
  15484. <p>A full state group just records the event id for each piece of state in the room at that point.</p>
  15485. <h2 id="known-bugs-with-state-groups"><a class="header" href="#known-bugs-with-state-groups">Known bugs with state groups</a></h2>
  15486. <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>
  15487. <h2 id="compression-tool"><a class="header" href="#compression-tool">Compression tool</a></h2>
  15488. <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>
  15489. <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>
  15490. <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>
  15491. <p>See the following for how to decode the dense data available from the default logging configuration.</p>
  15492. <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]
  15493. -AAAAAAAAAAAAAAAAAAAAA- -BBBBBBBBBBBBBBBBBBBBBB- -C- -DD- -EEEEEE- -FFFFFFFFF- -GG- -HHHHHHHHHHHHHHHHHHHHHHH- -IIIIII- -JJJJJJJ- -KKKKKK-, -LLLLLL- -MMMMMMM- -NNNNNN- O -P- -QQ- -RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR- -SSSSSSSSSSSS- -TTTTTT-
  15494. </code></pre>
  15495. <table><thead><tr><th>Part</th><th>Explanation</th></tr></thead><tbody>
  15496. <tr><td>AAAA</td><td>Timestamp request was logged (not received)</td></tr>
  15497. <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>
  15498. <tr><td>CCCC</td><td>Line number in code</td></tr>
  15499. <tr><td>DDDD</td><td>Log Level</td></tr>
  15500. <tr><td>EEEE</td><td>Request Identifier (This identifier is shared by related log lines)</td></tr>
  15501. <tr><td>FFFF</td><td>Source IP (Or X-Forwarded-For if enabled)</td></tr>
  15502. <tr><td>GGGG</td><td>Server Port</td></tr>
  15503. <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>
  15504. <tr><td>IIII</td><td>Total Time to process the request</td></tr>
  15505. <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>
  15506. <tr><td>KKKK</td><td>Userland CPU time</td></tr>
  15507. <tr><td>LLLL</td><td>System CPU time</td></tr>
  15508. <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>
  15509. <tr><td>NNNN</td><td>Total time waiting for response to DB queries across all parallel DB work from this request</td></tr>
  15510. <tr><td>OOOO</td><td>Count of DB transactions performed</td></tr>
  15511. <tr><td>PPPP</td><td>Response body size</td></tr>
  15512. <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>
  15513. <tr><td>RRRR</td><td>Request</td></tr>
  15514. <tr><td>SSSS</td><td>User-agent</td></tr>
  15515. <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>
  15516. </tbody></table>
  15517. <p>MMMM / NNNN can be greater than IIII if there are multiple slow database queries
  15518. running in parallel.</p>
  15519. <p>Some actions can result in multiple identical http requests, which will return
  15520. the same data, but only the first request will report time/transactions in
  15521. <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
  15522. response and will simultaneously return with the first request, but with very
  15523. small processing times.</p>
  15524. <div style="break-before: page; page-break-before: always;"></div><h2 id="admin-faq"><a class="header" href="#admin-faq">Admin FAQ</a></h2>
  15525. <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>
  15526. <p>If your server already has an admin account you should use the
  15527. <a href="usage/administration/../../admin_api/user_admin_api.html#change-whether-a-user-is-a-server-administrator-or-not">User Admin API</a>
  15528. to promote other accounts to become admins.</p>
  15529. <p>If you don't have any admin accounts yet you won't be able to use the admin API,
  15530. so you'll have to edit the database manually. Manually editing the database is
  15531. generally not recommended so once you have an admin account: use the admin APIs
  15532. to make further changes.</p>
  15533. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  15534. </code></pre>
  15535. <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>
  15536. <p>Run this sql query on your db:</p>
  15537. <pre><code class="language-sql">SELECT * FROM destinations;
  15538. </code></pre>
  15539. <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>
  15540. <p>Run this sql query on your db:</p>
  15541. <pre><code class="language-sql">SELECT DISTINCT split_part(state_key, ':', 2)
  15542. FROM current_state_events
  15543. WHERE room_id = '!cURbafjkfsMDVwdRDQ:matrix.org' AND membership = 'join';
  15544. </code></pre>
  15545. <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>
  15546. <pre><code class="language-sql">SELECT NAME from users;
  15547. </code></pre>
  15548. <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>
  15549. <p>Synapse includes a Python command to export data for a specific user. It takes the homeserver
  15550. configuration file and the full Matrix ID of the user to export:</p>
  15551. <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;
  15552. </code></pre>
  15553. <p>If you uses <a href="usage/administration/../../development/dependencies.html#managing-dependencies-with-poetry">Poetry</a>
  15554. to run Synapse:</p>
  15555. <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;
  15556. </code></pre>
  15557. <p>The directory to store the export data in can be customised with the
  15558. <code>--output-directory</code> parameter; ensure that the provided directory is
  15559. empty. If this parameter is not provided, Synapse defaults to creating
  15560. a temporary directory (which starts with &quot;synapse-exfiltrate&quot;) in <code>/tmp</code>,
  15561. <code>/var/tmp</code>, or <code>/usr/tmp</code>, in that order.</p>
  15562. <p>The exported data has the following layout:</p>
  15563. <pre><code>output-directory
  15564. ├───rooms
  15565. │ └───&lt;room_id&gt;
  15566. │ ├───events
  15567. │ ├───state
  15568. │ ├───invite_state
  15569. │ └───knock_state
  15570. ├───user_data
  15571. │ ├───account_data
  15572. │ │ ├───global
  15573. │ │ └───&lt;room_id&gt;
  15574. │ ├───connections
  15575. │ ├───devices
  15576. │ └───profile
  15577. └───media_ids
  15578. └───&lt;media_id&gt;
  15579. </code></pre>
  15580. <p>The <code>media_ids</code> folder contains only the metadata of the media uploaded by the user.
  15581. It does not contain the media itself.
  15582. Furthermore, only the <code>media_ids</code> that Synapse manages itself are exported.
  15583. If another media repository (e.g. <a href="https://github.com/turt2live/matrix-media-repo">matrix-media-repo</a>)
  15584. is used, the data must be exported separately.</p>
  15585. <p>With the <code>media_ids</code> the media files can be downloaded.
  15586. Media that have been sent in encrypted rooms are only retrieved in encrypted form.
  15587. The following script can help with download the media files:</p>
  15588. <pre><code class="language-bash">#!/usr/bin/env bash
  15589. # Parameters
  15590. #
  15591. # source_directory: Directory which contains the export with the media_ids.
  15592. # target_directory: Directory into which all files are to be downloaded.
  15593. # repository_url: Address of the media repository resp. media worker.
  15594. # serverName: Name of the server (`server_name` from homeserver.yaml).
  15595. #
  15596. # Example:
  15597. # ./download_media.sh /tmp/export_data/media_ids/ /tmp/export_data/media_files/ http://localhost:8008 matrix.example.com
  15598. source_directory=$1
  15599. target_directory=$2
  15600. repository_url=$3
  15601. serverName=$4
  15602. mkdir -p $target_directory
  15603. for file in $source_directory/*; do
  15604. filename=$(basename ${file})
  15605. url=$repository_url/_matrix/media/v3/download/$serverName/$filename
  15606. echo &quot;Downloading $filename - $url&quot;
  15607. if ! wget -o /dev/null -P $target_directory $url; then
  15608. echo &quot;Could not download $filename&quot;
  15609. fi
  15610. done
  15611. </code></pre>
  15612. <h2 id="manually-resetting-passwords"><a class="header" href="#manually-resetting-passwords">Manually resetting passwords</a></h2>
  15613. <p>Users can reset their password through their client. Alternatively, a server admin
  15614. can reset a user's password using the <a href="usage/administration/../../admin_api/user_admin_api.html#reset-password">admin API</a>.</p>
  15615. <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>
  15616. <p>Deleting your database is unlikely to make anything better.</p>
  15617. <p>It's easy to make the mistake of thinking that you can start again from a clean
  15618. slate by dropping your database, but things don't work like that in a federated
  15619. network: lots of other servers have information about your server.</p>
  15620. <p>For example: other servers might think that you are in a room, your server will
  15621. think that you are not, and you'll probably be unable to interact with that room
  15622. in a sensible way ever again.</p>
  15623. <p>In general, there are better solutions to any problem than dropping the database.
  15624. Come and seek help in https://matrix.to/#/#synapse:matrix.org.</p>
  15625. <p>There are two exceptions when it might be sensible to delete your database and start again:</p>
  15626. <ul>
  15627. <li>You have <em>never</em> joined any rooms which are federated with other servers. For
  15628. instance, a local deployment which the outside world can't talk to.</li>
  15629. <li>You are changing the <code>server_name</code> in the homeserver configuration. In effect
  15630. this makes your server a completely new one from the point of view of the network,
  15631. so in this case it makes sense to start with a clean database.
  15632. (In both cases you probably also want to clear out the media_store.)</li>
  15633. </ul>
  15634. <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>
  15635. <p>Using the following curl command:</p>
  15636. <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;
  15637. </code></pre>
  15638. <p><code>&lt;access-token&gt;</code> - can be obtained in riot by looking in the riot settings, down the bottom is:
  15639. Access Token:&lt;click to reveal&gt;</p>
  15640. <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>
  15641. <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>
  15642. <p>Synapse tags each log line according to the HTTP request it is processing. When
  15643. it finishes processing each request, it logs a line containing the words
  15644. <code>Processed request: </code>. For example:</p>
  15645. <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;
  15646. </code></pre>
  15647. <p>Here we can see that the request has been tagged with <code>GET-37</code>. (The tag depends
  15648. on the method of the HTTP request, so might start with <code>GET-</code>, <code>PUT-</code>, <code>POST-</code>,
  15649. <code>OPTIONS-</code> or <code>DELETE-</code>.) So to find all lines corresponding to this request, we can do:</p>
  15650. <pre><code class="language-console">grep 'GET-37' homeserver.log
  15651. </code></pre>
  15652. <p>If you want to paste that output into a github issue or matrix room, please
  15653. remember to surround it with triple-backticks (```) to make it legible
  15654. (see <a href="https://help.github.com/en/articles/basic-writing-and-formatting-syntax#quoting-code">quoting code</a>).</p>
  15655. <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>
  15656. <p>See <a href="usage/administration/request_log.html">Request log format</a>.</p>
  15657. <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>
  15658. <pre><code class="language-sql">SELECT s.canonical_alias, g.room_id, count(*) AS num_rows
  15659. FROM
  15660. state_groups_state AS g,
  15661. room_stats_state AS s
  15662. WHERE g.room_id = s.room_id
  15663. GROUP BY s.canonical_alias, g.room_id
  15664. ORDER BY num_rows desc
  15665. LIMIT 10;
  15666. </code></pre>
  15667. <p>You can also use the <a href="usage/administration/../../admin_api/rooms.html#list-room-api">List Room API</a>
  15668. and <code>order_by</code> <code>state_events</code>.</p>
  15669. <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>
  15670. <p>The typical failure mode here is that you send an invitation to someone
  15671. to join a room or direct chat, but when they go to accept it, they get an
  15672. error (typically along the lines of &quot;Invalid signature&quot;). They might see
  15673. something like the following in their logs:</p>
  15674. <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;
  15675. </code></pre>
  15676. <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>
  15677. <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>
  15678. <p>First, ensure you are running the latest version of Synapse, using Python 3
  15679. with a <a href="usage/administration/../../postgres.html">PostgreSQL database</a>.</p>
  15680. <p>Synapse's architecture is quite RAM hungry currently - we deliberately
  15681. cache a lot of recent room data and metadata in RAM in order to speed up
  15682. common requests. We'll improve this in the future, but for now the easiest
  15683. way to either reduce the RAM usage (at the risk of slowing things down)
  15684. is to set the almost-undocumented <code>SYNAPSE_CACHE_FACTOR</code> environment
  15685. variable. The default is 0.5, which can be decreased to reduce RAM usage
  15686. in memory constrained environments, or increased if performance starts to
  15687. degrade.</p>
  15688. <p>However, degraded performance due to a low cache factor, common on
  15689. machines with slow disks, often leads to explosions in memory use due
  15690. backlogged requests. In this case, reducing the cache factor will make
  15691. things worse. Instead, try increasing it drastically. 2.0 is a good
  15692. starting value.</p>
  15693. <p>Using <a href="https://jemalloc.net">libjemalloc</a> can also yield a significant
  15694. improvement in overall memory use, and especially in terms of giving back
  15695. RAM to the OS. To use it, the library must simply be put in the
  15696. LD_PRELOAD environment variable when launching Synapse. On Debian, this
  15697. can be done by installing the <code>libjemalloc1</code> package and adding this
  15698. line to <code>/etc/default/matrix-synapse</code>:</p>
  15699. <pre><code>LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.1
  15700. </code></pre>
  15701. <p>This made a significant difference on Python 2.7 - it's unclear how
  15702. much of an improvement it provides on Python 3.x.</p>
  15703. <p>If you're encountering high CPU use by the Synapse process itself, you
  15704. may be affected by a bug with presence tracking that leads to a
  15705. massive excess of outgoing federation requests (see <a href="https://github.com/matrix-org/synapse/issues/3971">discussion</a>). If metrics
  15706. indicate that your server is also issuing far more outgoing federation
  15707. requests than can be accounted for by your users' activity, this is a
  15708. likely cause. The misbehavior can be worked around by disabling presence
  15709. in the Synapse config file: <a href="usage/administration/../configuration/config_documentation.html#presence">see here</a>.</p>
  15710. <h2 id="running-out-of-file-handles"><a class="header" href="#running-out-of-file-handles">Running out of File Handles</a></h2>
  15711. <p>If Synapse runs out of file handles, it typically fails badly - live-locking
  15712. at 100% CPU, and/or failing to accept new TCP connections (blocking the
  15713. connecting client). Matrix currently can legitimately use a lot of file handles,
  15714. thanks to busy rooms like <code>#matrix:matrix.org</code> containing hundreds of participating
  15715. servers. The first time a server talks in a room it will try to connect
  15716. simultaneously to all participating servers, which could exhaust the available
  15717. file descriptors between DNS queries &amp; HTTPS sockets, especially if DNS is slow
  15718. to respond. (We need to improve the routing algorithm used to be better than
  15719. full mesh, but as of March 2019 this hasn't happened yet).</p>
  15720. <p>If you hit this failure mode, we recommend increasing the maximum number of
  15721. open file handles to be at least 4096 (assuming a default of 1024 or 256).
  15722. This is typically done by editing <code>/etc/security/limits.conf</code></p>
  15723. <p>Separately, Synapse may leak file handles if inbound HTTP requests get stuck
  15724. during processing - e.g. blocked behind a lock or talking to a remote server etc.
  15725. This is best diagnosed by matching up the 'Received request' and 'Processed request'
  15726. log lines and looking for any 'Processed request' lines which take more than
  15727. 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
  15728. you see this failure mode so we can help debug it, however.</p>
  15729. <div style="break-before: page; page-break-before: always;"></div><h1 id="contributing"><a class="header" href="#contributing">Contributing</a></h1>
  15730. <p>This document aims to get you started with contributing to Synapse!</p>
  15731. <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>
  15732. <p>Everyone is welcome to contribute code to <a href="https://github.com/matrix-org">matrix.org
  15733. projects</a>, provided that they are willing to
  15734. license their contributions under the same license as the project itself. We
  15735. follow a simple 'inbound=outbound' model for contributions: the act of
  15736. submitting an 'inbound' contribution means that the contributor agrees to
  15737. license the code under the same terms as the project's overall 'outbound'
  15738. license - in our case, this is almost always Apache Software License v2 (see
  15739. <a href="https://github.com/matrix-org/synapse/blob/develop/LICENSE">LICENSE</a>).</p>
  15740. <h1 id="2-what-do-i-need"><a class="header" href="#2-what-do-i-need">2. What do I need?</a></h1>
  15741. <p>If you are running Windows, the Windows Subsystem for Linux (WSL) is strongly
  15742. recommended for development. More information about WSL can be found at
  15743. <a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>. Running Synapse natively
  15744. on Windows is not officially supported.</p>
  15745. <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>
  15746. <p>A recent version of the Rust compiler is needed to build the native modules. The
  15747. easiest way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  15748. <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>
  15749. <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>
  15750. <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>
  15751. <p>For some tests, you will need <a href="https://docs.docker.com/get-docker/">a recent version of Docker</a>.</p>
  15752. <h1 id="3-get-the-source"><a class="header" href="#3-get-the-source">3. Get the source.</a></h1>
  15753. <p>The preferred and easiest way to contribute changes is to fork the relevant
  15754. 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
  15755. changes into our repo.</p>
  15756. <p>Please base your changes on the <code>develop</code> branch.</p>
  15757. <pre><code class="language-sh">git clone git@github.com:YOUR_GITHUB_USER_NAME/synapse.git
  15758. git checkout develop
  15759. </code></pre>
  15760. <p>If you need help getting started with git, this is beyond the scope of the document, but you
  15761. can find many good git tutorials on the web.</p>
  15762. <h1 id="4-install-the-dependencies"><a class="header" href="#4-install-the-dependencies">4. Install the dependencies</a></h1>
  15763. <p>Before installing the Python dependencies, make sure you have installed a recent version
  15764. of Rust (see the &quot;What do I need?&quot; section above). The easiest way of installing the
  15765. latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  15766. <p>Synapse uses the <a href="https://python-poetry.org/">poetry</a> project to manage its dependencies
  15767. and development environment. Once you have installed Python 3 and added the
  15768. source, you should install <code>poetry</code>.
  15769. Of their installation methods, we recommend
  15770. <a href="https://python-poetry.org/docs/#installing-with-pipx">installing <code>poetry</code> using <code>pipx</code></a>,</p>
  15771. <pre><code class="language-shell">pip install --user pipx
  15772. pipx install poetry
  15773. </code></pre>
  15774. <p>but see poetry's <a href="https://python-poetry.org/docs/#installation">installation instructions</a>
  15775. for other installation methods.</p>
  15776. <p>Developing Synapse requires Poetry version 1.3.2 or later.</p>
  15777. <p>Next, open a terminal and install dependencies as follows:</p>
  15778. <pre><code class="language-sh">cd path/where/you/have/cloned/the/repository
  15779. poetry install --extras all
  15780. </code></pre>
  15781. <p>This will install the runtime and developer dependencies for the project. Be sure to check
  15782. that the <code>poetry install</code> step completed cleanly.</p>
  15783. <h2 id="running-synapse-via-poetry"><a class="header" href="#running-synapse-via-poetry">Running Synapse via poetry</a></h2>
  15784. <p>To start a local instance of Synapse in the locked poetry environment, create a config file:</p>
  15785. <pre><code class="language-sh">cp docs/sample_config.yaml homeserver.yaml
  15786. cp docs/sample_log_config.yaml log_config.yaml
  15787. </code></pre>
  15788. <p>Now edit <code>homeserver.yaml</code>, things you might want to change include:</p>
  15789. <ul>
  15790. <li>Set a <code>server_name</code></li>
  15791. <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>
  15792. <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>
  15793. <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>
  15794. </ul>
  15795. <p>And then run Synapse with the following command:</p>
  15796. <pre><code class="language-sh">poetry run python -m synapse.app.homeserver -c homeserver.yaml
  15797. </code></pre>
  15798. <p>If you get an error like the following:</p>
  15799. <pre><code>importlib.metadata.PackageNotFoundError: matrix-synapse
  15800. </code></pre>
  15801. <p>this probably indicates that the <code>poetry install</code> step did not complete cleanly - go back and
  15802. resolve any issues and re-run until successful.</p>
  15803. <h1 id="5-get-in-touch"><a class="header" href="#5-get-in-touch">5. Get in touch.</a></h1>
  15804. <p>Join our developer community on Matrix: <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>!</p>
  15805. <h1 id="6-pick-an-issue"><a class="header" href="#6-pick-an-issue">6. Pick an issue.</a></h1>
  15806. <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>
  15807. to work on.</p>
  15808. <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>
  15809. <p>There is a growing amount of documentation located in the
  15810. <a href="https://github.com/matrix-org/synapse/tree/develop/docs"><code>docs</code></a>
  15811. directory, with a rendered version <a href="https://matrix-org.github.io/synapse">available online</a>.
  15812. This documentation is intended primarily for sysadmins running their
  15813. own Synapse instance, as well as developers interacting externally with
  15814. Synapse.
  15815. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/development"><code>docs/development</code></a>
  15816. exists primarily to house documentation for
  15817. Synapse developers.
  15818. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/admin_api"><code>docs/admin_api</code></a> houses documentation
  15819. regarding Synapse's Admin API, which is used mostly by sysadmins and external
  15820. service developers.</p>
  15821. <p>Synapse's code style is documented <a href="development/../code_style.html">here</a>. Please follow
  15822. it, including the conventions for <a href="development/../code_style.html#configuration-code-and-documentation-format">configuration
  15823. options and documentation</a>.</p>
  15824. <p>We welcome improvements and additions to our documentation itself! When
  15825. writing new pages, please
  15826. <a href="https://github.com/matrix-org/synapse/tree/develop/docs#adding-to-the-documentation">build <code>docs</code> to a book</a>
  15827. to check that your contributions render correctly. The docs are written in
  15828. <a href="https://guides.github.com/features/mastering-markdown/">GitHub-Flavoured Markdown</a>.</p>
  15829. <p>Some documentation also exists in <a href="https://github.com/matrix-org/synapse/wiki">Synapse's GitHub
  15830. Wiki</a>, although this is primarily
  15831. contributed to by community authors.</p>
  15832. <p>When changes are made to any Rust code then you must call either <code>poetry install</code>
  15833. or <code>maturin develop</code> (if installed) to rebuild the Rust code. Using <a href="https://github.com/PyO3/maturin"><code>maturin</code></a>
  15834. is quicker than <code>poetry install</code>, so is recommended when making frequent
  15835. changes to the Rust code.</p>
  15836. <h1 id="8-test-test-test"><a class="header" href="#8-test-test-test">8. Test, test, test!</a></h1>
  15837. <p><a name="test-test-test" id="test-test-test"></a></p>
  15838. <p>While you're developing and before submitting a patch, you'll
  15839. want to test your code.</p>
  15840. <h2 id="run-the-linters"><a class="header" href="#run-the-linters">Run the linters.</a></h2>
  15841. <p>The linters look at your code and do two things:</p>
  15842. <ul>
  15843. <li>ensure that your code follows the coding style adopted by the project;</li>
  15844. <li>catch a number of errors in your code.</li>
  15845. </ul>
  15846. <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>
  15847. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh
  15848. </code></pre>
  15849. <p>Note that this script <em>will modify your files</em> to fix styling errors.
  15850. Make sure that you have saved all your files.</p>
  15851. <p>If you wish to restrict the linters to only the files changed since the last commit
  15852. (much faster!), you can instead run:</p>
  15853. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh -d
  15854. </code></pre>
  15855. <p>Or if you know exactly which files you wish to lint, you can instead run:</p>
  15856. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh path/to/file1.py path/to/file2.py path/to/folder
  15857. </code></pre>
  15858. <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>
  15859. <p>The unit tests run parts of Synapse, including your changes, to see if anything
  15860. was broken. They are slower than the linters but will typically catch more errors.</p>
  15861. <pre><code class="language-sh">poetry run trial tests
  15862. </code></pre>
  15863. <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>
  15864. <pre><code class="language-sh">poetry run trial -j4 tests
  15865. </code></pre>
  15866. <p>If you wish to only run <em>some</em> unit tests, you may specify
  15867. another module instead of <code>tests</code> - or a test class or a method:</p>
  15868. <pre><code class="language-sh">poetry run trial tests.rest.admin.test_room tests.handlers.test_admin.ExfiltrateData.test_invite
  15869. </code></pre>
  15870. <p>If your tests fail, you may wish to look at the logs (the default log level is <code>ERROR</code>):</p>
  15871. <pre><code class="language-sh">less _trial_temp/test.log
  15872. </code></pre>
  15873. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>:</p>
  15874. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG poetry run trial tests
  15875. </code></pre>
  15876. <p>By default, tests will use an in-memory SQLite database for test data. For additional
  15877. help with debugging, one can use an on-disk SQLite database file instead, in order to
  15878. review database state during and after running tests. This can be done by setting
  15879. the <code>SYNAPSE_TEST_PERSIST_SQLITE_DB</code> environment variable. Doing so will cause the
  15880. database state to be stored in a file named <code>test.db</code> under the trial process'
  15881. working directory. Typically, this ends up being <code>_trial_temp/test.db</code>. For example:</p>
  15882. <pre><code class="language-sh">SYNAPSE_TEST_PERSIST_SQLITE_DB=1 poetry run trial tests
  15883. </code></pre>
  15884. <p>The database file can then be inspected with:</p>
  15885. <pre><code class="language-sh">sqlite3 _trial_temp/test.db
  15886. </code></pre>
  15887. <p>Note that the database file is cleared at the beginning of each test run. Thus it
  15888. will always only contain the data generated by the <em>last run test</em>. Though generally
  15889. when debugging, one is only running a single test anyway.</p>
  15890. <h3 id="running-tests-under-postgresql"><a class="header" href="#running-tests-under-postgresql">Running tests under PostgreSQL</a></h3>
  15891. <p>Invoking <code>trial</code> as above will use an in-memory SQLite database. This is great for
  15892. quick development and testing. However, we recommend using a PostgreSQL database
  15893. in production (and indeed, we have some code paths specific to each database).
  15894. This means that we need to run our unit tests against PostgreSQL too. Our CI does
  15895. this automatically for pull requests and release candidates, but it's sometimes
  15896. useful to reproduce this locally.</p>
  15897. <h4 id="using-docker"><a class="header" href="#using-docker">Using Docker</a></h4>
  15898. <p>The easiest way to do so is to run Postgres via a docker container. In one
  15899. terminal:</p>
  15900. <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
  15901. </code></pre>
  15902. <p>If you see an error like</p>
  15903. <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.
  15904. </code></pre>
  15905. <p>then something is already bound to port 5432. You're probably already running postgres locally.</p>
  15906. <p>Once you have a postgres server running, invoke <code>trial</code> in a second terminal:</p>
  15907. <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
  15908. </code></pre>
  15909. <h4 id="using-an-existing-postgres-installation"><a class="header" href="#using-an-existing-postgres-installation">Using an existing Postgres installation</a></h4>
  15910. <p>If you have postgres already installed on your system, you can run <code>trial</code> with the
  15911. following environment variables matching your configuration:</p>
  15912. <ul>
  15913. <li><code>SYNAPSE_POSTGRES</code> to anything nonempty</li>
  15914. <li><code>SYNAPSE_POSTGRES_HOST</code> (optional if it's the default: UNIX socket)</li>
  15915. <li><code>SYNAPSE_POSTGRES_PORT</code> (optional if it's the default: 5432)</li>
  15916. <li><code>SYNAPSE_POSTGRES_USER</code> (optional if using a UNIX socket)</li>
  15917. <li><code>SYNAPSE_POSTGRES_PASSWORD</code> (optional if using a UNIX socket)</li>
  15918. </ul>
  15919. <p>For example:</p>
  15920. <pre><code class="language-shell">export SYNAPSE_POSTGRES=1
  15921. export SYNAPSE_POSTGRES_HOST=localhost
  15922. export SYNAPSE_POSTGRES_USER=postgres
  15923. export SYNAPSE_POSTGRES_PASSWORD=mydevenvpassword
  15924. trial
  15925. </code></pre>
  15926. <p>You don't need to specify the host, user, port or password if your Postgres
  15927. server is set to authenticate you over the UNIX socket (i.e. if the <code>psql</code> command
  15928. works without further arguments).</p>
  15929. <p>Your Postgres account needs to be able to create databases; see the postgres
  15930. docs for <a href="https://www.postgresql.org/docs/current/sql-alterrole.html"><code>ALTER ROLE</code></a>.</p>
  15931. <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>
  15932. <p>The integration tests are a more comprehensive suite of tests. They
  15933. run a full version of Synapse, including your changes, to check if
  15934. anything was broken. They are slower than the unit tests but will
  15935. typically catch more errors.</p>
  15936. <p>The following command will let you run the integration test with the most common
  15937. configuration:</p>
  15938. <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
  15939. </code></pre>
  15940. <p>(Note that the paths must be full paths! You could also write <code>$(realpath relative/path)</code> if needed.)</p>
  15941. <p>This configuration should generally cover your needs.</p>
  15942. <ul>
  15943. <li>To run with Postgres, supply the <code>-e POSTGRES=1 -e MULTI_POSTGRES=1</code> environment flags.</li>
  15944. <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>
  15945. </ul>
  15946. <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>
  15947. <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>
  15948. <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>
  15949. <p>It's often nice to develop on Synapse and write Complement tests at the same time.
  15950. Here is how to run your local Synapse checkout against your local Complement checkout.</p>
  15951. <p>(checkout <a href="https://github.com/matrix-org/complement"><code>complement</code></a> alongside your <code>synapse</code> checkout)</p>
  15952. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh
  15953. </code></pre>
  15954. <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>
  15955. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  15956. </code></pre>
  15957. <p>To run a specific test, you can specify the whole name structure:</p>
  15958. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages/parallel/Historical_events_resolve_in_the_correct_order
  15959. </code></pre>
  15960. <p>The above will run a monolithic (single-process) Synapse with SQLite as the database. For other configurations, try:</p>
  15961. <ul>
  15962. <li>Passing <code>POSTGRES=1</code> as an environment variable to use the Postgres database instead.</li>
  15963. <li>Passing <code>WORKERS=1</code> as an environment variable to use a workerised setup instead. This option implies the use of Postgres.
  15964. <ul>
  15965. <li>If setting <code>WORKERS=1</code>, optionally set <code>WORKER_TYPES=</code> to declare which worker
  15966. types you wish to test. A simple comma-delimited string containing the worker types
  15967. defined from the <code>WORKERS_CONFIG</code> template in
  15968. <a href="https://github.com/matrix-org/synapse/blob/develop/docker/configure_workers_and_start.py#L54">here</a>.
  15969. A safe example would be <code>WORKER_TYPES=&quot;federation_inbound, federation_sender, synchrotron&quot;</code>.
  15970. See the <a href="development/../workers.html">worker documentation</a> for additional information on workers.</li>
  15971. </ul>
  15972. </li>
  15973. <li>Passing <code>ASYNCIO_REACTOR=1</code> as an environment variable to use the Twisted asyncio reactor instead of the default one.</li>
  15974. <li>Passing <code>PODMAN=1</code> will use the <a href="https://podman.io/">podman</a> container runtime, instead of docker.</li>
  15975. <li>Passing <code>UNIX_SOCKETS=1</code> will utilise Unix socket functionality for Synapse, Redis, and Postgres(when applicable).</li>
  15976. </ul>
  15977. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>, e.g:</p>
  15978. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  15979. </code></pre>
  15980. <h3 id="prettier-formatting-with-gotestfmt"><a class="header" href="#prettier-formatting-with-gotestfmt">Prettier formatting with <code>gotestfmt</code></a></h3>
  15981. <p>If you want to format the output of the tests the same way as it looks in CI,
  15982. install <a href="https://github.com/GoTestTools/gotestfmt">gotestfmt</a>.</p>
  15983. <p>You can then use this incantation to format the tests appropriately:</p>
  15984. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -json | gotestfmt -hide successful-tests
  15985. </code></pre>
  15986. <p>(Remove <code>-hide successful-tests</code> if you don't want to hide successful tests.)</p>
  15987. <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>
  15988. <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>
  15989. <ol>
  15990. <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>
  15991. <li>Start the Complement tests</li>
  15992. <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>
  15993. <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>
  15994. <li>Install sqlite (database driver), <code>apt-get update &amp;&amp; apt-get install -y sqlite3</code></li>
  15995. <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>
  15996. </ol>
  15997. <h1 id="9-submit-your-patch"><a class="header" href="#9-submit-your-patch">9. Submit your patch.</a></h1>
  15998. <p>Once you're happy with your patch, it's time to prepare a Pull Request.</p>
  15999. <p>To prepare a Pull Request, please:</p>
  16000. <ol>
  16001. <li>verify that <a href="development/contributing_guide.html#test-test-test">all the tests pass</a>, including the coding style;</li>
  16002. <li><a href="development/contributing_guide.html#sign-off">sign off</a> your contribution;</li>
  16003. <li><code>git push</code> your commit to your fork of Synapse;</li>
  16004. <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>
  16005. <li>add a <a href="development/contributing_guide.html#changelog">changelog entry</a> and push it to your Pull Request;</li>
  16006. <li>that's it for now, a non-draft pull request will automatically request review from the team;</li>
  16007. <li>if you need to update your PR, please avoid rebasing and just add new commits to your branch.</li>
  16008. </ol>
  16009. <h2 id="changelog"><a class="header" href="#changelog">Changelog</a></h2>
  16010. <p>All changes, even minor ones, need a corresponding changelog / newsfragment
  16011. entry. These are managed by <a href="https://github.com/twisted/towncrier">Towncrier</a>.</p>
  16012. <p>To create a changelog entry, make a new file in the <code>changelog.d</code> directory named
  16013. in the format of <code>PRnumber.type</code>. The type can be one of the following:</p>
  16014. <ul>
  16015. <li><code>feature</code></li>
  16016. <li><code>bugfix</code></li>
  16017. <li><code>docker</code> (for updates to the Docker image)</li>
  16018. <li><code>doc</code> (for updates to the documentation)</li>
  16019. <li><code>removal</code> (also used for deprecations)</li>
  16020. <li><code>misc</code> (for internal-only changes)</li>
  16021. </ul>
  16022. <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
  16023. release, so the content of the file should be a short description of your
  16024. change in the same style as the rest of the changelog. The file can contain Markdown
  16025. formatting, and must end with a full stop (.) or an exclamation mark (!) for
  16026. consistency.</p>
  16027. <p>Adding credits to the changelog is encouraged, we value your
  16028. contributions and would like to have you shouted out in the release notes!</p>
  16029. <p>For example, a fix in PR #1234 would have its changelog entry in
  16030. <code>changelog.d/1234.bugfix</code>, and contain content like:</p>
  16031. <blockquote>
  16032. <p>The security levels of Florbs are now validated when received
  16033. via the <code>/federation/florb</code> endpoint. Contributed by Jane Matrix.</p>
  16034. </blockquote>
  16035. <p>If there are multiple pull requests involved in a single bugfix/feature/etc,
  16036. then the content for each <code>changelog.d</code> file should be the same. Towncrier will
  16037. merge the matching files together into a single changelog entry when we come to
  16038. release.</p>
  16039. <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>
  16040. <p>Obviously, you don't know if you should call your newsfile
  16041. <code>1234.bugfix</code> or <code>5678.bugfix</code> until you create the PR, which leads to a
  16042. chicken-and-egg problem.</p>
  16043. <p>There are two options for solving this:</p>
  16044. <ol>
  16045. <li>
  16046. <p>Open the PR without a changelog file, see what number you got, and <em>then</em>
  16047. add the changelog file to your branch, or:</p>
  16048. </li>
  16049. <li>
  16050. <p>Look at the <a href="https://github.com/matrix-org/synapse/issues?q=">list of all
  16051. issues/PRs</a>, add one to the
  16052. highest number you see, and quickly open the PR before somebody else claims
  16053. your number.</p>
  16054. <p><a href="https://github.com/richvdh/scripts/blob/master/next_github_number.sh">This
  16055. script</a>
  16056. might be helpful if you find yourself doing this a lot.</p>
  16057. </li>
  16058. </ol>
  16059. <p>Sorry, we know it's a bit fiddly, but it's <em>really</em> helpful for us when we come
  16060. to put together a release!</p>
  16061. <h3 id="debian-changelog"><a class="header" href="#debian-changelog">Debian changelog</a></h3>
  16062. <p>Changes which affect the debian packaging files (in <code>debian</code>) are an
  16063. exception to the rule that all changes require a <code>changelog.d</code> file.</p>
  16064. <p>In this case, you will need to add an entry to the debian changelog for the
  16065. next release. For this, run the following command:</p>
  16066. <pre><code>dch
  16067. </code></pre>
  16068. <p>This will make up a new version number (if there isn't already an unreleased
  16069. version in flight), and open an editor where you can add a new changelog entry.
  16070. (Our release process will ensure that the version number and maintainer name is
  16071. corrected for the release.)</p>
  16072. <p>If your change affects both the debian packaging <em>and</em> files outside the debian
  16073. directory, you will need both a regular newsfragment <em>and</em> an entry in the
  16074. debian changelog. (Though typically such changes should be submitted as two
  16075. separate pull requests.)</p>
  16076. <h2 id="sign-off"><a class="header" href="#sign-off">Sign off</a></h2>
  16077. <p>In order to have a concrete record that your contribution is intentional
  16078. and you agree to license it under the same terms as the project's license, we've adopted the
  16079. same lightweight approach that the Linux Kernel
  16080. <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>,
  16081. <a href="https://github.com/docker/docker/blob/master/CONTRIBUTING.md">Docker</a>, and many other
  16082. projects use: the DCO (<a href="http://developercertificate.org/">Developer Certificate of Origin</a>).
  16083. This is a simple declaration that you wrote
  16084. the contribution or otherwise have the right to contribute it to Matrix:</p>
  16085. <pre><code>Developer Certificate of Origin
  16086. Version 1.1
  16087. Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
  16088. 660 York Street, Suite 102,
  16089. San Francisco, CA 94110 USA
  16090. Everyone is permitted to copy and distribute verbatim copies of this
  16091. license document, but changing it is not allowed.
  16092. Developer's Certificate of Origin 1.1
  16093. By making a contribution to this project, I certify that:
  16094. (a) The contribution was created in whole or in part by me and I
  16095. have the right to submit it under the open source license
  16096. indicated in the file; or
  16097. (b) The contribution is based upon previous work that, to the best
  16098. of my knowledge, is covered under an appropriate open source
  16099. license and I have the right under that license to submit that
  16100. work with modifications, whether created in whole or in part
  16101. by me, under the same open source license (unless I am
  16102. permitted to submit under a different license), as indicated
  16103. in the file; or
  16104. (c) The contribution was provided directly to me by some other
  16105. person who certified (a), (b) or (c) and I have not modified
  16106. it.
  16107. (d) I understand and agree that this project and the contribution
  16108. are public and that a record of the contribution (including all
  16109. personal information I submit with it, including my sign-off) is
  16110. maintained indefinitely and may be redistributed consistent with
  16111. this project or the open source license(s) involved.
  16112. </code></pre>
  16113. <p>If you agree to this for your contribution, then all that's needed is to
  16114. include the line in your commit or pull request comment:</p>
  16115. <pre><code>Signed-off-by: Your Name &lt;your@email.example.org&gt;
  16116. </code></pre>
  16117. <p>We accept contributions under a legally identifiable name, such as
  16118. your name on government documentation or common-law names (names
  16119. claimed by legitimate usage or repute). Unfortunately, we cannot
  16120. accept anonymous contributions at this time.</p>
  16121. <p>Git allows you to add this signoff automatically when using the <code>-s</code>
  16122. flag to <code>git commit</code>, which uses the name and email set in your
  16123. <code>user.name</code> and <code>user.email</code> git configs.</p>
  16124. <h3 id="private-sign-off"><a class="header" href="#private-sign-off">Private Sign off</a></h3>
  16125. <p>If you would like to provide your legal name privately to the Matrix.org
  16126. Foundation (instead of in a public commit or comment), you can do so
  16127. by emailing your legal name and a link to the pull request to
  16128. <a href="mailto:dco@matrix.org?subject=Private%20sign%20off">dco@matrix.org</a>.
  16129. It helps to include &quot;sign off&quot; or similar in the subject line. You will then
  16130. be instructed further.</p>
  16131. <p>Once private sign off is complete, doing so for future contributions will not
  16132. be required.</p>
  16133. <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>
  16134. <p>Once the Pull Request is opened, you will see a few things:</p>
  16135. <ol>
  16136. <li>our automated CI (Continuous Integration) pipeline will run (again) the linters, the unit tests, the integration tests and more;</li>
  16137. <li>one or more of the developers will take a look at your Pull Request and offer feedback.</li>
  16138. </ol>
  16139. <p>From this point, you should:</p>
  16140. <ol>
  16141. <li>Look at the results of the CI pipeline.
  16142. <ul>
  16143. <li>If there is any error, fix the error.</li>
  16144. </ul>
  16145. </li>
  16146. <li>If a developer has requested changes, make these changes and let us know if it is ready for a developer to review again.
  16147. <ul>
  16148. <li>A pull request is a conversation, if you disagree with the suggestions, please respond and discuss it.</li>
  16149. </ul>
  16150. </li>
  16151. <li>Create a new commit with the changes.
  16152. <ul>
  16153. <li>Please do NOT overwrite the history. New commits make the reviewer's life easier.</li>
  16154. <li>Push this commits to your Pull Request.</li>
  16155. </ul>
  16156. </li>
  16157. <li>Back to 1.</li>
  16158. <li>Once the pull request is ready for review again please re-request review from whichever developer did your initial
  16159. review (or leave a comment in the pull request that you believe all required changes have been done).</li>
  16160. </ol>
  16161. <p>Once both the CI and the developers are happy, the patch will be merged into Synapse and released shortly!</p>
  16162. <h1 id="11-find-a-new-issue"><a class="header" href="#11-find-a-new-issue">11. Find a new issue.</a></h1>
  16163. <p>By now, you know the drill!</p>
  16164. <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>
  16165. <p>There are some notes for those with commit access to the project on how we
  16166. manage git <a href="development/git.html">here</a>.</p>
  16167. <h1 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h1>
  16168. <p>That's it! Matrix is a very open and collaborative project as you might expect
  16169. given our obsession with open communication. If we're going to successfully
  16170. matrix together all the fragmented communication technologies out there we are
  16171. reliant on contributions and collaboration from the community to do so. So
  16172. please get involved - and we hope you have as much fun hacking on Matrix as we
  16173. do!</p>
  16174. <div style="break-before: page; page-break-before: always;"></div><h1 id="code-style"><a class="header" href="#code-style">Code Style</a></h1>
  16175. <h2 id="formatting-tools"><a class="header" href="#formatting-tools">Formatting tools</a></h2>
  16176. <p>The Synapse codebase uses a number of code formatting tools in order to
  16177. quickly and automatically check for formatting (and sometimes logical)
  16178. errors in code.</p>
  16179. <p>The necessary tools are:</p>
  16180. <ul>
  16181. <li><a href="https://black.readthedocs.io/en/stable/">black</a>, a source code formatter;</li>
  16182. <li><a href="https://pycqa.github.io/isort/">isort</a>, which organises each file's imports;</li>
  16183. <li><a href="https://github.com/charliermarsh/ruff">ruff</a>, which can spot common errors; and</li>
  16184. <li><a href="https://mypy.readthedocs.io/en/stable/">mypy</a>, a type checker.</li>
  16185. </ul>
  16186. <p>See <a href="development/contributing_guide.html#run-the-linters">the contributing guide</a> for instructions
  16187. on how to install the above tools and run the linters.</p>
  16188. <p>It's worth noting that modern IDEs and text editors can run these tools
  16189. automatically on save. It may be worth looking into whether this
  16190. functionality is supported in your editor for a more convenient
  16191. development workflow. It is not, however, recommended to run <code>mypy</code>
  16192. on save as it takes a while and can be very resource intensive.</p>
  16193. <h2 id="general-rules"><a class="header" href="#general-rules">General rules</a></h2>
  16194. <ul>
  16195. <li><strong>Naming</strong>:
  16196. <ul>
  16197. <li>Use <code>CamelCase</code> for class and type names</li>
  16198. <li>Use underscores for <code>function_names</code> and <code>variable_names</code>.</li>
  16199. </ul>
  16200. </li>
  16201. <li><strong>Docstrings</strong>: should follow the <a href="https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings">google code
  16202. style</a>.
  16203. See the
  16204. <a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html">examples</a>
  16205. in the sphinx documentation.</li>
  16206. <li><strong>Imports</strong>:
  16207. <ul>
  16208. <li>
  16209. <p>Imports should be sorted by <code>isort</code> as described above.</p>
  16210. </li>
  16211. <li>
  16212. <p>Prefer to import classes and functions rather than packages or
  16213. modules.</p>
  16214. <p>Example:</p>
  16215. <pre><code class="language-python">from synapse.types import UserID
  16216. ...
  16217. user_id = UserID(local, server)
  16218. </code></pre>
  16219. <p>is preferred over:</p>
  16220. <pre><code class="language-python">from synapse import types
  16221. ...
  16222. user_id = types.UserID(local, server)
  16223. </code></pre>
  16224. <p>(or any other variant).</p>
  16225. <p>This goes against the advice in the Google style guide, but it
  16226. means that errors in the name are caught early (at import time).</p>
  16227. </li>
  16228. <li>
  16229. <p>Avoid wildcard imports (<code>from synapse.types import *</code>) and
  16230. relative imports (<code>from .types import UserID</code>).</p>
  16231. </li>
  16232. </ul>
  16233. </li>
  16234. </ul>
  16235. <h2 id="configuration-code-and-documentation-format"><a class="header" href="#configuration-code-and-documentation-format">Configuration code and documentation format</a></h2>
  16236. <p>When adding a configuration option to the code, if several settings are grouped into a single dict, ensure that your code
  16237. correctly handles the top-level option being set to <code>None</code> (as it will be if no sub-options are enabled).</p>
  16238. <p>The <a href="usage/configuration/config_documentation.html">configuration manual</a> acts as a
  16239. reference to Synapse's configuration options for server administrators.
  16240. Remember that many readers will be unfamiliar with YAML and server
  16241. administration in general, so it is important that when you add
  16242. a configuration option the documentation be as easy to understand as possible, which
  16243. includes following a consistent format.</p>
  16244. <p>Some guidelines follow:</p>
  16245. <ul>
  16246. <li>
  16247. <p>Each option should be listed in the config manual with the following format:</p>
  16248. <ul>
  16249. <li>
  16250. <p>The name of the option, prefixed by <code>###</code>. </p>
  16251. </li>
  16252. <li>
  16253. <p>A comment which describes the default behaviour (i.e. what
  16254. happens if the setting is omitted), as well as what the effect
  16255. will be if the setting is changed.</p>
  16256. </li>
  16257. <li>
  16258. <p>An example setting, using backticks to define the code block</p>
  16259. <p>For boolean (on/off) options, convention is that this example
  16260. should be the <em>opposite</em> to the default. For other options, the example should give
  16261. some non-default value which is likely to be useful to the reader.</p>
  16262. </li>
  16263. </ul>
  16264. </li>
  16265. <li>
  16266. <p>There should be a horizontal rule between each option, which can be achieved by adding <code>---</code> before and
  16267. after the option.</p>
  16268. </li>
  16269. <li>
  16270. <p><code>true</code> and <code>false</code> are spelt thus (as opposed to <code>True</code>, etc.)</p>
  16271. </li>
  16272. </ul>
  16273. <p>Example:</p>
  16274. <hr />
  16275. <h3 id="modules-3"><a class="header" href="#modules-3"><code>modules</code></a></h3>
  16276. <p>Use the <code>module</code> sub-option to add a module under <code>modules</code> to extend functionality.
  16277. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  16278. for the <code>module</code>.</p>
  16279. <p>Defaults to none.</p>
  16280. <p>Example configuration:</p>
  16281. <pre><code class="language-yaml">modules:
  16282. - module: my_super_module.MySuperClass
  16283. config:
  16284. do_thing: true
  16285. - module: my_other_super_module.SomeClass
  16286. config: {}
  16287. </code></pre>
  16288. <hr />
  16289. <p>Note that the sample configuration is generated from the synapse code
  16290. and is maintained by a script, <code>scripts-dev/generate_sample_config.sh</code>.
  16291. Making sure that the output from this script matches the desired format
  16292. is left as an exercise for the reader!</p>
  16293. <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>
  16294. <p>The Synapse team works off a shared review queue -- any new pull requests for
  16295. Synapse (or related projects) has a review requested from the entire team. Team
  16296. members should process this queue using the following rules:</p>
  16297. <ul>
  16298. <li>Any high urgency pull requests (e.g. fixes for broken continuous integration
  16299. or fixes for release blockers);</li>
  16300. <li>Follow-up reviews for pull requests which have previously received reviews;</li>
  16301. <li>Any remaining pull requests.</li>
  16302. </ul>
  16303. <p>For the latter two categories above, older pull requests should be prioritised.</p>
  16304. <p>It is explicit that there is no priority given to pull requests from the team
  16305. (vs from the community). If a pull request requires a quick turn around, please
  16306. explicitly communicate this via <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>
  16307. or as a comment on the pull request.</p>
  16308. <p>Once an initial review has been completed and the author has made additional changes,
  16309. follow-up reviews should go back to the same reviewer. This helps build a shared
  16310. context and conversation between author and reviewer.</p>
  16311. <p>As a team we aim to keep the number of inflight pull requests to a minimum to ensure
  16312. that ongoing work is finished before starting new work.</p>
  16313. <h2 id="performing-a-review"><a class="header" href="#performing-a-review">Performing a review</a></h2>
  16314. <p>To communicate to the rest of the team the status of each pull request, team
  16315. members should do the following:</p>
  16316. <ul>
  16317. <li>Assign themselves to the pull request (they should be left assigned to the
  16318. pull request until it is merged, closed, or are no longer the reviewer);</li>
  16319. <li>Review the pull request by leaving comments, questions, and suggestions;</li>
  16320. <li>Mark the pull request appropriately (as needing changes or accepted).</li>
  16321. </ul>
  16322. <p>If you are unsure about a particular part of the pull request (or are not confident
  16323. in your understanding of part of the code) then ask questions or request review
  16324. from the team again. When requesting review from the team be sure to leave a comment
  16325. with the rationale on why you're putting it back in the queue.</p>
  16326. <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>
  16327. <p>Releases of Synapse follow a two week release cycle with new releases usually
  16328. occurring on Tuesdays:</p>
  16329. <ul>
  16330. <li>Day 0: Synapse <code>N - 1</code> is released.</li>
  16331. <li>Day 7: Synapse <code>N</code> release candidate 1 is released.</li>
  16332. <li>Days 7 - 13: Synapse <code>N</code> release candidates 2+ are released, if bugs are found.</li>
  16333. <li>Day 14: Synapse <code>N</code> is released.</li>
  16334. </ul>
  16335. <p>Note that this schedule might be modified depending on the availability of the
  16336. Synapse team, e.g. releases may be skipped to avoid holidays.</p>
  16337. <p>Release announcements can be found in the
  16338. <a href="https://matrix.org/blog/category/releases">release category of the Matrix blog</a>.</p>
  16339. <h2 id="bugfix-releases"><a class="header" href="#bugfix-releases">Bugfix releases</a></h2>
  16340. <p>If a bug is found after release that is deemed severe enough (by a combination
  16341. of the impacted users and the impact on those users) then a bugfix release may
  16342. be issued. This may be at any point in the release cycle.</p>
  16343. <h2 id="security-releases"><a class="header" href="#security-releases">Security releases</a></h2>
  16344. <p>Security will sometimes be backported to the previous version and released
  16345. immediately before the next release candidate. An example of this might be:</p>
  16346. <ul>
  16347. <li>Day 0: Synapse N - 1 is released.</li>
  16348. <li>Day 7: Synapse (N - 1).1 is released as Synapse N - 1 + the security fix.</li>
  16349. <li>Day 7: Synapse N release candidate 1 is released (including the security fix).</li>
  16350. </ul>
  16351. <p>Depending on the impact and complexity of security fixes, multiple fixes might
  16352. be held to be released together.</p>
  16353. <p>In some cases, a pre-disclosure of a security release will be issued as a notice
  16354. to Synapse operators that there is an upcoming security release. These can be
  16355. found in the <a href="https://matrix.org/blog/category/security">security category of the Matrix blog</a>.</p>
  16356. <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>
  16357. <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>
  16358. <p>In an ideal world, our git commit history would be a linear progression of
  16359. commits each of which contains a single change building on what came
  16360. before. Here, by way of an arbitrary example, is the top of <code>git log --graph b2dba0607</code>:</p>
  16361. <img src="development/img/git/clean.png" alt="clean git graph" width="500px">
  16362. <p>Note how the commit comment explains clearly what is changing and why. Also
  16363. note the <em>absence</em> of merge commits, as well as the absence of commits called
  16364. things like (to pick a few culprits):
  16365. <a href="https://github.com/matrix-org/synapse/commit/84691da6c">“pep8”</a>, <a href="https://github.com/matrix-org/synapse/commit/474810d9d">“fix broken
  16366. test”</a>,
  16367. <a href="https://github.com/matrix-org/synapse/commit/c9d72e457">“oops”</a>,
  16368. <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
  16369. the president?”</a>.</p>
  16370. <p>There are a number of reasons why keeping a clean commit history is a good
  16371. thing:</p>
  16372. <ul>
  16373. <li>
  16374. <p>From time to time, after a change lands, it turns out to be necessary to
  16375. revert it, or to backport it to a release branch. Those operations are
  16376. <em>much</em> easier when the change is contained in a single commit.</p>
  16377. </li>
  16378. <li>
  16379. <p>Similarly, it's much easier to answer questions like “is the fix for
  16380. <code>/publicRooms</code> on the release branch?” if that change consists of a single
  16381. commit.</p>
  16382. </li>
  16383. <li>
  16384. <p>Likewise: “what has changed on this branch in the last week?” is much
  16385. clearer without merges and “pep8” commits everywhere.</p>
  16386. </li>
  16387. <li>
  16388. <p>Sometimes we need to figure out where a bug got introduced, or some
  16389. behaviour changed. One way of doing that is with <code>git bisect</code>: pick an
  16390. arbitrary commit between the known good point and the known bad point, and
  16391. see how the code behaves. However, that strategy fails if the commit you
  16392. chose is the middle of someone's epic branch in which they broke the world
  16393. before putting it back together again.</p>
  16394. </li>
  16395. </ul>
  16396. <p>One counterargument is that it is sometimes useful to see how a PR evolved as
  16397. it went through review cycles. This is true, but that information is always
  16398. 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
  16399. namespace</a>).</p>
  16400. <p>Of course, in reality, things are more complicated than that. We have release
  16401. branches as well as <code>develop</code> and <code>master</code>, and we deliberately merge changes
  16402. between them. Bugs often slip through and have to be fixed later. That's all
  16403. fine: this not a cast-iron rule which must be obeyed, but an ideal to aim
  16404. towards.</p>
  16405. <h2 id="merges-squashes-rebases-wtf"><a class="header" href="#merges-squashes-rebases-wtf">Merges, squashes, rebases: wtf?</a></h2>
  16406. <p>Ok, so that's what we'd like to achieve. How do we achieve it?</p>
  16407. <p>The TL;DR is: when you come to merge a pull request, you <em>probably</em> want to
  16408. “squash and merge”:</p>
  16409. <p><img src="development/img/git/squash.png" alt="squash and merge" />.</p>
  16410. <p>(This applies whether you are merging your own PR, or that of another
  16411. contributor.)</p>
  16412. <p>“Squash and merge”<sup id="a1"><a href="development/git.html#f1">1</a></sup> takes all of the changes in the
  16413. PR, and bundles them into a single commit. GitHub gives you the opportunity to
  16414. edit the commit message before you confirm, and normally you should do so,
  16415. because the default will be useless (again: <code>* woops typo</code> is not a useful
  16416. thing to keep in the historical record).</p>
  16417. <p>The main problem with this approach comes when you have a series of pull
  16418. requests which build on top of one another: as soon as you squash-merge the
  16419. first PR, you'll end up with a stack of conflicts to resolve in all of the
  16420. others. In general, it's best to avoid this situation in the first place by
  16421. trying not to have multiple related PRs in flight at the same time. Still,
  16422. sometimes that's not possible and doing a regular merge is the lesser evil.</p>
  16423. <p>Another occasion in which a regular merge makes more sense is a PR where you've
  16424. deliberately created a series of commits each of which makes sense in its own
  16425. right. For example: <a href="https://github.com/matrix-org/synapse/pull/6837">a PR which gradually propagates a refactoring operation
  16426. through the codebase</a>, or <a href="https://github.com/matrix-org/synapse/pull/5987">a
  16427. PR which is the culmination of several other
  16428. PRs</a>. In this case the ability
  16429. to figure out when a particular change/bug was introduced could be very useful.</p>
  16430. <p>Ultimately: <strong>this is not a hard-and-fast-rule</strong>. If in doubt, ask yourself “do
  16431. each of the commits I am about to merge make sense in their own right”, but
  16432. remember that we're just doing our best to balance “keeping the commit history
  16433. clean” with other factors.</p>
  16434. <h2 id="git-branching-model"><a class="header" href="#git-branching-model">Git branching model</a></h2>
  16435. <p>A <a href="https://nvie.com/posts/a-successful-git-branching-model/">lot</a>
  16436. <a href="http://scottchacon.com/2011/08/31/github-flow.html">of</a>
  16437. <a href="https://www.endoflineblog.com/gitflow-considered-harmful">words</a> have been
  16438. written in the past about git branching models (no really, <a href="https://martinfowler.com/articles/branching-patterns.html">a
  16439. lot</a>). I tend to
  16440. think the whole thing is overblown. Fundamentally, it's not that
  16441. complicated. Here's how we do it.</p>
  16442. <p>Let's start with a picture:</p>
  16443. <p><img src="development/img/git/branches.jpg" alt="branching model" /></p>
  16444. <p>It looks complicated, but it's really not. There's one basic rule: <em>anyone</em> is
  16445. free to merge from <em>any</em> more-stable branch to <em>any</em> less-stable branch at
  16446. <em>any</em> time<sup id="a2"><a href="development/git.html#f2">2</a></sup>. (The principle behind this is that if a
  16447. change is good enough for the more-stable branch, then it's also good enough go
  16448. put in a less-stable branch.)</p>
  16449. <p>Meanwhile, merging (or squashing, as per the above) from a less-stable to a
  16450. more-stable branch is a deliberate action in which you want to publish a change
  16451. or a set of changes to (some subset of) the world: for example, this happens
  16452. when a PR is landed, or as part of our release process.</p>
  16453. <p>So, what counts as a more- or less-stable branch? A little reflection will show
  16454. that our active branches are ordered thus, from more-stable to less-stable:</p>
  16455. <ul>
  16456. <li><code>master</code> (tracks our last release).</li>
  16457. <li><code>release-vX.Y</code> (the branch where we prepare the next release)<sup
  16458. id="a3"><a href="development/git.html#f3">3</a></sup>.</li>
  16459. <li>PR branches which are targeting the release.</li>
  16460. <li><code>develop</code> (our &quot;mainline&quot; branch containing our bleeding-edge).</li>
  16461. <li>regular PR branches.</li>
  16462. </ul>
  16463. <p>The corollary is: if you have a bugfix that needs to land in both
  16464. <code>release-vX.Y</code> <em>and</em> <code>develop</code>, then you should base your PR on
  16465. <code>release-vX.Y</code>, get it merged there, and then merge from <code>release-vX.Y</code> to
  16466. <code>develop</code>. (If a fix lands in <code>develop</code> and we later need it in a
  16467. release-branch, we can of course cherry-pick it, but landing it in the release
  16468. branch first helps reduce the chance of annoying conflicts.)</p>
  16469. <hr />
  16470. <p><b id="f1">[1]</b>: “Squash and merge” is GitHub's term for this
  16471. operation. Given that there is no merge involved, I'm not convinced it's the
  16472. most intuitive name. <a href="development/git.html#a1">^</a></p>
  16473. <p><b id="f2">[2]</b>: Well, anyone with commit access.<a href="development/git.html#a2">^</a></p>
  16474. <p><b id="f3">[3]</b>: Very, very occasionally (I think this has happened once in
  16475. the history of Synapse), we've had two releases in flight at once. Obviously,
  16476. <code>release-v1.2</code> is more-stable than <code>release-v1.3</code>. <a href="development/git.html#a3">^</a></p>
  16477. <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>
  16478. <p><strong>DO NOT USE THESE DEMO SERVERS IN PRODUCTION</strong></p>
  16479. <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>
  16480. <p>The demo setup allows running three federation Synapse servers, with server
  16481. names <code>localhost:8480</code>, <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  16482. <p>You can access them via any Matrix client over HTTP at <code>localhost:8080</code>,
  16483. <code>localhost:8081</code>, and <code>localhost:8082</code> or over HTTPS at <code>localhost:8480</code>,
  16484. <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  16485. <p>To enable the servers to communicate, self-signed SSL certificates are generated
  16486. and the servers are configured in a highly insecure way, including:</p>
  16487. <ul>
  16488. <li>Not checking certificates over federation.</li>
  16489. <li>Not verifying keys.</li>
  16490. </ul>
  16491. <p>The servers are configured to store their data under <code>demo/8080</code>, <code>demo/8081</code>, and
  16492. <code>demo/8082</code>. This includes configuration, logs, SQLite databases, and media.</p>
  16493. <p>Note that when joining a public room on a different homeserver via &quot;#foo:bar.net&quot;,
  16494. then you are (in the current implementation) joining a room with room_id &quot;foo&quot;.
  16495. This means that it won't work if your homeserver already has a room with that
  16496. name.</p>
  16497. <h2 id="using-the-demo-scripts"><a class="header" href="#using-the-demo-scripts">Using the demo scripts</a></h2>
  16498. <p>There's three main scripts with straightforward purposes:</p>
  16499. <ul>
  16500. <li><code>start.sh</code> will start the Synapse servers, generating any missing configuration.
  16501. <ul>
  16502. <li>This accepts a single parameter <code>--no-rate-limit</code> to &quot;disable&quot; rate limits
  16503. (they actually still exist, but are very high).</li>
  16504. </ul>
  16505. </li>
  16506. <li><code>stop.sh</code> will stop the Synapse servers.</li>
  16507. <li><code>clean.sh</code> will delete the configuration, databases, log files, etc.</li>
  16508. </ul>
  16509. <p>To start a completely new set of servers, run:</p>
  16510. <pre><code class="language-sh">./demo/stop.sh; ./demo/clean.sh &amp;&amp; ./demo/start.sh
  16511. </code></pre>
  16512. <div style="break-before: page; page-break-before: always;"></div><h1 id="opentracing-2"><a class="header" href="#opentracing-2">OpenTracing</a></h1>
  16513. <h2 id="background"><a class="header" href="#background">Background</a></h2>
  16514. <p>OpenTracing is a semi-standard being adopted by a number of distributed
  16515. tracing platforms. It is a common api for facilitating vendor-agnostic
  16516. tracing instrumentation. That is, we can use the OpenTracing api and
  16517. select one of a number of tracer implementations to do the heavy lifting
  16518. in the background. Our current selected implementation is Jaeger.</p>
  16519. <p>OpenTracing is a tool which gives an insight into the causal
  16520. relationship of work done in and between servers. The servers each track
  16521. events and report them to a centralised server - in Synapse's case:
  16522. Jaeger. The basic unit used to represent events is the span. The span
  16523. roughly represents a single piece of work that was done and the time at
  16524. which it occurred. A span can have child spans, meaning that the work of
  16525. the child had to be completed for the parent span to complete, or it can
  16526. have follow-on spans which represent work that is undertaken as a result
  16527. of the parent but is not depended on by the parent to in order to
  16528. finish.</p>
  16529. <p>Since this is undertaken in a distributed environment a request to
  16530. another server, such as an RPC or a simple GET, can be considered a span
  16531. (a unit or work) for the local server. This causal link is what
  16532. OpenTracing aims to capture and visualise. In order to do this metadata
  16533. about the local server's span, i.e the 'span context', needs to be
  16534. included with the request to the remote.</p>
  16535. <p>It is up to the remote server to decide what it does with the spans it
  16536. creates. This is called the sampling policy and it can be configured
  16537. through Jaeger's settings.</p>
  16538. <p>For OpenTracing concepts see
  16539. <a href="https://opentracing.io/docs/overview/what-is-tracing/">https://opentracing.io/docs/overview/what-is-tracing/</a>.</p>
  16540. <p>For more information about Jaeger's implementation see
  16541. <a href="https://www.jaegertracing.io/docs/">https://www.jaegertracing.io/docs/</a></p>
  16542. <h2 id="setting-up-opentracing"><a class="header" href="#setting-up-opentracing">Setting up OpenTracing</a></h2>
  16543. <p>To receive OpenTracing spans, start up a Jaeger server. This can be done
  16544. using docker like so:</p>
  16545. <pre><code class="language-sh">docker run -d --name jaeger \
  16546. -p 6831:6831/udp \
  16547. -p 6832:6832/udp \
  16548. -p 5778:5778 \
  16549. -p 16686:16686 \
  16550. -p 14268:14268 \
  16551. jaegertracing/all-in-one:1
  16552. </code></pre>
  16553. <p>Latest documentation is probably at
  16554. https://www.jaegertracing.io/docs/latest/getting-started.</p>
  16555. <h2 id="enable-opentracing-in-synapse"><a class="header" href="#enable-opentracing-in-synapse">Enable OpenTracing in Synapse</a></h2>
  16556. <p>OpenTracing is not enabled by default. It must be enabled in the
  16557. homeserver config by adding the <code>opentracing</code> option to your config file. You can find
  16558. documentation about how to do this in the <a href="usage/configuration/config_documentation.html#opentracing">config manual under the header 'Opentracing'</a>.
  16559. See below for an example Opentracing configuration: </p>
  16560. <pre><code class="language-yaml">opentracing:
  16561. enabled: true
  16562. homeserver_whitelist:
  16563. - &quot;mytrustedhomeserver.org&quot;
  16564. - &quot;*.myotherhomeservers.com&quot;
  16565. </code></pre>
  16566. <h2 id="homeserver-whitelisting"><a class="header" href="#homeserver-whitelisting">Homeserver whitelisting</a></h2>
  16567. <p>The homeserver whitelist is configured using regular expressions. A list
  16568. of regular expressions can be given and their union will be compared
  16569. when propagating any spans contexts to another homeserver.</p>
  16570. <p>Though it's mostly safe to send and receive span contexts to and from
  16571. untrusted users since span contexts are usually opaque ids it can lead
  16572. to two problems, namely:</p>
  16573. <ul>
  16574. <li>If the span context is marked as sampled by the sending homeserver
  16575. the receiver will sample it. Therefore two homeservers with wildly
  16576. different sampling policies could incur higher sampling counts than
  16577. intended.</li>
  16578. <li>Sending servers can attach arbitrary data to spans, known as
  16579. 'baggage'. For safety this has been disabled in Synapse but that
  16580. doesn't prevent another server sending you baggage which will be
  16581. logged to OpenTracing's logs.</li>
  16582. </ul>
  16583. <h2 id="configuring-jaeger"><a class="header" href="#configuring-jaeger">Configuring Jaeger</a></h2>
  16584. <p>Sampling strategies can be set as in this document:
  16585. <a href="https://www.jaegertracing.io/docs/latest/sampling/">https://www.jaegertracing.io/docs/latest/sampling/</a>.</p>
  16586. <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>
  16587. <p>Synapse's database schema is stored in the <code>synapse.storage.schema</code> module.</p>
  16588. <h2 id="logical-databases"><a class="header" href="#logical-databases">Logical databases</a></h2>
  16589. <p>Synapse supports splitting its datastore across multiple physical databases (which can
  16590. be useful for large installations), and the schema files are therefore split according
  16591. to the logical database they apply to.</p>
  16592. <p>At the time of writing, the following &quot;logical&quot; databases are supported:</p>
  16593. <ul>
  16594. <li><code>state</code> - used to store Matrix room state (more specifically, <code>state_groups</code>,
  16595. their relationships and contents).</li>
  16596. <li><code>main</code> - stores everything else.</li>
  16597. </ul>
  16598. <p>Additionally, the <code>common</code> directory contains schema files for tables which must be
  16599. present on <em>all</em> physical databases.</p>
  16600. <h2 id="synapse-schema-versions"><a class="header" href="#synapse-schema-versions">Synapse schema versions</a></h2>
  16601. <p>Synapse manages its database schema via &quot;schema versions&quot;. These are mainly used to
  16602. help avoid confusion if the Synapse codebase is rolled back after the database is
  16603. updated. They work as follows:</p>
  16604. <ul>
  16605. <li>
  16606. <p>The Synapse codebase defines a constant <code>synapse.storage.schema.SCHEMA_VERSION</code>
  16607. which represents the expectations made about the database by that version. For
  16608. example, as of Synapse v1.36, this is <code>59</code>.</p>
  16609. </li>
  16610. <li>
  16611. <p>The database stores a &quot;compatibility version&quot; in
  16612. <code>schema_compat_version.compat_version</code> which defines the <code>SCHEMA_VERSION</code> of the
  16613. oldest version of Synapse which will work with the database. On startup, if
  16614. <code>compat_version</code> is found to be newer than <code>SCHEMA_VERSION</code>, Synapse will refuse to
  16615. start.</p>
  16616. <p>Synapse automatically updates this field from
  16617. <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code>.</p>
  16618. </li>
  16619. <li>
  16620. <p>Whenever a backwards-incompatible change is made to the database format (normally
  16621. via a <code>delta</code> file), <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code> is also updated
  16622. so that administrators can not accidentally roll back to a too-old version of Synapse.</p>
  16623. </li>
  16624. </ul>
  16625. <p>Generally, the goal is to maintain compatibility with at least one or two previous
  16626. releases of Synapse, so any substantial change tends to require multiple releases and a
  16627. bit of forward-planning to get right.</p>
  16628. <p>As a worked example: we want to remove the <code>room_stats_historical</code> table. Here is how it
  16629. might pan out.</p>
  16630. <ol>
  16631. <li>
  16632. <p>Replace any code that <em>reads</em> from <code>room_stats_historical</code> with alternative
  16633. implementations, but keep writing to it in case of rollback to an earlier version.
  16634. Also, increase <code>synapse.storage.schema.SCHEMA_VERSION</code>. In this
  16635. instance, there is no existing code which reads from <code>room_stats_historical</code>, so
  16636. our starting point is:</p>
  16637. <p>v1.36.0: <code>SCHEMA_VERSION=59</code>, <code>SCHEMA_COMPAT_VERSION=59</code></p>
  16638. </li>
  16639. <li>
  16640. <p>Next (say in Synapse v1.37.0): remove the code that <em>writes</em> to
  16641. <code>room_stats_historical</code>, but don’t yet remove the table in case of rollback to
  16642. v1.36.0. Again, we increase <code>synapse.storage.schema.SCHEMA_VERSION</code>, but
  16643. because we have not broken compatibility with v1.36, we do not yet update
  16644. <code>SCHEMA_COMPAT_VERSION</code>. We now have:</p>
  16645. <p>v1.37.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=59</code>.</p>
  16646. </li>
  16647. <li>
  16648. <p>Later (say in Synapse v1.38.0): we can remove the table altogether. This will
  16649. break compatibility with v1.36.0, so we must update <code>SCHEMA_COMPAT_VERSION</code> accordingly.
  16650. There is no need to update <code>synapse.storage.schema.SCHEMA_VERSION</code>, since there is no
  16651. change to the Synapse codebase here. So we end up with:</p>
  16652. <p>v1.38.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=60</code>.</p>
  16653. </li>
  16654. </ol>
  16655. <p>If in doubt about whether to update <code>SCHEMA_VERSION</code> or not, it is generally best to
  16656. lean towards doing so.</p>
  16657. <h2 id="full-schema-dumps"><a class="header" href="#full-schema-dumps">Full schema dumps</a></h2>
  16658. <p>In the <code>full_schemas</code> directories, only the most recently-numbered snapshot is used
  16659. (<code>54</code> at the time of writing). Older snapshots (eg, <code>16</code>) are present for historical
  16660. reference only.</p>
  16661. <h3 id="building-full-schema-dumps"><a class="header" href="#building-full-schema-dumps">Building full schema dumps</a></h3>
  16662. <p>If you want to recreate these schemas, they need to be made from a database that
  16663. has had all background updates run.</p>
  16664. <p>To do so, use <code>scripts-dev/make_full_schema.sh</code>. This will produce new
  16665. <code>full.sql.postgres</code> and <code>full.sql.sqlite</code> files.</p>
  16666. <p>Ensure postgres is installed, then run:</p>
  16667. <pre><code class="language-sh">./scripts-dev/make_full_schema.sh -p postgres_username -o output_dir/
  16668. </code></pre>
  16669. <p>NB at the time of writing, this script predates the split into separate <code>state</code>/<code>main</code>
  16670. databases so will require updates to handle that correctly.</p>
  16671. <h2 id="delta-files"><a class="header" href="#delta-files">Delta files</a></h2>
  16672. <p>Delta files define the steps required to upgrade the database from an earlier version.
  16673. They can be written as either a file containing a series of SQL statements, or a Python
  16674. module.</p>
  16675. <p>Synapse remembers which delta files it has applied to a database (they are stored in the
  16676. <code>applied_schema_deltas</code> table) and will not re-apply them (even if a given file is
  16677. subsequently updated).</p>
  16678. <p>Delta files should be placed in a directory named <code>synapse/storage/schema/&lt;database&gt;/delta/&lt;version&gt;/</code>.
  16679. They are applied in alphanumeric order, so by convention the first two characters
  16680. of the filename should be an integer such as <code>01</code>, to put the file in the right order.</p>
  16681. <h3 id="sql-delta-files"><a class="header" href="#sql-delta-files">SQL delta files</a></h3>
  16682. <p>These should be named <code>*.sql</code>, or — for changes which should only be applied for a
  16683. given database engine — <code>*.sql.posgres</code> or <code>*.sql.sqlite</code>. For example, a delta which
  16684. adds a new column to the <code>foo</code> table might be called <code>01add_bar_to_foo.sql</code>.</p>
  16685. <p>Note that our SQL parser is a bit simple - it understands comments (<code>--</code> and <code>/*...*/</code>),
  16686. 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>
  16687. <h3 id="python-delta-files"><a class="header" href="#python-delta-files">Python delta files</a></h3>
  16688. <p>For more flexibility, a delta file can take the form of a python module. These should
  16689. be named <code>*.py</code>. Note that database-engine-specific modules are not supported here –
  16690. instead you can write <code>if isinstance(database_engine, PostgresEngine)</code> or similar.</p>
  16691. <p>A Python delta module should define either or both of the following functions:</p>
  16692. <pre><code class="language-python">import synapse.config.homeserver
  16693. import synapse.storage.engines
  16694. import synapse.storage.types
  16695. def run_create(
  16696. cur: synapse.storage.types.Cursor,
  16697. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  16698. ) -&gt; None:
  16699. &quot;&quot;&quot;Called whenever an existing or new database is to be upgraded&quot;&quot;&quot;
  16700. ...
  16701. def run_upgrade(
  16702. cur: synapse.storage.types.Cursor,
  16703. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  16704. config: synapse.config.homeserver.HomeServerConfig,
  16705. ) -&gt; None:
  16706. &quot;&quot;&quot;Called whenever an existing database is to be upgraded.&quot;&quot;&quot;
  16707. ...
  16708. </code></pre>
  16709. <h2 id="boolean-columns"><a class="header" href="#boolean-columns">Boolean columns</a></h2>
  16710. <p>Boolean columns require special treatment, since SQLite treats booleans the
  16711. same as integers.</p>
  16712. <p>Any new boolean column must be added to the <code>BOOLEAN_COLUMNS</code> list in
  16713. <code>synapse/_scripts/synapse_port_db.py</code>. This tells the port script to cast
  16714. the integer value from SQLite to a boolean before writing the value to the
  16715. postgres database.</p>
  16716. <h2 id="event_id-global-uniqueness"><a class="header" href="#event_id-global-uniqueness"><code>event_id</code> global uniqueness</a></h2>
  16717. <p><code>event_id</code>'s can be considered globally unique although there has been a lot of
  16718. debate on this topic in places like
  16719. <a href="https://github.com/matrix-org/matrix-spec-proposals/issues/2779">MSC2779</a> and
  16720. <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/2848">MSC2848</a> which
  16721. has no resolution yet (as of 2022-09-01). There are several places in Synapse
  16722. 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>
  16723. where we assume that event IDs are globally unique.</p>
  16724. <p>When scoping <code>event_id</code> in a database schema, it is often nice to accompany it
  16725. 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
  16726. makes it very easy to find and clean up everything in a room when it needs to be
  16727. purged (no need to use sub-<code>select</code> query or join from the <code>events</code> table).</p>
  16728. <p>A note on collisions: In room versions <code>1</code> and <code>2</code> it's possible to end up with
  16729. two events with the same <code>event_id</code> (in the same or different rooms). After room
  16730. version <code>3</code>, that can only happen with a hash collision, which we basically hope
  16731. will never happen (SHA256 has a massive big key space).</p>
  16732. <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>
  16733. <p>It can be desirable to implement &quot;experimental&quot; features which are disabled by
  16734. default and must be explicitly enabled via the Synapse configuration. This is
  16735. applicable for features which:</p>
  16736. <ul>
  16737. <li>Are unstable in the Matrix spec (e.g. those defined by an MSC that has not yet been merged).</li>
  16738. <li>Developers are not confident in their use by general Synapse administrators/users
  16739. (e.g. a feature is incomplete, buggy, performs poorly, or needs further testing).</li>
  16740. </ul>
  16741. <p>Note that this only really applies to features which are expected to be desirable
  16742. to a broad audience. The <a href="development/../modules/index.html">module infrastructure</a> should
  16743. instead be investigated for non-standard features.</p>
  16744. <p>Guarding experimental features behind configuration flags should help with some
  16745. of the following scenarios:</p>
  16746. <ul>
  16747. <li>Ensure that clients do not assume that unstable features exist (failing
  16748. gracefully if they do not).</li>
  16749. <li>Unstable features do not become de-facto standards and can be removed
  16750. aggressively (since only those who have opted-in will be affected).</li>
  16751. <li>Ease finding the implementation of unstable features in Synapse (for future
  16752. removal or stabilization).</li>
  16753. <li>Ease testing a feature (or removal of feature) due to enabling/disabling without
  16754. code changes. It also becomes possible to ask for wider testing, if desired.</li>
  16755. </ul>
  16756. <p>Experimental configuration flags should be disabled by default (requiring Synapse
  16757. administrators to explicitly opt-in), although there are situations where it makes
  16758. sense (from a product point-of-view) to enable features by default. This is
  16759. expected and not an issue.</p>
  16760. <p>It is not a requirement for experimental features to be behind a configuration flag,
  16761. but one should be used if unsure.</p>
  16762. <p>New experimental configuration flags should be added under the <code>experimental</code>
  16763. configuration key (see the <code>synapse.config.experimental</code> file) and either explain
  16764. (briefly) what is being enabled, or include the MSC number.</p>
  16765. <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>
  16766. <p>This is a quick cheat sheet for developers on how to use <a href="https://python-poetry.org/"><code>poetry</code></a>.</p>
  16767. <h1 id="installing"><a class="header" href="#installing">Installing</a></h1>
  16768. <p>See the <a href="development/contributing_guide.html#4-install-the-dependencies">contributing guide</a>.</p>
  16769. <p>Developers should use Poetry 1.3.2 or higher. If you encounter problems related
  16770. to poetry, please <a href="development/dependencies.html#check-the-version-of-poetry-with-poetry---version">double-check your poetry version</a>.</p>
  16771. <h1 id="background-1"><a class="header" href="#background-1">Background</a></h1>
  16772. <p>Synapse uses a variety of third-party Python packages to function as a homeserver.
  16773. Some of these are direct dependencies, listed in <code>pyproject.toml</code> under the
  16774. <code>[tool.poetry.dependencies]</code> section. The rest are transitive dependencies (the
  16775. things that our direct dependencies themselves depend on, and so on recursively.)</p>
  16776. <p>We maintain a locked list of all our dependencies (transitive included) so that
  16777. we can track exactly which version of each dependency appears in a given release.
  16778. See <a href="https://github.com/matrix-org/synapse/issues/11537#issue-1074469665">here</a>
  16779. for discussion of why we wanted this for Synapse. We chose to use
  16780. <a href="https://python-poetry.org/"><code>poetry</code></a> to manage this locked list; see
  16781. <a href="https://github.com/matrix-org/synapse/issues/11537#issuecomment-1015975819">this comment</a>
  16782. for the reasoning.</p>
  16783. <p>The locked dependencies get included in our &quot;self-contained&quot; releases: namely,
  16784. our docker images and our debian packages. We also use the locked dependencies
  16785. in development and our continuous integration.</p>
  16786. <p>Separately, our &quot;broad&quot; dependencies—the version ranges specified in
  16787. <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
  16788. to PyPI</a>. Installing from PyPI or from
  16789. the Synapse source tree directly will <em>not</em> use the locked dependencies; instead,
  16790. they'll pull in the latest version of each package available at install time.</p>
  16791. <h2 id="example-dependency"><a class="header" href="#example-dependency">Example dependency</a></h2>
  16792. <p>An example may help. We have a broad dependency on
  16793. <a href="https://pypi.org/project/phonenumbers/"><code>phonenumbers</code></a>, as declared in
  16794. 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>
  16795. <pre><code class="language-toml">[tool.poetry.dependencies]
  16796. # ...
  16797. phonenumbers = &quot;&gt;=8.2.0&quot;
  16798. </code></pre>
  16799. <p>In our lockfile this is
  16800. <a href="https://github.com/matrix-org/synapse/blob/dfc7646504cef3e4ff396c36089e1c6f1b1634de/poetry.lock#L679-L685">pinned</a>
  16801. to version 8.12.44, even though
  16802. <a href="https://pypi.org/project/phonenumbers/#history">newer versions are available</a>.</p>
  16803. <pre><code class="language-toml">[[package]]
  16804. name = &quot;phonenumbers&quot;
  16805. version = &quot;8.12.44&quot;
  16806. description = &quot;Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.&quot;
  16807. category = &quot;main&quot;
  16808. optional = false
  16809. python-versions = &quot;*&quot;
  16810. </code></pre>
  16811. <p>The lockfile also includes a
  16812. <a href="https://github.com/matrix-org/synapse/blob/release-v1.57/poetry.lock#L2178-L2181">cryptographic checksum</a>
  16813. of the sdists and wheels provided for this version of <code>phonenumbers</code>.</p>
  16814. <pre><code class="language-toml">[metadata.files]
  16815. # ...
  16816. phonenumbers = [
  16817. {file = &quot;phonenumbers-8.12.44-py2.py3-none-any.whl&quot;, hash = &quot;sha256:cc1299cf37b309ecab6214297663ab86cb3d64ae37fd5b88e904fe7983a874a6&quot;},
  16818. {file = &quot;phonenumbers-8.12.44.tar.gz&quot;, hash = &quot;sha256:26cfd0257d1704fe2f88caff2caabb70d16a877b1e65b6aae51f9fbbe10aa8ce&quot;},
  16819. ]
  16820. </code></pre>
  16821. <p>We can see this pinned version inside the docker image for that release:</p>
  16822. <pre><code>$ docker pull matrixdotorg/synapse:v1.57.0
  16823. ...
  16824. $ docker run --entrypoint pip matrixdotorg/synapse:v1.57.0 show phonenumbers
  16825. Name: phonenumbers
  16826. Version: 8.12.44
  16827. Summary: Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.
  16828. Home-page: https://github.com/daviddrysdale/python-phonenumbers
  16829. Author: David Drysdale
  16830. Author-email: dmd@lurklurk.org
  16831. License: Apache License 2.0
  16832. Location: /usr/local/lib/python3.9/site-packages
  16833. Requires:
  16834. Required-by: matrix-synapse
  16835. </code></pre>
  16836. <p>Whereas the wheel metadata just contains the broad dependencies:</p>
  16837. <pre><code>$ cd /tmp
  16838. $ wget https://files.pythonhosted.org/packages/ca/5e/d722d572cc5b3092402b783d6b7185901b444427633bd8a6b00ea0dd41b7/matrix_synapse-1.57.0rc1-py3-none-any.whl
  16839. ...
  16840. $ unzip -c matrix_synapse-1.57.0rc1-py3-none-any.whl matrix_synapse-1.57.0rc1.dist-info/METADATA | grep phonenumbers
  16841. Requires-Dist: phonenumbers (&gt;=8.2.0)
  16842. </code></pre>
  16843. <h1 id="tooling-recommendation-direnv"><a class="header" href="#tooling-recommendation-direnv">Tooling recommendation: direnv</a></h1>
  16844. <p><a href="https://direnv.net/"><code>direnv</code></a> is a tool for activating environments in your
  16845. shell inside a given directory. Its support for poetry is unofficial (a
  16846. community wiki recipe only), but works solidly in our experience. We thoroughly
  16847. recommend it for daily use. To use it:</p>
  16848. <ol>
  16849. <li><a href="https://direnv.net/docs/installation.html">Install <code>direnv</code></a> - it's likely
  16850. packaged for your system already.</li>
  16851. <li>Teach direnv about poetry. The <a href="https://github.com/direnv/direnv/wiki/Python#poetry">shell config here</a>
  16852. needs to be added to <code>~/.config/direnv/direnvrc</code> (or more generally <code>$XDG_CONFIG_HOME/direnv/direnvrc</code>).</li>
  16853. <li>Mark the synapse checkout as a poetry project: <code>echo layout poetry &gt; .envrc</code>.</li>
  16854. <li>Convince yourself that you trust this <code>.envrc</code> configuration and project.
  16855. Then formally confirm this to <code>direnv</code> by running <code>direnv allow</code>.</li>
  16856. </ol>
  16857. <p>Then whenever you navigate to the synapse checkout, you should be able to run
  16858. e.g. <code>mypy</code> instead of <code>poetry run mypy</code>; <code>python</code> instead of
  16859. <code>poetry run python</code>; and your shell commands will automatically run in the
  16860. context of poetry's venv, without having to run <code>poetry shell</code> beforehand.</p>
  16861. <h1 id="how-do-i"><a class="header" href="#how-do-i">How do I...</a></h1>
  16862. <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>
  16863. <pre><code class="language-shell">poetry install --all-extras --sync
  16864. </code></pre>
  16865. <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>
  16866. <pre><code class="language-shell"># Stop the current virtualenv if active
  16867. $ deactivate
  16868. # Remove all of the files from the current environment.
  16869. # Don't worry, even though it says &quot;all&quot;, this will only
  16870. # remove the Poetry virtualenvs for the current project.
  16871. $ poetry env remove --all
  16872. # Reactivate Poetry shell to create the virtualenv again
  16873. $ poetry shell
  16874. # Install everything again
  16875. $ poetry install --extras all
  16876. </code></pre>
  16877. <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>
  16878. <p>Use <code>poetry run cmd args</code> when you need the python virtualenv context.
  16879. To avoid typing <code>poetry run</code> all the time, you can run <code>poetry shell</code>
  16880. to start a new shell in the poetry virtualenv context. Within <code>poetry shell</code>,
  16881. <code>python</code>, <code>pip</code>, <code>mypy</code>, <code>trial</code>, etc. are all run inside the project virtualenv
  16882. and isolated from the rest o the system.</p>
  16883. <p>Roughly speaking, the translation from a traditional virtualenv is:</p>
  16884. <ul>
  16885. <li><code>env/bin/activate</code> -&gt; <code>poetry shell</code>, and</li>
  16886. <li><code>deactivate</code> -&gt; close the terminal (Ctrl-D, <code>exit</code>, etc.)</li>
  16887. </ul>
  16888. <p>See also the direnv recommendation above, which makes <code>poetry run</code> and
  16889. <code>poetry shell</code> unnecessary.</p>
  16890. <h2 id="inspect-the-poetry-virtualenv"><a class="header" href="#inspect-the-poetry-virtualenv">...inspect the <code>poetry</code> virtualenv?</a></h2>
  16891. <p>Some suggestions:</p>
  16892. <pre><code class="language-shell"># Current env only
  16893. poetry env info
  16894. # All envs: this allows you to have e.g. a poetry managed venv for Python 3.7,
  16895. # and another for Python 3.10.
  16896. poetry env list --full-path
  16897. poetry run pip list
  16898. </code></pre>
  16899. <p>Note that <code>poetry show</code> describes the abstract <em>lock file</em> rather than your
  16900. on-disk environment. With that said, <code>poetry show --tree</code> can sometimes be
  16901. useful.</p>
  16902. <h2 id="add-a-new-dependency"><a class="header" href="#add-a-new-dependency">...add a new dependency?</a></h2>
  16903. <p>Either:</p>
  16904. <ul>
  16905. <li>manually update <code>pyproject.toml</code>; then <code>poetry lock --no-update</code>; or else</li>
  16906. <li><code>poetry add packagename</code>. See <code>poetry add --help</code>; note the <code>--dev</code>,
  16907. <code>--extras</code> and <code>--optional</code> flags in particular.</li>
  16908. </ul>
  16909. <p>Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> files in your commit.</p>
  16910. <h2 id="remove-a-dependency"><a class="header" href="#remove-a-dependency">...remove a dependency?</a></h2>
  16911. <p>This is not done often and is untested, but</p>
  16912. <pre><code class="language-shell">poetry remove packagename
  16913. </code></pre>
  16914. <p>ought to do the trick. Alternatively, manually update <code>pyproject.toml</code> and
  16915. <code>poetry lock --no-update</code>. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code>
  16916. files in your commit.</p>
  16917. <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>
  16918. <p>Best done by manually editing <code>pyproject.toml</code>, then <code>poetry lock --no-update</code>.
  16919. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> in your commit.</p>
  16920. <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>
  16921. <p>Use</p>
  16922. <pre><code class="language-shell">poetry update packagename
  16923. </code></pre>
  16924. <p>to use the latest version of <code>packagename</code> in the locked environment, without
  16925. affecting the broad dependencies listed in the wheel.</p>
  16926. <p>There doesn't seem to be a way to do this whilst locking a <em>specific</em> version of
  16927. <code>packagename</code>. We can workaround this (crudely) as follows:</p>
  16928. <pre><code class="language-shell">poetry add packagename==1.2.3
  16929. # This should update pyproject.lock.
  16930. # Now undo the changes to pyproject.toml. For example
  16931. # git restore pyproject.toml
  16932. # Get poetry to recompute the content-hash of pyproject.toml without changing
  16933. # the locked package versions.
  16934. poetry lock --no-update
  16935. </code></pre>
  16936. <p>Either way, include the updated <code>poetry.lock</code> file in your commit.</p>
  16937. <h2 id="export-a-requirementstxt-file"><a class="header" href="#export-a-requirementstxt-file">...export a <code>requirements.txt</code> file?</a></h2>
  16938. <pre><code class="language-shell">poetry export --extras all
  16939. </code></pre>
  16940. <p>Be wary of bugs in <code>poetry export</code> and <code>pip install -r requirements.txt</code>.</p>
  16941. <h2 id="build-a-test-wheel"><a class="header" href="#build-a-test-wheel">...build a test wheel?</a></h2>
  16942. <p>I usually use</p>
  16943. <pre><code class="language-shell">poetry run pip install build &amp;&amp; poetry run python -m build
  16944. </code></pre>
  16945. <p>because <a href="https://github.com/pypa/build"><code>build</code></a> is a standardish tool which
  16946. doesn't require poetry. (It's what we use in CI too). However, you could try
  16947. <code>poetry build</code> too.</p>
  16948. <h2 id="handle-a-dependabot-pull-request"><a class="header" href="#handle-a-dependabot-pull-request">...handle a Dependabot pull request?</a></h2>
  16949. <p>Synapse uses Dependabot to keep the <code>poetry.lock</code> and <code>Cargo.lock</code> file
  16950. up-to-date with the latest releases of our dependencies. The changelog check is
  16951. omitted for Dependabot PRs; the release script will include them in the
  16952. changelog.</p>
  16953. <p>When reviewing a dependabot PR, ensure that:</p>
  16954. <ul>
  16955. <li>the lockfile changes look reasonable;</li>
  16956. <li>the upstream changelog file (linked in the description) doesn't include any
  16957. breaking changes;</li>
  16958. <li>continuous integration passes.</li>
  16959. </ul>
  16960. <p>In particular, any updates to the type hints (usually packages which start with <code>types-</code>)
  16961. should be safe to merge if linting passes.</p>
  16962. <h1 id="troubleshooting-4"><a class="header" href="#troubleshooting-4">Troubleshooting</a></h1>
  16963. <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>
  16964. <p>The minimum version of poetry supported by Synapse is 1.3.2.</p>
  16965. <p>It can also be useful to check the version of <code>poetry-core</code> in use. If you've
  16966. installed <code>poetry</code> with <code>pipx</code>, try <code>pipx runpip poetry list | grep poetry-core</code>.</p>
  16967. <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>
  16968. <p>Poetry caches a bunch of information about packages that isn't readily available
  16969. from PyPI. (This is what makes poetry seem slow when doing the first
  16970. <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>
  16971. <h2 id="remove-outdated-egg-info"><a class="header" href="#remove-outdated-egg-info">Remove outdated egg-info</a></h2>
  16972. <p>Delete the <code>matrix_synapse.egg-info/</code> directory from the root of your Synapse
  16973. install.</p>
  16974. <p>This stores some cached information about dependencies and often conflicts with
  16975. letting Poetry do the right thing.</p>
  16976. <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>
  16977. <p>Sometimes useful to see what poetry's internal logic is.</p>
  16978. <div style="break-before: page; page-break-before: always;"></div><h1 id="cancellation"><a class="header" href="#cancellation">Cancellation</a></h1>
  16979. <p>Sometimes, requests take a long time to service and clients disconnect
  16980. before Synapse produces a response. To avoid wasting resources, Synapse
  16981. can cancel request processing for select endpoints marked with the
  16982. <code>@cancellable</code> decorator.</p>
  16983. <p>Synapse makes use of Twisted's <code>Deferred.cancel()</code> feature to make
  16984. cancellation work. The <code>@cancellable</code> decorator does nothing by itself
  16985. and merely acts as a flag, signalling to developers and other code alike
  16986. that a method can be cancelled.</p>
  16987. <h2 id="enabling-cancellation-for-an-endpoint"><a class="header" href="#enabling-cancellation-for-an-endpoint">Enabling cancellation for an endpoint</a></h2>
  16988. <ol>
  16989. <li>Check that the endpoint method, and any <code>async</code> functions in its call
  16990. tree handle cancellation correctly. See
  16991. <a href="development/synapse_architecture/cancellation.html#handling-cancellation-correctly">Handling cancellation correctly</a>
  16992. for a list of things to look out for.</li>
  16993. <li>Add the <code>@cancellable</code> decorator to the <code>on_GET/POST/PUT/DELETE</code>
  16994. method. It's not recommended to make non-<code>GET</code> methods cancellable,
  16995. since cancellation midway through some database updates is less
  16996. likely to be handled correctly.</li>
  16997. </ol>
  16998. <h2 id="mechanics"><a class="header" href="#mechanics">Mechanics</a></h2>
  16999. <p>There are two stages to cancellation: downward propagation of a
  17000. <code>cancel()</code> call, followed by upwards propagation of a <code>CancelledError</code>
  17001. out of a blocked <code>await</code>.
  17002. Both Twisted and asyncio have a cancellation mechanism.</p>
  17003. <table><thead><tr><th></th><th>Method</th><th>Exception</th><th>Exception inherits from</th></tr></thead><tbody>
  17004. <tr><td>Twisted</td><td><code>Deferred.cancel()</code></td><td><code>twisted.internet.defer.CancelledError</code></td><td><code>Exception</code> (!)</td></tr>
  17005. <tr><td>asyncio</td><td><code>Task.cancel()</code></td><td><code>asyncio.CancelledError</code></td><td><code>BaseException</code></td></tr>
  17006. </tbody></table>
  17007. <h3 id="deferredcancel"><a class="header" href="#deferredcancel">Deferred.cancel()</a></h3>
  17008. <p>When Synapse starts handling a request, it runs the async method
  17009. responsible for handling it using <code>defer.ensureDeferred</code>, which returns
  17010. a <code>Deferred</code>. For example:</p>
  17011. <pre><code class="language-python">def do_something() -&gt; Deferred[None]:
  17012. ...
  17013. @cancellable
  17014. async def on_GET() -&gt; Tuple[int, JsonDict]:
  17015. d = make_deferred_yieldable(do_something())
  17016. await d
  17017. return 200, {}
  17018. request = defer.ensureDeferred(on_GET())
  17019. </code></pre>
  17020. <p>When a client disconnects early, Synapse checks for the presence of the
  17021. <code>@cancellable</code> decorator on <code>on_GET</code>. Since <code>on_GET</code> is cancellable,
  17022. <code>Deferred.cancel()</code> is called on the <code>Deferred</code> from
  17023. <code>defer.ensureDeferred</code>, ie. <code>request</code>. Twisted knows which <code>Deferred</code>
  17024. <code>request</code> is waiting on and passes the <code>cancel()</code> call on to <code>d</code>.</p>
  17025. <p>The <code>Deferred</code> being waited on, <code>d</code>, may have its own handling for
  17026. <code>cancel()</code> and pass the call on to other <code>Deferred</code>s.</p>
  17027. <p>Eventually, a <code>Deferred</code> handles the <code>cancel()</code> call by resolving itself
  17028. with a <code>CancelledError</code>.</p>
  17029. <h3 id="cancellederror"><a class="header" href="#cancellederror">CancelledError</a></h3>
  17030. <p>The <code>CancelledError</code> gets raised out of the <code>await</code> and bubbles up, as
  17031. per normal Python exception handling.</p>
  17032. <h2 id="handling-cancellation-correctly"><a class="header" href="#handling-cancellation-correctly">Handling cancellation correctly</a></h2>
  17033. <p>In general, when writing code that might be subject to cancellation, two
  17034. things must be considered:</p>
  17035. <ul>
  17036. <li>The effect of <code>CancelledError</code>s raised out of <code>await</code>s.</li>
  17037. <li>The effect of <code>Deferred</code>s being <code>cancel()</code>ed.</li>
  17038. </ul>
  17039. <p>Examples of code that handles cancellation incorrectly include:</p>
  17040. <ul>
  17041. <li><code>try-except</code> blocks which swallow <code>CancelledError</code>s.</li>
  17042. <li>Code that shares the same <code>Deferred</code>, which may be cancelled, between
  17043. multiple requests.</li>
  17044. <li>Code that starts some processing that's exempt from cancellation, but
  17045. uses a logging context from cancellable code. The logging context
  17046. will be finished upon cancellation, while the uncancelled processing
  17047. is still using it.</li>
  17048. </ul>
  17049. <p>Some common patterns are listed below in more detail.</p>
  17050. <h3 id="async-function-calls"><a class="header" href="#async-function-calls"><code>async</code> function calls</a></h3>
  17051. <p>Most functions in Synapse are relatively straightforward from a
  17052. cancellation standpoint: they don't do anything with <code>Deferred</code>s and
  17053. purely call and <code>await</code> other <code>async</code> functions.</p>
  17054. <p>An <code>async</code> function handles cancellation correctly if its own code
  17055. handles cancellation correctly and all the async function it calls
  17056. handle cancellation correctly. For example:</p>
  17057. <pre><code class="language-python">async def do_two_things() -&gt; None:
  17058. check_something()
  17059. await do_something()
  17060. await do_something_else()
  17061. </code></pre>
  17062. <p><code>do_two_things</code> handles cancellation correctly if <code>do_something</code> and
  17063. <code>do_something_else</code> handle cancellation correctly.</p>
  17064. <p>That is, when checking whether a function handles cancellation
  17065. correctly, its implementation and all its <code>async</code> function calls need to
  17066. be checked, recursively.</p>
  17067. <p>As <code>check_something</code> is not <code>async</code>, it does not need to be checked.</p>
  17068. <h3 id="cancellederrors"><a class="header" href="#cancellederrors">CancelledErrors</a></h3>
  17069. <p>Because Twisted's <code>CancelledError</code>s are <code>Exception</code>s, it's easy to
  17070. accidentally catch and suppress them. Care must be taken to ensure that
  17071. <code>CancelledError</code>s are allowed to propagate upwards.</p>
  17072. <table width="100%">
  17073. <tr>
  17074. <td width="50%" valign="top">
  17075. <p><strong>Bad</strong>:</p>
  17076. <pre><code class="language-python">try:
  17077. await do_something()
  17078. except Exception:
  17079. # `CancelledError` gets swallowed here.
  17080. logger.info(...)
  17081. </code></pre>
  17082. </td>
  17083. <td width="50%" valign="top">
  17084. <p><strong>Good</strong>:</p>
  17085. <pre><code class="language-python">try:
  17086. await do_something()
  17087. except CancelledError:
  17088. raise
  17089. except Exception:
  17090. logger.info(...)
  17091. </code></pre>
  17092. </td>
  17093. </tr>
  17094. <tr>
  17095. <td width="50%" valign="top">
  17096. <p><strong>OK</strong>:</p>
  17097. <pre><code class="language-python">try:
  17098. check_something()
  17099. # A `CancelledError` won't ever be raised here.
  17100. except Exception:
  17101. logger.info(...)
  17102. </code></pre>
  17103. </td>
  17104. <td width="50%" valign="top">
  17105. <p><strong>Good</strong>:</p>
  17106. <pre><code class="language-python">try:
  17107. await do_something()
  17108. except ValueError:
  17109. logger.info(...)
  17110. </code></pre>
  17111. </td>
  17112. </tr>
  17113. </table>
  17114. <h4 id="defergatherresults"><a class="header" href="#defergatherresults">defer.gatherResults</a></h4>
  17115. <p><code>defer.gatherResults</code> produces a <code>Deferred</code> which:</p>
  17116. <ul>
  17117. <li>broadcasts <code>cancel()</code> calls to every <code>Deferred</code> being waited on.</li>
  17118. <li>wraps the first exception it sees in a <code>FirstError</code>.</li>
  17119. </ul>
  17120. <p>Together, this means that <code>CancelledError</code>s will be wrapped in
  17121. a <code>FirstError</code> unless unwrapped. Such <code>FirstError</code>s are liable to be
  17122. swallowed, so they must be unwrapped.</p>
  17123. <table width="100%">
  17124. <tr>
  17125. <td width="50%" valign="top">
  17126. <p><strong>Bad</strong>:</p>
  17127. <pre><code class="language-python">async def do_something() -&gt; None:
  17128. await make_deferred_yieldable(
  17129. defer.gatherResults([...], consumeErrors=True)
  17130. )
  17131. try:
  17132. await do_something()
  17133. except CancelledError:
  17134. raise
  17135. except Exception:
  17136. # `FirstError(CancelledError)` gets swallowed here.
  17137. logger.info(...)
  17138. </code></pre>
  17139. </td>
  17140. <td width="50%" valign="top">
  17141. <p><strong>Good</strong>:</p>
  17142. <pre><code class="language-python">async def do_something() -&gt; None:
  17143. await make_deferred_yieldable(
  17144. defer.gatherResults([...], consumeErrors=True)
  17145. ).addErrback(unwrapFirstError)
  17146. try:
  17147. await do_something()
  17148. except CancelledError:
  17149. raise
  17150. except Exception:
  17151. logger.info(...)
  17152. </code></pre>
  17153. </td>
  17154. </tr>
  17155. </table>
  17156. <h3 id="creation-of-deferreds"><a class="header" href="#creation-of-deferreds">Creation of <code>Deferred</code>s</a></h3>
  17157. <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>
  17158. <table width="100%">
  17159. <tr>
  17160. <td width="50%" valign="top">
  17161. <p><strong>Bad</strong>:</p>
  17162. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  17163. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  17164. deferred = cache.get(room_id)
  17165. if deferred is None:
  17166. deferred = Deferred()
  17167. cache[room_id] = deferred
  17168. # `deferred` can have multiple waiters.
  17169. # All of them will observe a `CancelledError`
  17170. # if any one of them is cancelled.
  17171. return make_deferred_yieldable(deferred)
  17172. # Request 1
  17173. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17174. # Request 2
  17175. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17176. </code></pre>
  17177. </td>
  17178. <td width="50%" valign="top">
  17179. <p><strong>Good</strong>:</p>
  17180. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  17181. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  17182. deferred = cache.get(room_id)
  17183. if deferred is None:
  17184. deferred = Deferred()
  17185. cache[room_id] = deferred
  17186. # `deferred` will never be cancelled now.
  17187. # A `CancelledError` will still come out of
  17188. # the `await`.
  17189. # `delay_cancellation` may also be used.
  17190. return make_deferred_yieldable(stop_cancellation(deferred))
  17191. # Request 1
  17192. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17193. # Request 2
  17194. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17195. </code></pre>
  17196. </td>
  17197. </tr>
  17198. <tr>
  17199. <td width="50%" valign="top">
  17200. </td>
  17201. <td width="50%" valign="top">
  17202. <p><strong>Good</strong>:</p>
  17203. <pre><code class="language-python">cache: Dict[str, List[Deferred[None]]] = {}
  17204. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  17205. if room_id not in cache:
  17206. cache[room_id] = []
  17207. # Each request gets its own `Deferred` to wait on.
  17208. deferred = Deferred()
  17209. cache[room_id]].append(deferred)
  17210. return make_deferred_yieldable(deferred)
  17211. # Request 1
  17212. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17213. # Request 2
  17214. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17215. </code></pre>
  17216. </td>
  17217. </table>
  17218. <h3 id="uncancelled-processing"><a class="header" href="#uncancelled-processing">Uncancelled processing</a></h3>
  17219. <p>Some <code>async</code> functions may kick off some <code>async</code> processing which is
  17220. intentionally protected from cancellation, by <code>stop_cancellation</code> or
  17221. other means. If the <code>async</code> processing inherits the logcontext of the
  17222. request which initiated it, care must be taken to ensure that the
  17223. logcontext is not finished before the <code>async</code> processing completes.</p>
  17224. <table width="100%">
  17225. <tr>
  17226. <td width="50%" valign="top">
  17227. <p><strong>Bad</strong>:</p>
  17228. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  17229. async def do_something_else(
  17230. to_resolve: Deferred[None]
  17231. ) -&gt; None:
  17232. await ...
  17233. logger.info(&quot;done!&quot;)
  17234. to_resolve.callback(None)
  17235. async def do_something() -&gt; None:
  17236. if not cache:
  17237. to_resolve = Deferred()
  17238. cache = ObservableDeferred(to_resolve)
  17239. # `do_something_else` will never be cancelled and
  17240. # can outlive the `request-1` logging context.
  17241. run_in_background(do_something_else, to_resolve)
  17242. await make_deferred_yieldable(cache.observe())
  17243. with LoggingContext(&quot;request-1&quot;):
  17244. await do_something()
  17245. </code></pre>
  17246. </td>
  17247. <td width="50%" valign="top">
  17248. <p><strong>Good</strong>:</p>
  17249. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  17250. async def do_something_else(
  17251. to_resolve: Deferred[None]
  17252. ) -&gt; None:
  17253. await ...
  17254. logger.info(&quot;done!&quot;)
  17255. to_resolve.callback(None)
  17256. async def do_something() -&gt; None:
  17257. if not cache:
  17258. to_resolve = Deferred()
  17259. cache = ObservableDeferred(to_resolve)
  17260. run_in_background(do_something_else, to_resolve)
  17261. # We'll wait until `do_something_else` is
  17262. # done before raising a `CancelledError`.
  17263. await make_deferred_yieldable(
  17264. delay_cancellation(cache.observe())
  17265. )
  17266. else:
  17267. await make_deferred_yieldable(cache.observe())
  17268. with LoggingContext(&quot;request-1&quot;):
  17269. await do_something()
  17270. </code></pre>
  17271. </td>
  17272. </tr>
  17273. <tr>
  17274. <td width="50%">
  17275. <p><strong>OK</strong>:</p>
  17276. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  17277. async def do_something_else(
  17278. to_resolve: Deferred[None]
  17279. ) -&gt; None:
  17280. await ...
  17281. logger.info(&quot;done!&quot;)
  17282. to_resolve.callback(None)
  17283. async def do_something() -&gt; None:
  17284. if not cache:
  17285. to_resolve = Deferred()
  17286. cache = ObservableDeferred(to_resolve)
  17287. # `do_something_else` will get its own independent
  17288. # logging context. `request-1` will not count any
  17289. # metrics from `do_something_else`.
  17290. run_as_background_process(
  17291. &quot;do_something_else&quot;,
  17292. do_something_else,
  17293. to_resolve,
  17294. )
  17295. await make_deferred_yieldable(cache.observe())
  17296. with LoggingContext(&quot;request-1&quot;):
  17297. await do_something()
  17298. </code></pre>
  17299. </td>
  17300. <td width="50%">
  17301. </td>
  17302. </tr>
  17303. </table>
  17304. <div style="break-before: page; page-break-before: always;"></div><h1 id="log-contexts"><a class="header" href="#log-contexts">Log Contexts</a></h1>
  17305. <p>To help track the processing of individual requests, synapse uses a
  17306. '<code>log context</code>' to track which request it is handling at any given
  17307. moment. This is done via a thread-local variable; a <code>logging.Filter</code> is
  17308. then used to fish the information back out of the thread-local variable
  17309. and add it to each log record.</p>
  17310. <p>Logcontexts are also used for CPU and database accounting, so that we
  17311. can track which requests were responsible for high CPU use or database
  17312. activity.</p>
  17313. <p>The <code>synapse.logging.context</code> module provides facilities for managing
  17314. the current log context (as well as providing the <code>LoggingContextFilter</code>
  17315. class).</p>
  17316. <p>Asynchronous functions make the whole thing complicated, so this document describes
  17317. how it all works, and how to write code which follows the rules.</p>
  17318. <p>In this document, &quot;awaitable&quot; refers to any object which can be <code>await</code>ed. In the context of
  17319. Synapse, that normally means either a coroutine or a Twisted
  17320. <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html"><code>Deferred</code></a>.</p>
  17321. <h2 id="logcontexts-without-asynchronous-code"><a class="header" href="#logcontexts-without-asynchronous-code">Logcontexts without asynchronous code</a></h2>
  17322. <p>In the absence of any asynchronous voodoo, things are simple enough. As with
  17323. any code of this nature, the rule is that our function should leave
  17324. things as it found them:</p>
  17325. <pre><code class="language-python">from synapse.logging import context # omitted from future snippets
  17326. def handle_request(request_id):
  17327. request_context = context.LoggingContext()
  17328. calling_context = context.set_current_context(request_context)
  17329. try:
  17330. request_context.request = request_id
  17331. do_request_handling()
  17332. logger.debug(&quot;finished&quot;)
  17333. finally:
  17334. context.set_current_context(calling_context)
  17335. def do_request_handling():
  17336. logger.debug(&quot;phew&quot;) # this will be logged against request_id
  17337. </code></pre>
  17338. <p>LoggingContext implements the context management methods, so the above
  17339. can be written much more succinctly as:</p>
  17340. <pre><code class="language-python">def handle_request(request_id):
  17341. with context.LoggingContext() as request_context:
  17342. request_context.request = request_id
  17343. do_request_handling()
  17344. logger.debug(&quot;finished&quot;)
  17345. def do_request_handling():
  17346. logger.debug(&quot;phew&quot;)
  17347. </code></pre>
  17348. <h2 id="using-logcontexts-with-awaitables"><a class="header" href="#using-logcontexts-with-awaitables">Using logcontexts with awaitables</a></h2>
  17349. <p>Awaitables break the linear flow of code so that there is no longer a single entry point
  17350. where we should set the logcontext and a single exit point where we should remove it.</p>
  17351. <p>Consider the example above, where <code>do_request_handling</code> needs to do some
  17352. blocking operation, and returns an awaitable:</p>
  17353. <pre><code class="language-python">async def handle_request(request_id):
  17354. with context.LoggingContext() as request_context:
  17355. request_context.request = request_id
  17356. await do_request_handling()
  17357. logger.debug(&quot;finished&quot;)
  17358. </code></pre>
  17359. <p>In the above flow:</p>
  17360. <ul>
  17361. <li>The logcontext is set</li>
  17362. <li><code>do_request_handling</code> is called, and returns an awaitable</li>
  17363. <li><code>handle_request</code> awaits the awaitable</li>
  17364. <li>Execution of <code>handle_request</code> is suspended</li>
  17365. </ul>
  17366. <p>So we have stopped processing the request (and will probably go on to
  17367. start processing the next), without clearing the logcontext.</p>
  17368. <p>To circumvent this problem, synapse code assumes that, wherever you have
  17369. an awaitable, you will want to <code>await</code> it. To that end, whereever
  17370. functions return awaitables, we adopt the following conventions:</p>
  17371. <p><strong>Rules for functions returning awaitables:</strong></p>
  17372. <blockquote>
  17373. <ul>
  17374. <li>If the awaitable is already complete, the function returns with the
  17375. same logcontext it started with.</li>
  17376. <li>If the awaitable is incomplete, the function clears the logcontext
  17377. before returning; when the awaitable completes, it restores the
  17378. logcontext before running any callbacks.</li>
  17379. </ul>
  17380. </blockquote>
  17381. <p>That sounds complicated, but actually it means a lot of code (including
  17382. the example above) &quot;just works&quot;. There are two cases:</p>
  17383. <ul>
  17384. <li>
  17385. <p>If <code>do_request_handling</code> returns a completed awaitable, then the
  17386. logcontext will still be in place. In this case, execution will
  17387. continue immediately after the <code>await</code>; the &quot;finished&quot; line will
  17388. be logged against the right context, and the <code>with</code> block restores
  17389. the original context before we return to the caller.</p>
  17390. </li>
  17391. <li>
  17392. <p>If the returned awaitable is incomplete, <code>do_request_handling</code> clears
  17393. the logcontext before returning. The logcontext is therefore clear
  17394. when <code>handle_request</code> <code>await</code>s the awaitable.</p>
  17395. <p>Once <code>do_request_handling</code>'s awaitable completes, it will reinstate
  17396. the logcontext, before running the second half of <code>handle_request</code>,
  17397. so again the &quot;finished&quot; line will be logged against the right context,
  17398. and the <code>with</code> block restores the original context.</p>
  17399. </li>
  17400. </ul>
  17401. <p>As an aside, it's worth noting that <code>handle_request</code> follows our rules</p>
  17402. <ul>
  17403. <li>though that only matters if the caller has its own logcontext which it
  17404. cares about.</li>
  17405. </ul>
  17406. <p>The following sections describe pitfalls and helpful patterns when
  17407. implementing these rules.</p>
  17408. <h2 id="always-await-your-awaitables"><a class="header" href="#always-await-your-awaitables">Always await your awaitables</a></h2>
  17409. <p>Whenever you get an awaitable back from a function, you should <code>await</code> on
  17410. it as soon as possible. Do not pass go; do not do any logging; do not
  17411. call any other functions.</p>
  17412. <pre><code class="language-python">async def fun():
  17413. logger.debug(&quot;starting&quot;)
  17414. await do_some_stuff() # just like this
  17415. coro = more_stuff()
  17416. result = await coro # also fine, of course
  17417. return result
  17418. </code></pre>
  17419. <p>Provided this pattern is followed all the way back up to the callchain
  17420. to where the logcontext was set, this will make things work out ok:
  17421. provided <code>do_some_stuff</code> and <code>more_stuff</code> follow the rules above, then
  17422. so will <code>fun</code>.</p>
  17423. <p>It's all too easy to forget to <code>await</code>: for instance if we forgot that
  17424. <code>do_some_stuff</code> returned an awaitable, we might plough on regardless. This
  17425. leads to a mess; it will probably work itself out eventually, but not
  17426. before a load of stuff has been logged against the wrong context.
  17427. (Normally, other things will break, more obviously, if you forget to
  17428. <code>await</code>, so this tends not to be a major problem in practice.)</p>
  17429. <p>Of course sometimes you need to do something a bit fancier with your
  17430. awaitable - not all code follows the linear A-then-B-then-C pattern.
  17431. Notes on implementing more complex patterns are in later sections.</p>
  17432. <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>
  17433. <p>Most of the time, an awaitable comes from another synapse function.
  17434. Sometimes, though, we need to make up a new awaitable, or we get an awaitable
  17435. back from external code. We need to make it follow our rules.</p>
  17436. <p>The easy way to do it is by using <code>context.make_deferred_yieldable</code>. Suppose we want to implement
  17437. <code>sleep</code>, which returns a deferred which will run its callbacks after a
  17438. given number of seconds. That might look like:</p>
  17439. <pre><code class="language-python"># not a logcontext-rules-compliant function
  17440. def get_sleep_deferred(seconds):
  17441. d = defer.Deferred()
  17442. reactor.callLater(seconds, d.callback, None)
  17443. return d
  17444. </code></pre>
  17445. <p>That doesn't follow the rules, but we can fix it by calling it through
  17446. <code>context.make_deferred_yieldable</code>:</p>
  17447. <pre><code class="language-python">async def sleep(seconds):
  17448. return await context.make_deferred_yieldable(get_sleep_deferred(seconds))
  17449. </code></pre>
  17450. <h2 id="fire-and-forget"><a class="header" href="#fire-and-forget">Fire-and-forget</a></h2>
  17451. <p>Sometimes you want to fire off a chain of execution, but not wait for
  17452. its result. That might look a bit like this:</p>
  17453. <pre><code class="language-python">async def do_request_handling():
  17454. await foreground_operation()
  17455. # *don't* do this
  17456. background_operation()
  17457. logger.debug(&quot;Request handling complete&quot;)
  17458. async def background_operation():
  17459. await first_background_step()
  17460. logger.debug(&quot;Completed first step&quot;)
  17461. await second_background_step()
  17462. logger.debug(&quot;Completed second step&quot;)
  17463. </code></pre>
  17464. <p>The above code does a couple of steps in the background after
  17465. <code>do_request_handling</code> has finished. The log lines are still logged
  17466. against the <code>request_context</code> logcontext, which may or may not be
  17467. desirable. There are two big problems with the above, however. The first
  17468. problem is that, if <code>background_operation</code> returns an incomplete
  17469. awaitable, it will expect its caller to <code>await</code> immediately, so will have
  17470. cleared the logcontext. In this example, that means that 'Request
  17471. handling complete' will be logged without any context.</p>
  17472. <p>The second problem, which is potentially even worse, is that when the
  17473. awaitable returned by <code>background_operation</code> completes, it will restore
  17474. the original logcontext. There is nothing waiting on that awaitable, so
  17475. the logcontext will leak into the reactor and possibly get attached to
  17476. some arbitrary future operation.</p>
  17477. <p>There are two potential solutions to this.</p>
  17478. <p>One option is to surround the call to <code>background_operation</code> with a
  17479. <code>PreserveLoggingContext</code> call. That will reset the logcontext before
  17480. starting <code>background_operation</code> (so the context restored when the
  17481. deferred completes will be the empty logcontext), and will restore the
  17482. current logcontext before continuing the foreground process:</p>
  17483. <pre><code class="language-python">async def do_request_handling():
  17484. await foreground_operation()
  17485. # start background_operation off in the empty logcontext, to
  17486. # avoid leaking the current context into the reactor.
  17487. with PreserveLoggingContext():
  17488. background_operation()
  17489. # this will now be logged against the request context
  17490. logger.debug(&quot;Request handling complete&quot;)
  17491. </code></pre>
  17492. <p>Obviously that option means that the operations done in
  17493. <code>background_operation</code> would be not be logged against a logcontext
  17494. (though that might be fixed by setting a different logcontext via a
  17495. <code>with LoggingContext(...)</code> in <code>background_operation</code>).</p>
  17496. <p>The second option is to use <code>context.run_in_background</code>, which wraps a
  17497. function so that it doesn't reset the logcontext even when it returns
  17498. an incomplete awaitable, and adds a callback to the returned awaitable to
  17499. reset the logcontext. In other words, it turns a function that follows
  17500. the Synapse rules about logcontexts and awaitables into one which behaves
  17501. more like an external function --- the opposite operation to that
  17502. described in the previous section. It can be used like this:</p>
  17503. <pre><code class="language-python">async def do_request_handling():
  17504. await foreground_operation()
  17505. context.run_in_background(background_operation)
  17506. # this will now be logged against the request context
  17507. logger.debug(&quot;Request handling complete&quot;)
  17508. </code></pre>
  17509. <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>
  17510. <p>A typical example of this is where we want to collect together two or
  17511. more awaitables via <code>defer.gatherResults</code>:</p>
  17512. <pre><code class="language-python">a1 = operation1()
  17513. a2 = operation2()
  17514. a3 = defer.gatherResults([a1, a2])
  17515. </code></pre>
  17516. <p>This is really a variation of the fire-and-forget problem above, in that
  17517. we are firing off <code>a1</code> and <code>a2</code> without awaiting on them. The difference
  17518. is that we now have third-party code attached to their callbacks. Anyway
  17519. either technique given in the <a href="log_contexts.html#fire-and-forget">Fire-and-forget</a>
  17520. section will work.</p>
  17521. <p>Of course, the new awaitable returned by <code>gather</code> needs to be
  17522. wrapped in order to make it follow the logcontext rules before we can
  17523. 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
  17524. follow the
  17525. rules</a>.</p>
  17526. <p>So, option one: reset the logcontext before starting the operations to
  17527. be gathered:</p>
  17528. <pre><code class="language-python">async def do_request_handling():
  17529. with PreserveLoggingContext():
  17530. a1 = operation1()
  17531. a2 = operation2()
  17532. result = await defer.gatherResults([a1, a2])
  17533. </code></pre>
  17534. <p>In this case particularly, though, option two, of using
  17535. <code>context.run_in_background</code> almost certainly makes more sense, so that
  17536. <code>operation1</code> and <code>operation2</code> are both logged against the original
  17537. logcontext. This looks like:</p>
  17538. <pre><code class="language-python">async def do_request_handling():
  17539. a1 = context.run_in_background(operation1)
  17540. a2 = context.run_in_background(operation2)
  17541. result = await make_deferred_yieldable(defer.gatherResults([a1, a2]))
  17542. </code></pre>
  17543. <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>
  17544. <p>It turns out that our logcontext rules do not play nicely with awaitable
  17545. chains which get orphaned and garbage-collected.</p>
  17546. <p>Imagine we have some code that looks like this:</p>
  17547. <pre><code class="language-python">listener_queue = []
  17548. def on_something_interesting():
  17549. for d in listener_queue:
  17550. d.callback(&quot;foo&quot;)
  17551. async def await_something_interesting():
  17552. new_awaitable = defer.Deferred()
  17553. listener_queue.append(new_awaitable)
  17554. with PreserveLoggingContext():
  17555. await new_awaitable
  17556. </code></pre>
  17557. <p>Obviously, the idea here is that we have a bunch of things which are
  17558. waiting for an event. (It's just an example of the problem here, but a
  17559. relatively common one.)</p>
  17560. <p>Now let's imagine two further things happen. First of all, whatever was
  17561. waiting for the interesting thing goes away. (Perhaps the request times
  17562. out, or something <em>even more</em> interesting happens.)</p>
  17563. <p>Secondly, let's suppose that we decide that the interesting thing is
  17564. never going to happen, and we reset the listener queue:</p>
  17565. <pre><code class="language-python">def reset_listener_queue():
  17566. listener_queue.clear()
  17567. </code></pre>
  17568. <p>So, both ends of the awaitable chain have now dropped their references,
  17569. and the awaitable chain is now orphaned, and will be garbage-collected at
  17570. some point. Note that <code>await_something_interesting</code> is a coroutine,
  17571. which Python implements as a generator function. When Python
  17572. garbage-collects generator functions, it gives them a chance to
  17573. clean up by making the <code>await</code> (or <code>yield</code>) raise a <code>GeneratorExit</code>
  17574. exception. In our case, that means that the <code>__exit__</code> handler of
  17575. <code>PreserveLoggingContext</code> will carefully restore the request context, but
  17576. there is now nothing waiting for its return, so the request context is
  17577. never cleared.</p>
  17578. <p>To reiterate, this problem only arises when <em>both</em> ends of a awaitable
  17579. chain are dropped. Dropping the the reference to an awaitable you're
  17580. supposed to be awaiting is bad practice, so this doesn't
  17581. actually happen too much. Unfortunately, when it does happen, it will
  17582. lead to leaked logcontexts which are incredibly hard to track down.</p>
  17583. <div style="break-before: page; page-break-before: always;"></div><h1 id="replication-architecture"><a class="header" href="#replication-architecture">Replication Architecture</a></h1>
  17584. <h2 id="motivation"><a class="header" href="#motivation">Motivation</a></h2>
  17585. <p>We'd like to be able to split some of the work that synapse does into
  17586. multiple python processes. In theory multiple synapse processes could
  17587. share a single postgresql database and we'd scale up by running more
  17588. synapse processes. However much of synapse assumes that only one process
  17589. is interacting with the database, both for assigning unique identifiers
  17590. when inserting into tables, notifying components about new updates, and
  17591. for invalidating its caches.</p>
  17592. <p>So running multiple copies of the current code isn't an option. One way
  17593. to run multiple processes would be to have a single writer process and
  17594. multiple reader processes connected to the same database. In order to do
  17595. this we'd need a way for the reader process to invalidate its in-memory
  17596. caches when an update happens on the writer. One way to do this is for
  17597. the writer to present an append-only log of updates which the readers
  17598. can consume to invalidate their caches and to push updates to listening
  17599. clients or pushers.</p>
  17600. <p>Synapse already stores much of its data as an append-only log so that it
  17601. can correctly respond to <code>/sync</code> requests so the amount of code changes
  17602. needed to expose the append-only log to the readers should be fairly
  17603. minimal.</p>
  17604. <h2 id="architecture"><a class="header" href="#architecture">Architecture</a></h2>
  17605. <h3 id="the-replication-protocol"><a class="header" href="#the-replication-protocol">The Replication Protocol</a></h3>
  17606. <p>See <a href="tcp_replication.html">the TCP replication documentation</a>.</p>
  17607. <h3 id="the-tcp-replication-module"><a class="header" href="#the-tcp-replication-module">The TCP Replication Module</a></h3>
  17608. <p>Information about how the tcp replication module is structured, including how
  17609. the classes interact, can be found in
  17610. <code>synapse/replication/tcp/__init__.py</code></p>
  17611. <div style="break-before: page; page-break-before: always;"></div><h1 id="tcp-replication"><a class="header" href="#tcp-replication">TCP Replication</a></h1>
  17612. <h2 id="motivation-1"><a class="header" href="#motivation-1">Motivation</a></h2>
  17613. <p>Previously the workers used an HTTP long poll mechanism to get updates
  17614. from the master, which had the problem of causing a lot of duplicate
  17615. work on the server. This TCP protocol replaces those APIs with the aim
  17616. of increased efficiency.</p>
  17617. <h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
  17618. <p>The protocol is based on fire and forget, line based commands. An
  17619. example flow would be (where '&gt;' indicates master to worker and
  17620. '&lt;' worker to master flows):</p>
  17621. <pre><code>&gt; SERVER example.com
  17622. &lt; REPLICATE
  17623. &gt; POSITION events master 53 53
  17624. &gt; RDATA events master 54 [&quot;$foo1:bar.com&quot;, ...]
  17625. &gt; RDATA events master 55 [&quot;$foo4:bar.com&quot;, ...]
  17626. </code></pre>
  17627. <p>The example shows the server accepting a new connection and sending its identity
  17628. with the <code>SERVER</code> command, followed by the client server to respond with the
  17629. position of all streams. The server then periodically sends <code>RDATA</code> commands
  17630. which have the format <code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row&gt;</code>, where
  17631. the format of <code>&lt;row&gt;</code> is defined by the individual streams. The
  17632. <code>&lt;instance_name&gt;</code> is the name of the Synapse process that generated the data
  17633. (usually &quot;master&quot;). We expect an RDATA for every row in the DB.</p>
  17634. <p>Error reporting happens by either the client or server sending an ERROR
  17635. command, and usually the connection will be closed.</p>
  17636. <p>Since the protocol is a simple line based, its possible to manually
  17637. connect to the server using a tool like netcat. A few things should be
  17638. noted when manually using the protocol:</p>
  17639. <ul>
  17640. <li>The federation stream is only available if federation sending has
  17641. been disabled on the main process.</li>
  17642. <li>The server will only time connections out that have sent a <code>PING</code>
  17643. command. If a ping is sent then the connection will be closed if no
  17644. further commands are receieved within 15s. Both the client and
  17645. server protocol implementations will send an initial PING on
  17646. connection and ensure at least one command every 5s is sent (not
  17647. necessarily <code>PING</code>).</li>
  17648. <li><code>RDATA</code> commands <em>usually</em> include a numeric token, however if the
  17649. stream has multiple rows to replicate per token the server will send
  17650. multiple <code>RDATA</code> commands, with all but the last having a token of
  17651. <code>batch</code>. See the documentation on <code>commands.RdataCommand</code> for
  17652. further details.</li>
  17653. </ul>
  17654. <h2 id="architecture-1"><a class="header" href="#architecture-1">Architecture</a></h2>
  17655. <p>The basic structure of the protocol is line based, where the initial
  17656. word of each line specifies the command. The rest of the line is parsed
  17657. based on the command. For example, the RDATA command is defined as:</p>
  17658. <pre><code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row_json&gt;
  17659. </code></pre>
  17660. <p>(Note that &lt;row_json&gt; may contains spaces, but cannot contain
  17661. newlines.)</p>
  17662. <p>Blank lines are ignored.</p>
  17663. <h3 id="keep-alives"><a class="header" href="#keep-alives">Keep alives</a></h3>
  17664. <p>Both sides are expected to send at least one command every 5s or so, and
  17665. should send a <code>PING</code> command if necessary. If either side do not receive
  17666. a command within e.g. 15s then the connection should be closed.</p>
  17667. <p>Because the server may be connected to manually using e.g. netcat, the
  17668. timeouts aren't enabled until an initial <code>PING</code> command is seen. Both
  17669. the client and server implementations below send a <code>PING</code> command
  17670. immediately on connection to ensure the timeouts are enabled.</p>
  17671. <p>This ensures that both sides can quickly realize if the tcp connection
  17672. has gone and handle the situation appropriately.</p>
  17673. <h3 id="start-up"><a class="header" href="#start-up">Start up</a></h3>
  17674. <p>When a new connection is made, the server:</p>
  17675. <ul>
  17676. <li>Sends a <code>SERVER</code> command, which includes the identity of the server,
  17677. allowing the client to detect if its connected to the expected
  17678. server</li>
  17679. <li>Sends a <code>PING</code> command as above, to enable the client to time out
  17680. connections promptly.</li>
  17681. </ul>
  17682. <p>The client:</p>
  17683. <ul>
  17684. <li>Sends a <code>NAME</code> command, allowing the server to associate a human
  17685. friendly name with the connection. This is optional.</li>
  17686. <li>Sends a <code>PING</code> as above</li>
  17687. <li>Sends a <code>REPLICATE</code> to get the current position of all streams.</li>
  17688. <li>On receipt of a <code>SERVER</code> command, checks that the server name
  17689. matches the expected server name.</li>
  17690. </ul>
  17691. <h3 id="error-handling"><a class="header" href="#error-handling">Error handling</a></h3>
  17692. <p>If either side detects an error it can send an <code>ERROR</code> command and close
  17693. the connection.</p>
  17694. <p>If the client side loses the connection to the server it should
  17695. reconnect, following the steps above.</p>
  17696. <h3 id="congestion"><a class="header" href="#congestion">Congestion</a></h3>
  17697. <p>If the server sends messages faster than the client can consume them the
  17698. server will first buffer a (fairly large) number of commands and then
  17699. disconnect the client. This ensures that we don't queue up an unbounded
  17700. number of commands in memory and gives us a potential opportunity to
  17701. squawk loudly. When/if the client recovers it can reconnect to the
  17702. server and ask for missed messages.</p>
  17703. <h3 id="reliability"><a class="header" href="#reliability">Reliability</a></h3>
  17704. <p>In general the replication stream should be considered an unreliable
  17705. transport since e.g. commands are not resent if the connection
  17706. disappears.</p>
  17707. <p>The exception to that are the replication streams, i.e. RDATA commands,
  17708. since these include tokens which can be used to restart the stream on
  17709. connection errors.</p>
  17710. <p>The client should keep track of the token in the last RDATA command
  17711. received for each stream so that on reconnection it can start streaming
  17712. from the correct place. Note: not all RDATA have valid tokens due to
  17713. batching. See <code>RdataCommand</code> for more details.</p>
  17714. <h3 id="example-5"><a class="header" href="#example-5">Example</a></h3>
  17715. <p>An example iteraction is shown below. Each line is prefixed with '&gt;'
  17716. or '&lt;' to indicate which side is sending, these are <em>not</em> included on
  17717. the wire:</p>
  17718. <pre><code>* connection established *
  17719. &gt; SERVER localhost:8823
  17720. &gt; PING 1490197665618
  17721. &lt; NAME synapse.app.appservice
  17722. &lt; PING 1490197665618
  17723. &lt; REPLICATE
  17724. &gt; POSITION events master 1 1
  17725. &gt; POSITION backfill master 1 1
  17726. &gt; POSITION caches master 1 1
  17727. &gt; RDATA caches master 2 [&quot;get_user_by_id&quot;,[&quot;@01register-user:localhost:8823&quot;],1490197670513]
  17728. &gt; RDATA events master 14 [&quot;$149019767112vOHxz:localhost:8823&quot;,
  17729. &quot;!AFDCvgApUmpdfVjIXm:localhost:8823&quot;,&quot;m.room.guest_access&quot;,&quot;&quot;,null]
  17730. &lt; PING 1490197675618
  17731. &gt; ERROR server stopping
  17732. * connection closed by server *
  17733. </code></pre>
  17734. <p>The <code>POSITION</code> command sent by the server is used to set the clients
  17735. position without needing to send data with the <code>RDATA</code> command.</p>
  17736. <p>An example of a batched set of <code>RDATA</code> is:</p>
  17737. <pre><code>&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test:localhost:8823&quot;],1490197670513]
  17738. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test2:localhost:8823&quot;],1490197670513]
  17739. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test3:localhost:8823&quot;],1490197670513]
  17740. &gt; RDATA caches master 54 [&quot;get_user_by_id&quot;,[&quot;@test4:localhost:8823&quot;],1490197670513]
  17741. </code></pre>
  17742. <p>In this case the client shouldn't advance their caches token until it
  17743. sees the the last <code>RDATA</code>.</p>
  17744. <h3 id="list-of-commands"><a class="header" href="#list-of-commands">List of commands</a></h3>
  17745. <p>The list of valid commands, with which side can send it: server (S) or
  17746. client (C):</p>
  17747. <h4 id="server-s"><a class="header" href="#server-s">SERVER (S)</a></h4>
  17748. <p>Sent at the start to identify which server the client is talking to</p>
  17749. <h4 id="rdata-s"><a class="header" href="#rdata-s">RDATA (S)</a></h4>
  17750. <p>A single update in a stream</p>
  17751. <h4 id="position-s"><a class="header" href="#position-s">POSITION (S)</a></h4>
  17752. <p>On receipt of a POSITION command clients should check if they have missed any
  17753. updates, and if so then fetch them out of band. Sent in response to a
  17754. REPLICATE command (but can happen at any time).</p>
  17755. <p>The POSITION command includes the source of the stream. Currently all streams
  17756. are written by a single process (usually &quot;master&quot;). If fetching missing
  17757. updates via HTTP API, rather than via the DB, then processes should make the
  17758. request to the appropriate process.</p>
  17759. <p>Two positions are included, the &quot;new&quot; position and the last position sent respectively.
  17760. This allows servers to tell instances that the positions have advanced but no
  17761. data has been written, without clients needlessly checking to see if they
  17762. have missed any updates. Instances will only fetch stuff if there is a gap between
  17763. their current position and the given last position.</p>
  17764. <h4 id="error-s-c"><a class="header" href="#error-s-c">ERROR (S, C)</a></h4>
  17765. <p>There was an error</p>
  17766. <h4 id="ping-s-c"><a class="header" href="#ping-s-c">PING (S, C)</a></h4>
  17767. <p>Sent periodically to ensure the connection is still alive</p>
  17768. <h4 id="name-c"><a class="header" href="#name-c">NAME (C)</a></h4>
  17769. <p>Sent at the start by client to inform the server who they are</p>
  17770. <h4 id="replicate-c"><a class="header" href="#replicate-c">REPLICATE (C)</a></h4>
  17771. <p>Asks the server for the current position of all streams.</p>
  17772. <h4 id="user_sync-c"><a class="header" href="#user_sync-c">USER_SYNC (C)</a></h4>
  17773. <p>A user has started or stopped syncing on this process.</p>
  17774. <h4 id="clear_user_sync-c"><a class="header" href="#clear_user_sync-c">CLEAR_USER_SYNC (C)</a></h4>
  17775. <p>The server should clear all associated user sync data from the worker.</p>
  17776. <p>This is used when a worker is shutting down.</p>
  17777. <h4 id="federation_ack-c"><a class="header" href="#federation_ack-c">FEDERATION_ACK (C)</a></h4>
  17778. <p>Acknowledge receipt of some federation data</p>
  17779. <h3 id="remote_server_up-s-c"><a class="header" href="#remote_server_up-s-c">REMOTE_SERVER_UP (S, C)</a></h3>
  17780. <p>Inform other processes that a remote server may have come back online.</p>
  17781. <p>See <code>synapse/replication/tcp/commands.py</code> for a detailed description and
  17782. the format of each command.</p>
  17783. <h3 id="cache-invalidation-stream"><a class="header" href="#cache-invalidation-stream">Cache Invalidation Stream</a></h3>
  17784. <p>The cache invalidation stream is used to inform workers when they need
  17785. to invalidate any of their caches in the data store. This is done by
  17786. streaming all cache invalidations done on master down to the workers,
  17787. assuming that any caches on the workers also exist on the master.</p>
  17788. <p>Each individual cache invalidation results in a row being sent down
  17789. replication, which includes the cache name (the name of the function)
  17790. and they key to invalidate. For example:</p>
  17791. <pre><code>&gt; RDATA caches master 550953771 [&quot;get_user_by_id&quot;, [&quot;@bob:example.com&quot;], 1550574873251]
  17792. </code></pre>
  17793. <p>Alternatively, an entire cache can be invalidated by sending down a <code>null</code>
  17794. instead of the key. For example:</p>
  17795. <pre><code>&gt; RDATA caches master 550953772 [&quot;get_user_by_id&quot;, null, 1550574873252]
  17796. </code></pre>
  17797. <p>However, there are times when a number of caches need to be invalidated
  17798. at the same time with the same key. To reduce traffic we batch those
  17799. invalidations into a single poke by defining a special cache name that
  17800. workers understand to mean to expand to invalidate the correct caches.</p>
  17801. <p>Currently the special cache names are declared in
  17802. <code>synapse/storage/_base.py</code> and are:</p>
  17803. <ol>
  17804. <li><code>cs_cache_fake</code> ─ invalidates caches that depend on the current
  17805. state</li>
  17806. </ol>
  17807. <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>
  17808. <p>This is a work-in-progress set of notes with two goals:</p>
  17809. <ul>
  17810. <li>act as a reference, explaining how Synapse implements faster joins; and</li>
  17811. <li>record the rationale behind our choices.</li>
  17812. </ul>
  17813. <p>See also <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3902">MSC3902</a>.</p>
  17814. <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
  17815. request a lightweight response to the federation <code>/send_join</code> endpoint.
  17816. This is called a <strong>faster join</strong>, also known as a <strong>partial join</strong>. In these
  17817. notes we'll usually use the word &quot;partial&quot; as it matches the database schema.</p>
  17818. <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>
  17819. <p>The response to a partial join consists of</p>
  17820. <ul>
  17821. <li>the requested join event <code>J</code>,</li>
  17822. <li>a list of the servers in the room (according to the state before <code>J</code>),</li>
  17823. <li>a subset of the state of the room before <code>J</code>,</li>
  17824. <li>the full auth chain of that state subset.</li>
  17825. </ul>
  17826. <p>Synapse marks the room as partially joined by adding a row to the database table
  17827. <code>partial_state_rooms</code>. It also marks the join event <code>J</code> as &quot;partially stated&quot;,
  17828. meaning that we have neither received nor computed the full state before/after
  17829. <code>J</code>. This is done by adding a row to <code>partial_state_events</code>.</p>
  17830. <details><summary>DB schema</summary>
  17831. <pre><code>matrix=&gt; \d partial_state_events
  17832. Table &quot;matrix.partial_state_events&quot;
  17833. Column │ Type │ Collation │ Nullable │ Default
  17834. ══════════╪══════╪═══════════╪══════════╪═════════
  17835. room_id │ text │ │ not null │
  17836. event_id │ text │ │ not null │
  17837. matrix=&gt; \d partial_state_rooms
  17838. Table &quot;matrix.partial_state_rooms&quot;
  17839. Column │ Type │ Collation │ Nullable │ Default
  17840. ════════════════════════╪════════╪═══════════╪══════════╪═════════
  17841. room_id │ text │ │ not null │
  17842. device_lists_stream_id │ bigint │ │ not null │ 0
  17843. join_event_id │ text │ │ │
  17844. joined_via │ text │ │ │
  17845. matrix=&gt; \d partial_state_rooms_servers
  17846. Table &quot;matrix.partial_state_rooms_servers&quot;
  17847. Column │ Type │ Collation │ Nullable │ Default
  17848. ═════════════╪══════╪═══════════╪══════════╪═════════
  17849. room_id │ text │ │ not null │
  17850. server_name │ text │ │ not null │
  17851. </code></pre>
  17852. <p>Indices, foreign-keys and check constraints are omitted for brevity.</p>
  17853. </details>
  17854. <p>While partially joined to a room, Synapse receives events <code>E</code> from remote
  17855. homeservers as normal, and can create events at the request of its local users.
  17856. 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>
  17857. <blockquote>
  17858. <ol>
  17859. <li>Is a valid event, otherwise it is dropped. For an event to be valid, it
  17860. must contain a room_id, and it must comply with the event format of that
  17861. room version.</li>
  17862. <li>Passes signature checks, otherwise it is dropped.</li>
  17863. <li>Passes hash checks, otherwise it is redacted before being processed further.</li>
  17864. <li>Passes authorization rules based on the event’s auth events, otherwise it
  17865. is rejected.</li>
  17866. <li><strong>Passes authorization rules based on the state before the event, otherwise
  17867. it is rejected.</strong></li>
  17868. <li><strong>Passes authorization rules based on the current state of the room,
  17869. otherwise it is “soft failed”.</strong></li>
  17870. </ol>
  17871. </blockquote>
  17872. <p>We can enforce checks 1--4 without any problems.
  17873. But we cannot enforce checks 5 or 6 with complete certainty, since Synapse does
  17874. not know the full state before <code>E</code>, nor that of the room.</p>
  17875. <h3 id="partial-state"><a class="header" href="#partial-state">Partial state</a></h3>
  17876. <p>Instead, we make a best-effort approximation.
  17877. While the room is considered partially joined, Synapse tracks the &quot;partial
  17878. state&quot; before events.
  17879. This works in a similar way as regular state:</p>
  17880. <ul>
  17881. <li>The partial state before <code>J</code> is that given to us by the partial join response.</li>
  17882. <li>The partial state before an event <code>E</code> is the resolution of the partial states
  17883. after each of <code>E</code>'s <code>prev_event</code>s.</li>
  17884. <li>If <code>E</code> is rejected or a message event, the partial state after <code>E</code> is the
  17885. partial state before <code>E</code>.</li>
  17886. <li>Otherwise, the partial state after <code>E</code> is the partial state before <code>E</code>, plus
  17887. <code>E</code> itself.</li>
  17888. </ul>
  17889. <p>More concisely, partial state propagates just like full state; the only
  17890. difference is that we &quot;seed&quot; it with an incomplete initial state.
  17891. Synapse records that we have only calculated partial state for this event with
  17892. a row in <code>partial_state_events</code>.</p>
  17893. <p>While the room remains partially stated, check 5 on incoming events to that
  17894. room becomes:</p>
  17895. <blockquote>
  17896. <ol start="5">
  17897. <li>Passes authorization rules based on <strong>the resolution between the partial
  17898. state before <code>E</code> and <code>E</code>'s auth events.</strong> If the event fails to pass
  17899. authorization rules, it is rejected.</li>
  17900. </ol>
  17901. </blockquote>
  17902. <p>Additionally, check 6 is deleted: no soft-failures are enforced.</p>
  17903. <p>While partially joined, the current partial state of the room is defined as the
  17904. resolution across the partial states after all forward extremities in the room.</p>
  17905. <p><em>Remark.</em> Events with partial state are <em>not</em> considered
  17906. <a href="development/synapse_architecture/../room-dag-concepts.html#outliers">outliers</a>.</p>
  17907. <h3 id="approximation-error"><a class="header" href="#approximation-error">Approximation error</a></h3>
  17908. <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>
  17909. <div class="footnote-definition" id="2"><sup class="footnote-definition-label">1</sup>
  17910. <p>Is this exhaustive?</p>
  17911. </div>
  17912. <ul>
  17913. <li>We may erroneously accept an incoming event in check 5 based on partial state
  17914. when it would have been rejected based on full state, or vice versa.</li>
  17915. <li>This means that an event could erroneously be added to the current partial
  17916. state of the room when it would not be present in the full state of the room,
  17917. or vice versa.</li>
  17918. <li>Additionally, we may have skipped soft-failing an event that would have been
  17919. soft-failed based on full state.</li>
  17920. </ul>
  17921. <p>(Note that the discrepancies described in the last two bullets are user-visible.)</p>
  17922. <p>This means that we have to be very careful when we want to lookup pieces of room
  17923. state in a partially-joined room. Our approximation of the state may be
  17924. incorrect or missing. But we can make some educated guesses. If</p>
  17925. <ul>
  17926. <li>our partial state is likely to be correct, or</li>
  17927. <li>the consequences of our partial state being incorrect are minor,</li>
  17928. </ul>
  17929. <p>then we proceed as normal, and let the resync process fix up any mistakes (see
  17930. below).</p>
  17931. <p>When is our partial state likely to be correct?</p>
  17932. <ul>
  17933. <li>It's more accurate the closer we are to the partial join event. (So we should
  17934. ideally complete the resync as soon as possible.)</li>
  17935. <li>Non-member events: we will have received them as part of the partial join
  17936. response, if they were part of the room state at that point. We may
  17937. incorrectly accept or reject updates to that state (at first because we lack
  17938. remote membership information; later because of compounding errors), so these
  17939. can become incorrect over time.</li>
  17940. <li>Local members' memberships: we are the only ones who can create join and
  17941. knock events for our users. We can't be completely confident in the
  17942. correctness of bans, invites and kicks from other homeservers, but the resync
  17943. process should correct any mistakes.</li>
  17944. <li>Remote members' memberships: we did not receive these in the /send_join
  17945. response, so we have essentially no idea if these are correct or not.</li>
  17946. </ul>
  17947. <p>In short, we deem it acceptable to trust the partial state for non-membership
  17948. and local membership events. For remote membership events, we wait for the
  17949. resync to complete, at which point we have the full state of the room and can
  17950. proceed as normal.</p>
  17951. <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>
  17952. <p>The partial-state approximation is only a temporary affair. In the background,
  17953. synapse beings a &quot;resync&quot; process. This is a continuous loop, starting at the
  17954. partial join event and proceeding downwards through the event graph. For each
  17955. <code>E</code> seen in the room since partial join, Synapse will fetch </p>
  17956. <ul>
  17957. <li>the event ids in the state of the room before <code>E</code>, via
  17958. <a href="https://spec.matrix.org/v1.5/server-server-api/#get_matrixfederationv1state_idsroomid"><code>/state_ids</code></a>;</li>
  17959. <li>the event ids in the full auth chain of <code>E</code>, included in the <code>/state_ids</code>
  17960. response; and</li>
  17961. <li>any events from the previous two bullets that Synapse hasn't persisted, via
  17962. <a href="https://spec.matrix.org/v1.5/server-server-api/#get_matrixfederationv1stateroomid">`/state</a>.</li>
  17963. </ul>
  17964. <p>This means Synapse has (or can compute) the full state before <code>E</code>, which allows
  17965. Synapse to properly authorise or reject <code>E</code>. At this point ,the event
  17966. is considered to have &quot;full state&quot; rather than &quot;partial state&quot;. We record this
  17967. by removing <code>E</code> from the <code>partial_state_events</code> table.</p>
  17968. <p>[<strong>TODO:</strong> Does Synapse persist a new state group for the full state
  17969. before <code>E</code>, or do we alter the (partial-)state group in-place? Are state groups
  17970. ever marked as partially-stated? ]</p>
  17971. <p>This scheme means it is possible for us to have accepted and sent an event to
  17972. clients, only to reject it during the resync. From a client's perspective, the
  17973. effect is similar to a retroactive
  17974. state change due to state resolution---i.e. a &quot;state reset&quot;.<sup class="footnote-reference"><a href="#3">2</a></sup></p>
  17975. <div class="footnote-definition" id="3"><sup class="footnote-definition-label">2</sup>
  17976. <p>Clients should refresh caches to detect such a change. Rumour has it that
  17977. sliding sync will fix this.</p>
  17978. </div>
  17979. <p>When all events since the join <code>J</code> have been fully-stated, the room resync
  17980. process is complete. We record this by removing the room from
  17981. <code>partial_state_rooms</code>.</p>
  17982. <h2 id="faster-joins-on-workers"><a class="header" href="#faster-joins-on-workers">Faster joins on workers</a></h2>
  17983. <p>For the time being, the resync process happens on the master worker.
  17984. A new replication stream <code>un_partial_stated_room</code> is added. Whenever a resync
  17985. completes and a partial-state room becomes fully stated, a new message is sent
  17986. into that stream containing the room ID.</p>
  17987. <h2 id="notes-on-specific-cases"><a class="header" href="#notes-on-specific-cases">Notes on specific cases</a></h2>
  17988. <blockquote>
  17989. <p><strong>NB.</strong> The notes below are rough. Some of them are hidden under <code>&lt;details&gt;</code>
  17990. disclosures because they have yet to be implemented in mainline Synapse.</p>
  17991. </blockquote>
  17992. <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>
  17993. <p>When sending out messages during a partial join, we assume our partial state is
  17994. accurate and proceed as normal. For this to have any hope of succeeding at all,
  17995. our partial state must contain an entry for each of the (type, state key) pairs
  17996. <a href="https://spec.matrix.org/v1.3/rooms/v10/#authorization-rules">specified by the auth rules</a>:</p>
  17997. <ul>
  17998. <li><code>m.room.create</code></li>
  17999. <li><code>m.room.join_rules</code></li>
  18000. <li><code>m.room.power_levels</code></li>
  18001. <li><code>m.room.third_party_invite</code></li>
  18002. <li><code>m.room.member</code></li>
  18003. </ul>
  18004. <p>The first four of these should be present in the state before <code>J</code> that is given
  18005. to us in the partial join response; only membership events are omitted. In order
  18006. for us to consider the user joined, we must have their membership event. That
  18007. means the only possible omission is the target's membership in an invite, kick
  18008. or ban.</p>
  18009. <p>The worst possibility is that we locally invite someone who is banned according to
  18010. the full state, because we lack their ban in our current partial state. The rest
  18011. of the federation---at least, those who are fully joined---should correctly
  18012. 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
  18013. homeservers and resolved by the resync for partially-joined homeservers.</p>
  18014. <p>In more generality, there are two problems we're worrying about here:</p>
  18015. <ul>
  18016. <li>We might create an event that is valid under our partial state, only to later
  18017. find out that is actually invalid according to the full state.</li>
  18018. <li>Or: we might refuse to create an event that is invalid under our partial
  18019. state, even though it would be perfectly valid under the full state.</li>
  18020. </ul>
  18021. <p>However we expect such problems to be unlikely in practise, because</p>
  18022. <ul>
  18023. <li>We trust that the room has sensible power levels, e.g. that bad actors with
  18024. high power levels are demoted before their ban.</li>
  18025. <li>We trust that the resident server provides us up-to-date power levels, join
  18026. rules, etc.</li>
  18027. <li>State changes in rooms are relatively infrequent, and the resync period is
  18028. relatively quick.</li>
  18029. </ul>
  18030. <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>
  18031. <p><strong>TODO:</strong> needs prose fleshing out.</p>
  18032. <p>Normally: send out in a fed txn to all HSes in the room.
  18033. We only know that some HSes were in the room at some point. Wat do.
  18034. Send it out to the list of servers from the first join.
  18035. <strong>TODO</strong> what do we do here if we have full state?
  18036. 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...)
  18037. But don't want to send out sensitive data in other HS's events in this way.</p>
  18038. <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.
  18039. What about if we didn't send them an event but shouldn't've?
  18040. E.g. what if someone joined from a new HS shortly after you did? We wouldn't talk to them.
  18041. 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.
  18042. Instead, just send them the latest event (if they're still in the room after resync) and let them backfill.(?)</p>
  18043. <ul>
  18044. <li>Don't do this currently.</li>
  18045. <li>If anyone who has received our messages sends a message to a HS we missed, they can backfill our messages</li>
  18046. <li>Gap: rooms which are infrequently used and take a long time to resync.</li>
  18047. </ul>
  18048. <h3 id="joining-after-a-partial-join"><a class="header" href="#joining-after-a-partial-join">Joining after a partial join</a></h3>
  18049. <p><strong>NB.</strong> Not yet implemented.</p>
  18050. <details>
  18051. <p><strong>TODO:</strong> needs prose fleshing out. Liase with Matthieu. Explain why /send_join
  18052. (Rich was surprised we didn't just create it locally. Answer: to try and avoid
  18053. a join which then gets rejected after resync.)</p>
  18054. <p>We don't know for sure that any join we create would be accepted.
  18055. 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.
  18056. Instead, do another partial make-join/send-join handshake to confirm that the join works.</p>
  18057. <ul>
  18058. <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>
  18059. <li>What if the second send_join response includes a different list of reisdent HSes? Could ignore it.
  18060. <ul>
  18061. <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>
  18062. </ul>
  18063. </li>
  18064. <li>SQ: wrt device lists it's a lot safer to ignore it!!!!!</li>
  18065. <li>What if the state at the second join is inconsistent with what we have? Ignore it?</li>
  18066. </ul>
  18067. </details>
  18068. <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>
  18069. <p><strong>NB.</strong> Not yet implemented.</p>
  18070. <details>
  18071. <p>When you're fully joined to a room, to have <code>U</code> leave a room their homeserver
  18072. needs to</p>
  18073. <ul>
  18074. <li>create a new leave event for <code>U</code> which will be accepted by other homeservers,
  18075. and</li>
  18076. <li>send that event <code>U</code> out to the homeservers in the federation.</li>
  18077. </ul>
  18078. <p>When is a leave event accepted? See
  18079. <a href="https://spec.matrix.org/v1.5/rooms/v10/#authorization-rules">v10 auth rules</a>:</p>
  18080. <blockquote>
  18081. <ol start="4">
  18082. <li>If type is m.room.member: [...]
  18083. &gt;
  18084. &gt; 5. If membership is leave:
  18085. &gt;
  18086. &gt; 1. If the sender matches state_key, allow if and only if that user’s current membership state is invite, join, or knock.
  18087. 2. [...]</li>
  18088. </ol>
  18089. </blockquote>
  18090. <p>I think this means that (well-formed!) self-leaves are governed entirely by
  18091. 4.5.1. This means that if we correctly calculate state which says that <code>U</code> is
  18092. invited, joined or knocked and include it in the leave's auth events, our event
  18093. is accepted by checks 4 and 5 on incoming events.</p>
  18094. <blockquote>
  18095. <ol start="4">
  18096. <li>Passes authorization rules based on the event’s auth events, otherwise
  18097. &gt; it is rejected.</li>
  18098. <li>Passes authorization rules based on the state before the event, otherwise
  18099. &gt; it is rejected.</li>
  18100. </ol>
  18101. </blockquote>
  18102. <p>The only way to fail check 6 is if the receiving server's current state of the
  18103. room says that <code>U</code> is banned, has left, or has no membership event. But this is
  18104. fine: the receiving server already thinks that <code>U</code> isn't in the room.</p>
  18105. <blockquote>
  18106. <ol start="6">
  18107. <li>Passes authorization rules based on the current state of the room,
  18108. &gt; otherwise it is “soft failed”.</li>
  18109. </ol>
  18110. </blockquote>
  18111. <p>For the second point (publishing the leave event), the best thing we can do is
  18112. to is publish to all HSes we know to be currently in the room. If they miss that
  18113. event, they might send us traffic in the room that we don't care about. This is
  18114. a problem with leaving after a &quot;full&quot; join; we don't seek to fix this with
  18115. partial joins.</p>
  18116. <p>(With that said: there's nothing machine-readable in the /send response. I don't
  18117. think we can deduce &quot;destination has left the room&quot; from a failure to /send an
  18118. event into that room?)</p>
  18119. <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>
  18120. <p>We can create leave events and can choose what gets included in our auth events,
  18121. so we can be sure that we pass check 4 on incoming events. For check 5, we might
  18122. have an incorrect view of the state before an event.
  18123. The only way we might erroneously think a leave is valid is if</p>
  18124. <ul>
  18125. <li>the partial state before the leave has <code>U</code> joined, invited or knocked, but</li>
  18126. <li>the full state before the leave has <code>U</code> banned, left or not present,</li>
  18127. </ul>
  18128. <p>in which case the leave doesn't make anything worse: other HSes already consider
  18129. us as not in the room, and will continue to do so after seeing the leave.</p>
  18130. <p>The remaining obstacle is then: can we safely broadcast the leave event? We may
  18131. miss servers or incorrectly think that a server is in the room. Or the
  18132. destination server may be offline and miss the transaction containing our leave
  18133. event.This should self-heal when they see an event whose <code>prev_events</code> descends
  18134. from our leave.</p>
  18135. <p>Another option we considered was to use federation <code>/send_leave</code> to ask a
  18136. fully-joined server to send out the event on our behalf. But that introduces
  18137. complexity without much benefit. Besides, as Rich put it,</p>
  18138. <blockquote>
  18139. <p>sending out leaves is pretty best-effort currently</p>
  18140. </blockquote>
  18141. <p>so this is probably good enough as-is.</p>
  18142. <h4 id="cleanup-after-the-last-leave"><a class="header" href="#cleanup-after-the-last-leave">Cleanup after the last leave</a></h4>
  18143. <p><strong>TODO</strong>: what cleanup is necessary? Is it all just nice-to-have to save unused
  18144. work?</p>
  18145. </details>
  18146. <div style="break-before: page; page-break-before: always;"></div><h1 id="internal-documentation"><a class="header" href="#internal-documentation">Internal Documentation</a></h1>
  18147. <p>This section covers implementation documentation for various parts of Synapse.</p>
  18148. <p>If a developer is planning to make a change to a feature of Synapse, it can be useful for
  18149. general documentation of how that feature is implemented to be available. This saves the
  18150. developer time in place of needing to understand how the feature works by reading the
  18151. code.</p>
  18152. <p>Documentation that would be more useful for the perspective of a system administrator,
  18153. rather than a developer who's intending to change to code, should instead be placed
  18154. under the Usage section of the documentation.</p>
  18155. <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>
  18156. <p>https://fujifish.github.io/samling/samling.html (https://github.com/fujifish/samling) is a great resource for being able to tinker with the
  18157. SAML options within Synapse without needing to deploy and configure a complicated software stack.</p>
  18158. <p>To make Synapse (and therefore Element) use it:</p>
  18159. <ol>
  18160. <li>Use the samling.html URL above or deploy your own and visit the IdP Metadata tab.</li>
  18161. <li>Copy the XML to your clipboard.</li>
  18162. <li>On your Synapse server, create a new file <code>samling.xml</code> next to your <code>homeserver.yaml</code> with
  18163. the XML from step 2 as the contents.</li>
  18164. <li>Edit your <code>homeserver.yaml</code> to include:
  18165. <pre><code class="language-yaml">saml2_config:
  18166. sp_config:
  18167. allow_unknown_attributes: true # Works around a bug with AVA Hashes: https://github.com/IdentityPython/pysaml2/issues/388
  18168. metadata:
  18169. local: [&quot;samling.xml&quot;]
  18170. </code></pre>
  18171. </li>
  18172. <li>Ensure that your <code>homeserver.yaml</code> has a setting for <code>public_baseurl</code>:
  18173. <pre><code class="language-yaml">public_baseurl: http://localhost:8080/
  18174. </code></pre>
  18175. </li>
  18176. <li>Run <code>apt-get install xmlsec1</code> and <code>pip install --upgrade --force 'pysaml2&gt;=4.5.0'</code> to ensure
  18177. the dependencies are installed and ready to go.</li>
  18178. <li>Restart Synapse.</li>
  18179. </ol>
  18180. <p>Then in Element:</p>
  18181. <ol>
  18182. <li>Visit the login page and point Element towards your homeserver using the <code>public_baseurl</code> above.</li>
  18183. <li>Click the Single Sign-On button.</li>
  18184. <li>On the samling page, enter a Name Identifier and add a SAML Attribute for <code>uid=your_localpart</code>.
  18185. The response must also be signed.</li>
  18186. <li>Click &quot;Next&quot;.</li>
  18187. <li>Click &quot;Post Response&quot; (change nothing).</li>
  18188. <li>You should be logged in.</li>
  18189. </ol>
  18190. <p>If you try and repeat this process, you may be automatically logged in using the information you
  18191. gave previously. To fix this, open your developer console (<code>F12</code> or <code>Ctrl+Shift+I</code>) while on the
  18192. samling page and clear the site data. In Chrome, this will be a button on the Application tab.</p>
  18193. <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>
  18194. <p>The <a href="https://github.com/jbittel/django-mama-cas">django-mama-cas</a> project is an
  18195. easy to run CAS implementation built on top of Django.</p>
  18196. <h2 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h2>
  18197. <ol>
  18198. <li>Create a new virtualenv: <code>python3 -m venv &lt;your virtualenv&gt;</code></li>
  18199. <li>Activate your virtualenv: <code>source /path/to/your/virtualenv/bin/activate</code></li>
  18200. <li>Install Django and django-mama-cas:
  18201. <pre><code class="language-sh">python -m pip install &quot;django&lt;3&quot; &quot;django-mama-cas==2.4.0&quot;
  18202. </code></pre>
  18203. </li>
  18204. <li>Create a Django project in the current directory:
  18205. <pre><code class="language-sh">django-admin startproject cas_test .
  18206. </code></pre>
  18207. </li>
  18208. <li>Follow the <a href="https://django-mama-cas.readthedocs.io/en/latest/installation.html#configuring">install directions</a> for django-mama-cas</li>
  18209. <li>Setup the SQLite database: <code>python manage.py migrate</code></li>
  18210. <li>Create a user:
  18211. <pre><code class="language-sh">python manage.py createsuperuser
  18212. </code></pre>
  18213. <ol>
  18214. <li>Use whatever you want as the username and password.</li>
  18215. <li>Leave the other fields blank.</li>
  18216. </ol>
  18217. </li>
  18218. <li>Use the built-in Django test server to serve the CAS endpoints on port 8000:
  18219. <pre><code class="language-sh">python manage.py runserver
  18220. </code></pre>
  18221. </li>
  18222. </ol>
  18223. <p>You should now have a Django project configured to serve CAS authentication with
  18224. a single user created.</p>
  18225. <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>
  18226. <ol>
  18227. <li>Modify your <code>homeserver.yaml</code> to enable CAS and point it to your locally
  18228. running Django test server:
  18229. <pre><code class="language-yaml">cas_config:
  18230. enabled: true
  18231. server_url: &quot;http://localhost:8000&quot;
  18232. service_url: &quot;http://localhost:8081&quot;
  18233. #displayname_attribute: name
  18234. #required_attributes:
  18235. # name: value
  18236. </code></pre>
  18237. </li>
  18238. <li>Restart Synapse.</li>
  18239. </ol>
  18240. <p>Note that the above configuration assumes the homeserver is running on port 8081
  18241. and that the CAS server is on port 8000, both on localhost.</p>
  18242. <h2 id="testing-the-configuration"><a class="header" href="#testing-the-configuration">Testing the configuration</a></h2>
  18243. <p>Then in Element:</p>
  18244. <ol>
  18245. <li>Visit the login page with a Element pointing at your homeserver.</li>
  18246. <li>Click the Single Sign-On button.</li>
  18247. <li>Login using the credentials created with <code>createsuperuser</code>.</li>
  18248. <li>You should be logged in.</li>
  18249. </ol>
  18250. <p>If you want to repeat this process you'll need to manually logout first:</p>
  18251. <ol>
  18252. <li>http://localhost:8000/admin/</li>
  18253. <li>Click &quot;logout&quot; in the top right.</li>
  18254. </ol>
  18255. <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>
  18256. <h2 id="edges"><a class="header" href="#edges">Edges</a></h2>
  18257. <p>The word &quot;edge&quot; comes from graph theory lingo. An edge is just a connection
  18258. between two events. In Synapse, we connect events by specifying their
  18259. <code>prev_events</code>. A subsequent event points back at a previous event.</p>
  18260. <pre><code>A (oldest) &lt;---- B &lt;---- C (most recent)
  18261. </code></pre>
  18262. <h2 id="depth-and-stream-ordering"><a class="header" href="#depth-and-stream-ordering">Depth and stream ordering</a></h2>
  18263. <p>Events are normally sorted by <code>(topological_ordering, stream_ordering)</code> where
  18264. <code>topological_ordering</code> is just <code>depth</code>. In other words, we first sort by <code>depth</code>
  18265. and then tie-break based on <code>stream_ordering</code>. <code>depth</code> is incremented as new
  18266. messages are added to the DAG. Normally, <code>stream_ordering</code> is an auto
  18267. incrementing integer, but backfilled events start with <code>stream_ordering=-1</code> and decrement.</p>
  18268. <hr />
  18269. <ul>
  18270. <li><code>/sync</code> returns things in the order they arrive at the server (<code>stream_ordering</code>).</li>
  18271. <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>
  18272. </ul>
  18273. <p>The general idea is that, if you're following a room in real-time (i.e.
  18274. <code>/sync</code>), you probably want to see the messages as they arrive at your server,
  18275. rather than skipping any that arrived late; whereas if you're looking at a
  18276. historical section of timeline (i.e. <code>/messages</code>), you want to see the best
  18277. representation of the state of the room as others were seeing it at the time.</p>
  18278. <h2 id="outliers"><a class="header" href="#outliers">Outliers</a></h2>
  18279. <p>We mark an event as an <code>outlier</code> when we haven't figured out the state for the
  18280. room at that point in the DAG yet. They are &quot;floating&quot; events that we haven't
  18281. yet correlated to the DAG.</p>
  18282. <p>Outliers typically arise when we fetch the auth chain or state for a given
  18283. event. When that happens, we just grab the events in the state/auth chain,
  18284. without calculating the state at those events, or backfilling their
  18285. <code>prev_events</code>. Since we don't have the state at any events fetched in that
  18286. way, we mark them as outliers.</p>
  18287. <p>So, typically, we won't have the <code>prev_events</code> of an <code>outlier</code> in the database,
  18288. (though it's entirely possible that we <em>might</em> have them for some other
  18289. reason). Other things that make outliers different from regular events:</p>
  18290. <ul>
  18291. <li>
  18292. <p>We don't have state for them, so there should be no entry in
  18293. <code>event_to_state_groups</code> for an outlier. (In practice this isn't always
  18294. the case, though I'm not sure why: see https://github.com/matrix-org/synapse/issues/12201).</p>
  18295. </li>
  18296. <li>
  18297. <p>We don't record entries for them in the <code>event_edges</code>,
  18298. <code>event_forward_extremeties</code> or <code>event_backward_extremities</code> tables.</p>
  18299. </li>
  18300. </ul>
  18301. <p>Since outliers are not tied into the DAG, they do not normally form part of the
  18302. timeline sent down to clients via <code>/sync</code> or <code>/messages</code>; however there is an
  18303. exception:</p>
  18304. <h3 id="out-of-band-membership-events"><a class="header" href="#out-of-band-membership-events">Out-of-band membership events</a></h3>
  18305. <p>A special case of outlier events are some membership events for federated rooms
  18306. that we aren't full members of. For example:</p>
  18307. <ul>
  18308. <li>invites received over federation, before we join the room</li>
  18309. <li><em>rejections</em> for said invites</li>
  18310. <li>knock events for rooms that we would like to join but have not yet joined.</li>
  18311. </ul>
  18312. <p>In all the above cases, we don't have the state for the room, which is why they
  18313. are treated as outliers. They are a bit special though, in that they are
  18314. proactively sent to clients via <code>/sync</code>.</p>
  18315. <h2 id="forward-extremity"><a class="header" href="#forward-extremity">Forward extremity</a></h2>
  18316. <p>Most-recent-in-time events in the DAG which are not referenced by any other
  18317. events' <code>prev_events</code> yet. (In this definition, outliers, rejected events, and
  18318. soft-failed events don't count.)</p>
  18319. <p>The forward extremities of a room (or at least, a subset of them, if there are
  18320. more than ten) are used as the <code>prev_events</code> when the next event is sent.</p>
  18321. <p>The &quot;current state&quot; of a room (ie: the state which would be used if we
  18322. generated a new event) is, therefore, the resolution of the room states
  18323. at each of the forward extremities.</p>
  18324. <h2 id="backward-extremity"><a class="header" href="#backward-extremity">Backward extremity</a></h2>
  18325. <p>The current marker of where we have backfilled up to and will generally be the
  18326. <code>prev_events</code> of the oldest-in-time events we have in the DAG. This gives a starting point when
  18327. backfilling history.</p>
  18328. <p>Note that, unlike forward extremities, we typically don't have any backward
  18329. extremity events themselves in the database - or, if we do, they will be &quot;outliers&quot; (see
  18330. above). Either way, we don't expect to have the room state at a backward extremity.</p>
  18331. <p>When we persist a non-outlier event, if it was previously a backward extremity,
  18332. we clear it as a backward extremity and set all of its <code>prev_events</code> as the new
  18333. backward extremities if they aren't already persisted as non-outliers. This
  18334. therefore keeps the backward extremities up-to-date.</p>
  18335. <h2 id="state-groups"><a class="header" href="#state-groups">State groups</a></h2>
  18336. <p>For every non-outlier event we need to know the state at that event. Instead of
  18337. storing the full state for each event in the DB (i.e. a <code>event_id -&gt; state</code>
  18338. mapping), which is <em>very</em> space inefficient when state doesn't change, we
  18339. instead assign each different set of state a &quot;state group&quot; and then have
  18340. mappings of <code>event_id -&gt; state_group</code> and <code>state_group -&gt; state</code>.</p>
  18341. <h3 id="stage-group-edges"><a class="header" href="#stage-group-edges">Stage group edges</a></h3>
  18342. <p>TODO: <code>state_group_edges</code> is a further optimization...
  18343. notes from @Azrenbeth, https://pastebin.com/seUGVGeT</p>
  18344. <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>
  18345. <p>The auth chain difference algorithm is used by V2 state resolution, where a
  18346. naive implementation can be a significant source of CPU and DB usage.</p>
  18347. <h3 id="definitions"><a class="header" href="#definitions">Definitions</a></h3>
  18348. <p>A <em>state set</em> is a set of state events; e.g. the input of a state resolution
  18349. algorithm is a collection of state sets.</p>
  18350. <p>The <em>auth chain</em> of a set of events are all the events' auth events and <em>their</em>
  18351. auth events, recursively (i.e. the events reachable by walking the graph induced
  18352. by an event's auth events links).</p>
  18353. <p>The <em>auth chain difference</em> of a collection of state sets is the union minus the
  18354. intersection of the sets of auth chains corresponding to the state sets, i.e an
  18355. event is in the auth chain difference if it is reachable by walking the auth
  18356. event graph from at least one of the state sets but not from <em>all</em> of the state
  18357. sets.</p>
  18358. <h2 id="breadth-first-walk-algorithm"><a class="header" href="#breadth-first-walk-algorithm">Breadth First Walk Algorithm</a></h2>
  18359. <p>A way of calculating the auth chain difference without calculating the full auth
  18360. chains for each state set is to do a parallel breadth first walk (ordered by
  18361. depth) of each state set's auth chain. By tracking which events are reachable
  18362. from each state set we can finish early if every pending event is reachable from
  18363. every state set.</p>
  18364. <p>This can work well for state sets that have a small auth chain difference, but
  18365. can be very inefficient for larger differences. However, this algorithm is still
  18366. used if we don't have a chain cover index for the room (e.g. because we're in
  18367. the process of indexing it).</p>
  18368. <h2 id="chain-cover-index"><a class="header" href="#chain-cover-index">Chain Cover Index</a></h2>
  18369. <p>Synapse computes auth chain differences by pre-computing a &quot;chain cover&quot; index
  18370. for the auth chain in a room, allowing us to efficiently make reachability queries
  18371. like &quot;is event <code>A</code> in the auth chain of event <code>B</code>?&quot;. We could do this with an index
  18372. that tracks all pairs <code>(A, B)</code> such that <code>A</code> is in the auth chain of <code>B</code>. However, this
  18373. would be prohibitively large, scaling poorly as the room accumulates more state
  18374. events.</p>
  18375. <p>Instead, we break down the graph into <em>chains</em>. A chain is a subset of a DAG
  18376. with the following property: for any pair of events <code>E</code> and <code>F</code> in the chain,
  18377. the chain contains a path <code>E -&gt; F</code> or a path <code>F -&gt; E</code>. This forces a chain to be
  18378. linear (without forks), e.g. <code>E -&gt; F -&gt; G -&gt; ... -&gt; H</code>. Each event in the chain
  18379. is given a <em>sequence number</em> local to that chain. The oldest event <code>E</code> in the
  18380. chain has sequence number 1. If <code>E</code> has a child <code>F</code> in the chain, then <code>F</code> has
  18381. sequence number 2. If <code>E</code> has a grandchild <code>G</code> in the chain, then <code>G</code> has
  18382. sequence number 3; and so on.</p>
  18383. <p>Synapse ensures that each persisted event belongs to exactly one chain, and
  18384. tracks how the chains are connected to one another. This allows us to
  18385. efficiently answer reachability queries. Doing so uses less storage than
  18386. tracking reachability on an event-by-event basis, particularly when we have
  18387. fewer and longer chains. See</p>
  18388. <blockquote>
  18389. <p>Jagadish, H. (1990). <a href="https://doi.org/10.1145/99935.99944">A compression technique to materialize transitive closure</a>.
  18390. <em>ACM Transactions on Database Systems (TODS)</em>, 15*(4)*, 558-598.</p>
  18391. </blockquote>
  18392. <p>for the original idea or</p>
  18393. <blockquote>
  18394. <p>Y. Chen, Y. Chen, <a href="https://doi.org/10.1109/ICDE.2008.4497498">An efficient algorithm for answering graph
  18395. reachability queries</a>,
  18396. in: 2008 IEEE 24th International Conference on Data Engineering, April 2008,
  18397. 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>
  18398. </blockquote>
  18399. <p>for a more modern take.</p>
  18400. <p>In practical terms, the chain cover assigns every event a
  18401. <em>chain ID</em> and <em>sequence number</em> (e.g. <code>(5,3)</code>), and maintains a map of <em>links</em>
  18402. between events in chains (e.g. <code>(5,3) -&gt; (2,4)</code>) such that <code>A</code> is reachable by <code>B</code>
  18403. (i.e. <code>A</code> is in the auth chain of <code>B</code>) if and only if either:</p>
  18404. <ol>
  18405. <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
  18406. sequence number; or</li>
  18407. <li>there is a link <code>L</code> between <code>B</code>'s chain ID and <code>A</code>'s chain ID such that
  18408. <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>
  18409. </ol>
  18410. <p>There are actually two potential implementations, one where we store links from
  18411. each chain to every other reachable chain (the transitive closure of the links
  18412. graph), and one where we remove redundant links (the transitive reduction of the
  18413. links graph) e.g. if we have chains <code>C3 -&gt; C2 -&gt; C1</code> then the link <code>C3 -&gt; C1</code>
  18414. would not be stored. Synapse uses the former implementation so that it doesn't
  18415. need to recurse to test reachability between chains. This trades-off extra storage
  18416. in order to save CPU cycles and DB queries.</p>
  18417. <h3 id="example-6"><a class="header" href="#example-6">Example</a></h3>
  18418. <p>An example auth graph would look like the following, where chains have been
  18419. formed based on type/state_key and are denoted by colour and are labelled with
  18420. <code>(chain ID, sequence number)</code>. Links are denoted by the arrows (links in grey
  18421. are those that would be remove in the second implementation described above).</p>
  18422. <p><img src="auth_chain_diff.dot.png" alt="Example" /></p>
  18423. <p>Note that we don't include all links between events and their auth events, as
  18424. most of those links would be redundant. For example, all events point to the
  18425. create event, but each chain only needs the one link from it's base to the
  18426. create event.</p>
  18427. <h2 id="using-the-index"><a class="header" href="#using-the-index">Using the Index</a></h2>
  18428. <p>This index can be used to calculate the auth chain difference of the state sets
  18429. by looking at the chain ID and sequence numbers reachable from each state set:</p>
  18430. <ol>
  18431. <li>For every state set lookup the chain ID/sequence numbers of each state event</li>
  18432. <li>Use the index to find all chains and the maximum sequence number reachable
  18433. from each state set.</li>
  18434. <li>The auth chain difference is then all events in each chain that have sequence
  18435. numbers between the maximum sequence number reachable from <em>any</em> state set and
  18436. the minimum reachable by <em>all</em> state sets (if any).</li>
  18437. </ol>
  18438. <p>Note that steps 2 is effectively calculating the auth chain for each state set
  18439. (in terms of chain IDs and sequence numbers), and step 3 is calculating the
  18440. difference between the union and intersection of the auth chains.</p>
  18441. <h3 id="worked-example"><a class="header" href="#worked-example">Worked Example</a></h3>
  18442. <p>For example, given the above graph, we can calculate the difference between
  18443. state sets consisting of:</p>
  18444. <ol>
  18445. <li><code>S1</code>: Alice's invite <code>(4,1)</code> and Bob's second join <code>(2,2)</code>; and</li>
  18446. <li><code>S2</code>: Alice's second join <code>(4,3)</code> and Bob's first join <code>(2,1)</code>.</li>
  18447. </ol>
  18448. <p>Using the index we see that the following auth chains are reachable from each
  18449. state set:</p>
  18450. <ol>
  18451. <li><code>S1</code>: <code>(1,1)</code>, <code>(2,2)</code>, <code>(3,1)</code> &amp; <code>(4,1)</code></li>
  18452. <li><code>S2</code>: <code>(1,1)</code>, <code>(2,1)</code>, <code>(3,2)</code> &amp; <code>(4,3)</code></li>
  18453. </ol>
  18454. <p>And so, for each the ranges that are in the auth chain difference:</p>
  18455. <ol>
  18456. <li>Chain 1: None, (since everything can reach the create event).</li>
  18457. <li>Chain 2: The range <code>(1, 2]</code> (i.e. just <code>2</code>), as <code>1</code> is reachable by all state
  18458. sets and the maximum reachable is <code>2</code> (corresponding to Bob's second join).</li>
  18459. <li>Chain 3: Similarly the range <code>(1, 2]</code> (corresponding to the second power
  18460. level).</li>
  18461. <li>Chain 4: The range <code>(1, 3]</code> (corresponding to both of Alice's joins).</li>
  18462. </ol>
  18463. <p>So the final result is: Bob's second join <code>(2,2)</code>, the second power level
  18464. <code>(3,2)</code> and both of Alice's joins <code>(4,2)</code> &amp; <code>(4,3)</code>.</p>
  18465. <div style="break-before: page; page-break-before: always;"></div><h1 id="media-repository"><a class="header" href="#media-repository">Media Repository</a></h1>
  18466. <p><em>Synapse implementation-specific details for the media repository</em></p>
  18467. <p>The media repository</p>
  18468. <ul>
  18469. <li>stores avatars, attachments and their thumbnails for media uploaded by local
  18470. users.</li>
  18471. <li>caches avatars, attachments and their thumbnails for media uploaded by remote
  18472. users.</li>
  18473. <li>caches resources and thumbnails used for URL previews.</li>
  18474. </ul>
  18475. <p>All media in Matrix can be identified by a unique
  18476. <a href="https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris">MXC URI</a>,
  18477. consisting of a server name and media ID:</p>
  18478. <pre><code>mxc://&lt;server-name&gt;/&lt;media-id&gt;
  18479. </code></pre>
  18480. <h2 id="local-media"><a class="header" href="#local-media">Local Media</a></h2>
  18481. <p>Synapse generates 24 character media IDs for content uploaded by local users.
  18482. These media IDs consist of upper and lowercase letters and are case-sensitive.
  18483. Other homeserver implementations may generate media IDs differently.</p>
  18484. <p>Local media is recorded in the <code>local_media_repository</code> table, which includes
  18485. metadata such as MIME types, upload times and file sizes.
  18486. Note that this table is shared by the URL cache, which has a different media ID
  18487. scheme.</p>
  18488. <h3 id="paths"><a class="header" href="#paths">Paths</a></h3>
  18489. <p>A file with media ID <code>aabbcccccccccccccccccccc</code> and its <code>128x96</code> <code>image/jpeg</code>
  18490. thumbnail, created by scaling, would be stored at:</p>
  18491. <pre><code>local_content/aa/bb/cccccccccccccccccccc
  18492. local_thumbnails/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  18493. </code></pre>
  18494. <h2 id="remote-media"><a class="header" href="#remote-media">Remote Media</a></h2>
  18495. <p>When media from a remote homeserver is requested from Synapse, it is assigned
  18496. a local <code>filesystem_id</code>, with the same format as locally-generated media IDs,
  18497. as described above.</p>
  18498. <p>A record of remote media is stored in the <code>remote_media_cache</code> table, which
  18499. can be used to map remote MXC URIs (server names and media IDs) to local
  18500. <code>filesystem_id</code>s.</p>
  18501. <h3 id="paths-1"><a class="header" href="#paths-1">Paths</a></h3>
  18502. <p>A file from <code>matrix.org</code> with <code>filesystem_id</code> <code>aabbcccccccccccccccccccc</code> and its
  18503. <code>128x96</code> <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  18504. <pre><code>remote_content/matrix.org/aa/bb/cccccccccccccccccccc
  18505. remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  18506. </code></pre>
  18507. <p>Older thumbnails may omit the thumbnailing method:</p>
  18508. <pre><code>remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg
  18509. </code></pre>
  18510. <p>Note that <code>remote_thumbnail/</code> does not have an <code>s</code>.</p>
  18511. <h2 id="url-previews-1"><a class="header" href="#url-previews-1">URL Previews</a></h2>
  18512. <p>When generating previews for URLs, Synapse may download and cache various
  18513. resources, including images. These resources are assigned temporary media IDs
  18514. of the form <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code>, where <code>yyyy-mm-dd</code> is the current
  18515. date and <code>aaaaaaaaaaaaaaaa</code> is a random sequence of 16 case-sensitive letters.</p>
  18516. <p>The metadata for these cached resources is stored in the
  18517. <code>local_media_repository</code> and <code>local_media_repository_url_cache</code> tables.</p>
  18518. <p>Resources for URL previews are deleted after a few days.</p>
  18519. <h3 id="paths-2"><a class="header" href="#paths-2">Paths</a></h3>
  18520. <p>The file with media ID <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code> and its <code>128x96</code>
  18521. <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  18522. <pre><code>url_cache/yyyy-mm-dd/aaaaaaaaaaaaaaaa
  18523. url_cache_thumbnails/yyyy-mm-dd/aaaaaaaaaaaaaaaa/128-96-image-jpeg-scale
  18524. </code></pre>
  18525. <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>
  18526. <p>Synapse maintains room and user statistics in various tables. These can be used
  18527. for administrative purposes but are also used when generating the public room
  18528. directory.</p>
  18529. <h1 id="synapse-developer-documentation"><a class="header" href="#synapse-developer-documentation">Synapse Developer Documentation</a></h1>
  18530. <h2 id="high-level-concepts"><a class="header" href="#high-level-concepts">High-Level Concepts</a></h2>
  18531. <h3 id="definitions-1"><a class="header" href="#definitions-1">Definitions</a></h3>
  18532. <ul>
  18533. <li><strong>subject</strong>: Something we are tracking stats about – currently a room or user.</li>
  18534. <li><strong>current row</strong>: An entry for a subject in the appropriate current statistics
  18535. table. Each subject can have only one.</li>
  18536. </ul>
  18537. <h3 id="overview-4"><a class="header" href="#overview-4">Overview</a></h3>
  18538. <p>Stats correspond to the present values. Current rows contain the most up-to-date
  18539. statistics for a room. Each subject can only have one entry.</p>
  18540. <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>
  18541. <p>Synapse has a number of platform dependencies, including Python, Rust,
  18542. PostgreSQL and SQLite. This document outlines the policy towards which versions
  18543. we support, and when we drop support for versions in the future.</p>
  18544. <h2 id="policy"><a class="header" href="#policy">Policy</a></h2>
  18545. <p>Synapse follows the upstream support life cycles for Python and PostgreSQL,
  18546. i.e. when a version reaches End of Life Synapse will withdraw support for that
  18547. version in future releases.</p>
  18548. <p>Details on the upstream support life cycles for Python and PostgreSQL are
  18549. documented at <a href="https://endoflife.date/python">https://endoflife.date/python</a> and
  18550. <a href="https://endoflife.date/postgresql">https://endoflife.date/postgresql</a>.</p>
  18551. <p>A Rust compiler is required to build Synapse from source. For any given release
  18552. the minimum required version may be bumped up to a recent Rust version, and so
  18553. people building from source should ensure they can fetch recent versions of Rust
  18554. (e.g. by using <a href="https://rustup.rs/">rustup</a>).</p>
  18555. <p>The oldest supported version of SQLite is the version
  18556. <a href="https://packages.debian.org/bullseye/libsqlite3-0">provided</a> by
  18557. <a href="https://wiki.debian.org/DebianOldStable">Debian oldstable</a>.</p>
  18558. <h2 id="context"><a class="header" href="#context">Context</a></h2>
  18559. <p>It is important for system admins to have a clear understanding of the platform
  18560. requirements of Synapse and its deprecation policies so that they can
  18561. effectively plan upgrading their infrastructure ahead of time. This is
  18562. especially important in contexts where upgrading the infrastructure requires
  18563. auditing and approval from a security team, or where otherwise upgrading is a
  18564. long process.</p>
  18565. <p>By following the upstream support life cycles Synapse can ensure that its
  18566. dependencies continue to get security patches, while not requiring system admins
  18567. to constantly update their platform dependencies to the latest versions.</p>
  18568. <p>For Rust, the situation is a bit different given that a) the Rust foundation
  18569. does not generally support older Rust versions, and b) the library ecosystem
  18570. generally bump their minimum support Rust versions frequently. In general, the
  18571. Synapse team will try to avoid updating the dependency on Rust to the absolute
  18572. latest version, but introducing a formal policy is hard given the constraints of
  18573. the ecosystem.</p>
  18574. <p>On a similar note, SQLite does not generally have a concept of &quot;supported
  18575. release&quot;; bugfixes are published for the latest minor release only. We chose to
  18576. track Debian's oldstable as this is relatively conservative, predictably updated
  18577. and is consistent with the <code>.deb</code> packages released by Matrix.org.</p>
  18578. <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>
  18579. <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>
  18580. <ul>
  18581. <li><strong>Platform</strong>: 2x1GHz armhf 2GiB ram <a href="https://wiki.debian.org/CheapServerBoxHardware">Single-board computers</a>, SSD, postgres.</li>
  18582. </ul>
  18583. <h3 id="presence-1"><a class="header" href="#presence-1">Presence</a></h3>
  18584. <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>
  18585. <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>
  18586. <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>
  18587. <h3 id="joining"><a class="header" href="#joining">Joining</a></h3>
  18588. <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>
  18589. <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>
  18590. <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>
  18591. <h3 id="sessions"><a class="header" href="#sessions">Sessions</a></h3>
  18592. <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>
  18593. <h3 id="recommended-configuration"><a class="header" href="#recommended-configuration">Recommended configuration</a></h3>
  18594. <p>Put the below in a new file at /etc/matrix-synapse/conf.d/sbc.yaml to override the defaults in homeserver.yaml.</p>
  18595. <pre><code># Disable presence tracking, which is currently fairly resource intensive
  18596. # More info: https://github.com/matrix-org/synapse/issues/9478
  18597. use_presence: false
  18598. # Set a small complexity limit, preventing users from joining large rooms
  18599. # which may be resource-intensive to remain a part of.
  18600. #
  18601. # Note that this will not prevent users from joining smaller rooms that
  18602. # eventually become complex.
  18603. limit_remote_rooms:
  18604. enabled: true
  18605. complexity: 3.0
  18606. # Database configuration
  18607. database:
  18608. # Use postgres for the best performance
  18609. name: psycopg2
  18610. args:
  18611. user: matrix-synapse
  18612. # Generate a long, secure password using a password manager
  18613. password: hunter2
  18614. database: matrix-synapse
  18615. host: localhost
  18616. </code></pre>
  18617. <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>
  18618. <pre><code>admin@homeserver:~$ zgrep '/client/r0/join/' /var/log/matrix-synapse/homeserver.log* | awk '{print $18, $25}' | sort --human-numeric-sort
  18619. 29.922sec/-0.002sec /_matrix/client/r0/join/%23debian-fasttrack%3Apoddery.com
  18620. 182.088sec/0.003sec /_matrix/client/r0/join/%23decentralizedweb-general%3Amatrix.org
  18621. 911.625sec/-570.847sec /_matrix/client/r0/join/%23synapse%3Amatrix.org
  18622. 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'
  18623. canonical_alias | joined_members | current_state_events
  18624. -------------------------------+----------------+----------------------
  18625. #_oftc_#debian:matrix.org | 871 | 52355
  18626. #matrix:matrix.org | 6379 | 10684
  18627. #irc:matrix.org | 461 | 3751
  18628. #decentralizedweb-general:matrix.org | 997 | 1509
  18629. #whatsapp:maunium.net | 554 | 854
  18630. </code></pre>
  18631. </main>
  18632. <nav class="nav-wrapper" aria-label="Page navigation">
  18633. <!-- Mobile navigation buttons -->
  18634. <div style="clear: both"></div>
  18635. </nav>
  18636. </div>
  18637. </div>
  18638. <nav class="nav-wide-wrapper" aria-label="Page navigation">
  18639. </nav>
  18640. </div>
  18641. <script type="text/javascript">
  18642. window.playground_copyable = true;
  18643. </script>
  18644. <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
  18645. <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
  18646. <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
  18647. <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
  18648. <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
  18649. <script src="book.js" type="text/javascript" charset="utf-8"></script>
  18650. <!-- Custom JS scripts -->
  18651. <script type="text/javascript" src="docs/website_files/table-of-contents.js"></script>
  18652. <script type="text/javascript" src="docs/website_files/version-picker.js"></script>
  18653. <script type="text/javascript" src="docs/website_files/version.js"></script>
  18654. <script type="text/javascript">
  18655. window.addEventListener('load', function() {
  18656. window.setTimeout(window.print, 100);
  18657. });
  18658. </script>
  18659. </body>
  18660. </html>